forked from sdllc/cmjs-shell
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshell.js
1629 lines (1387 loc) · 47.1 KB
/
shell.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
/**
*
* Copyright (c) 2016 Structured Data LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*
codemirror partial readonly
https://discuss.codemirror.net/t/how-to-make-certain-ranges-readonly-in-codemirror6/3400
https://www.npmjs.com/package/codemirror-readonly-ranges
https://stackoverflow.com/questions/17415100/codemirror-particular-lines-readonly
https://discuss.codemirror.net/t/easily-track-remove-content-with-decorations/4606
2021-01-14 codemirror 6
https://github.com/codemirror/dev/issues/44#issuecomment-789093799
https://codemirror.net/6/docs/guide/#state-fields
how to listen for changes
import { EditorState, EditorView, basicSetup } from '@codemirror/basic-setup';
import { StateField } from '@codemirror/state';
// Define StateField
const listenChangesExtension = StateField.define({
// we won't use the actual StateField value, null or undefined is fine
create: () => null,
update: (value, transaction) => {
if (transaction.docChanged) {
// access new content via the Transaction
console.log(transaction.newDoc.toJSON());
}
return null;
},
});
// Element for EditorView
const parent = window.document.querySelector('#my-div') as HTMLDivElement;
// Initialize with StateField as extension
const editor = EditorView({
state: EditorState.create({
extensions: [basicSetup, listenChangesExtension],
doc: 'print("hello github")',
}),
parent,
});
*/
//import * as CodeMirror from "codemirror"
//import {EditorView, Range, Decoration} from "@codemirror/view"
import { EditorView, Decoration, keymap } from "@codemirror/view"
import { StateField, StateEffect } from "@codemirror/state"
import { StreamLanguage } from "@codemirror/language"
//import { javascript } from "@codemirror/lang-javascript"
//import { parseMixed } from "@lezer/common"
//import readOnlyRangesExtension from "codemirror-readonly-ranges"
import { defaultKeymap, history, historyKeymap } from "@codemirror/commands"
import setImmediate from "queue-microtask"
export const EXEC_STATE = {
EDIT: "edit",
EXEC: "exec",
}
export const PARSE_STATUS = {
NULL: "",
OK: "OK",
INCOMPLETE: "Incomplete",
PARSE_ERR: "ParseError",
ERR: "Err",
}
const MAX_HISTORY_DEFAULT = 2500
const HISTORY_KEY_DEFAULT = "shell.history"
const DEFAULT_PROMPT_CLASS = "shell-prompt"
function posToOffset(doc, pos) {
//return doc.line(pos.line + 1).from + pos.ch
return doc.line(pos.line).from + pos.ch
}
function offsetToPos(doc, offset) {
let line = doc.lineAt(offset)
//return {line: line.number - 1, ch: offset - line.from}
return { line: line.number, ch: offset - line.from }
}
// https://codemirror.net/docs/migration/#marked-text
const addMarks = StateEffect.define()
const filterMarks = StateEffect.define()
// This value must be added to the set of extensions to enable this
const markFieldExtension = StateField.define({
// Start with an empty set of decorations
create() {
return Decoration.none
},
// This is called whenever the editor updates—it computes the new set
update(value, tr) {
// Move the decorations to account for document changes
value = value.map(tr.changes)
// If this transaction adds or removes decorations, apply those changes
for (let effect of tr.effects) {
if (effect.is(addMarks))
value = value.update({ add: effect.value, sort: true })
else if (effect.is(filterMarks))
value = value.update({ filter: effect.value })
}
return value
},
// Indicate that this field provides a set of decorations
provide: (f) => EditorView.decorations.from(f),
})
/**
* shell implmentation based on CodeMirror (which is awesome)
* see http://codemirror.net/.
*
* Example options:
*
* initial_prompt: "> "
* continuation_prompt: "+ "
* exec_function( command, callback )
* hint_function( line, position, callback( list, start ))
* container: element or id, document.body
* mode: "javascript"
* drop_files: [ mime types ]
* function_key_callback: called on function keys (+ some others)
*
*/
export default function Shell(opts) {
/** @type {import("codemirror").EditorView} */
var view
var state = EXEC_STATE.EDIT
var prompt_text = ""
var instance = this
instance.opts = opts
instance.cm = null
this.function_tip = {}
this.EXEC_STATE = EXEC_STATE
this.PARSE_STATUS = PARSE_STATUS
instance.language = null
var prompt_len = 0
var command_buffer = []
var paste_buffer = []
var unstyled_lines = []
var block_reset = []
var unstyled_flag = false
var cached_prompt = null
var event_cache = null
var event_cache_skip = false
var event_playback = false
/**
* FIXME: cap and flush this thing at (X) number of lines
*
* soft persistence, meaning: up up to a command, modify it
* slightly, then down, up, modifications are retained. reverts
* on new command.
*/
class History {
/** @type {string | null} */
current_line = null
commands = []
actual_commands = []
pointer = 0
reset_pointer() {
this.pointer = 0
this.commands = this.actual_commands.slice(0)
}
push(line) {
this.actual_commands.push(line)
this.commands = this.actual_commands.slice(0)
}
save(opts) {
opts = opts || {}
var max = opts.max || MAX_HISTORY_DEFAULT
var key = opts.key || HISTORY_KEY_DEFAULT
localStorage.setItem(
key,
JSON.stringify(this.actual_commands.slice(-max))
)
}
restore(opts) {
opts = opts || {}
var key = opts.key || HISTORY_KEY_DEFAULT
var val = localStorage.getItem(key)
if (val) this.actual_commands = JSON.parse(val)
this.reset_pointer()
}
clear() {
this.actual_commands = []
this.commands = []
this.pointer = 0
this.save()
}
}
const history = new History()
/**
* overlay mode to support unstyled text -- file contents (the pager)
* in our particular case but could be anything. this is based on
* CM's "overlay" mode, but that one doesn't work because it parses
* regardless and we get stuck in string-mode after a stray apostrophe.
*
* in this one, null styling is the default, and greedy; but if we are
* not unstyled, then we pass through to (base). base should be a string
* mode name, which must have been previously registered.
*/
/**
*
* // TODO param {import("@codemirror/language").Language} innerLanguage
* // TODO param {import("@codemirror/legacy-modes").Mode} innerMode
* @param {*} base
*/
function init_overlay_mode(base) {
// CodeMirror.defineMode in codemirror 6
// https://discuss.codemirror.net/t/how-to-create-custom-syntax-highlighter-using-stream-parser/3752
// https://github.com/codemirror/legacy-modes/blob/main/mode/shell.js
// https://github.com/codemirror/legacy-modes/search?q=startState
// https://github.com/codemirror/legacy-modes/search?q=copyState
// https://codemirror.net/examples/mixed-language/
// https://discuss.codemirror.net/t/equivalent-of-getstateafter-in-cm6/3855
// https://marijnhaverbeke.nl/blog/codemirror-mode-system.html
/*
CM.defineMode( name, function(config, parserConfig) {
base = CM.getMode( config, parserConfig.backdrop || baseMode );
return { ... };
});
*/
//var config = {} // TODO
//var parserConfig = {} // TODO
//var base = CM.getMode( config, parserConfig.backdrop || baseName );
var outerLanguage = StreamLanguage.define({
startState: function () {
return {
base: base.startState(),
linecount: 0,
}
},
/* FIXME TypeError: base.copyState is not a function
copyState: function(state) {
return {
base: base.copyState(state.base),
linecount: state.linecount
};
},
*/
token: function (stream, state) {
if (stream.sol()) {
var lc = state.linecount
state.linecount++
if (unstyled_flag || unstyled_lines[lc]) {
stream.skipToEnd()
return "unstyled"
}
if (block_reset[lc]) {
state.base = base.startState()
}
}
return base.token(stream, state.base)
},
// FIXME TypeError: Cannot read properties of undefined (reading 'unit')
indent:
base?.indent &&
function (state, textAfter) {
console.log("outerLanguage indent", { base, state, textAfter })
return base.indent(state.base, textAfter)
},
// FIXME
//electricChars: base.electricChars,
// FIXME
//innerMode: function(state) { return {state: state.base, mode: base}; },
blankLine: function (state) {
state.linecount++
if (base.blankLine) base.blankLine(state.base)
},
})
/* TODO overlay LRLanguage and StreamLanguage
const mixedParser = outerLanguage.parser.configure({
// simple: one node has the inner content
//wrap: parseMixed(node => {
// return node.name == "ScriptText" ? {parser: innerParser} : null
//}),
// overlay: multiple node have the inner content
wrap: parseMixed(node => {
return node.type.isTop ? {
parser: innerLanguage.parser,
overlay: node => node.type.name == "Text"
} : null
})
})
const mixedLang = LRLanguage.define({parser: mixedParser})
*/
instance.language = outerLanguage
}
/** destructively clear all history */
this.clearHistory = function () {
history.clear()
}
/**
* get the CM object. necessary for some clients
* to handle events. FIXME -- pass through events.
*/
this.getCM = function () {
return view
}
/** set CM option directly -- REMOVE */
this.setOption = function (option, value) {
if (opts.debug) console.info("set option", option, value)
// FIXME
//cm.setOption( option, value );
}
/** get CM option directly -- REMOVE */
this.getOption = function (option) {
if (opts.debug) console.info("get option", option)
// FIXME
//return cm.getOption( option );
}
/** cache events if we're blocking */
var cacheEvent = function (event) {
if (event_cache && !event_playback) {
if (event_cache_skip) {
if (event.type === "keyup" && event.key === "Enter")
event_cache_skip = false
} else {
event_cache.push(event)
}
}
}
/**
* when unblocking (exiting an explicit block or exec),
* replay cached keyboard events. in some cases a played-back
* event may trigger execution, which turns caching back on.
* in that case, stop processing and dump all the
* original source events back into the cache.
*/
var playbackEvents = function () {
// flush cache. set to null to act as flag
var tmp = event_cache
event_cache = null
event_cache_skip = false
if (tmp && tmp.length) {
console.log(`playbackEvents: tmp=${JSON.stringify(tmp)}`)
// FIXME
var inputTarget = view.getInputField()
tmp.forEach(function (src) {
if (event_cache) {
cacheEvent(src)
return
}
var event = new KeyboardEvent(src.type, src)
Object.defineProperties(event, {
charCode: {
get: function () {
return src.charCode
},
},
which: {
get: function () {
return src.which
},
},
keyCode: {
get: function () {
return src.keyCode
},
},
key: {
get: function () {
return src.key
},
},
char: {
get: function () {
return src.char
},
},
target: {
get: function () {
return src.target
},
},
})
event_playback = true
inputTarget.dispatchEvent(event)
event_playback = false
})
}
}
/**
* block. this is used for operations called by the code, rather than
* the user -- we don't want the user to be able to run commands, because
* they'll fail.
* @param {string} message
*/
this.block = function block(message) {
console.log(`block: state=${JSON.stringify(state)}`)
// this bit is right from exec:
if (state === EXEC_STATE.EXEC) {
return false
}
console.log("block: view", view)
var doc = view.state.doc
var lineno = doc.lines
var line = doc.line(lineno)
console.log(`block: message=${JSON.stringify(message)}`)
if (!message) message = "\n"
else message = "\n" + message + "\n"
//doc.replaceRange( message, { line: lineno+1, ch: 0 }, undefined, "prompt");
var pos = doc.line(doc.lines).from
view.dispatch({ changes: { from: pos, to: undefined, insert: message } })
//view.dispatch({selection: {anchor: pos}})
state = EXEC_STATE.EXEC
var command = line.text.slice(prompt_len)
command_buffer.push(command)
if (command.trim().length > 0) {
history.push(command)
history.save() // this is perhaps unecessarily aggressive
}
// this automatically resets the pointer (NOT windows style)
history.reset_pointer()
// turn on event caching
event_cache = []
// now leave it in this state...
return true
}
/** unblock, should be symmetrical. */
this.unblock = function (result, ignore_cached_events) {
// again this is from exec (but we're skipping the
// bit about pasting)
state = EXEC_STATE.EDIT
if (result && result.prompt) {
command_buffer = []
set_prompt(
result.prompt || instance.opts.initial_prompt,
result.prompt_class,
result.continuation
)
} else {
var ps = result
? result.parsestatus || PARSE_STATUS.OK
: PARSE_STATUS.NULL
if (ps === PARSE_STATUS.INCOMPLETE) {
set_prompt(instance.opts.continuation_prompt, undefined, true)
} else {
command_buffer = []
set_prompt(instance.opts.initial_prompt)
}
}
if (!ignore_cached_events) playbackEvents()
}
/**
* get history as array
*/
this.get_history = function () {
return history.actual_commands.slice(0)
}
/**
* insert an arbitrary node, via CM's widget
*
* @param scroll -- scroll to the following line so the node is visible
*/
this.insert_node = function (node, scroll) {
var doc = view.state.doc
var line = Math.max(doc.lines - 1, 0)
view.addLineWidget(line, node, {
handleMouseEvents: true,
})
if (scroll)
view.dispatch({ effects: EditorView.scrollIntoView(doc.line(line).from) })
}
/**
* select all -- this doesn't seem to work using the standard event... ?
*/
this.select_all = function () {
//cm.execCommand( 'selectAll' );
view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } })
}
this.scrollToEnd = function scrollToEnd() {
var doc = view.state.doc
//console.log(`doc.length ${doc.length}`)
// wait for new doc.length
//setImmediate(() => {
//console.log(`setImmediate doc.length ${doc.length}`)
// scroll to end
view.dispatch({ effects: EditorView.scrollIntoView(doc.length) })
// set cursor
view.dispatch({ selection: { anchor: view.state.doc.length } })
//})
}
/**
* handler for command responses, stuff that the system
* sends to the shell (callbacks, generally). optional className is a
* style applied to the block. "unstyled", if set, prevents language
* styling on the block.
*/
this.response = function response(text, className, unstyled) {
// FIXME add newline after result
console.log(`response: text=${JSON.stringify(text)}`)
var doc = view.state.doc
var lineno = doc.lines
var end,
start = lineno
if (text && typeof text !== "string") {
try {
text = text.toString()
} catch (e) {
text = "Unrenderable message: " + e.message
}
}
// don't add newlines. respect existing length. this is so we
// can handle \r (without a \n). FIXME: if there's a prompt, go
// up one line.
var lastline = doc.line(lineno)
var ch = lastline ? lastline.length : 0
// second cut, a little more thorough
// one more patch, to stop breaking on windows CRLFs
var lines = text.split("\n")
var replace_end = undefined
var inline_replacement = false
// fix here in case there's already a prompt (this is a rare case?)
if (state !== EXEC_STATE.EXEC) {
ch = 0 // insert before anything else on line
// this is new: in the event that there is already a prompt,
// and we are maintaining styling "breaks", then we may
// need to offset the last break by some number of lines.
// actually we know it's only going to be the last one, so
// we can skip the loop.
if (lines.length > 1 && block_reset.length) {
var blast = block_reset.length - 1
block_reset[blast] = undefined
block_reset[blast + lines.length - 1] = 1
}
}
// parse carriage-return \r
text = ""
for (var i = 0; i < lines.length; i++) {
var overwrite = lines[i].split("\r")
if (i) text += "\n"
else if (overwrite.length > 1) inline_replacement = true
if (overwrite.length > 1) {
var final_text = ""
for (var j = overwrite.length - 1; j >= 0; j--) {
final_text = final_text + overwrite[j].substring(final_text.length)
}
text += final_text
} else text += lines[i]
}
console.log(`response: text2=${JSON.stringify(text)}`)
if (inline_replacement) {
replace_end = { line: start, ch: ch }
ch = 0
}
// for styling before we have built the table
if (unstyled) unstyled_flag = true
//doc.replaceRange( text, { line: start, ch: ch }, replace_end, "callback");
view.dispatch({
changes: {
from: posToOffset(doc, { line: start, ch: ch }),
to: replace_end && posToOffset(doc, replace_end),
insert: text,
// TODO class callback?
},
})
end = doc.lines
lastline = doc.line(end)
var endch = lastline.text.length
console.log(
`doc.lines=${doc.lines} lastline.text=${lastline.text} endch=${endch}`
)
// TODO what is this?
if (unstyled) {
var u_end = end
if (endch == 0) u_end--
if (u_end >= start) {
for (
// @ts-ignore
var i = start;
i <= u_end;
i++
)
unstyled_lines[i] = 1
}
}
// can specify class
/* FIXME
if( className ){
doc.markText( { line: start, ch: ch }, { line: end, ch: endch }, {
className: className
});
}
*/
if (className) {
const from = posToOffset(doc, { line: start, ch: ch })
const to = posToOffset(doc, { line: end, ch: endch })
if (from < to) {
// https://codemirror.net/docs/migration/#marked-text
const strikeMark = Decoration.mark({
attributes: {
//style: "text-decoration: line-through",
className: className,
},
})
console.dir([
`addMarks: className = ${className}`,
{ line: start, ch: ch },
{ line: end, ch: endch },
])
view.dispatch({
effects: addMarks.of([strikeMark.range(from, to)]),
})
}
// else: range is empty
}
// don't scroll in exec mode, on the theory that (1) we might get
// more messages, and (2) we'll scroll when we enter the caret
//if( state !== EXEC_STATE.EXEC )
/* FIXME
{
cm.scrollIntoView({line: doc.lines, ch: endch});
}
*/
this.scrollToEnd()
// the problem with that is that it's annoying when you want to see
// the messages (for long-running code, for example).
unstyled_flag = false
}
/**
* this is history in the sense of up arrow/down arrow in the shell.
* it's not really connected to any underlying history (although that
* would probably be useful).
*
* FIXME: move more of this into the history class
*/
function shell_history(up) {
if (state == EXEC_STATE.EXEC) return
// can we move in this direction? [FIXME: bell?]
if (up && history.pointer >= history.commands.length) return
if (!up && history.pointer == 0) return
var doc = view.state.doc
var lineno = doc.lines
var line = doc.line(lineno).text.slice(prompt_len)
// capture current (see history class for note on soft persistence)
if (history.pointer == 0) history.current_line = line
else history.commands[history.commands.length - history.pointer] = line
// move
if (up) history.pointer++
else history.pointer--
// at current, use our buffer
if (history.pointer == 0) {
//doc.replaceRange( history.current_line, { line: lineno, ch: prompt_len }, {line: lineno, ch: prompt_len + line.length }, "history");
view.dispatch({
changes: {
from: posToOffset(doc, { line: lineno, ch: prompt_len }),
to: posToOffset(doc, { line: lineno, ch: prompt_len + line.length }),
insert: String(history.current_line), // FIXME
},
})
} else {
var text = history.commands[history.commands.length - history.pointer]
// FIXME
doc.replaceRange(
text,
{ line: lineno, ch: prompt_len },
{ line: lineno, ch: prompt_len + line.length },
"history"
)
}
var linelen = view.state.doc.line(lineno).text.length
// after changing the text the caret should be at the end of the line
// (and the line should be in view)
view.scrollIntoView({ line: lineno, ch: linelen })
view.state.doc.setSelection({ line: lineno, ch: linelen })
}
/**
* set prompt with optional class
*/
function set_prompt(text, prompt_class, is_continuation) {
if (typeof prompt_class === "undefined") prompt_class = DEFAULT_PROMPT_CLASS
if (typeof text === "undefined") {
if (instance.opts) prompt_text = instance.opts.default_prompt
else text = "? "
}
prompt_text = text
console.log("set_prompt: cm", view)
var doc = view.state.doc
var lineno = doc.lines
console.log("set_prompt: doc.lines", doc.lines)
console.log(
"set_prompt: cm.state.doc.line(doc.lines)",
view.state.doc.line(doc.lines)
)
var lastline = view.state.doc.line(lineno).text
if (!is_continuation) block_reset[lineno] = 1
/*
const docLength = doc.length;
view.dispatch({changes: {
//from: posToOffset(doc, { line: lineno, ch: 0 }),
from: docLength,
to: undefined,
insert: "\n",
// TODO class prompt?
}})
//doc.setCursor({ line: lineno+1, ch: 0 });
//view.dispatch({selection: {anchor: posToOffset(doc, { line: lineno, ch: 0 })}})
// doc.length is not-yet updated at this point
// so we use docLength + 1
view.dispatch({selection: {anchor: docLength + 1}})
*/
prompt_len = lastline.length + prompt_text.length
console.log(`set_prompt: lastline=${lastline} prompt_text=${prompt_text}`)
//doc.replaceRange( prompt_text, { line: lineno, ch: lastline.length }, undefined, "prompt" );
view.dispatch({
changes: {
from: posToOffset(doc, { line: lineno, ch: lastline.length }),
to: undefined,
//insert: prompt_text,
insert: prompt_text,
},
})
/* FIXME
if( prompt_class ){
doc.markText( { line: lineno, ch: lastline.length }, { line: lineno, ch: prompt_len }, {
className: prompt_class
});
}
*/
if (prompt_class) {
// https://codemirror.net/docs/migration/#marked-text
const strikeMark = Decoration.mark({
attributes: {
//style: "text-decoration: line-through",
className: prompt_class,
},
})
false &&
console.dir([
`addMarks: prompt_class = ${prompt_class}`,
{ line: lineno, ch: lastline.length },
{ line: lineno, ch: prompt_len },
])
view.dispatch({
effects: addMarks.of([
strikeMark.range(
posToOffset(doc, { line: lineno, ch: lastline.length }),
posToOffset(doc, { line: lineno, ch: prompt_len })
),
]),
})
}
/* FIXME
doc.setSelection({ line: lineno, ch: prompt_len });
cm.scrollIntoView({line: lineno, ch: prompt_len });
*/
}
/**
* external function to set a prompt. this is intended to be used with
* a delayed startup, where there may be text echoed to the screen (and
* hence we need an initialized console) before we know what the correct
* prompt is.
*/
this.prompt = function (text, className, is_continuation) {
set_prompt(text, className, is_continuation)
}
/**
* for external client that wants to execute a block of code with
* side effects -- as if the user had typed it in.
*/
this.execute_block = function (code) {
let lines = code.split(/\n/g)
paste_buffer = paste_buffer.concat(lines)
exec_line(view)
}
/**
* execute the current line. this happens on enter as
* well as on paste (in the case of paste, it might
* get called multiple times -- once for each line in
* the paste).
*/
function exec_line(view, cancel) {
if (state === EXEC_STATE.EXEC) {
return
}
var doc = view.state.doc
var lineno = doc.lines
var line = doc.line(lineno)
console.log("line", line)
// TODO what is this?
//doc.replaceRange( "\n", { line: lineno+1, ch: 0 }, undefined, "prompt");
//var pos = doc.line(doc.lines).from;
// insert newline at end of document
const docLength = doc.length
view.dispatch({
changes: {
//from: posToOffset(doc, { line: lineno, ch: 0 }),
from: docLength,
to: undefined,
insert: "\n",
// TODO class prompt?
},
})
//doc.setCursor({ line: lineno+1, ch: 0 });
//view.dispatch({selection: {anchor: posToOffset(doc, { line: lineno, ch: 0 })}})
// doc.length is not-yet updated at this point
// so we use docLength + 1
//view.dispatch({selection: {anchor: docLength + 1}})
state = EXEC_STATE.EXEC
var command
if (cancel) {
command = ""
command_buffer = [command]
} else {
command = line.text.slice(prompt_len)
command_buffer.push(command)
}
// you can exec an empty line, but we don't put it into history.
// the container can just do nothing on an empty command, if it
// wants to, but it might want to know about it.
if (command.trim().length > 0) {
history.push(command)
history.save() // this is perhaps unecessarily aggressive
}
// this automatically resets the pointer (NOT windows style)
history.reset_pointer()
if (instance.opts.exec_function) {
// turn on event caching. if we're being called
// from a paste block, it might already be in place
// so don't destroy it.
if (!event_cache) event_cache = []
console.log("command_buffer", command_buffer)
instance.opts.exec_function.call(
this,
command_buffer,
// callback
function handleResult(result) {
//console.log(`handleResult: result=${JSON.stringify(result)}`)
// handleResult: result={"parsestatus":"OK"}
// UPDATE: new style of return where the command processor
// handles the multiline-buffer (specifically for R's debugger).
// in that case, always clear command buffer and accept the prompt
// from the callback.
state = EXEC_STATE.EDIT
if (result && result.prompt) {
command_buffer = []
set_prompt(
result.prompt || instance.opts.initial_prompt,
result.prompt_class,
result.continuation
)
} else {
var parseStatus = result
? result.parsestatus || PARSE_STATUS.OK