forked from atom/atom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext-editor.coffee
3705 lines (3127 loc) · 141 KB
/
text-editor.coffee
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
_ = require 'underscore-plus'
path = require 'path'
fs = require 'fs-plus'
Grim = require 'grim'
{CompositeDisposable, Emitter} = require 'event-kit'
{Point, Range} = TextBuffer = require 'text-buffer'
LanguageMode = require './language-mode'
DecorationManager = require './decoration-manager'
TokenizedBuffer = require './tokenized-buffer'
Cursor = require './cursor'
Model = require './model'
Selection = require './selection'
TextMateScopeSelector = require('first-mate').ScopeSelector
GutterContainer = require './gutter-container'
TextEditorElement = require './text-editor-element'
{isDoubleWidthCharacter, isHalfWidthCharacter, isKoreanCharacter, isWrapBoundary} = require './text-utils'
ZERO_WIDTH_NBSP = '\ufeff'
# 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. If you're
# interested in the visual appearance of editors, use {TextEditorElement}
# instead.
#
# 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.
#
# ```coffee
# 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 extends Model
serializationVersion: 1
buffer: null
languageMode: null
cursors: null
selections: null
suppressSelectionMerging: false
selectionFlashDuration: 500
gutterContainer: null
editorElement: null
verticalScrollMargin: 2
horizontalScrollMargin: 6
softWrapped: null
editorWidthInChars: null
lineHeightInPixels: null
defaultCharWidth: null
height: null
width: null
registered: false
atomicSoftTabs: true
invisibles: null
showLineNumbers: true
scrollSensitivity: 40
Object.defineProperty @prototype, "element",
get: -> @getElement()
Object.defineProperty(@prototype, 'displayBuffer', get: ->
Grim.deprecate("""
`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.
""")
this
)
@deserialize: (state, atomEnvironment) ->
# TODO: Return null on version mismatch when 1.8.0 has been out for a while
if state.version isnt @prototype.serializationVersion and state.displayBuffer?
state.tokenizedBuffer = state.displayBuffer.tokenizedBuffer
try
state.tokenizedBuffer = TokenizedBuffer.deserialize(state.tokenizedBuffer, atomEnvironment)
state.tabLength = state.tokenizedBuffer.getTabLength()
catch error
if error.syscall is 'read'
return # Error reading the file, don't deserialize an editor for it
else
throw error
state.buffer = state.tokenizedBuffer.buffer
if state.displayLayer = state.buffer.getDisplayLayer(state.displayLayerId)
state.selectionsMarkerLayer = state.displayLayer.getMarkerLayer(state.selectionsMarkerLayerId)
state.clipboard = atomEnvironment.clipboard
state.assert = atomEnvironment.assert.bind(atomEnvironment)
editor = new this(state)
if state.registered
disposable = atomEnvironment.textEditors.add(editor)
editor.onDidDestroy -> disposable.dispose()
editor
constructor: (params={}) ->
super
{
@softTabs, @firstVisibleScreenRow, @firstVisibleScreenColumn, initialLine, initialColumn, tabLength,
@softWrapped, @decorationManager, @selectionsMarkerLayer, @buffer, suppressCursorCreation,
@mini, @placeholderText, lineNumberGutterVisible, @largeFileMode, @clipboard,
@assert, grammar, @showInvisibles, @autoHeight, @autoWidth, @scrollPastEnd, @editorWidthInChars,
@tokenizedBuffer, @displayLayer, @invisibles, @showIndentGuide,
@softWrapped, @softWrapAtPreferredLineLength, @preferredLineLength
} = params
throw new Error("Must pass a clipboard parameter when constructing TextEditors") unless @clipboard?
@assert ?= (condition) -> condition
@firstVisibleScreenRow ?= 0
@firstVisibleScreenColumn ?= 0
@emitter = new Emitter
@disposables = new CompositeDisposable
@cursors = []
@cursorsByMarkerId = new Map
@selections = []
@hasTerminatedPendingState = false
@mini ?= false
@scrollPastEnd ?= true
@showInvisibles ?= true
@softTabs ?= true
tabLength ?= 2
@autoIndent ?= true
@autoIndentOnPaste ?= true
@undoGroupingInterval ?= 300
@nonWordCharacters ?= "/\\()\"':,.;<>~!@#$%^&*|+=[]{}`?-…"
@softWrapped ?= false
@softWrapAtPreferredLineLength ?= false
@preferredLineLength ?= 80
@buffer ?= new TextBuffer
@tokenizedBuffer ?= new TokenizedBuffer({
grammar, tabLength, @buffer, @largeFileMode, @assert
})
displayLayerParams = {
invisibles: @getInvisibles(),
softWrapColumn: @getSoftWrapColumn(),
showIndentGuides: not @isMini() and @doesShowIndentGuide(),
atomicSoftTabs: params.atomicSoftTabs ? true,
tabLength: tabLength,
ratioForCharacter: @ratioForCharacter.bind(this),
isWrapBoundary: isWrapBoundary,
foldCharacter: ZERO_WIDTH_NBSP,
softWrapHangingIndent: params.softWrapHangingIndentLength ? 0
}
if @displayLayer?
@displayLayer.reset(displayLayerParams)
else
@displayLayer = @buffer.addDisplayLayer(displayLayerParams)
@displayLayer.setTextDecorationLayer(@tokenizedBuffer)
@defaultMarkerLayer = @displayLayer.addMarkerLayer()
@selectionsMarkerLayer ?= @addMarkerLayer(maintainHistory: true, persistent: true)
@decorationManager = new DecorationManager(@displayLayer, @defaultMarkerLayer)
@decorateMarkerLayer(@displayLayer.foldsMarkerLayer, {type: 'line-number', class: 'folded'})
for marker in @selectionsMarkerLayer.getMarkers()
@addSelection(marker)
@subscribeToBuffer()
@subscribeToDisplayLayer()
if @cursors.length is 0 and not suppressCursorCreation
initialLine = Math.max(parseInt(initialLine) or 0, 0)
initialColumn = Math.max(parseInt(initialColumn) or 0, 0)
@addCursorAtBufferPosition([initialLine, initialColumn])
@languageMode = new LanguageMode(this)
@gutterContainer = new GutterContainer(this)
@lineNumberGutter = @gutterContainer.addGutter
name: 'line-number'
priority: 0
visible: lineNumberGutterVisible
update: (params) ->
displayLayerParams = {}
for param in Object.keys(params)
value = params[param]
switch param
when 'autoIndent'
@autoIndent = value
when 'autoIndentOnPaste'
@autoIndentOnPaste = value
when 'undoGroupingInterval'
@undoGroupingInterval = value
when 'nonWordCharacters'
@nonWordCharacters = value
when 'scrollSensitivity'
@scrollSensitivity = value
when 'encoding'
@buffer.setEncoding(value)
when 'softTabs'
if value isnt @softTabs
@softTabs = value
when 'atomicSoftTabs'
if value isnt @displayLayer.atomicSoftTabs
displayLayerParams.atomicSoftTabs = value
when 'tabLength'
if value? and value isnt @tokenizedBuffer.getTabLength()
@tokenizedBuffer.setTabLength(value)
displayLayerParams.tabLength = value
when 'softWrapped'
if value isnt @softWrapped
@softWrapped = value
displayLayerParams.softWrapColumn = @getSoftWrapColumn()
@emitter.emit 'did-change-soft-wrapped', @isSoftWrapped()
when 'softWrapHangingIndentLength'
if value isnt @displayLayer.softWrapHangingIndent
displayLayerParams.softWrapHangingIndent = value
when 'softWrapAtPreferredLineLength'
if value isnt @softWrapAtPreferredLineLength
@softWrapAtPreferredLineLength = value
displayLayerParams.softWrapColumn = @getSoftWrapColumn() if @isSoftWrapped()
when 'preferredLineLength'
if value isnt @preferredLineLength
@preferredLineLength = value
displayLayerParams.softWrapColumn = @getSoftWrapColumn() if @isSoftWrapped()
when 'mini'
if value isnt @mini
@mini = value
@emitter.emit 'did-change-mini', value
displayLayerParams.invisibles = @getInvisibles()
displayLayerParams.showIndentGuides = @doesShowIndentGuide()
when 'placeholderText'
if value isnt @placeholderText
@placeholderText = value
@emitter.emit 'did-change-placeholder-text', value
when 'lineNumberGutterVisible'
if value isnt @lineNumberGutterVisible
if value
@lineNumberGutter.show()
else
@lineNumberGutter.hide()
@emitter.emit 'did-change-line-number-gutter-visible', @lineNumberGutter.isVisible()
when 'showIndentGuide'
if value isnt @showIndentGuide
@showIndentGuide = value
displayLayerParams.showIndentGuides = @doesShowIndentGuide()
when 'showLineNumbers'
if value isnt @showLineNumbers
@showLineNumbers = value
@presenter?.didChangeShowLineNumbers()
when 'showInvisibles'
if value isnt @showInvisibles
@showInvisibles = value
displayLayerParams.invisibles = @getInvisibles()
when 'invisibles'
if not _.isEqual(value, @invisibles)
@invisibles = value
displayLayerParams.invisibles = @getInvisibles()
when 'editorWidthInChars'
if value > 0 and value isnt @editorWidthInChars
@editorWidthInChars = value
displayLayerParams.softWrapColumn = @getSoftWrapColumn() if @isSoftWrapped()
when 'width'
if value isnt @width
@width = value
displayLayerParams.softWrapColumn = @getSoftWrapColumn() if @isSoftWrapped()
when 'scrollPastEnd'
if value isnt @scrollPastEnd
@scrollPastEnd = value
@presenter?.didChangeScrollPastEnd()
when 'autoHeight'
if value isnt @autoHeight
@autoHeight = value
@presenter?.setAutoHeight(@autoHeight)
when 'autoWidth'
if value isnt @autoWidth
@autoWidth = value
@presenter?.didChangeAutoWidth()
else
throw new TypeError("Invalid TextEditor parameter: '#{param}'")
if Object.keys(displayLayerParams).length > 0
@displayLayer.reset(displayLayerParams)
if @editorElement?
@editorElement.views.getNextUpdatePromise()
else
Promise.resolve()
serialize: ->
tokenizedBufferState = @tokenizedBuffer.serialize()
{
deserializer: 'TextEditor'
version: @serializationVersion
# TODO: Remove this forward-compatible fallback once 1.8 reaches stable.
displayBuffer: {tokenizedBuffer: tokenizedBufferState}
tokenizedBuffer: tokenizedBufferState
displayLayerId: @displayLayer.id
selectionsMarkerLayerId: @selectionsMarkerLayer.id
firstVisibleScreenRow: @getFirstVisibleScreenRow()
firstVisibleScreenColumn: @getFirstVisibleScreenColumn()
atomicSoftTabs: @displayLayer.atomicSoftTabs
softWrapHangingIndentLength: @displayLayer.softWrapHangingIndent
@id, @softTabs, @softWrapped, @softWrapAtPreferredLineLength,
@preferredLineLength, @mini, @editorWidthInChars, @width, @largeFileMode,
@registered, @invisibles, @showInvisibles, @showIndentGuide, @autoHeight, @autoWidth
}
subscribeToBuffer: ->
@buffer.retain()
@disposables.add @buffer.onDidChangePath =>
@emitter.emit 'did-change-title', @getTitle()
@emitter.emit 'did-change-path', @getPath()
@disposables.add @buffer.onDidChangeEncoding =>
@emitter.emit 'did-change-encoding', @getEncoding()
@disposables.add @buffer.onDidDestroy => @destroy()
@disposables.add @buffer.onDidChangeModified =>
@terminatePendingState() if not @hasTerminatedPendingState and @buffer.isModified()
@preserveCursorPositionOnBufferReload()
terminatePendingState: ->
@emitter.emit 'did-terminate-pending-state' if not @hasTerminatedPendingState
@hasTerminatedPendingState = true
onDidTerminatePendingState: (callback) ->
@emitter.on 'did-terminate-pending-state', callback
subscribeToDisplayLayer: ->
@disposables.add @selectionsMarkerLayer.onDidCreateMarker @addSelection.bind(this)
@disposables.add @tokenizedBuffer.onDidChangeGrammar @handleGrammarChange.bind(this)
@disposables.add @displayLayer.onDidChangeSync (e) =>
@mergeIntersectingSelections()
@emitter.emit 'did-change', e
destroyed: ->
@disposables.dispose()
@displayLayer.destroy()
@disposables.dispose()
@tokenizedBuffer.destroy()
selection.destroy() for selection in @selections.slice()
@selectionsMarkerLayer.destroy()
@buffer.release()
@languageMode.destroy()
@gutterContainer.destroy()
@emitter.emit 'did-destroy'
###
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) ->
@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) ->
@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) ->
@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) ->
@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) ->
@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) ->
@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) ->
@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) ->
@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(@getGrammar())
@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) ->
@emitter.on 'did-change-grammar', callback
# 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) ->
@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) ->
@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) ->
@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) ->
@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) ->
@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) ->
@emitter.on '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) ->
callback(cursor) for cursor in @getCursors()
@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) ->
@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) ->
@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) ->
callback(selection) for selection in @getSelections()
@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) ->
@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) ->
@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) ->
@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) ->
@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) ->
@decorationManager.onDidRemoveDecoration(callback)
# 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) ->
@emitter.on 'did-change-placeholder-text', callback
onDidChangeFirstVisibleScreenRow: (callback, fromView) ->
@emitter.on 'did-change-first-visible-screen-row', callback
onDidChangeScrollTop: (callback) ->
Grim.deprecate("This is now a view method. Call TextEditorElement::onDidChangeScrollTop instead.")
@getElement().onDidChangeScrollTop(callback)
onDidChangeScrollLeft: (callback) ->
Grim.deprecate("This is now a view method. Call TextEditorElement::onDidChangeScrollLeft instead.")
@getElement().onDidChangeScrollLeft(callback)
onDidRequestAutoscroll: (callback) ->
@emitter.on 'did-request-autoscroll', callback
# TODO Remove once the tabs package no longer uses .on subscriptions
onDidChangeIcon: (callback) ->
@emitter.on 'did-change-icon', callback
onDidUpdateDecorations: (callback) ->
@decorationManager.onDidUpdateDecorations(callback)
# Essential: Retrieves the current {TextBuffer}.
getBuffer: -> @buffer
# Retrieves the current buffer's URI.
getURI: -> @buffer.getUri()
# Create an {TextEditor} with its initial state based on this object
copy: ->
displayLayer = @displayLayer.copy()
selectionsMarkerLayer = displayLayer.getMarkerLayer(@buffer.getMarkerLayer(@selectionsMarkerLayer.id).copy().id)
softTabs = @getSoftTabs()
new TextEditor({
@buffer, selectionsMarkerLayer, softTabs,
suppressCursorCreation: true,
tabLength: @tokenizedBuffer.getTabLength(),
@firstVisibleScreenRow, @firstVisibleScreenColumn,
@clipboard, @assert, displayLayer, grammar: @getGrammar(),
@autoWidth, @autoHeight
})
# Controls visibility based on the given {Boolean}.
setVisible: (visible) -> @tokenizedBuffer.setVisible(visible)
setMini: (mini) ->
@update({mini})
@mini
isMini: -> @mini
setUpdatedSynchronously: (updatedSynchronously) ->
@decorationManager.setUpdatedSynchronously(updatedSynchronously)
onDidChangeMini: (callback) ->
@emitter.on 'did-change-mini', callback
setLineNumberGutterVisible: (lineNumberGutterVisible) -> @update({lineNumberGutterVisible})
isLineNumberGutterVisible: -> @lineNumberGutter.isVisible()
onDidChangeLineNumberGutterVisible: (callback) ->
@emitter.on 'did-change-line-number-gutter-visible', callback
# Essential: Calls your `callback` when a {Gutter} is added to the editor.
# Immediately calls your callback for each existing gutter.
#
# * `callback` {Function}
# * `gutter` {Gutter} that currently exists/was added.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeGutters: (callback) ->
@gutterContainer.observeGutters callback
# Essential: Calls your `callback` when a {Gutter} is added to the editor.
#
# * `callback` {Function}
# * `gutter` {Gutter} that was added.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddGutter: (callback) ->
@gutterContainer.onDidAddGutter callback
# Essential: Calls your `callback` when a {Gutter} is removed from the editor.
#
# * `callback` {Function}
# * `name` The name of the {Gutter} that was removed.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidRemoveGutter: (callback) ->
@gutterContainer.onDidRemoveGutter callback
# Set the number of characters that can be displayed horizontally in the
# editor.
#
# * `editorWidthInChars` A {Number} representing the width of the
# {TextEditorElement} in characters.
setEditorWidthInChars: (editorWidthInChars) -> @update({editorWidthInChars})
# Returns the editor width in characters.
getEditorWidthInChars: ->
if @width? and @defaultCharWidth > 0
Math.max(0, Math.floor(@width / @defaultCharWidth))
else
@editorWidthInChars
###
Section: File Details
###
# Essential: Get the editor's title for display in other parts of the
# UI such as the tabs.
#
# If the editor's buffer is saved, its title is the file name. If it is
# unsaved, its title is "untitled".
#
# Returns a {String}.
getTitle: ->
@getFileName() ? 'untitled'
# Essential: Get unique title for display in other parts of the UI, such as
# the window title.
#
# If the editor's buffer is unsaved, its title is "untitled"
# If the editor's buffer is saved, its unique title is formatted as one
# of the following,
# * "<filename>" when it is the only editing buffer with this file name.
# * "<filename> — <unique-dir-prefix>" when other buffers have this file name.
#
# Returns a {String}
getLongTitle: ->
if @getPath()
fileName = @getFileName()
allPathSegments = []
for textEditor in atom.workspace.getTextEditors() when textEditor isnt this
if textEditor.getFileName() is fileName
directoryPath = fs.tildify(textEditor.getDirectoryPath())
allPathSegments.push(directoryPath.split(path.sep))
if allPathSegments.length is 0
return fileName
ourPathSegments = fs.tildify(@getDirectoryPath()).split(path.sep)
allPathSegments.push ourPathSegments
loop
firstSegment = ourPathSegments[0]
commonBase = _.all(allPathSegments, (pathSegments) -> pathSegments.length > 1 and pathSegments[0] is firstSegment)
if commonBase
pathSegments.shift() for pathSegments in allPathSegments
else
break
"#{fileName} \u2014 #{path.join(pathSegments...)}"
else
'untitled'
# Essential: Returns the {String} path of this editor's text buffer.
getPath: -> @buffer.getPath()
getFileName: ->
if fullPath = @getPath()
path.basename(fullPath)
else
null
getDirectoryPath: ->
if fullPath = @getPath()
path.dirname(fullPath)
else
null
# Extended: Returns the {String} character set encoding of this editor's text
# buffer.
getEncoding: -> @buffer.getEncoding()
# Extended: Set the character set encoding to use in this editor's text
# buffer.
#
# * `encoding` The {String} character set encoding name such as 'utf8'
setEncoding: (encoding) -> @buffer.setEncoding(encoding)
# Essential: Returns {Boolean} `true` if this editor has been modified.
isModified: -> @buffer.isModified()
# Essential: Returns {Boolean} `true` if this editor has no content.
isEmpty: -> @buffer.isEmpty()
###
Section: File Operations
###
# Essential: Saves the editor's text buffer.
#
# See {TextBuffer::save} for more details.
save: -> @buffer.save()
# Essential: Saves the editor's text buffer as the given path.
#
# See {TextBuffer::saveAs} for more details.
#
# * `filePath` A {String} path.
saveAs: (filePath) -> @buffer.saveAs(filePath)
# Determine whether the user should be prompted to save before closing
# this editor.
shouldPromptToSave: ({windowCloseRequested}={}) ->
if windowCloseRequested
false
else
@isModified() and not @buffer.hasMultipleEditors()
# Returns an {Object} to configure dialog shown when this editor is saved
# via {Pane::saveItemAs}.
getSaveDialogOptions: -> {}
###
Section: Reading Text
###
# Essential: Returns a {String} representing the entire contents of the editor.
getText: -> @buffer.getText()
# Essential: Get the text in the given {Range} in buffer coordinates.
#
# * `range` A {Range} or range-compatible {Array}.
#
# Returns a {String}.
getTextInBufferRange: (range) ->
@buffer.getTextInRange(range)
# Essential: Returns a {Number} representing the number of lines in the buffer.
getLineCount: -> @buffer.getLineCount()
# Essential: Returns a {Number} representing the number of screen lines in the
# editor. This accounts for folds.
getScreenLineCount: -> @displayLayer.getScreenLineCount()
# Essential: Returns a {Number} representing the last zero-indexed buffer row
# number of the editor.
getLastBufferRow: -> @buffer.getLastRow()
# Essential: Returns a {Number} representing the last zero-indexed screen row
# number of the editor.
getLastScreenRow: -> @getScreenLineCount() - 1
# Essential: Returns a {String} representing the contents of the line at the
# given buffer row.
#
# * `bufferRow` A {Number} representing a zero-indexed buffer row.
lineTextForBufferRow: (bufferRow) -> @buffer.lineForRow(bufferRow)
# Essential: Returns a {String} representing the contents of the line at the
# given screen row.
#
# * `screenRow` A {Number} representing a zero-indexed screen row.
lineTextForScreenRow: (screenRow) ->
@screenLineForScreenRow(screenRow)?.lineText
logScreenLines: (start=0, end=@getLastScreenRow()) ->
for row in [start..end]
line = @lineTextForScreenRow(row)
console.log row, @bufferRowForScreenRow(row), line, line.length
return
tokensForScreenRow: (screenRow) ->
tokens = []
lineTextIndex = 0
currentTokenScopes = []
{lineText, tagCodes} = @screenLineForScreenRow(screenRow)
for tagCode in tagCodes
if @displayLayer.isOpenTagCode(tagCode)
currentTokenScopes.push(@displayLayer.tagForCode(tagCode))
else if @displayLayer.isCloseTagCode(tagCode)
currentTokenScopes.pop()
else
tokens.push({
text: lineText.substr(lineTextIndex, tagCode)
scopes: currentTokenScopes.slice()
})
lineTextIndex += tagCode
tokens
screenLineForScreenRow: (screenRow) ->
return if screenRow < 0 or screenRow > @getLastScreenRow()
@displayLayer.getScreenLines(screenRow, screenRow + 1)[0]
bufferRowForScreenRow: (screenRow) ->
@displayLayer.translateScreenPosition(Point(screenRow, 0)).row
bufferRowsForScreenRows: (startScreenRow, endScreenRow) ->
for screenRow in [startScreenRow..endScreenRow]
@bufferRowForScreenRow(screenRow)
screenRowForBufferRow: (row) ->
if @largeFileMode
row
else
@displayLayer.translateBufferPosition(Point(row, 0)).row
getRightmostScreenPosition: -> @displayLayer.getRightmostScreenPosition()
getMaxScreenLineLength: -> @getRightmostScreenPosition().column
getLongestScreenRow: -> @getRightmostScreenPosition().row
lineLengthForScreenRow: (screenRow) -> @displayLayer.lineLengthForScreenRow(screenRow)
# Returns the range for the given buffer row.
#
# * `row` A row {Number}.
# * `options` (optional) An options hash with an `includeNewline` key.
#
# Returns a {Range}.
bufferRangeForBufferRow: (row, {includeNewline}={}) -> @buffer.rangeForRow(row, includeNewline)
# Get the text in the given {Range}.
#
# Returns a {String}.
getTextInRange: (range) -> @buffer.getTextInRange(range)
# {Delegates to: TextBuffer.isRowBlank}
isBufferRowBlank: (bufferRow) -> @buffer.isRowBlank(bufferRow)
# {Delegates to: TextBuffer.nextNonBlankRow}
nextNonBlankBufferRow: (bufferRow) -> @buffer.nextNonBlankRow(bufferRow)
# {Delegates to: TextBuffer.getEndPosition}
getEofBufferPosition: -> @buffer.getEndPosition()