This repository has been archived by the owner on Mar 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17.4k
/
Copy pathtext-editor.js
4911 lines (4311 loc) · 185 KB
/
text-editor.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
const _ = require('underscore-plus')
const path = require('path')
const fs = require('fs-plus')
const Grim = require('grim')
const dedent = require('dedent')
const {CompositeDisposable, Disposable, Emitter} = require('event-kit')
const TextBuffer = require('text-buffer')
const {Point, Range} = TextBuffer
const DecorationManager = require('./decoration-manager')
const Cursor = require('./cursor')
const Selection = require('./selection')
const NullGrammar = require('./null-grammar')
const TextMateLanguageMode = require('./text-mate-language-mode')
const ScopeDescriptor = require('./scope-descriptor')
const TextMateScopeSelector = require('first-mate').ScopeSelector
const GutterContainer = require('./gutter-container')
let TextEditorComponent = null
let TextEditorElement = null
const {isDoubleWidthCharacter, isHalfWidthCharacter, isKoreanCharacter, isWrapBoundary} = require('./text-utils')
const SERIALIZATION_VERSION = 1
const NON_WHITESPACE_REGEXP = /\S/
const ZERO_WIDTH_NBSP = '\ufeff'
let nextId = 0
const DEFAULT_NON_WORD_CHARACTERS = "/\\()\"':,.;<>~!@#$%^&*|+=[]{}`?-…"
// Essential: This class represents all essential editing state for a single
// {TextBuffer}, including cursor and selection positions, folds, and soft wraps.
// If you're manipulating the state of an editor, use this class.
//
// A single {TextBuffer} can belong to multiple editors. For example, if the
// same file is open in two different panes, Atom creates a separate editor for
// each pane. If the buffer is manipulated the changes are reflected in both
// editors, but each maintains its own cursor position, folded lines, etc.
//
// ## Accessing TextEditor Instances
//
// The easiest way to get hold of `TextEditor` objects is by registering a callback
// with `::observeTextEditors` on the `atom.workspace` global. Your callback will
// then be called with all current editor instances and also when any editor is
// created in the future.
//
// ```js
// atom.workspace.observeTextEditors(editor => {
// editor.insertText('Hello World')
// })
// ```
//
// ## Buffer vs. Screen Coordinates
//
// Because editors support folds and soft-wrapping, the lines on screen don't
// always match the lines in the buffer. For example, a long line that soft wraps
// twice renders as three lines on screen, but only represents one line in the
// buffer. Similarly, if rows 5-10 are folded, then row 6 on screen corresponds
// to row 11 in the buffer.
//
// Your choice of coordinates systems will depend on what you're trying to
// achieve. For example, if you're writing a command that jumps the cursor up or
// down by 10 lines, you'll want to use screen coordinates because the user
// probably wants to skip lines *on screen*. However, if you're writing a package
// that jumps between method definitions, you'll want to work in buffer
// coordinates.
//
// **When in doubt, just default to buffer coordinates**, then experiment with
// soft wraps and folds to ensure your code interacts with them correctly.
module.exports =
class TextEditor {
static setClipboard (clipboard) {
this.clipboard = clipboard
}
static setScheduler (scheduler) {
if (TextEditorComponent == null) { TextEditorComponent = require('./text-editor-component') }
return TextEditorComponent.setScheduler(scheduler)
}
static didUpdateStyles () {
if (TextEditorComponent == null) { TextEditorComponent = require('./text-editor-component') }
return TextEditorComponent.didUpdateStyles()
}
static didUpdateScrollbarStyles () {
if (TextEditorComponent == null) { TextEditorComponent = require('./text-editor-component') }
return TextEditorComponent.didUpdateScrollbarStyles()
}
static viewForItem (item) { return item.element || item }
static deserialize (state, atomEnvironment) {
if (state.version !== SERIALIZATION_VERSION) return null
let bufferId = state.tokenizedBuffer
? state.tokenizedBuffer.bufferId
: state.bufferId
try {
state.buffer = atomEnvironment.project.bufferForIdSync(bufferId)
if (!state.buffer) return null
} catch (error) {
if (error.syscall === 'read') {
return // Error reading the file, don't deserialize an editor for it
} else {
throw error
}
}
state.assert = atomEnvironment.assert.bind(atomEnvironment)
// Semantics of the readOnly flag have changed since its introduction.
// Only respect readOnly2, which has been set with the current readOnly semantics.
delete state.readOnly
state.readOnly = state.readOnly2
delete state.readOnly2
const editor = new TextEditor(state)
if (state.registered) {
const disposable = atomEnvironment.textEditors.add(editor)
editor.onDidDestroy(() => disposable.dispose())
}
return editor
}
constructor (params = {}) {
if (this.constructor.clipboard == null) {
throw new Error('Must call TextEditor.setClipboard at least once before creating TextEditor instances')
}
this.id = params.id != null ? params.id : nextId++
if (this.id >= nextId) {
// Ensure that new editors get unique ids:
nextId = this.id + 1
}
this.initialScrollTopRow = params.initialScrollTopRow
this.initialScrollLeftColumn = params.initialScrollLeftColumn
this.decorationManager = params.decorationManager
this.selectionsMarkerLayer = params.selectionsMarkerLayer
this.mini = (params.mini != null) ? params.mini : false
this.keyboardInputEnabled = (params.keyboardInputEnabled != null) ? params.keyboardInputEnabled : true
this.readOnly = (params.readOnly != null) ? params.readOnly : false
this.placeholderText = params.placeholderText
this.showLineNumbers = params.showLineNumbers
this.assert = params.assert || (condition => condition)
this.showInvisibles = (params.showInvisibles != null) ? params.showInvisibles : true
this.autoHeight = params.autoHeight
this.autoWidth = params.autoWidth
this.scrollPastEnd = (params.scrollPastEnd != null) ? params.scrollPastEnd : false
this.scrollSensitivity = (params.scrollSensitivity != null) ? params.scrollSensitivity : 40
this.editorWidthInChars = params.editorWidthInChars
this.invisibles = params.invisibles
this.showIndentGuide = params.showIndentGuide
this.softWrapped = params.softWrapped
this.softWrapAtPreferredLineLength = params.softWrapAtPreferredLineLength
this.preferredLineLength = params.preferredLineLength
this.showCursorOnSelection = (params.showCursorOnSelection != null) ? params.showCursorOnSelection : true
this.maxScreenLineLength = params.maxScreenLineLength
this.softTabs = (params.softTabs != null) ? params.softTabs : true
this.autoIndent = (params.autoIndent != null) ? params.autoIndent : true
this.autoIndentOnPaste = (params.autoIndentOnPaste != null) ? params.autoIndentOnPaste : true
this.undoGroupingInterval = (params.undoGroupingInterval != null) ? params.undoGroupingInterval : 300
this.softWrapped = (params.softWrapped != null) ? params.softWrapped : false
this.softWrapAtPreferredLineLength = (params.softWrapAtPreferredLineLength != null) ? params.softWrapAtPreferredLineLength : false
this.preferredLineLength = (params.preferredLineLength != null) ? params.preferredLineLength : 80
this.maxScreenLineLength = (params.maxScreenLineLength != null) ? params.maxScreenLineLength : 500
this.showLineNumbers = (params.showLineNumbers != null) ? params.showLineNumbers : true
const {tabLength = 2} = params
this.alive = true
this.doBackgroundWork = this.doBackgroundWork.bind(this)
this.serializationVersion = 1
this.suppressSelectionMerging = false
this.selectionFlashDuration = 500
this.gutterContainer = null
this.verticalScrollMargin = 2
this.horizontalScrollMargin = 6
this.lineHeightInPixels = null
this.defaultCharWidth = null
this.height = null
this.width = null
this.registered = false
this.atomicSoftTabs = true
this.emitter = new Emitter()
this.disposables = new CompositeDisposable()
this.cursors = []
this.cursorsByMarkerId = new Map()
this.selections = []
this.hasTerminatedPendingState = false
if (params.buffer) {
this.buffer = params.buffer
} else {
this.buffer = new TextBuffer({
shouldDestroyOnFileDelete () { return atom.config.get('core.closeDeletedFileTabs') }
})
this.buffer.setLanguageMode(new TextMateLanguageMode({buffer: this.buffer, config: atom.config}))
}
const languageMode = this.buffer.getLanguageMode()
this.languageModeSubscription = languageMode.onDidTokenize && languageMode.onDidTokenize(() => {
this.emitter.emit('did-tokenize')
})
if (this.languageModeSubscription) this.disposables.add(this.languageModeSubscription)
if (params.displayLayer) {
this.displayLayer = params.displayLayer
} else {
const displayLayerParams = {
invisibles: this.getInvisibles(),
softWrapColumn: this.getSoftWrapColumn(),
showIndentGuides: this.doesShowIndentGuide(),
atomicSoftTabs: params.atomicSoftTabs != null ? params.atomicSoftTabs : true,
tabLength,
ratioForCharacter: this.ratioForCharacter.bind(this),
isWrapBoundary,
foldCharacter: ZERO_WIDTH_NBSP,
softWrapHangingIndent: params.softWrapHangingIndentLength != null ? params.softWrapHangingIndentLength : 0
}
this.displayLayer = this.buffer.getDisplayLayer(params.displayLayerId)
if (this.displayLayer) {
this.displayLayer.reset(displayLayerParams)
this.selectionsMarkerLayer = this.displayLayer.getMarkerLayer(params.selectionsMarkerLayerId)
} else {
this.displayLayer = this.buffer.addDisplayLayer(displayLayerParams)
}
}
this.backgroundWorkHandle = requestIdleCallback(this.doBackgroundWork)
this.disposables.add(new Disposable(() => {
if (this.backgroundWorkHandle != null) return cancelIdleCallback(this.backgroundWorkHandle)
}))
this.defaultMarkerLayer = this.displayLayer.addMarkerLayer()
if (!this.selectionsMarkerLayer) {
this.selectionsMarkerLayer = this.addMarkerLayer({maintainHistory: true, persistent: true, role: 'selections'})
}
this.decorationManager = new DecorationManager(this)
this.decorateMarkerLayer(this.selectionsMarkerLayer, {type: 'cursor'})
if (!this.isMini()) this.decorateCursorLine()
this.decorateMarkerLayer(this.displayLayer.foldsMarkerLayer, {type: 'line-number', class: 'folded'})
for (let marker of this.selectionsMarkerLayer.getMarkers()) {
this.addSelection(marker)
}
this.subscribeToBuffer()
this.subscribeToDisplayLayer()
if (this.cursors.length === 0 && !params.suppressCursorCreation) {
const initialLine = Math.max(parseInt(params.initialLine) || 0, 0)
const initialColumn = Math.max(parseInt(params.initialColumn) || 0, 0)
this.addCursorAtBufferPosition([initialLine, initialColumn])
}
this.gutterContainer = new GutterContainer(this)
this.lineNumberGutter = this.gutterContainer.addGutter({
name: 'line-number',
type: 'line-number',
priority: 0,
visible: params.lineNumberGutterVisible
})
}
get element () {
return this.getElement()
}
get editorElement () {
Grim.deprecate(dedent`\
\`TextEditor.prototype.editorElement\` has always been private, but now
it is gone. Reading the \`editorElement\` property still returns a
reference to the editor element but this field will be removed in a
later version of Atom, so we recommend using the \`element\` property instead.\
`)
return this.getElement()
}
get displayBuffer () {
Grim.deprecate(dedent`\
\`TextEditor.prototype.displayBuffer\` has always been private, but now
it is gone. Reading the \`displayBuffer\` property now returns a reference
to the containing \`TextEditor\`, which now provides *some* of the API of
the defunct \`DisplayBuffer\` class.\
`)
return this
}
get languageMode () { return this.buffer.getLanguageMode() }
get tokenizedBuffer () { return this.buffer.getLanguageMode() }
get rowsPerPage () {
return this.getRowsPerPage()
}
decorateCursorLine () {
this.cursorLineDecorations = [
this.decorateMarkerLayer(this.selectionsMarkerLayer, {type: 'line', class: 'cursor-line', onlyEmpty: true}),
this.decorateMarkerLayer(this.selectionsMarkerLayer, {type: 'line-number', class: 'cursor-line'}),
this.decorateMarkerLayer(this.selectionsMarkerLayer, {type: 'line-number', class: 'cursor-line-no-selection', onlyHead: true, onlyEmpty: true})
]
}
doBackgroundWork (deadline) {
const previousLongestRow = this.getApproximateLongestScreenRow()
if (this.displayLayer.doBackgroundWork(deadline)) {
this.backgroundWorkHandle = requestIdleCallback(this.doBackgroundWork)
} else {
this.backgroundWorkHandle = null
}
if (this.component && this.getApproximateLongestScreenRow() !== previousLongestRow) {
this.component.scheduleUpdate()
}
}
update (params) {
const displayLayerParams = {}
for (let param of Object.keys(params)) {
const value = params[param]
switch (param) {
case 'autoIndent':
this.autoIndent = value
break
case 'autoIndentOnPaste':
this.autoIndentOnPaste = value
break
case 'undoGroupingInterval':
this.undoGroupingInterval = value
break
case 'scrollSensitivity':
this.scrollSensitivity = value
break
case 'encoding':
this.buffer.setEncoding(value)
break
case 'softTabs':
if (value !== this.softTabs) {
this.softTabs = value
}
break
case 'atomicSoftTabs':
if (value !== this.displayLayer.atomicSoftTabs) {
displayLayerParams.atomicSoftTabs = value
}
break
case 'tabLength':
if (value > 0 && value !== this.displayLayer.tabLength) {
displayLayerParams.tabLength = value
}
break
case 'softWrapped':
if (value !== this.softWrapped) {
this.softWrapped = value
displayLayerParams.softWrapColumn = this.getSoftWrapColumn()
this.emitter.emit('did-change-soft-wrapped', this.isSoftWrapped())
}
break
case 'softWrapHangingIndentLength':
if (value !== this.displayLayer.softWrapHangingIndent) {
displayLayerParams.softWrapHangingIndent = value
}
break
case 'softWrapAtPreferredLineLength':
if (value !== this.softWrapAtPreferredLineLength) {
this.softWrapAtPreferredLineLength = value
displayLayerParams.softWrapColumn = this.getSoftWrapColumn()
}
break
case 'preferredLineLength':
if (value !== this.preferredLineLength) {
this.preferredLineLength = value
displayLayerParams.softWrapColumn = this.getSoftWrapColumn()
}
break
case 'maxScreenLineLength':
if (value !== this.maxScreenLineLength) {
this.maxScreenLineLength = value
displayLayerParams.softWrapColumn = this.getSoftWrapColumn()
}
break
case 'mini':
if (value !== this.mini) {
this.mini = value
this.emitter.emit('did-change-mini', value)
displayLayerParams.invisibles = this.getInvisibles()
displayLayerParams.softWrapColumn = this.getSoftWrapColumn()
displayLayerParams.showIndentGuides = this.doesShowIndentGuide()
if (this.mini) {
for (let decoration of this.cursorLineDecorations) { decoration.destroy() }
this.cursorLineDecorations = null
} else {
this.decorateCursorLine()
}
if (this.component != null) {
this.component.scheduleUpdate()
}
}
break
case 'readOnly':
if (value !== this.readOnly) {
this.readOnly = value
if (this.component != null) {
this.component.scheduleUpdate()
}
}
break
case 'keyboardInputEnabled':
if (value !== this.keyboardInputEnabled) {
this.keyboardInputEnabled = value
if (this.component != null) {
this.component.scheduleUpdate()
}
}
break
case 'placeholderText':
if (value !== this.placeholderText) {
this.placeholderText = value
this.emitter.emit('did-change-placeholder-text', value)
}
break
case 'lineNumberGutterVisible':
if (value !== this.lineNumberGutterVisible) {
if (value) {
this.lineNumberGutter.show()
} else {
this.lineNumberGutter.hide()
}
this.emitter.emit('did-change-line-number-gutter-visible', this.lineNumberGutter.isVisible())
}
break
case 'showIndentGuide':
if (value !== this.showIndentGuide) {
this.showIndentGuide = value
displayLayerParams.showIndentGuides = this.doesShowIndentGuide()
}
break
case 'showLineNumbers':
if (value !== this.showLineNumbers) {
this.showLineNumbers = value
if (this.component != null) {
this.component.scheduleUpdate()
}
}
break
case 'showInvisibles':
if (value !== this.showInvisibles) {
this.showInvisibles = value
displayLayerParams.invisibles = this.getInvisibles()
}
break
case 'invisibles':
if (!_.isEqual(value, this.invisibles)) {
this.invisibles = value
displayLayerParams.invisibles = this.getInvisibles()
}
break
case 'editorWidthInChars':
if (value > 0 && value !== this.editorWidthInChars) {
this.editorWidthInChars = value
displayLayerParams.softWrapColumn = this.getSoftWrapColumn()
}
break
case 'width':
if (value !== this.width) {
this.width = value
displayLayerParams.softWrapColumn = this.getSoftWrapColumn()
}
break
case 'scrollPastEnd':
if (value !== this.scrollPastEnd) {
this.scrollPastEnd = value
if (this.component) this.component.scheduleUpdate()
}
break
case 'autoHeight':
if (value !== this.autoHeight) {
this.autoHeight = value
}
break
case 'autoWidth':
if (value !== this.autoWidth) {
this.autoWidth = value
}
break
case 'showCursorOnSelection':
if (value !== this.showCursorOnSelection) {
this.showCursorOnSelection = value
if (this.component) this.component.scheduleUpdate()
}
break
default:
if (param !== 'ref' && param !== 'key') {
throw new TypeError(`Invalid TextEditor parameter: '${param}'`)
}
}
}
this.displayLayer.reset(displayLayerParams)
if (this.component) {
return this.component.getNextUpdatePromise()
} else {
return Promise.resolve()
}
}
scheduleComponentUpdate () {
if (this.component) this.component.scheduleUpdate()
}
serialize () {
return {
deserializer: 'TextEditor',
version: SERIALIZATION_VERSION,
displayLayerId: this.displayLayer.id,
selectionsMarkerLayerId: this.selectionsMarkerLayer.id,
initialScrollTopRow: this.getScrollTopRow(),
initialScrollLeftColumn: this.getScrollLeftColumn(),
tabLength: this.displayLayer.tabLength,
atomicSoftTabs: this.displayLayer.atomicSoftTabs,
softWrapHangingIndentLength: this.displayLayer.softWrapHangingIndent,
id: this.id,
bufferId: this.buffer.id,
softTabs: this.softTabs,
softWrapped: this.softWrapped,
softWrapAtPreferredLineLength: this.softWrapAtPreferredLineLength,
preferredLineLength: this.preferredLineLength,
mini: this.mini,
readOnly2: this.readOnly, // readOnly encompassed both readOnly and keyboardInputEnabled
keyboardInputEnabled: this.keyboardInputEnabled,
editorWidthInChars: this.editorWidthInChars,
width: this.width,
maxScreenLineLength: this.maxScreenLineLength,
registered: this.registered,
invisibles: this.invisibles,
showInvisibles: this.showInvisibles,
showIndentGuide: this.showIndentGuide,
autoHeight: this.autoHeight,
autoWidth: this.autoWidth
}
}
subscribeToBuffer () {
this.buffer.retain()
this.disposables.add(this.buffer.onDidChangeLanguageMode(this.handleLanguageModeChange.bind(this)))
this.disposables.add(this.buffer.onDidChangePath(() => {
this.emitter.emit('did-change-title', this.getTitle())
this.emitter.emit('did-change-path', this.getPath())
}))
this.disposables.add(this.buffer.onDidChangeEncoding(() => {
this.emitter.emit('did-change-encoding', this.getEncoding())
}))
this.disposables.add(this.buffer.onDidDestroy(() => this.destroy()))
this.disposables.add(this.buffer.onDidChangeModified(() => {
if (!this.hasTerminatedPendingState && this.buffer.isModified()) this.terminatePendingState()
}))
}
terminatePendingState () {
if (!this.hasTerminatedPendingState) this.emitter.emit('did-terminate-pending-state')
this.hasTerminatedPendingState = true
}
onDidTerminatePendingState (callback) {
return this.emitter.on('did-terminate-pending-state', callback)
}
subscribeToDisplayLayer () {
this.disposables.add(this.displayLayer.onDidChange(changes => {
this.mergeIntersectingSelections()
if (this.component) this.component.didChangeDisplayLayer(changes)
this.emitter.emit('did-change', changes.map(change => new ChangeEvent(change)))
}))
this.disposables.add(this.displayLayer.onDidReset(() => {
this.mergeIntersectingSelections()
if (this.component) this.component.didResetDisplayLayer()
this.emitter.emit('did-change', {})
}))
this.disposables.add(this.selectionsMarkerLayer.onDidCreateMarker(this.addSelection.bind(this)))
return this.disposables.add(this.selectionsMarkerLayer.onDidUpdate(() => (this.component != null ? this.component.didUpdateSelections() : undefined)))
}
destroy () {
if (!this.alive) return
this.alive = false
this.disposables.dispose()
this.displayLayer.destroy()
for (let selection of this.selections.slice()) {
selection.destroy()
}
this.buffer.release()
this.gutterContainer.destroy()
this.emitter.emit('did-destroy')
this.emitter.clear()
if (this.component) this.component.element.component = null
this.component = null
this.lineNumberGutter.element = null
}
isAlive () { return this.alive }
isDestroyed () { return !this.alive }
/*
Section: Event Subscription
*/
// Essential: Calls your `callback` when the buffer's title has changed.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeTitle (callback) {
return this.emitter.on('did-change-title', callback)
}
// Essential: Calls your `callback` when the buffer's path, and therefore title, has changed.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangePath (callback) {
return this.emitter.on('did-change-path', callback)
}
// Essential: Invoke the given callback synchronously when the content of the
// buffer changes.
//
// Because observers are invoked synchronously, it's important not to perform
// any expensive operations via this method. Consider {::onDidStopChanging} to
// delay expensive operations until after changes stop occurring.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChange (callback) {
return this.emitter.on('did-change', callback)
}
// Essential: Invoke `callback` when the buffer's contents change. It is
// emit asynchronously 300ms after the last buffer change. This is a good place
// to handle changes to the buffer without compromising typing performance.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidStopChanging (callback) {
return this.getBuffer().onDidStopChanging(callback)
}
// Essential: Calls your `callback` when a {Cursor} is moved. If there are
// multiple cursors, your callback will be called for each cursor.
//
// * `callback` {Function}
// * `event` {Object}
// * `oldBufferPosition` {Point}
// * `oldScreenPosition` {Point}
// * `newBufferPosition` {Point}
// * `newScreenPosition` {Point}
// * `textChanged` {Boolean}
// * `cursor` {Cursor} that triggered the event
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeCursorPosition (callback) {
return this.emitter.on('did-change-cursor-position', callback)
}
// Essential: Calls your `callback` when a selection's screen range changes.
//
// * `callback` {Function}
// * `event` {Object}
// * `oldBufferRange` {Range}
// * `oldScreenRange` {Range}
// * `newBufferRange` {Range}
// * `newScreenRange` {Range}
// * `selection` {Selection} that triggered the event
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeSelectionRange (callback) {
return this.emitter.on('did-change-selection-range', callback)
}
// Extended: Calls your `callback` when soft wrap was enabled or disabled.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeSoftWrapped (callback) {
return this.emitter.on('did-change-soft-wrapped', callback)
}
// Extended: Calls your `callback` when the buffer's encoding has changed.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeEncoding (callback) {
return this.emitter.on('did-change-encoding', callback)
}
// Extended: Calls your `callback` when the grammar that interprets and
// colorizes the text has been changed. Immediately calls your callback with
// the current grammar.
//
// * `callback` {Function}
// * `grammar` {Grammar}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeGrammar (callback) {
callback(this.getGrammar())
return this.onDidChangeGrammar(callback)
}
// Extended: Calls your `callback` when the grammar that interprets and
// colorizes the text has been changed.
//
// * `callback` {Function}
// * `grammar` {Grammar}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeGrammar (callback) {
return this.buffer.onDidChangeLanguageMode(() => {
callback(this.buffer.getLanguageMode().grammar)
})
}
// Extended: Calls your `callback` when the result of {::isModified} changes.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeModified (callback) {
return this.getBuffer().onDidChangeModified(callback)
}
// Extended: Calls your `callback` when the buffer's underlying file changes on
// disk at a moment when the result of {::isModified} is true.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidConflict (callback) {
return this.getBuffer().onDidConflict(callback)
}
// Extended: Calls your `callback` before text has been inserted.
//
// * `callback` {Function}
// * `event` event {Object}
// * `text` {String} text to be inserted
// * `cancel` {Function} Call to prevent the text from being inserted
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onWillInsertText (callback) {
return this.emitter.on('will-insert-text', callback)
}
// Extended: Calls your `callback` after text has been inserted.
//
// * `callback` {Function}
// * `event` event {Object}
// * `text` {String} text to be inserted
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidInsertText (callback) {
return this.emitter.on('did-insert-text', callback)
}
// Essential: Invoke the given callback after the buffer is saved to disk.
//
// * `callback` {Function} to be called after the buffer is saved.
// * `event` {Object} with the following keys:
// * `path` The path to which the buffer was saved.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidSave (callback) {
return this.getBuffer().onDidSave(callback)
}
// Essential: Invoke the given callback when the editor is destroyed.
//
// * `callback` {Function} to be called when the editor is destroyed.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidDestroy (callback) {
return this.emitter.once('did-destroy', callback)
}
// Extended: Calls your `callback` when a {Cursor} is added to the editor.
// Immediately calls your callback for each existing cursor.
//
// * `callback` {Function}
// * `cursor` {Cursor} that was added
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeCursors (callback) {
this.getCursors().forEach(callback)
return this.onDidAddCursor(callback)
}
// Extended: Calls your `callback` when a {Cursor} is added to the editor.
//
// * `callback` {Function}
// * `cursor` {Cursor} that was added
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddCursor (callback) {
return this.emitter.on('did-add-cursor', callback)
}
// Extended: Calls your `callback` when a {Cursor} is removed from the editor.
//
// * `callback` {Function}
// * `cursor` {Cursor} that was removed
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidRemoveCursor (callback) {
return this.emitter.on('did-remove-cursor', callback)
}
// Extended: Calls your `callback` when a {Selection} is added to the editor.
// Immediately calls your callback for each existing selection.
//
// * `callback` {Function}
// * `selection` {Selection} that was added
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeSelections (callback) {
this.getSelections().forEach(callback)
return this.onDidAddSelection(callback)
}
// Extended: Calls your `callback` when a {Selection} is added to the editor.
//
// * `callback` {Function}
// * `selection` {Selection} that was added
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddSelection (callback) {
return this.emitter.on('did-add-selection', callback)
}
// Extended: Calls your `callback` when a {Selection} is removed from the editor.
//
// * `callback` {Function}
// * `selection` {Selection} that was removed
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidRemoveSelection (callback) {
return this.emitter.on('did-remove-selection', callback)
}
// Extended: Calls your `callback` with each {Decoration} added to the editor.
// Calls your `callback` immediately for any existing decorations.
//
// * `callback` {Function}
// * `decoration` {Decoration}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeDecorations (callback) {
return this.decorationManager.observeDecorations(callback)
}
// Extended: Calls your `callback` when a {Decoration} is added to the editor.
//
// * `callback` {Function}
// * `decoration` {Decoration} that was added
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddDecoration (callback) {
return this.decorationManager.onDidAddDecoration(callback)
}
// Extended: Calls your `callback` when a {Decoration} is removed from the editor.
//
// * `callback` {Function}
// * `decoration` {Decoration} that was removed
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidRemoveDecoration (callback) {
return this.decorationManager.onDidRemoveDecoration(callback)
}
// Called by DecorationManager when a decoration is added.
didAddDecoration (decoration) {
if (this.component && decoration.isType('block')) {
this.component.addBlockDecoration(decoration)
}
}
// Extended: Calls your `callback` when the placeholder text is changed.
//
// * `callback` {Function}
// * `placeholderText` {String} new text
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangePlaceholderText (callback) {
return this.emitter.on('did-change-placeholder-text', callback)
}
onDidChangeScrollTop (callback) {
Grim.deprecate('This is now a view method. Call TextEditorElement::onDidChangeScrollTop instead.')
return this.getElement().onDidChangeScrollTop(callback)
}
onDidChangeScrollLeft (callback) {
Grim.deprecate('This is now a view method. Call TextEditorElement::onDidChangeScrollLeft instead.')
return this.getElement().onDidChangeScrollLeft(callback)
}
onDidRequestAutoscroll (callback) {
return this.emitter.on('did-request-autoscroll', callback)
}
// TODO Remove once the tabs package no longer uses .on subscriptions
onDidChangeIcon (callback) {
return this.emitter.on('did-change-icon', callback)
}
onDidUpdateDecorations (callback) {
return this.decorationManager.onDidUpdateDecorations(callback)
}
// Essential: Retrieves the current {TextBuffer}.
getBuffer () { return this.buffer }
// Retrieves the current buffer's URI.
getURI () { return this.buffer.getUri() }
// Create an {TextEditor} with its initial state based on this object
copy () {
const displayLayer = this.displayLayer.copy()
const selectionsMarkerLayer = displayLayer.getMarkerLayer(this.buffer.getMarkerLayer(this.selectionsMarkerLayer.id).copy().id)
const softTabs = this.getSoftTabs()
return new TextEditor({
buffer: this.buffer,
selectionsMarkerLayer,
softTabs,
suppressCursorCreation: true,
tabLength: this.getTabLength(),
initialScrollTopRow: this.getScrollTopRow(),
initialScrollLeftColumn: this.getScrollLeftColumn(),
assert: this.assert,
displayLayer,
grammar: this.getGrammar(),
autoWidth: this.autoWidth,
autoHeight: this.autoHeight,
showCursorOnSelection: this.showCursorOnSelection
})
}
// Controls visibility based on the given {Boolean}.
setVisible (visible) {
if (visible) {
const languageMode = this.buffer.getLanguageMode()
if (languageMode.startTokenizing) languageMode.startTokenizing()
}
}
setMini (mini) {
this.update({mini})
}