-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinker.js
2529 lines (2256 loc) · 68.2 KB
/
tinker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (c) 2022-2025, SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Run SWI-Prolog interactively in the browser
* @author Jan Wielemaker
*
* @description
* This file provides a number of JavaScript classes that allow
* building interactive Prolog applications in a web page. Below is a
* short introduction of the exported classes.
*
* ## Classes
*
* - `Query` <br>
* A query manages a Prolog query. It allows for entering and
* running a query. It manages interaction (`read/1`, the
* Prolog debugger, asking for more answers, etc.) and collects
* both the answers and console output produced by running the
* query.
* - `Console`<br>
* A console manages a number of `Query` instances.
* - `Source`<br>
* The source instance manages files, and editing files. It uses
* an instance of `Editor` to edit sources and an instance of
* `Persist` to persist files from the virtual WASM file system
* to the browser's localStorage.
* - `Editor`<br>
* Encapsulates an instance of [CodeMirror](https://codemirror.net/).
* - `Input`<br>
* Encapsulates an HTML `<input>` element and a prompt to read
* queries, terms and lines. It is embedded in a `Query` instance
* and is sensitive to the query state.
* - `Persist`<br>
* Deals with saving files and the query history to the browser's
* localStorage.
* - `Tinker`<br>
* Simple small class that binds the various components together
* to establish [SWI-Tinker](https://wasm.swi-prolog.org/wasm/tinker)
*
* ## Design notes
*
* Except for class `Persist`, each instance controls an HTML element.
* This element can be accessed using the `.elem` property and the
* controlling instance can be found from `.data.instance` from the
* HTML element.
*/
/*******************************
* GLOBALS *
*******************************/
/**
* WASM Module. Instantiated by the `Tinker` constructor from
* the `SWIPL` instantiation.
* @type {SWIPL}
*/
let Module; // The WASM module
/**
* The one and only instance of class `Prolog` that is made available
* from the `SWIPL` `Module` instance as `Module.prolog`.
* @type {Prolog}
*/
let Prolog; // The one and only Prolog instance
/*******************************
* SOURCE *
*******************************/
/**
* Encapsulate the right pane of Tinker, providing the editor, file
* selector, (re)consult button and up/download buttons.
*/
export class Source {
files; // Current and available
default_file; // Use scratch file
user_dir; // Directory for user files
select_file; // File selector
editor; // Editor instance
elem; // The <form>
persist; // Persist instance
con; // Console instance
/**
* Create the Tinker source file manager from an DOM structure that
* contains the various components. Components are found by name.
* Most components are optional, not providing the functionality
* when missing.
*
* @param {HTMLFormElement} elem Toplevel element used.
* @param {object} [options] Options processed.
* @param {string} [options.user_dir] Working directory where user
* files are placed. Defaults to `"/prolog"`.
* @param {string} [options.default_file_name] Default (scratch)
* file. Defaults to `"scratch.pl"`
* @param {Persist} [options.persist] Persistency manager. Defaults
* to `new Persist()`.
* @param {Console} [options.console] Console into which to inject
* queries.
*/
constructor(elem, opts) {
const self = this;
this.elem = elem;
elem.data = {instance: this};
opts = opts||{};
this.persist = opts.persist||new Persist();
this.persist.source = this;
this.con = opts.console;
if ( this.con )
this.con.source = this;
this.user_dir = opts.user_dir||"/prolog";
this.default_file =
`${this.user_dir}/${opts.default_file_name||"scratch.pl"}`
this.files = { current: this.default_file,
list: [this.default_file]
};
this.select_file = this.byname("select-file");
Module.FS.mkdir(this.user_dir);
this.editor = new Editor(this.byname("editor"),
() => self.afterEditor(),
{ source:this });
// Register event handling
this.armFileSelect();
this.armNewFileButton();
this.armFileCreateButton();
this.armDeleteFile();
this.armDownloadButton();
this.armUploadButton();
this.armConsult();
}
afterEditor() {
this.persist.restore();
this.addExamples();
}
set value(source) { this.editor.value = source; }
get value() { return this.editor.value; }
goto(line,options) { this.editor.goto(line,options); }
mark(from,to,options) { this.editor.mark(from,to,options); }
clearMarks(from,to) { this.editor.clearMarks(from,to); }
/**
* The default translation to Prolog gets the content as an atom.
* We return an instance of Prolog.String.
* @return {Prolog.String} representing the current content of the
* editor.
*/
getValueAsPrologString() {
return new Prolog.String(this.value);
}
/**
* Add the examples to the file selector. This is not ideal as
* the standard HTML `<select>` does not allow for styling.
*/
async addExamples() {
const json = await fetch("examples/index.json").then((r) => {
return r.json();
});
if ( Array.isArray(json) && json.length > 0 ) {
const select = this.select_file;
const sep = document.createElement("option");
sep.textContent = "Demos";
sep.disabled = true;
select.appendChild(sep);
json.forEach((ex) => {
if ( !this.hasFileOption(this.userFile(ex.name)) ) {
const opt = document.createElement("option");
opt.className = "url";
opt.value = "/wasm/examples/"+ex.name;
opt.textContent = (ex.comment||ex.name) + " (demo)";
select.appendChild(opt);
}
});
}
}
/**
* Add name to the file menu.
* @param {string} name is the absolute name of the file that
* is stored in the `value` attribute of the `<option>` element.
* @return {HTMLElement} holding the `<option>` element.
*/
addFileOption(name) {
const select = this.select_file;
let node = this.hasFileOption(name);
if ( !node )
{ node = document.createElement('option');
node.textContent = this.baseName(name);
node.value = name;
node.selected = true;
const sep = this.demoOptionSep();
if ( sep )
select.insertBefore(node, sep);
else
select.appendChild(node);
}
return node;
}
/**
* Switch the source view to a specific file. This updates the file
* selector, saves the old file and loads the new file.
* @param {string} name is the full path of the file to switch to.
*/
switchToFile(name) {
const options = Array.from(this.select_file.childNodes);
options.forEach((e) => {
e.selected = e.value == name;
});
if ( this.files.current != name ) {
this.ensureSavedCurrentFile();
this.files.current = name;
this.editor.file = name;
if ( !this.files.list.includes(name) )
this.files.list.push(name);
this.persist.loadFile(name);
this.updateDownload(name);
}
}
/**
* Delete a file from the menu, the file system and the browser
* localStorage. The source view switches to the next file, unless
* this is the last. In that case it switches to the previous.
*
* @param {string} file is the file to be deleted.
*/
deleteFile(file) {
const select = this.select_file;
const opt = this.hasFileOption(file);
let to = opt.nextElementSibling;
const sep = this.demoOptionSep();
if ( !to || to == sep )
to = opt.previousElementSibling;
if ( !to )
to = default_file;
this.switchToFile(to.value);
opt.parentNode.removeChild(opt);
this.files.list = this.files.list.filter((n) => (n != file));
this.persist.removeFile(file);
Module.FS.unlink(file);
}
currentFileOption() {
return this.select_file.options[this.select_file.selectedIndex];
}
hasFileOption(name) {
return Array.from(this.select_file.childNodes)
.find((n) => n.value == name );
}
demoOptionSep() {
return Array.from(this.select_file.childNodes)
.find((n) => n.textContent == "Demos" && n.disabled);
}
armFileSelect() {
this.select_file.addEventListener("change", (e) => {
const opt = this.currentFileOption();
if ( opt.className == "url" ) {
fetch(opt.value)
.then((res) => res.text())
.then((s) => {
const name = this.baseName(opt.value);
opt.className = "local";
opt.value = this.userFile(name);
opt.textContent = name;
Module.FS.writeFile(opt.value, s);
this.switchToFile(opt.value);
});
} else
{ this.switchToFile(opt.value);
}
});
}
armNewFileButton() {
const btn = this.byname("new-file");
btn.addEventListener("click", (e) => {
const fname = this.byname("file-name");
e.preventDefault();
this.elem.classList.add("create-file");
e.target.disabled = true;
fname.value = "";
fname.focus();
});
}
armFileCreateButton() {
const btn = this.byname("create-button");
const input = this.byname("file-name");
input.addEventListener("keydown", (e) => {
if ( e.key === "Enter" )
btn.click();
});
btn.addEventListener("click", (e) => {
e.preventDefault();
let name = input.value.trim();
if ( /^[a-zA-Z 0-9.-_]+$/.test(name) )
{ if ( ! /\.pl$/.test(name) )
name += ".pl";
name = this.userFile(name);
this.addFileOption(name);
this.switchToFile(name);
this.elem.classList.remove("create-file");
this.byname("new-file").disabled = false;
} else
{ alert("No or invalid file name!");
}
});
}
armDeleteFile() {
const btn = this.byname("delete-file");
if ( btn ) {
btn.addEventListener("click", (e) => {
e.preventDefault();
const del = this.currentFileOption().value;
if ( del == this.default_file )
{ alert("Cannot delete the default file");
return;
}
if ( !this.isUserFile(del) )
{ alert("Cannot delete system files");
return;
}
this.deleteFile(del);
});
}
}
/**
* Update the title and download location of the download button
* after switching files.
*/
updateDownload(file) {
const btn = this.elem.querySelector("a.btn.download");
if ( btn ) {
file = this.baseName(file);
btn.download = file;
btn.title = `Download ${file}`;
btn.href = "download";
}
}
armDownloadButton() {
const btn = this.elem.querySelector("a.btn.download");
if ( btn ) {
btn.addEventListener("click", (ev) => {
const text = this.value;
const data = new Blob([text]);
const btn = ev.target;
btn.href = URL.createObjectURL(data);
})
}
}
async download_files(files) {
for(let i=0; i<files.length; i++) {
const file = files[i];
const content = await this.readAsText(file);
const name = this.userFile(this.baseName(file.name));
this.addFileOption(name);
this.switchToFile(name);
this.value = content;
this.ensureSavedCurrentFile();
}
}
armUploadButton() {
const btn = this.elem.querySelector("a.btn.upload");
if ( btn ) {
btn.addEventListener("click", (ev) => {
const exch = ev.target.closest("span.exch-files");
if ( exch.classList.contains("upload-armed") ) {
const files = exch.querySelector('input.upload-file').files;
this.download_files(files).then(() => {
exch.classList.remove("upload-armed");
});
} else {
exch.classList.add("upload-armed")
}
});
}
}
ensureSavedCurrentFile() {
const file = this.files.current;
if ( file ) {
if ( this.isUserFile(file) )
Module.FS.writeFile(file, this.value);
return file;
}
}
/**
* Arm the form submit button.
*/
armConsult() {
const btn = this.byname("consult");
if ( btn )
btn.addEventListener('click', (e) => {
e.preventDefault();
const file = this.ensureSavedCurrentFile();
this.con.injectQuery(`consult('${file}').`); // TODO: quote
}, false);
}
/**
* @return {Promise} for handling the content of an uploaded file.
*/
readAsText(file) {
return new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onerror = reject;
fr.onload = () => {
resolve(fr.result);
}
fr.readAsText(file);
});
}
/**
* @return {string} full path name of a user file from the base
* name.
*/
userFile(base) {
return `${this.user_dir}/${base}`;
}
/**
* @return {bool} `true` when `file` is a _user file_.
*/
isUserFile(file) {
return file.startsWith(`${this.user_dir}/`);
}
baseName(path) {
return path.split("/").pop();
}
/**
* Find one of my components by its name.
* @param {string} name Name of the component to find.
* @return {HTMLElement} Element with that name;
*/
byname(name) {
return this.elem.querySelector(`[name=${name}]`);
}
} // end class Source
/*******************************
* THE SOURCE EDITOR *
*******************************/
/**
* Encapsulate the editor. In this case the actual editor is
* [CodeMirror](https://codemirror.net/). Defines methods to
*
* - Initialise the editor
* - Set and get its value {@link Editor#value}
* - Go to a line/column {@link Editor#goto}
*
* By default, the editor instance is created by {@link Source} on the
* element named `editor` that must be part of the DOM used to create
* the {@link Source} instance.
*
* The CodeMirror code is downloaded from cdnjs.cloudflare.com and the
* Prolog mode from www.swi-prolog.org.
*/
export class Editor {
static cm_url = "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.9";
static cm_swi = "https://www.swi-prolog.org/download/codemirror";
CodeMirror; // Our CodeMirror instance
timeout; // Timeout to detect typing pause (highlight)
source; // Related Source instance
file; // Current file
current_var_clause; // Clause marked as current var
/**
* @param {HTMLDivElement} container Element in which to create the editor
* @param {function} cont Call-back called when the editor is completed.
* @param {object} options
* @param {object} options.source {@link Source} instance embedding me.
*/
constructor(container, cont, options) {
const instance = this;
this.source = options.source;
function cm_url(sub) {
return Editor.cm_url + sub;
}
function cm_swi(sub) {
return Editor.cm_swi + sub;
}
require.config({ paths: {
"cm/lib/codemirror": cm_url("/codemirror.min"),
"cm/addon/edit/matchbrackets": cm_url("/addon/edit/matchbrackets.min"),
"cm/mode/prolog": cm_swi("/mode/prolog")
}});
require(["cm/lib/codemirror",
"cm/addon/edit/matchbrackets",
"cm/mode/prolog/prolog",
"cm/mode/prolog/prolog_keys",
], (cm) => {
this.CodeMirror = cm;
this.createCM(container);
Prolog.consult("highlight.pl", {engine:true}).then(() => {
cont.call(this.cm);
});
});
loadCSS(cm_swi("/theme/prolog.css"));
}
createCM(container) {
this.cm = this.CodeMirror(container,
{ lineNumbers: true,
matchBrackets: true,
mode: "prolog",
theme: "prolog",
prologKeys: true
});
this.cm.on("change", (cm, change) => {
this.change(change);
});
this.cm.on("cursorActivity", (cm) => {
this.cursorActivity();
});
this.cm.on("viewportChange", (cm, from, to) => {
this.viewport(from, to);
});
}
/**
* Content of the editor
* @type {string}
*/
get value() {
return this.cm.getValue();
}
set value(content) {
this.cm.setValue(content);
}
/**
* Called on changes to the editor. This is used to drive
* highlighting updates. To sync with PceEmacs, the scheme is to
* - Do a full xref and highlight pass on changing the value
* and after 2 seconds idle time.
* - Do an incremental update for the current clause on each
* change. This gets the clause around the caret.
*/
change(change) {
const gen = this.cm.changeGeneration();
if ( this.timeout ) {
clearTimeout(this.timeout);
this.timeout = null;
}
if ( change.origin == "setValue" ) {
console.log("New value");
this.current_var_clause = null;
this.refreshHighlight("init");
} else {
this.refreshTermHighlight(this.getClause());
this.timeout = setTimeout(() => {
this.refreshHighlight("timed");
}, 2000);
}
}
/**
* Trap cursor activity to highlight the variable at the cursor
* position.
*/
cursorActivity() {
const cm = this.cm;
const cursor = cm.getCursor();
let word;
function getWord(from) {
const a = cm.findWordAt(from);
const w = cm.getRange(a.anchor, a.head);
if ( w.match(/\w+/) )
return w;
}
if ( !(word=getWord(cursor)) &&
cursor.ch > 0 ) {
const prev = {...cursor};
prev.ch--;
word=getWord(prev);
}
this.unmarkVar();
if ( word && /^(_|\p{Lu})/u.test(word) )
this.markVar(word);
}
/**
* Trap changes to the viewport. Currently unused. This must be
* used to avoid highlighting large files as a whole.
*/
viewport(from, to) {
//console.log("Showing lines", from, to);
}
/**
* Refresh the highlight of the clause around the cursor using
* the last cross-reference data.
*/
async refreshTermHighlight(clause) {
const source = this.source;
await Prolog.forEach("highlight:refresh_clause(Source, Clause)",
{Source:source, Clause:clause}, {engine:true});
}
/**
* Mark the variable named `varname` in the current clause.
*/
markVar(varname) {
const clause = this.getClause();
clause.current_variable = varname;
this.refreshTermHighlight(clause);
this.current_var_clause = clause;
}
unmarkVar() {
const clause = this.current_var_clause;
if ( clause ) {
this.current_var_clause = null;
delete clause.current_variable;
this.refreshTermHighlight(clause);
}
}
/**
* Refresh all highlighting over the entire file.
*/
async refreshHighlight(why) {
const source = this.source;
this.saveMarks();
await Prolog.forEach("highlight:highlight_all(Source)",
{Source:source}, {engine:true});
this.finalizeSavedMarks();
}
/**
* GetQ the editor text that holds the clause around the cursor.
* @return {object} An object holding the text as well as position
* information.
*/
getClause() {
const cm = this.cm;
const cursor = cm.getCursor();
const cline = cursor.line;
const first = cm.firstLine();
const last = cm.lastLine();
function lineEndState(ln) {
const info = cm.lineInfo(ln);
return info.handle.stateAfter;
}
function hasFullStop(ln) {
const info = cm.lineInfo(ln);
const handle = info.handle;
if ( handle.styles && handle.styles.includes("fullstop") )
return "token";
if ( /[^#$&*+-./:<=>?@\\^~]\.\s/.test(info.text) )
return "regex";
}
function bodyLine(ln) {
const info = lineEndState(ln);
return info && info.inBody;
}
let sline = cline;
let eline = cline;
let end;
while( sline > first && bodyLine(sline-1) )
sline--;
while( eline < last && !(end=hasFullStop(eline)) )
eline++;
//console.log(`Clause in lines ${sline}..${eline}`);
let lines = [];
for(let i = sline; i<=eline; i++)
lines.push(cm.lineInfo(i).text);
return ({ text: new Prolog.String(lines.join("\n")),
file: this.file,
start_line: sline,
end_line: eline,
end_reason: end,
start_char: this.startIndexOfLine(sline),
change_gen: cm.changeGeneration()
});
}
/**
* @param {number} 0-based line number
* @return {number} character index of the first character
* of the line.
*/
startIndexOfLine(ln) {
const cm = this.cm;
let index = 0;
for(let i=cm.firstLine(); i<ln; i++)
index += cm.lineInfo(i).text.length+1;
return index;
}
/**
* Go to a given 1-based line number. The target line is styled
* in CSS using the `.CodeMirror-search-match` selector.
*
* @param {number} line
* @param {Object} [options]
* @param {number} [options.linepos] Go to a specific column
* @param {string} [options.className] CSS class. Defaults to
* `CodeMirror-search-match`
* @param {string} [options.title] Element `title` attribute.
* Default to `"Target line"`
* @param {number} [options.margin] Vertical space visible above
* and below the target line. Defaults to 100 (pixels).
*/
goto(line, options) {
options = options||{};
const ch = options.linepos||0;
const cname = options.className||"CodeMirror-search-match";
const title = options.title||"Target line";
const margin = options.margin == undefined ? 100 : options.margin;
function clearSearchMarkers(cm)
{ if ( cm._searchMarkers !== undefined )
{ for(let i=0; i<cm._searchMarkers.length; i++)
cm._searchMarkers[i].clear();
cm.off("cursorActivity", clearSearchMarkers);
}
cm._searchMarkers = [];
}
clearSearchMarkers(this.cm);
line = line-1;
this.cm.setCursor({line:line,ch:ch});
if ( margin )
this.cm.scrollIntoView({line:line,ch:ch}, margin);
this.cm._searchMarkers.push(
this.cm.markText({line:line, ch:0},
{line:line, ch:this.cm.getLine(line).length},
{ className: cname,
clearOnEnter: true,
clearWhenEmpty: true,
title: title
}));
this.cm.on("cursorActivity", clearSearchMarkers);
}
indexCache;
indexToPos(index) {
const cm = this.cm;
let last = cm.lastLine();
let line;
let ls;
if ( this.indexCache &&
cm.changeGeneration() == this.indexCache.gen &&
index >= this.indexCache.start ) {
line = this.indexCache.line;
ls = this.indexCache.start;
} else {
line = cm.firstLine();
ls = 0;
}
for( ; line <= last ; line++ ) {
const info = cm.lineInfo(line);
const len = info.text.length;
if ( index <= ls+len ) {
this.indexCache = {
gen: cm.changeGeneration(),
line: line,
start: ls
};
return {line:line, ch:index-ls};
}
ls += len+1;
}
return {line:last, ch:0};
}
/**
* Add a CodeMirror text mark for the range (from,to).
* @param {number|object} from Start location as 0-based offset or CodeMirror
* {line:Line, ch:LinePos} object.
* @param {number|object} to End location as 0-based offset or CodeMirror
* {line:Line, ch:LinePos} object.
* @param {object} options Options passed to {@link
* CodeMirror#markText}. Typically contains `className`. May also
* contain `attributes for additional attributed on the `<span>` that
* is created. This often involves `title`.
*/
markers;
savedMarkers;
saveMarks() {
this.savedMarkers = this.markers;
this.markers = [];
}
finalizeSavedMarks() {
if ( this.savedMarkers ) {
for(let m of this.savedMarkers)
m.clear();
this.savedMarkers = null;
}
}
keepMark(from, to, options) {
if ( this.savedMarkers ) {
if ( typeof(from) !== "number" ||
typeof(to) !== "number" )
return false;
function equalMark(m, from, to, options) {
function equalAttrs(a1, a2) {
if ( !a1 && !a2 )
return true;
for(let a of ["title"]) {
if ( a1[a] || a2[a] && a1[a] != a2[a] )
return false;
}
return true;
}
return ( m._from == from && m._to == to &&
m.className == options.className &&
equalAttrs(options.attributes, m.attributes) );
}
for(let i=0; i<this.savedMarkers.length; i++) {
const m = this.savedMarkers[0];
if ( equalMark(m, from, to, options) ) {
this.markers.push(m);
this.savedMarkers.shift();
return true;
} else {
if ( m._from < to ) {
m.clear();
this.savedMarkers.shift();
return false;
}
}
}
}
return false;
}
mark(from, to, options) {
const cm = this.cm;
if ( this.keepMark(from, to, options) )
return;
const toPos = (x) => typeof(x) === "number" ? this.indexToPos(x) : x;
if ( !this.markers )
this.markers = [];
delete options["$tag"];
if ( options.attributes ) {
delete options.attributes["$tag"];
}
const f = toPos(from);
const t = toPos(to);
const m = cm.markText(f, t, options);
m._from = from;
m._to = to;
this.markers.push(m);
}
clearMarks(from, to) {
const cm = this.cm;
if ( this.markers ) {
if ( from === undefined ) from = 0;
if ( to === undefined ) to = 100000000;
let del = 0;
for(let i=0; i<this.markers.length; i++) {
const m = this.markers[i];
if ( (m._from >= from && m._from <= to) ||
(m._to >= from && m._to <= to) ) {
del++;
m.clear();
this.markers[i] = undefined;
}
}
if ( del )
this.markers = this.markers.filter((el) => el !== undefined);
}
}
} // End class Editor
function getPromiseFromEvent(item, event) {
return new Prolog.Promise((resolve) => {
const listener = (ev) => {
item.removeEventListener(event, listener);
resolve(ev);
}
item.addEventListener(event, listener);
})
}
/*******************************
* CREATE ELEMENTS *
*******************************/
function el(sel, ...content) {
const ar = sel.split(".");
const elem = document.createElement(ar.shift());
if ( ar.length > 0 )
elem.className = ar.join(" ");
for(let e of content) {
if ( typeof(e) === "string" )
e = document.createTextNode(e);
elem.appendChild(e);
}
return elem;