This repository was archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathtext-buffer.coffee
2016 lines (1762 loc) · 70.5 KB
/
text-buffer.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
{Emitter, CompositeDisposable, Disposable} = require 'event-kit'
{File} = require 'pathwatcher'
diff = require 'diff'
_ = require 'underscore-plus'
fs = require 'fs-plus'
path = require 'path'
crypto = require 'crypto'
mkdirp = require 'mkdirp'
{BufferOffsetIndex, Patch, TextBuffer: NativeTextBuffer} = require 'superstring'
Point = require './point'
Range = require './range'
DefaultHistoryProvider = require './default-history-provider'
MarkerLayer = require './marker-layer'
MatchIterator = require './match-iterator'
DisplayLayer = require './display-layer'
{spliceArray, newlineRegex, patchFromChanges, normalizePatchChanges, regexIsSingleLine, extentForText, debounce} = require './helpers'
{traverse, traversal} = require './point-helpers'
Grim = require 'grim'
class TransactionAbortedError extends Error
constructor: -> super
class ChangeEvent
constructor: (buffer, changes) ->
@changes = changes
start = changes[0].oldStart
oldEnd = changes[changes.length - 1].oldEnd
newEnd = changes[changes.length - 1].newEnd
@oldRange = new Range(start, oldEnd).freeze()
@newRange = new Range(start, newEnd).freeze()
oldText = null
newText = null
Object.defineProperty(this, 'oldText', {
enumerable: false,
get: ->
unless oldText?
oldBuffer = new NativeTextBuffer(@newText)
for change in changes by -1
oldBuffer.setTextInRange(
new Range(
traversal(change.newRange.start, start),
traversal(change.newRange.end, start)
),
change.oldText
)
oldText = oldBuffer.getText()
oldText
})
Object.defineProperty(this, 'newText', {
enumerable: false,
get: ->
unless newText?
newText = buffer.getTextInRange(@newRange)
newText
})
isEqual: (other) ->
(
@changes.length is other.changes.length and
@changes.every((change, i) -> change.isEqual(other.changes[i])) and
@oldRange.isEqual(other.oldRange) and
@newRange.isEqual(other.newRange)
)
# Extended: A mutable text container with undo/redo support and the ability to
# annotate logical regions in the text.
#
# ## Observing Changes
#
# You can observe changes in a {TextBuffer} using methods like {::onDidChange},
# {::onDidStopChanging}, and {::getChangesSinceCheckpoint}. These methods report
# aggregated buffer updates as arrays of change objects containing the following
# fields: `oldRange`, `newRange`, `oldText`, and `newText`. The `oldText`,
# `newText`, and `newRange` fields are self-explanatory, but the interepretation
# of `oldRange` is more nuanced:
#
# The reported `oldRange` is the range of the replaced text in the original
# contents of the buffer *irrespective of the spatial impact of any other
# reported change*. So, for example, if you wanted to apply all the changes made
# in a transaction to a clone of the observed buffer, the easiest approach would
# be to apply the changes in reverse:
#
# ```js
# buffer1.onDidChange(({changes}) => {
# for (const {oldRange, newText} of changes.reverse()) {
# buffer2.setTextInRange(oldRange, newText)
# }
# })
# ```
#
# If you needed to apply the changes in the forwards order, you would need to
# incorporate the impact of preceding changes into the range passed to
# {::setTextInRange}, as follows:
#
# ```js
# buffer1.onDidChange(({changes}) => {
# for (const {oldRange, newRange, newText} of changes) {
# const rangeToReplace = Range(
# newRange.start,
# newRange.start.traverse(oldRange.getExtent())
# )
# buffer2.setTextInRange(rangeToReplace, newText)
# }
# })
# ```
module.exports =
class TextBuffer
@version: 5
@Point: Point
@Range: Range
@newlineRegex: newlineRegex
encoding: null
stoppedChangingDelay: 300
fileChangeDelay: 200
stoppedChangingTimeout: null
conflict: false
file: null
refcount: 0
fileSubscriptions: null
backwardsScanChunkSize: 8000
defaultMaxUndoEntries: 10000
nextMarkerLayerId: 0
# Provide fallback in case people are using this renamed private field in packages.
Object.defineProperty(this, 'history', {
enumerable: false,
get: -> @historyProvider
})
###
Section: Construction
###
# Public: Create a new buffer with the given params.
#
# * `params` {Object} or {String} of text
# * `text` The initial {String} text of the buffer.
# * `shouldDestroyOnFileDelete` A {Function} that returns a {Boolean}
# indicating whether the buffer should be destroyed if its file is
# deleted.
constructor: (params) ->
text = if typeof params is 'string'
params
else
params?.text
@emitter = new Emitter
@changesSinceLastStoppedChangingEvent = []
@changesSinceLastDidChangeTextEvent = []
@id = crypto.randomBytes(16).toString('hex')
@buffer = new NativeTextBuffer(text)
@debouncedEmitDidStopChangingEvent = debounce(@emitDidStopChangingEvent.bind(this), @stoppedChangingDelay)
@textDecorationLayers = new Set()
@maxUndoEntries = params?.maxUndoEntries ? @defaultMaxUndoEntries
@setHistoryProvider(new DefaultHistoryProvider(this))
@nextMarkerLayerId = 0
@nextDisplayLayerId = 0
@defaultMarkerLayer = new MarkerLayer(this, String(@nextMarkerLayerId++))
@displayLayers = {}
@markerLayers = {}
@markerLayers[@defaultMarkerLayer.id] = @defaultMarkerLayer
@markerLayersWithPendingUpdateEvents = new Set()
@nextMarkerId = 1
@outstandingSaveCount = 0
@loadCount = 0
@_emittedWillChangeEvent = false
@setEncoding(params?.encoding)
@setPreferredLineEnding(params?.preferredLineEnding)
@loaded = false
@destroyed = false
@transactCallDepth = 0
@digestWhenLastPersisted = false
@shouldDestroyOnFileDelete = params?.shouldDestroyOnFileDelete ? -> false
if params?.filePath
@setPath(params.filePath)
if params?.load
Grim.deprecate(
'The `load` option to the TextBuffer constructor is deprecated. ' +
'Get a loaded buffer using TextBuffer.load(filePath) instead.'
)
@load(internal: true)
toString: -> "<TextBuffer #{@id}>"
# Public: Create a new buffer backed by the given file path.
#
# * `source` Either a {String} path to a local file or (experimentally) a file
# {Object} as described by the {::setFile} method.
# * `params` An {Object} with the following properties:
# * `encoding` (optional) {String} The file's encoding.
# * `shouldDestroyOnFileDelete` (optional) A {Function} that returns a
# {Boolean} indicating whether the buffer should be destroyed if its file
# is deleted.
#
# Returns a {Promise} that resolves with a {TextBuffer} instance.
@load: (source, params) ->
buffer = new TextBuffer(params)
if typeof source is 'string'
buffer.setPath(source)
else
buffer.setFile(source)
buffer.load(clearHistory: true, internal: true, mustExist: params?.mustExist)
.then -> buffer
.catch (err) ->
buffer.destroy()
throw err
# Public: Create a new buffer backed by the given file path. For better
# performance, use {TextBuffer.load} instead.
#
# * `filePath` The {String} file path.
# * `params` An {Object} with the following properties:
# * `encoding` (optional) {String} The file's encoding.
# * `shouldDestroyOnFileDelete` (optional) A {Function} that returns a
# {Boolean} indicating whether the buffer should be destroyed if its file
# is deleted.
#
# Returns a {TextBuffer} instance.
@loadSync: (filePath, params) ->
buffer = new TextBuffer(params)
buffer.setPath(filePath)
try
buffer.loadSync(internal: true, mustExist: params?.mustExist)
catch e
buffer.destroy()
throw e
buffer
# Public: Restore a {TextBuffer} based on an earlier state created using
# the {TextBuffer::serialize} method.
#
# * `params` An {Object} returned from {TextBuffer::serialize}
#
# Returns a {Promise} that resolves with a {TextBuffer} instance.
@deserialize: (params) ->
return if params.version isnt TextBuffer.prototype.version
delete params.load
if params.filePath?
promise = @load(params.filePath, params).then (buffer) ->
# TODO - Remove this once Atom 1.19 stable has been out for a while.
if typeof params.text is 'string'
buffer.setText(params.text)
else if buffer.digestWhenLastPersisted is params.digestWhenLastPersisted
buffer.buffer.deserializeChanges(params.outstandingChanges)
else
params.history = {}
buffer
else
promise = Promise.resolve(new TextBuffer(params))
promise.then (buffer) ->
buffer.id = params.id
buffer.preferredLineEnding = params.preferredLineEnding
buffer.nextMarkerId = params.nextMarkerId
buffer.nextMarkerLayerId = params.nextMarkerLayerId
buffer.nextDisplayLayerId = params.nextDisplayLayerId
buffer.historyProvider.deserialize(params.history, buffer)
for layerId, layerState of params.markerLayers
if layerId is params.defaultMarkerLayerId
buffer.defaultMarkerLayer.id = layerId
buffer.defaultMarkerLayer.deserialize(layerState)
layer = buffer.defaultMarkerLayer
else
layer = MarkerLayer.deserialize(buffer, layerState)
buffer.markerLayers[layerId] = layer
for layerId, layerState of params.displayLayers
buffer.displayLayers[layerId] = DisplayLayer.deserialize(buffer, layerState)
buffer
# Returns a {String} representing a unique identifier for this {TextBuffer}.
getId: ->
@id
serialize: (options) ->
options ?= {}
options.markerLayers ?= true
options.history ?= true
markerLayers = {}
if options.markerLayers
for id, layer of @markerLayers when layer.persistent
markerLayers[id] = layer.serialize()
displayLayers = {}
for id, layer of @displayLayers
displayLayers[id] = layer.serialize()
history = {}
if options.history
history = @historyProvider.serialize(options)
result = {
id: @getId()
defaultMarkerLayerId: @defaultMarkerLayer.id
markerLayers: markerLayers
displayLayers: displayLayers
nextMarkerLayerId: @nextMarkerLayerId
nextDisplayLayerId: @nextDisplayLayerId
history: history
encoding: @getEncoding()
preferredLineEnding: @preferredLineEnding
nextMarkerId: @nextMarkerId
}
if filePath = @getPath()
@baseTextDigestCache ?= @buffer.baseTextDigest()
result.filePath = filePath
result.digestWhenLastPersisted = @digestWhenLastPersisted
result.outstandingChanges = @buffer.serializeChanges()
else
result.text = @getText()
result
###
Section: Event Subscription
###
# Public: Invoke the given callback synchronously _before_ the content of the
# buffer changes.
#
# Because observers are invoked synchronously, it's important not to perform
# any expensive operations via this method.
#
# * `callback` {Function} to be called when the buffer changes.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onWillChange: (callback) ->
@emitter.on 'will-change', callback
# Public: Invoke the given callback synchronously when a transaction finishes
# with a list of all the changes in the transaction.
#
# * `callback` {Function} to be called when a transaction in which textual
# changes occurred is completed.
# * `event` {Object} with the following keys:
# * `oldRange` The smallest combined {Range} containing all of the old text.
# * `newRange` The smallest combined {Range} containing all of the new text.
# * `changes` {Array} of {Object}s summarizing the aggregated changes
# that occurred during the transaction. See *Working With Aggregated
# Changes* in the description of the {TextBuffer} class for details.
# * `oldRange` The {Range} of the deleted text in the contents of the
# buffer as it existed *before* the batch of changes reported by this
# event.
# * `newRange`: The {Range} of the inserted text in the current contents
# of the buffer.
# * `oldText`: A {String} representing the deleted text.
# * `newText`: A {String} representing the inserted text.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChange: (callback) ->
@emitter.on 'did-change-text', callback
# Public: This is now identical to {onDidChange}.
onDidChangeText: (callback) -> @onDidChange(callback)
# Public: Invoke the given callback asynchronously following one or more
# changes after {::getStoppedChangingDelay} milliseconds elapse without an
# additional change.
#
# This method can be used to perform potentially expensive operations that
# don't need to be performed synchronously. If you need to run your callback
# synchronously, use {::onDidChange} instead.
#
# * `callback` {Function} to be called when the buffer stops changing.
# * `event` {Object} with the following keys:
# * `changes` An {Array} containing {Object}s summarizing the aggregated
# changes. See *Working With Aggregated Changes* in the description of
# the {TextBuffer} class for details.
# * `oldRange` The {Range} of the deleted text in the contents of the
# buffer as it existed *before* the batch of changes reported by this
# event.
# * `newRange`: The {Range} of the inserted text in the current contents
# of the buffer.
# * `oldText`: A {String} representing the deleted text.
# * `newText`: A {String} representing the inserted text.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidStopChanging: (callback) ->
@emitter.on 'did-stop-changing', callback
# Public: Invoke the given callback when the in-memory contents of the
# buffer become in conflict with the contents of the file on disk.
#
# * `callback` {Function} to be called when the buffer enters conflict.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidConflict: (callback) ->
@emitter.on 'did-conflict', callback
# Public: Invoke the given callback if the value of {::isModified} changes.
#
# * `callback` {Function} to be called when {::isModified} changes.
# * `modified` {Boolean} indicating whether the buffer is modified.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeModified: (callback) ->
@emitter.on 'did-change-modified', callback
# Public: Invoke the given callback when all marker `::onDidChange`
# observers have been notified following a change to the buffer.
#
# The order of events following a buffer change is as follows:
#
# * The text of the buffer is changed
# * All markers are updated accordingly, but their `::onDidChange` observers
# are not notified.
# * `TextBuffer::onDidChange` observers are notified.
# * `Marker::onDidChange` observers are notified.
# * `TextBuffer::onDidUpdateMarkers` observers are notified.
#
# Basically, this method gives you a way to take action after both a buffer
# change and all associated marker changes.
#
# * `callback` {Function} to be called after markers are updated.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidUpdateMarkers: (callback) ->
@emitter.on 'did-update-markers', callback
# Public: Invoke the given callback when a marker is created.
#
# * `callback` {Function} to be called when a marker is created.
# * `marker` {Marker} that was created.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidCreateMarker: (callback) ->
@emitter.on 'did-create-marker', callback
# Public: Invoke the given callback when the value of {::getPath} changes.
#
# * `callback` {Function} to be called when the path changes.
# * `path` {String} representing the buffer's current path on disk.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangePath: (callback) ->
@emitter.on 'did-change-path', callback
# Public: Invoke the given callback when the value of {::getEncoding} changes.
#
# * `callback` {Function} to be called when the encoding changes.
# * `encoding` {String} character set encoding of the buffer.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeEncoding: (callback) ->
@emitter.on 'did-change-encoding', callback
# Public: Invoke the given callback before the buffer is saved to disk.
#
# * `callback` {Function} to be called before the buffer is saved. If this function returns
# a {Promise}, then the buffer will not be saved until the promise resolves.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onWillSave: (callback) ->
@emitter.on 'will-save', callback
# Public: 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) ->
@emitter.on 'did-save', callback
# Public: Invoke the given callback after the file backing the buffer is
# deleted.
#
# * `callback` {Function} to be called after the buffer is deleted.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidDelete: (callback) ->
@emitter.on 'did-delete', callback
# Public: Invoke the given callback before the buffer is reloaded from the
# contents of its file on disk.
#
# * `callback` {Function} to be called before the buffer is reloaded.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onWillReload: (callback) ->
@emitter.on 'will-reload', callback
# Public: Invoke the given callback after the buffer is reloaded from the
# contents of its file on disk.
#
# * `callback` {Function} to be called after the buffer is reloaded.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidReload: (callback) ->
@emitter.on 'did-reload', callback
# Public: Invoke the given callback when the buffer is destroyed.
#
# * `callback` {Function} to be called when the buffer is destroyed.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidDestroy: (callback) ->
@emitter.on 'did-destroy', callback
# Public: Invoke the given callback when there is an error in watching the
# file.
#
# * `callback` {Function} callback
# * `errorObject` {Object}
# * `error` {Object} the error object
# * `handle` {Function} call this to indicate you have handled the error.
# The error will not be thrown if this function is called.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onWillThrowWatchError: (callback) ->
@emitter.on 'will-throw-watch-error', callback
# Public: Get the number of milliseconds that will elapse without a change
# before {::onDidStopChanging} observers are invoked following a change.
#
# Returns a {Number}.
getStoppedChangingDelay: -> @stoppedChangingDelay
###
Section: File Details
###
# Public: Determine if the in-memory contents of the buffer differ from its
# contents on disk.
#
# If the buffer is unsaved, always returns `true` unless the buffer is empty.
#
# Returns a {Boolean}.
isModified: ->
if @file?
not @file.existsSync() or @buffer.isModified()
else
@buffer.getLength() > 0
# Public: Determine if the in-memory contents of the buffer conflict with the
# on-disk contents of its associated file.
#
# Returns a {Boolean}.
isInConflict: -> @isModified() and @fileHasChangedSinceLastLoad
# Public: Get the path of the associated file.
#
# Returns a {String}.
getPath: ->
@file?.getPath()
# Public: Set the path for the buffer's associated file.
#
# * `filePath` A {String} representing the new file path
setPath: (filePath) ->
return if filePath is @getPath()
if @file? and filePath
@file.setPath filePath
@updateFilePath()
return
@setFile(new File(filePath) if filePath)
# Experimental: Set a custom {File} object as the buffer's backing store.
#
# * `file` An {Object} with the following properties:
# * `getPath` A {Function} that returns the {String} path to the file.
# * `createReadStream` A {Function} that returns a `Readable` stream
# that can be used to load the file's content.
# * `createWriteStream` A {Function} that returns a `Writable` stream
# that can be used to save content to the file.
# * `onDidChange` (optional) A {Function} that invokes its callback argument
# when the file changes. The method should return a {Disposable} that
# can be used to prevent further calls to the callback.
# * `onDidDelete` (optional) A {Function} that invokes its callback argument
# when the file is deleted. The method should return a {Disposable} that
# can be used to prevent further calls to the callback.
# * `onDidRename` (optional) A {Function} that invokes its callback argument
# when the file is renamed. The method should return a {Disposable} that
# can be used to prevent further calls to the callback.
setFile: (file) ->
return if file?.getPath() is @getPath()
@file = file
@file?.setEncoding?(@getEncoding())
@updateFilePath()
updateFilePath: ->
if @file?
@subscribeToFile()
@emitter.emit 'did-change-path', @getPath()
# Public: Sets the character set encoding for this buffer.
#
# * `encoding` The {String} encoding to use (default: 'utf8').
setEncoding: (encoding='utf8') ->
return if encoding is @getEncoding()
@encoding = encoding
if @file?
@file.setEncoding?(encoding)
@emitter.emit 'did-change-encoding', encoding
@load(clearHistory: true, internal: true) unless @isModified()
else
@emitter.emit 'did-change-encoding', encoding
return
# Public: Returns the {String} encoding of this buffer.
getEncoding: -> @encoding ? @file?.getEncoding()
setPreferredLineEnding: (preferredLineEnding=null) ->
@preferredLineEnding = preferredLineEnding
getPreferredLineEnding: ->
@preferredLineEnding
# Public: Get the path of the associated file.
#
# Returns a {String}.
getUri: ->
@getPath()
# Get the basename of the associated file.
#
# The basename is the name portion of the file's path, without the containing
# directories.
#
# Returns a {String}.
getBaseName: ->
@file?.getBaseName()
###
Section: Reading Text
###
# Public: Determine whether the buffer is empty.
#
# Returns a {Boolean}.
isEmpty: -> @buffer.getLength() is 0
# Public: Get the entire text of the buffer.
#
# Returns a {String}.
getText: -> @cachedText ?= @buffer.getText()
# Public: Get the text in a range.
#
# * `range` A {Range}
#
# Returns a {String}
getTextInRange: (range) -> @buffer.getTextInRange(Range.fromObject(range))
# Public: Get the text of all lines in the buffer, without their line endings.
#
# Returns an {Array} of {String}s.
getLines: -> @buffer.getLines()
# Public: Get the text of the last line of the buffer, without its line
# ending.
#
# Returns a {String}.
getLastLine: ->
@lineForRow(@getLastRow())
# Public: Get the text of the line at the given row, without its line ending.
#
# * `row` A {Number} representing a 0-indexed row.
#
# Returns a {String}.
lineForRow: (row) -> @buffer.lineForRow(row)
# Public: Get the line ending for the given 0-indexed row.
#
# * `row` A {Number} indicating the row.
#
# Returns a {String}. The returned newline is represented as a literal string:
# `'\n'`, `'\r\n'`, or `''` for the last line of the buffer, which
# doesn't end in a newline.
lineEndingForRow: (row) -> @buffer.lineEndingForRow(row)
# Public: Get the length of the line for the given 0-indexed row, without its
# line ending.
#
# * `row` A {Number} indicating the row.
#
# Returns a {Number}.
lineLengthForRow: (row) -> @buffer.lineLengthForRow(row)
# Public: Determine if the given row contains only whitespace.
#
# * `row` A {Number} representing a 0-indexed row.
#
# Returns a {Boolean}.
isRowBlank: (row) ->
not /\S/.test(@lineForRow(row))
# Public: Given a row, find the first preceding row that's not blank.
#
# * `startRow` A {Number} identifying the row to start checking at.
#
# Returns a {Number} or `null` if there's no preceding non-blank row.
previousNonBlankRow: (startRow) ->
return null if startRow is 0
startRow = Math.min(startRow, @getLastRow())
for row in [(startRow - 1)..0]
return row unless @isRowBlank(row)
null
# Public: Given a row, find the next row that's not blank.
#
# * `startRow` A {Number} identifying the row to start checking at.
#
# Returns a {Number} or `null` if there's no next non-blank row.
nextNonBlankRow: (startRow) ->
lastRow = @getLastRow()
if startRow < lastRow
for row in [(startRow + 1)..lastRow]
return row unless @isRowBlank(row)
null
###
Section: Mutating Text
###
# Public: Replace the entire contents of the buffer with the given text.
#
# * `text` A {String}
#
# Returns a {Range} spanning the new buffer contents.
setText: (text) ->
@setTextInRange(@getRange(), text, normalizeLineEndings: false)
# Public: Replace the current buffer contents by applying a diff based on the
# given text.
#
# * `text` A {String} containing the new buffer contents.
setTextViaDiff: (text) ->
currentText = @getText()
return if currentText is text
computeBufferColumn = (str) ->
newlineIndex = str.lastIndexOf('\n')
if newlineIndex is -1
str.length
else
str.length - newlineIndex - 1
@transact =>
row = 0
column = 0
currentPosition = [0, 0]
lineDiff = diff.diffLines(currentText, text)
changeOptions = normalizeLineEndings: false
for change in lineDiff
lineCount = change.count
currentPosition[0] = row
currentPosition[1] = column
if change.added
row += lineCount
column = computeBufferColumn(change.value)
@setTextInRange([currentPosition, currentPosition], change.value, changeOptions)
else if change.removed
endRow = row + lineCount
endColumn = column + computeBufferColumn(change.value)
@setTextInRange([currentPosition, [endRow, endColumn]], '', changeOptions)
else
row += lineCount
column = computeBufferColumn(change.value)
return
# Public: Set the text in the given range.
#
# * `range` A {Range}
# * `text` A {String}
# * `options` (optional) {Object}
# * `normalizeLineEndings` (optional) {Boolean} (default: true)
# * `undo` (optional) {String} 'skip' will skip the undo system
#
# Returns the {Range} of the inserted text.
setTextInRange: (range, newText, options) ->
if options?
{normalizeLineEndings, undo} = options
normalizeLineEndings ?= true
if @transactCallDepth is 0 and undo isnt 'skip'
return @transact => @setTextInRange(range, newText, options)
oldRange = @clipRange(range)
oldText = @getTextInRange(oldRange)
if normalizeLineEndings
normalizedEnding = @preferredLineEnding or
@lineEndingForRow(oldRange.start.row) or
@lineEndingForRow(oldRange.start.row - 1)
if normalizedEnding
newText = newText.replace(newlineRegex, normalizedEnding)
change = {
oldStart: oldRange.start, oldEnd: oldRange.end,
newStart: oldRange.start, newEnd: traverse(oldRange.start, extentForText(newText))
oldText, newText
}
newRange = @applyChange(change, undo isnt 'skip')
if @transactCallDepth is 0 and undo is 'skip'
@emitDidChangeTextEvent()
@emitMarkerChangeEvents()
newRange
# Public: Insert text at the given position.
#
# * `position` A {Point} representing the insertion location. The position is
# clipped before insertion.
# * `text` A {String} representing the text to insert.
# * `options` (optional) {Object}
# * `normalizeLineEndings` (optional) {Boolean} (default: true)
# * `undo` (optional) {String} 'skip' will skip the undo system
#
# Returns the {Range} of the inserted text.
insert: (position, text, options) ->
@setTextInRange(new Range(position, position), text, options)
# Public: Append text to the end of the buffer.
#
# * `text` A {String} representing the text text to append.
# * `options` (optional) {Object}
# * `normalizeLineEndings` (optional) {Boolean} (default: true)
# * `undo` (optional) {String} 'skip' will skip the undo system
#
# Returns the {Range} of the inserted text
append: (text, options) ->
@insert(@getEndPosition(), text, options)
# Applies a change to the buffer based on its old range and new text.
applyChange: (change, pushToHistory = false) ->
{newStart, newEnd, oldStart, oldEnd, oldText, newText} = change
oldExtent = traversal(oldEnd, oldStart)
oldRange = Range(newStart, traverse(newStart, oldExtent))
oldRange.freeze()
newExtent = traversal(newEnd, newStart)
newRange = Range(newStart, traverse(newStart, newExtent))
newRange.freeze()
if pushToHistory
change.oldExtent ?= oldExtent
change.newExtent ?= newExtent
@historyProvider?.pushChange(change)
changeEvent = {oldRange, newRange, oldText, newText}
for id, displayLayer of @displayLayers
displayLayer.bufferWillChange(changeEvent)
@emitWillChangeEvent()
@buffer.setTextInRange(oldRange, newText)
if @markerLayers?
for id, markerLayer of @markerLayers
markerLayer.splice(oldRange.start, oldExtent, newExtent)
@markerLayersWithPendingUpdateEvents.add(markerLayer)
@cachedText = null
@changesSinceLastDidChangeTextEvent.push(change)
@changesSinceLastStoppedChangingEvent.push(change)
@emitDidChangeEvent(changeEvent)
newRange
emitDidChangeEvent: (changeEvent) ->
# Emit the change event on all the registered text decoration layers.
@textDecorationLayers.forEach (textDecorationLayer) ->
textDecorationLayer.bufferDidChange(changeEvent)
for id, displayLayer of @displayLayers
event = displayLayer.bufferDidChange(changeEvent)
return
# Public: Delete the text in the given range.
#
# * `range` A {Range} in which to delete. The range is clipped before deleting.
#
# Returns an empty {Range} starting at the start of deleted range.
delete: (range) ->
@setTextInRange(range, '')
# Public: Delete the line associated with a specified row.
#
# * `row` A {Number} representing the 0-indexed row to delete.
#
# Returns the {Range} of the deleted text.
deleteRow: (row) ->
@deleteRows(row, row)
# Public: Delete the lines associated with the specified row range.
#
# If the row range is out of bounds, it will be clipped. If the startRow is
# greater than the end row, they will be reordered.
#
# * `startRow` A {Number} representing the first row to delete.
# * `endRow` A {Number} representing the last row to delete, inclusive.
#
# Returns the {Range} of the deleted text.
deleteRows: (startRow, endRow) ->
lastRow = @getLastRow()
[startRow, endRow] = [endRow, startRow] if startRow > endRow
if endRow < 0
return new Range(@getFirstPosition(), @getFirstPosition())
if startRow > lastRow
return new Range(@getEndPosition(), @getEndPosition())
startRow = Math.max(0, startRow)
endRow = Math.min(lastRow, endRow)
if endRow < lastRow
startPoint = new Point(startRow, 0)
endPoint = new Point(endRow + 1, 0)
else
if startRow is 0
startPoint = new Point(startRow, 0)
else
startPoint = new Point(startRow - 1, @lineLengthForRow(startRow - 1))
endPoint = new Point(endRow, @lineLengthForRow(endRow))
@delete(new Range(startPoint, endPoint))
###
Section: Markers
###
# Public: Create a layer to contain a set of related markers.
#
# * `options` An object contaning the following keys:
# * `maintainHistory` A {Boolean} indicating whether or not the state of
# this layer should be restored on undo/redo operations. Defaults to
# `false`.
# * `persistent` A {Boolean} indicating whether or not this marker layer
# should be serialized and deserialized along with the rest of the
# buffer. Defaults to `false`. If `true`, the marker layer's id will be
# maintained across the serialization boundary, allowing you to retrieve
# it via {::getMarkerLayer}.
#
# Returns a {MarkerLayer}.
addMarkerLayer: (options) ->
layer = new MarkerLayer(this, String(@nextMarkerLayerId++), options)
@markerLayers[layer.id] = layer
layer
# Public: Get a {MarkerLayer} by id.
#
# * `id` The id of the marker layer to retrieve.
#
# Returns a {MarkerLayer} or `undefined` if no layer exists with the given
# id.
getMarkerLayer: (id) ->
@markerLayers[id]
# Public: Get the default {MarkerLayer}.
#
# All marker APIs not tied to an explicit layer interact with this default
# layer.
#
# Returns a {MarkerLayer}.
getDefaultMarkerLayer: ->
@defaultMarkerLayer
# Public: Create a marker with the given range in the default marker layer.
# This marker will maintain its logical location as the buffer is changed, so
# if you mark a particular word, the marker will remain over that word even if
# the word's location in the buffer changes.
#
# * `range` A {Range} or range-compatible {Array}
# * `properties` A hash of key-value pairs to associate with the marker. There
# are also reserved property names that have marker-specific meaning.
# * `reversed` (optional) {Boolean} Creates the marker in a reversed
# orientation. (default: false)
# * `invalidate` (optional) {String} Determines the rules by which changes
# to the buffer *invalidate* the marker. (default: 'overlap') It can be
# any of the following strategies, in order of fragility:
# * __never__: The marker is never marked as invalid. This is a good choice for
# markers representing selections in an editor.