forked from atom/atom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkspace.coffee
1121 lines (973 loc) · 43.1 KB
/
workspace.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'
url = require 'url'
path = require 'path'
{Emitter, Disposable, CompositeDisposable} = require 'event-kit'
fs = require 'fs-plus'
{Directory} = require 'pathwatcher'
DefaultDirectorySearcher = require './default-directory-searcher'
Model = require './model'
TextEditor = require './text-editor'
PaneContainer = require './pane-container'
Panel = require './panel'
PanelContainer = require './panel-container'
Task = require './task'
# Essential: Represents the state of the user interface for the entire window.
# An instance of this class is available via the `atom.workspace` global.
#
# Interact with this object to open files, be notified of current and future
# editors, and manipulate panes. To add panels, use {Workspace::addTopPanel}
# and friends.
#
# * `editor` {TextEditor} the new editor
#
module.exports =
class Workspace extends Model
constructor: (params) ->
super
{
@packageManager, @config, @project, @grammarRegistry, @notificationManager,
@clipboard, @viewRegistry, @grammarRegistry, @applicationDelegate, @assert,
@deserializerManager, @textEditorRegistry
} = params
@emitter = new Emitter
@openers = []
@destroyedItemURIs = []
@paneContainer = new PaneContainer({@config, @applicationDelegate, @notificationManager, @deserializerManager})
@paneContainer.onDidDestroyPaneItem(@didDestroyPaneItem)
@defaultDirectorySearcher = new DefaultDirectorySearcher()
@consumeServices(@packageManager)
# One cannot simply .bind here since it could be used as a component with
# Etch, in which case it'd be `new`d. And when it's `new`d, `this` is always
# the newly created object.
realThis = this
@buildTextEditor = -> Workspace.prototype.buildTextEditor.apply(realThis, arguments)
@panelContainers =
top: new PanelContainer({location: 'top'})
left: new PanelContainer({location: 'left'})
right: new PanelContainer({location: 'right'})
bottom: new PanelContainer({location: 'bottom'})
header: new PanelContainer({location: 'header'})
footer: new PanelContainer({location: 'footer'})
modal: new PanelContainer({location: 'modal'})
@subscribeToEvents()
reset: (@packageManager) ->
@emitter.dispose()
@emitter = new Emitter
@paneContainer.destroy()
panelContainer.destroy() for panelContainer in @panelContainers
@paneContainer = new PaneContainer({@config, @applicationDelegate, @notificationManager, @deserializerManager})
@paneContainer.onDidDestroyPaneItem(@didDestroyPaneItem)
@panelContainers =
top: new PanelContainer({location: 'top'})
left: new PanelContainer({location: 'left'})
right: new PanelContainer({location: 'right'})
bottom: new PanelContainer({location: 'bottom'})
header: new PanelContainer({location: 'header'})
footer: new PanelContainer({location: 'footer'})
modal: new PanelContainer({location: 'modal'})
@originalFontSize = null
@openers = []
@destroyedItemURIs = []
@consumeServices(@packageManager)
subscribeToEvents: ->
@subscribeToActiveItem()
@subscribeToFontSize()
@subscribeToAddedItems()
consumeServices: ({serviceHub}) ->
@directorySearchers = []
serviceHub.consume(
'atom.directory-searcher',
'^0.1.0',
(provider) => @directorySearchers.unshift(provider))
# Called by the Serializable mixin during serialization.
serialize: ->
deserializer: 'Workspace'
paneContainer: @paneContainer.serialize()
packagesWithActiveGrammars: @getPackageNamesWithActiveGrammars()
destroyedItemURIs: @destroyedItemURIs.slice()
deserialize: (state, deserializerManager) ->
for packageName in state.packagesWithActiveGrammars ? []
@packageManager.getLoadedPackage(packageName)?.loadGrammarsSync()
if state.destroyedItemURIs?
@destroyedItemURIs = state.destroyedItemURIs
@paneContainer.deserialize(state.paneContainer, deserializerManager)
getPackageNamesWithActiveGrammars: ->
packageNames = []
addGrammar = ({includedGrammarScopes, packageName}={}) =>
return unless packageName
# Prevent cycles
return if packageNames.indexOf(packageName) isnt -1
packageNames.push(packageName)
for scopeName in includedGrammarScopes ? []
addGrammar(@grammarRegistry.grammarForScopeName(scopeName))
return
editors = @getTextEditors()
addGrammar(editor.getGrammar()) for editor in editors
if editors.length > 0
for grammar in @grammarRegistry.getGrammars() when grammar.injectionSelector
addGrammar(grammar)
_.uniq(packageNames)
subscribeToActiveItem: ->
@updateWindowTitle()
@updateDocumentEdited()
@project.onDidChangePaths @updateWindowTitle
@observeActivePaneItem (item) =>
@updateWindowTitle()
@updateDocumentEdited()
@activeItemSubscriptions?.dispose()
@activeItemSubscriptions = new CompositeDisposable
if typeof item?.onDidChangeTitle is 'function'
titleSubscription = item.onDidChangeTitle(@updateWindowTitle)
else if typeof item?.on is 'function'
titleSubscription = item.on('title-changed', @updateWindowTitle)
unless typeof titleSubscription?.dispose is 'function'
titleSubscription = new Disposable => item.off('title-changed', @updateWindowTitle)
if typeof item?.onDidChangeModified is 'function'
modifiedSubscription = item.onDidChangeModified(@updateDocumentEdited)
else if typeof item?.on? is 'function'
modifiedSubscription = item.on('modified-status-changed', @updateDocumentEdited)
unless typeof modifiedSubscription?.dispose is 'function'
modifiedSubscription = new Disposable => item.off('modified-status-changed', @updateDocumentEdited)
@activeItemSubscriptions.add(titleSubscription) if titleSubscription?
@activeItemSubscriptions.add(modifiedSubscription) if modifiedSubscription?
subscribeToAddedItems: ->
@onDidAddPaneItem ({item, pane, index}) =>
if item instanceof TextEditor
subscriptions = new CompositeDisposable(
@textEditorRegistry.add(item)
@textEditorRegistry.maintainGrammar(item)
@textEditorRegistry.maintainConfig(item)
item.observeGrammar(@handleGrammarUsed.bind(this))
)
item.onDidDestroy -> subscriptions.dispose()
@emitter.emit 'did-add-text-editor', {textEditor: item, pane, index}
# Updates the application's title and proxy icon based on whichever file is
# open.
updateWindowTitle: =>
appName = 'Atom'
projectPaths = @project.getPaths() ? []
if item = @getActivePaneItem()
itemPath = item.getPath?()
itemTitle = item.getLongTitle?() ? item.getTitle?()
projectPath = _.find projectPaths, (projectPath) ->
itemPath is projectPath or itemPath?.startsWith(projectPath + path.sep)
itemTitle ?= "untitled"
projectPath ?= projectPaths[0]
if projectPath?
projectPath = fs.tildify(projectPath)
titleParts = []
if item? and projectPath?
titleParts.push itemTitle, projectPath
representedPath = itemPath ? projectPath
else if projectPath?
titleParts.push projectPath
representedPath = projectPath
else
titleParts.push itemTitle
representedPath = ""
unless process.platform is 'darwin'
titleParts.push appName
document.title = titleParts.join(" \u2014 ")
@applicationDelegate.setRepresentedFilename(representedPath)
# On macOS, fades the application window's proxy icon when the current file
# has been modified.
updateDocumentEdited: =>
modified = @getActivePaneItem()?.isModified?() ? false
@applicationDelegate.setWindowDocumentEdited(modified)
###
Section: Event Subscription
###
# Essential: Invoke the given callback with all current and future text
# editors in the workspace.
#
# * `callback` {Function} to be called with current and future text editors.
# * `editor` An {TextEditor} that is present in {::getTextEditors} at the time
# of subscription or that is added at some later time.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeTextEditors: (callback) ->
callback(textEditor) for textEditor in @getTextEditors()
@onDidAddTextEditor ({textEditor}) -> callback(textEditor)
# Essential: Invoke the given callback with all current and future panes items
# in the workspace.
#
# * `callback` {Function} to be called with current and future pane items.
# * `item` An item that is present in {::getPaneItems} at the time of
# subscription or that is added at some later time.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observePaneItems: (callback) -> @paneContainer.observePaneItems(callback)
# Essential: Invoke the given callback when the active pane item changes.
#
# Because observers are invoked synchronously, it's important not to perform
# any expensive operations via this method. Consider
# {::onDidStopChangingActivePaneItem} to delay operations until after changes
# stop occurring.
#
# * `callback` {Function} to be called when the active pane item changes.
# * `item` The active pane item.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeActivePaneItem: (callback) ->
@paneContainer.onDidChangeActivePaneItem(callback)
# Essential: Invoke the given callback when the active pane item stops
# changing.
#
# Observers are called asynchronously 100ms after the last active pane item
# change. Handling changes here rather than in the synchronous
# {::onDidChangeActivePaneItem} prevents unneeded work if the user is quickly
# changing or closing tabs and ensures critical UI feedback, like changing the
# highlighted tab, gets priority over work that can be done asynchronously.
#
# * `callback` {Function} to be called when the active pane item stopts
# changing.
# * `item` The active pane item.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidStopChangingActivePaneItem: (callback) ->
@paneContainer.onDidStopChangingActivePaneItem(callback)
# Essential: Invoke the given callback with the current active pane item and
# with all future active pane items in the workspace.
#
# * `callback` {Function} to be called when the active pane item changes.
# * `item` The current active pane item.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeActivePaneItem: (callback) -> @paneContainer.observeActivePaneItem(callback)
# Essential: Invoke the given callback whenever an item is opened. Unlike
# {::onDidAddPaneItem}, observers will be notified for items that are already
# present in the workspace when they are reopened.
#
# * `callback` {Function} to be called whenever an item is opened.
# * `event` {Object} with the following keys:
# * `uri` {String} representing the opened URI. Could be `undefined`.
# * `item` The opened item.
# * `pane` The pane in which the item was opened.
# * `index` The index of the opened item on its pane.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidOpen: (callback) ->
@emitter.on 'did-open', callback
# Extended: Invoke the given callback when a pane is added to the workspace.
#
# * `callback` {Function} to be called panes are added.
# * `event` {Object} with the following keys:
# * `pane` The added pane.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddPane: (callback) -> @paneContainer.onDidAddPane(callback)
# Extended: Invoke the given callback before a pane is destroyed in the
# workspace.
#
# * `callback` {Function} to be called before panes are destroyed.
# * `event` {Object} with the following keys:
# * `pane` The pane to be destroyed.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onWillDestroyPane: (callback) -> @paneContainer.onWillDestroyPane(callback)
# Extended: Invoke the given callback when a pane is destroyed in the
# workspace.
#
# * `callback` {Function} to be called panes are destroyed.
# * `event` {Object} with the following keys:
# * `pane` The destroyed pane.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidDestroyPane: (callback) -> @paneContainer.onDidDestroyPane(callback)
# Extended: Invoke the given callback with all current and future panes in the
# workspace.
#
# * `callback` {Function} to be called with current and future panes.
# * `pane` A {Pane} that is present in {::getPanes} at the time of
# subscription or that is added at some later time.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observePanes: (callback) -> @paneContainer.observePanes(callback)
# Extended: Invoke the given callback when the active pane changes.
#
# * `callback` {Function} to be called when the active pane changes.
# * `pane` A {Pane} that is the current return value of {::getActivePane}.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidChangeActivePane: (callback) -> @paneContainer.onDidChangeActivePane(callback)
# Extended: Invoke the given callback with the current active pane and when
# the active pane changes.
#
# * `callback` {Function} to be called with the current and future active#
# panes.
# * `pane` A {Pane} that is the current return value of {::getActivePane}.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observeActivePane: (callback) -> @paneContainer.observeActivePane(callback)
# Extended: Invoke the given callback when a pane item is added to the
# workspace.
#
# * `callback` {Function} to be called when pane items are added.
# * `event` {Object} with the following keys:
# * `item` The added pane item.
# * `pane` {Pane} containing the added item.
# * `index` {Number} indicating the index of the added item in its pane.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddPaneItem: (callback) -> @paneContainer.onDidAddPaneItem(callback)
# Extended: Invoke the given callback when a pane item is about to be
# destroyed, before the user is prompted to save it.
#
# * `callback` {Function} to be called before pane items are destroyed.
# * `event` {Object} with the following keys:
# * `item` The item to be destroyed.
# * `pane` {Pane} containing the item to be destroyed.
# * `index` {Number} indicating the index of the item to be destroyed in
# its pane.
#
# Returns a {Disposable} on which `.dispose` can be called to unsubscribe.
onWillDestroyPaneItem: (callback) -> @paneContainer.onWillDestroyPaneItem(callback)
# Extended: Invoke the given callback when a pane item is destroyed.
#
# * `callback` {Function} to be called when pane items are destroyed.
# * `event` {Object} with the following keys:
# * `item` The destroyed item.
# * `pane` {Pane} containing the destroyed item.
# * `index` {Number} indicating the index of the destroyed item in its
# pane.
#
# Returns a {Disposable} on which `.dispose` can be called to unsubscribe.
onDidDestroyPaneItem: (callback) -> @paneContainer.onDidDestroyPaneItem(callback)
# Extended: Invoke the given callback when a text editor is added to the
# workspace.
#
# * `callback` {Function} to be called panes are added.
# * `event` {Object} with the following keys:
# * `textEditor` {TextEditor} that was added.
# * `pane` {Pane} containing the added text editor.
# * `index` {Number} indicating the index of the added text editor in its
# pane.
#
# Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidAddTextEditor: (callback) ->
@emitter.on 'did-add-text-editor', callback
###
Section: Opening
###
# Essential: Opens the given URI in Atom asynchronously.
# If the URI is already open, the existing item for that URI will be
# activated. If no URI is given, or no registered opener can open
# the URI, a new empty {TextEditor} will be created.
#
# * `uri` (optional) A {String} containing a URI.
# * `options` (optional) {Object}
# * `initialLine` A {Number} indicating which row to move the cursor to
# initially. Defaults to `0`.
# * `initialColumn` A {Number} indicating which column to move the cursor to
# initially. Defaults to `0`.
# * `split` Either 'left', 'right', 'up' or 'down'.
# If 'left', the item will be opened in leftmost pane of the current active pane's row.
# If 'right', the item will be opened in the rightmost pane of the current active pane's row. If only one pane exists in the row, a new pane will be created.
# If 'up', the item will be opened in topmost pane of the current active pane's column.
# If 'down', the item will be opened in the bottommost pane of the current active pane's column. If only one pane exists in the column, a new pane will be created.
# * `activatePane` A {Boolean} indicating whether to call {Pane::activate} on
# containing pane. Defaults to `true`.
# * `activateItem` A {Boolean} indicating whether to call {Pane::activateItem}
# on containing pane. Defaults to `true`.
# * `pending` A {Boolean} indicating whether or not the item should be opened
# in a pending state. Existing pending items in a pane are replaced with
# new pending items when they are opened.
# * `searchAllPanes` A {Boolean}. If `true`, the workspace will attempt to
# activate an existing item for the given URI on any pane.
# If `false`, only the active pane will be searched for
# an existing item for the same URI. Defaults to `false`.
#
# Returns a {Promise} that resolves to the {TextEditor} for the file URI.
open: (uri, options={}) ->
searchAllPanes = options.searchAllPanes
split = options.split
uri = @project.resolvePath(uri)
if not atom.config.get('core.allowPendingPaneItems')
options.pending = false
# Avoid adding URLs as recent documents to work-around this Spotlight crash:
# https://github.com/atom/atom/issues/10071
if uri? and not url.parse(uri).protocol?
@applicationDelegate.addRecentDocument(uri)
pane = @paneContainer.paneForURI(uri) if searchAllPanes
pane ?= switch split
when 'left'
@getActivePane().findLeftmostSibling()
when 'right'
@getActivePane().findOrCreateRightmostSibling()
when 'up'
@getActivePane().findTopmostSibling()
when 'down'
@getActivePane().findOrCreateBottommostSibling()
else
@getActivePane()
@openURIInPane(uri, pane, options)
# Open Atom's license in the active pane.
openLicense: ->
@open(path.join(process.resourcesPath, 'LICENSE.md'))
# Synchronously open the given URI in the active pane. **Only use this method
# in specs. Calling this in production code will block the UI thread and
# everyone will be mad at you.**
#
# * `uri` A {String} containing a URI.
# * `options` An optional options {Object}
# * `initialLine` A {Number} indicating which row to move the cursor to
# initially. Defaults to `0`.
# * `initialColumn` A {Number} indicating which column to move the cursor to
# initially. Defaults to `0`.
# * `activatePane` A {Boolean} indicating whether to call {Pane::activate} on
# the containing pane. Defaults to `true`.
# * `activateItem` A {Boolean} indicating whether to call {Pane::activateItem}
# on containing pane. Defaults to `true`.
openSync: (uri='', options={}) ->
{initialLine, initialColumn} = options
activatePane = options.activatePane ? true
activateItem = options.activateItem ? true
uri = @project.resolvePath(uri)
item = @getActivePane().itemForURI(uri)
if uri
item ?= opener(uri, options) for opener in @getOpeners() when not item
item ?= @project.openSync(uri, {initialLine, initialColumn})
@getActivePane().activateItem(item) if activateItem
@itemOpened(item)
@getActivePane().activate() if activatePane
item
openURIInPane: (uri, pane, options={}) ->
activatePane = options.activatePane ? true
activateItem = options.activateItem ? true
if uri?
if item = pane.itemForURI(uri)
pane.clearPendingItem() if not options.pending and pane.getPendingItem() is item
item ?= opener(uri, options) for opener in @getOpeners() when not item
try
item ?= @openTextFile(uri, options)
catch error
switch error.code
when 'CANCELLED'
return Promise.resolve()
when 'EACCES'
@notificationManager.addWarning("Permission denied '#{error.path}'")
return Promise.resolve()
when 'EPERM', 'EBUSY', 'ENXIO', 'EIO', 'ENOTCONN', 'UNKNOWN', 'ECONNRESET', 'EINVAL', 'EMFILE', 'ENOTDIR', 'EAGAIN'
@notificationManager.addWarning("Unable to open '#{error.path ? uri}'", detail: error.message)
return Promise.resolve()
else
throw error
Promise.resolve(item)
.then (item) =>
return item if pane.isDestroyed()
@itemOpened(item)
pane.activateItem(item, {pending: options.pending}) if activateItem
pane.activate() if activatePane
initialLine = initialColumn = 0
unless Number.isNaN(options.initialLine)
initialLine = options.initialLine
unless Number.isNaN(options.initialColumn)
initialColumn = options.initialColumn
if initialLine >= 0 or initialColumn >= 0
item.setCursorBufferPosition?([initialLine, initialColumn])
index = pane.getActiveItemIndex()
@emitter.emit 'did-open', {uri, pane, item, index}
item
openTextFile: (uri, options) ->
filePath = @project.resolvePath(uri)
if filePath?
try
fs.closeSync(fs.openSync(filePath, 'r'))
catch error
# allow ENOENT errors to create an editor for paths that dont exist
throw error unless error.code is 'ENOENT'
fileSize = fs.getSizeSync(filePath)
largeFileMode = fileSize >= 2 * 1048576 # 2MB
if fileSize >= @config.get('core.warnOnLargeFileLimit') * 1048576 # 20MB by default
choice = @applicationDelegate.confirm
message: 'Atom will be unresponsive during the loading of very large files.'
detailedMessage: "Do you still want to load this file?"
buttons: ["Proceed", "Cancel"]
if choice is 1
error = new Error
error.code = 'CANCELLED'
throw error
@project.bufferForPath(filePath, options).then (buffer) =>
@textEditorRegistry.build(Object.assign({buffer, largeFileMode, autoHeight: false}, options))
handleGrammarUsed: (grammar) ->
return unless grammar?
@packageManager.triggerActivationHook("#{grammar.packageName}:grammar-used")
# Public: Returns a {Boolean} that is `true` if `object` is a `TextEditor`.
#
# * `object` An {Object} you want to perform the check against.
isTextEditor: (object) ->
object instanceof TextEditor
# Extended: Create a new text editor.
#
# Returns a {TextEditor}.
buildTextEditor: (params) ->
editor = @textEditorRegistry.build(params)
subscriptions = new CompositeDisposable(
@textEditorRegistry.maintainGrammar(editor)
@textEditorRegistry.maintainConfig(editor),
)
editor.onDidDestroy -> subscriptions.dispose()
editor
# Public: Asynchronously reopens the last-closed item's URI if it hasn't already been
# reopened.
#
# Returns a {Promise} that is resolved when the item is opened
reopenItem: ->
if uri = @destroyedItemURIs.pop()
@open(uri)
else
Promise.resolve()
# Public: Register an opener for a uri.
#
# When a URI is opened via {Workspace::open}, Atom loops through its registered
# opener functions until one returns a value for the given uri.
# Openers are expected to return an object that inherits from HTMLElement or
# a model which has an associated view in the {ViewRegistry}.
# A {TextEditor} will be used if no opener returns a value.
#
# ## Examples
#
# ```coffee
# atom.workspace.addOpener (uri) ->
# if path.extname(uri) is '.toml'
# return new TomlEditor(uri)
# ```
#
# * `opener` A {Function} to be called when a path is being opened.
#
# Returns a {Disposable} on which `.dispose()` can be called to remove the
# opener.
#
# Note that the opener will be called if and only if the URI is not already open
# in the current pane. The searchAllPanes flag expands the search from the
# current pane to all panes. If you wish to open a view of a different type for
# a file that is already open, consider changing the protocol of the URI. For
# example, perhaps you wish to preview a rendered version of the file `/foo/bar/baz.quux`
# that is already open in a text editor view. You could signal this by calling
# {Workspace::open} on the URI `quux-preview://foo/bar/baz.quux`. Then your opener
# can check the protocol for quux-preview and only handle those URIs that match.
addOpener: (opener) ->
@openers.push(opener)
new Disposable => _.remove(@openers, opener)
getOpeners: ->
@openers
###
Section: Pane Items
###
# Essential: Get all pane items in the workspace.
#
# Returns an {Array} of items.
getPaneItems: ->
@paneContainer.getPaneItems()
# Essential: Get the active {Pane}'s active item.
#
# Returns an pane item {Object}.
getActivePaneItem: ->
@paneContainer.getActivePaneItem()
# Essential: Get all text editors in the workspace.
#
# Returns an {Array} of {TextEditor}s.
getTextEditors: ->
@getPaneItems().filter (item) -> item instanceof TextEditor
# Essential: Get the active item if it is an {TextEditor}.
#
# Returns an {TextEditor} or `undefined` if the current active item is not an
# {TextEditor}.
getActiveTextEditor: ->
activeItem = @getActivePaneItem()
activeItem if activeItem instanceof TextEditor
# Save all pane items.
saveAll: ->
@paneContainer.saveAll()
confirmClose: (options) ->
@paneContainer.confirmClose(options)
# Save the active pane item.
#
# If the active pane item currently has a URI according to the item's
# `.getURI` method, calls `.save` on the item. Otherwise
# {::saveActivePaneItemAs} # will be called instead. This method does nothing
# if the active item does not implement a `.save` method.
saveActivePaneItem: ->
@getActivePane().saveActiveItem()
# Prompt the user for a path and save the active pane item to it.
#
# Opens a native dialog where the user selects a path on disk, then calls
# `.saveAs` on the item with the selected path. This method does nothing if
# the active item does not implement a `.saveAs` method.
saveActivePaneItemAs: ->
@getActivePane().saveActiveItemAs()
# Destroy (close) the active pane item.
#
# Removes the active pane item and calls the `.destroy` method on it if one is
# defined.
destroyActivePaneItem: ->
@getActivePane().destroyActiveItem()
###
Section: Panes
###
# Extended: Get all panes in the workspace.
#
# Returns an {Array} of {Pane}s.
getPanes: ->
@paneContainer.getPanes()
# Extended: Get the active {Pane}.
#
# Returns a {Pane}.
getActivePane: ->
@paneContainer.getActivePane()
# Extended: Make the next pane active.
activateNextPane: ->
@paneContainer.activateNextPane()
# Extended: Make the previous pane active.
activatePreviousPane: ->
@paneContainer.activatePreviousPane()
# Extended: Get the first {Pane} with an item for the given URI.
#
# * `uri` {String} uri
#
# Returns a {Pane} or `undefined` if no pane exists for the given URI.
paneForURI: (uri) ->
@paneContainer.paneForURI(uri)
# Extended: Get the {Pane} containing the given item.
#
# * `item` Item the returned pane contains.
#
# Returns a {Pane} or `undefined` if no pane exists for the given item.
paneForItem: (item) ->
@paneContainer.paneForItem(item)
# Destroy (close) the active pane.
destroyActivePane: ->
@getActivePane()?.destroy()
# Close the active pane item, or the active pane if it is empty,
# or the current window if there is only the empty root pane.
closeActivePaneItemOrEmptyPaneOrWindow: ->
if @getActivePaneItem()?
@destroyActivePaneItem()
else if @getPanes().length > 1
@destroyActivePane()
else if @config.get('core.closeEmptyWindows')
atom.close()
# Increase the editor font size by 1px.
increaseFontSize: ->
@config.set("editor.fontSize", @config.get("editor.fontSize") + 1)
# Decrease the editor font size by 1px.
decreaseFontSize: ->
fontSize = @config.get("editor.fontSize")
@config.set("editor.fontSize", fontSize - 1) if fontSize > 1
# Restore to the window's original editor font size.
resetFontSize: ->
if @originalFontSize
@config.set("editor.fontSize", @originalFontSize)
subscribeToFontSize: ->
@config.onDidChange 'editor.fontSize', ({oldValue}) =>
@originalFontSize ?= oldValue
# Removes the item's uri from the list of potential items to reopen.
itemOpened: (item) ->
if typeof item.getURI is 'function'
uri = item.getURI()
else if typeof item.getUri is 'function'
uri = item.getUri()
if uri?
_.remove(@destroyedItemURIs, uri)
# Adds the destroyed item's uri to the list of items to reopen.
didDestroyPaneItem: ({item}) =>
if typeof item.getURI is 'function'
uri = item.getURI()
else if typeof item.getUri is 'function'
uri = item.getUri()
if uri?
@destroyedItemURIs.push(uri)
# Called by Model superclass when destroyed
destroyed: ->
@paneContainer.destroy()
@activeItemSubscriptions?.dispose()
###
Section: Panels
Panels are used to display UI related to an editor window. They are placed at one of the four
edges of the window: left, right, top or bottom. If there are multiple panels on the same window
edge they are stacked in order of priority: higher priority is closer to the center, lower
priority towards the edge.
*Note:* If your panel changes its size throughout its lifetime, consider giving it a higher
priority, allowing fixed size panels to be closer to the edge. This allows control targets to
remain more static for easier targeting by users that employ mice or trackpads. (See
[atom/atom#4834](https://github.com/atom/atom/issues/4834) for discussion.)
###
# Essential: Get an {Array} of all the panel items at the bottom of the editor window.
getBottomPanels: ->
@getPanels('bottom')
# Essential: Adds a panel item to the bottom of the editor window.
#
# * `options` {Object}
# * `item` Your panel content. It can be DOM element, a jQuery element, or
# a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
# latter. See {ViewRegistry::addViewProvider} for more information.
# * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
# (default: true)
# * `priority` (optional) {Number} Determines stacking order. Lower priority items are
# forced closer to the edges of the window. (default: 100)
#
# Returns a {Panel}
addBottomPanel: (options) ->
@addPanel('bottom', options)
# Essential: Get an {Array} of all the panel items to the left of the editor window.
getLeftPanels: ->
@getPanels('left')
# Essential: Adds a panel item to the left of the editor window.
#
# * `options` {Object}
# * `item` Your panel content. It can be DOM element, a jQuery element, or
# a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
# latter. See {ViewRegistry::addViewProvider} for more information.
# * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
# (default: true)
# * `priority` (optional) {Number} Determines stacking order. Lower priority items are
# forced closer to the edges of the window. (default: 100)
#
# Returns a {Panel}
addLeftPanel: (options) ->
@addPanel('left', options)
# Essential: Get an {Array} of all the panel items to the right of the editor window.
getRightPanels: ->
@getPanels('right')
# Essential: Adds a panel item to the right of the editor window.
#
# * `options` {Object}
# * `item` Your panel content. It can be DOM element, a jQuery element, or
# a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
# latter. See {ViewRegistry::addViewProvider} for more information.
# * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
# (default: true)
# * `priority` (optional) {Number} Determines stacking order. Lower priority items are
# forced closer to the edges of the window. (default: 100)
#
# Returns a {Panel}
addRightPanel: (options) ->
@addPanel('right', options)
# Essential: Get an {Array} of all the panel items at the top of the editor window.
getTopPanels: ->
@getPanels('top')
# Essential: Adds a panel item to the top of the editor window above the tabs.
#
# * `options` {Object}
# * `item` Your panel content. It can be DOM element, a jQuery element, or
# a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
# latter. See {ViewRegistry::addViewProvider} for more information.
# * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
# (default: true)
# * `priority` (optional) {Number} Determines stacking order. Lower priority items are
# forced closer to the edges of the window. (default: 100)
#
# Returns a {Panel}
addTopPanel: (options) ->
@addPanel('top', options)
# Essential: Get an {Array} of all the panel items in the header.
getHeaderPanels: ->
@getPanels('header')
# Essential: Adds a panel item to the header.
#
# * `options` {Object}
# * `item` Your panel content. It can be DOM element, a jQuery element, or
# a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
# latter. See {ViewRegistry::addViewProvider} for more information.
# * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
# (default: true)
# * `priority` (optional) {Number} Determines stacking order. Lower priority items are
# forced closer to the edges of the window. (default: 100)
#
# Returns a {Panel}
addHeaderPanel: (options) ->
@addPanel('header', options)
# Essential: Get an {Array} of all the panel items in the footer.
getFooterPanels: ->
@getPanels('footer')
# Essential: Adds a panel item to the footer.
#
# * `options` {Object}
# * `item` Your panel content. It can be DOM element, a jQuery element, or
# a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
# latter. See {ViewRegistry::addViewProvider} for more information.
# * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
# (default: true)
# * `priority` (optional) {Number} Determines stacking order. Lower priority items are
# forced closer to the edges of the window. (default: 100)
#
# Returns a {Panel}
addFooterPanel: (options) ->
@addPanel('footer', options)
# Essential: Get an {Array} of all the modal panel items
getModalPanels: ->
@getPanels('modal')
# Essential: Adds a panel item as a modal dialog.
#
# * `options` {Object}
# * `item` Your panel content. It can be a DOM element, a jQuery element, or
# a model with a view registered via {ViewRegistry::addViewProvider}. We recommend the
# model option. See {ViewRegistry::addViewProvider} for more information.
# * `visible` (optional) {Boolean} false if you want the panel to initially be hidden
# (default: true)
# * `priority` (optional) {Number} Determines stacking order. Lower priority items are
# forced closer to the edges of the window. (default: 100)
#
# Returns a {Panel}
addModalPanel: (options={}) ->
@addPanel('modal', options)
# Essential: Returns the {Panel} associated with the given item. Returns
# `null` when the item has no panel.
#
# * `item` Item the panel contains
panelForItem: (item) ->
for location, container of @panelContainers
panel = container.panelForItem(item)
return panel if panel?
null
getPanels: (location) ->
@panelContainers[location].getPanels()
addPanel: (location, options) ->
options ?= {}
@panelContainers[location].addPanel(new Panel(options))
###
Section: Searching and Replacing
###
# Public: Performs a search across all files in the workspace.
#
# * `regex` {RegExp} to search with.
# * `options` (optional) {Object}
# * `paths` An {Array} of glob patterns to search within.
# * `onPathsSearched` (optional) {Function} to be periodically called
# with number of paths searched.
# * `iterator` {Function} callback on each file found.
#
# Returns a {Promise} with a `cancel()` method that will cancel all
# of the underlying searches that were started as part of this scan.
scan: (regex, options={}, iterator) ->
if _.isFunction(options)
iterator = options
options = {}
# Find a searcher for every Directory in the project. Each searcher that is matched
# will be associated with an Array of Directory objects in the Map.
directoriesForSearcher = new Map()
for directory in @project.getDirectories()
searcher = @defaultDirectorySearcher
for directorySearcher in @directorySearchers
if directorySearcher.canSearchDirectory(directory)
searcher = directorySearcher
break
directories = directoriesForSearcher.get(searcher)
unless directories
directories = []
directoriesForSearcher.set(searcher, directories)
directories.push(directory)
# Define the onPathsSearched callback.
if _.isFunction(options.onPathsSearched)
# Maintain a map of directories to the number of search results. When notified of a new count,
# replace the entry in the map and update the total.
onPathsSearchedOption = options.onPathsSearched
totalNumberOfPathsSearched = 0
numberOfPathsSearchedForSearcher = new Map()
onPathsSearched = (searcher, numberOfPathsSearched) ->