This repository has been archived by the owner on Mar 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 180
/
editor-proxy.coffee
238 lines (200 loc) · 8.04 KB
/
editor-proxy.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
{Point, Range} = require 'atom'
path = require 'path'
emmet = require 'emmet'
utils = require 'emmet/lib/utils/common'
tabStops = require 'emmet/lib/assets/tabStops'
resources = require 'emmet/lib/assets/resources'
editorUtils = require 'emmet/lib/utils/editor'
actionUtils = require 'emmet/lib/utils/action'
insertSnippet = (snippet, editor) ->
atom.packages.getLoadedPackage('snippets')?.mainModule?.insert(snippet, editor)
# Fetch expansions and assign to editor
editor.snippetExpansion = atom.packages.getLoadedPackage('snippets')?.mainModule?.getExpansions(editor)[0]
visualize = (str) ->
str
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\s/g, '\\s')
# Normalizes text before it goes to editor: replaces indentation
# and newlines with ones used in editor
# @param {String} text Text to normalize
# @param {Editor} editor Brackets editor instance
# @return {String}
normalize = (text, editor) ->
editorUtils.normalize text,
indentation: editor.getTabText(),
newline: '\n'
# Proprocess text data that should be used as snippet content
# Currently, Atom’s snippets implementation has the following issues:
# * multiple $0 are not treated as distinct final tabstops
preprocessSnippet = (value) ->
order = []
tabstopOptions =
tabstop: (data) ->
group = parseInt(data.group, 10)
if group is 0
order.push(-1)
group = order.length
else
order.push(group) if order.indexOf(group) is -1
group = order.indexOf(group) + 1
placeholder = data.placeholder or ''
if placeholder
# recursively update nested tabstops
placeholder = tabStops.processText(placeholder, tabstopOptions)
if placeholder then "${#{group}:#{placeholder}}" else "${#{group}}"
escape: (ch) ->
if ch == '$' then '\\$' else ch
tabStops.processText(value, tabstopOptions)
module.exports =
setup: (@editor, @selectionIndex=0) ->
buf = @editor.getBuffer()
bufRanges = @editor.getSelectedBufferRanges()
@_selection =
index: 0
saved: new Array(bufRanges.length)
bufferRanges: bufRanges
indexRanges: bufRanges.map (range) ->
start: buf.characterIndexForPosition(range.start)
end: buf.characterIndexForPosition(range.end)
# Executes given function for every selection
exec: (fn) ->
ix = @_selection.bufferRanges.length - 1
@_selection.saved = []
success = true
while ix >= 0
@_selection.index = ix
if fn(@_selection.index) is false
success = false
break
ix--
if success and @_selection.saved.length > 1
@_setSelectedBufferRanges(@_selection.saved)
_setSelectedBufferRanges: (sels) ->
filteredSels = sels.filter (s) -> !!s
if filteredSels.length
@editor.setSelectedBufferRanges(filteredSels)
_saveSelection: (delta) ->
@_selection.saved[@_selection.index] = @editor.getSelectedBufferRange()
if delta
i = @_selection.index
delta = Point.fromObject([delta, 0])
while ++i < @_selection.saved.length
range = @_selection.saved[i]
if range
@_selection.saved[i] = new Range(range.start.translate(delta), range.end.translate(delta))
selectionList: ->
@_selection.indexRanges
# Returns the current caret position.
getCaretPos: ->
@getSelectionRange().start
# Sets the current caret position.
setCaretPos: (pos) ->
@createSelection(pos)
# Fetches the character indexes of the selected text.
# Returns an {Object} with `start` and `end` properties.
getSelectionRange: ->
@_selection.indexRanges[@_selection.index]
getSelectionBufferRange: ->
@_selection.bufferRanges[@_selection.index]
# Creates a selection from the `start` to `end` character indexes.
#
# If `end` is ommited, this method should place a caret at the `start` index.
#
# start - A {Number} representing the starting character index
# end - A {Number} representing the ending character index
createSelection: (start, end=start) ->
sels = @_selection.bufferRanges
buf = @editor.getBuffer()
sels[@_selection.index] = new Range(buf.positionForCharacterIndex(start), buf.positionForCharacterIndex(end))
@_setSelectedBufferRanges(sels)
# Returns the currently selected text.
getSelection: ->
@editor.getTextInBufferRange(@getSelectionBufferRange())
# Fetches the current line's start and end indexes.
#
# Returns an {Object} with `start` and `end` properties
getCurrentLineRange: ->
sel = @getSelectionBufferRange()
row = sel.getRows()[0]
lineLength = @editor.lineTextForBufferRow(row).length
index = @editor.getBuffer().characterIndexForPosition({row: row, column: 0})
return {
start: index
end: index + lineLength
}
# Returns the current line.
getCurrentLine: ->
sel = @getSelectionBufferRange()
row = sel.getRows()[0]
return @editor.lineTextForBufferRow(row)
# Returns the editor content.
getContent: ->
return @editor.getText()
# Replace the editor's content (or part of it, if using `start` to
# `end` index).
#
# If `value` contains `caret_placeholder`, the editor puts a caret into
# this position. If you skip the `start` and `end` arguments, the whole target's
# content is replaced with `value`.
#
# If you pass just the `start` argument, the `value` is placed at the `start` string
# index of thr current content.
#
# If you pass both `start` and `end` arguments, the corresponding substring of
# the current target's content is replaced with `value`.
#
# value - A {String} of content you want to paste
# start - The optional start index {Number} of the editor's content
# end - The optional end index {Number} of the editor's content
# noIdent - An optional {Boolean} which, if `true`, does not attempt to auto indent `value`
replaceContent: (value, start, end, noIndent) ->
unless end?
end = unless start? then @getContent().length else start
start = 0 unless start?
value = normalize(value, @editor)
buf = @editor.getBuffer()
changeRange = new Range(
Point.fromObject(buf.positionForCharacterIndex(start)),
Point.fromObject(buf.positionForCharacterIndex(end))
)
oldValue = @editor.getTextInBufferRange(changeRange)
buf.setTextInRange(changeRange, '')
# Before inserting snippet we have to reset all available selections
# to insert snippent right in required place. Otherwise snippet
# will be inserted for each selection in editor
# Right after that we should save first available selection as buffer range
caret = buf.positionForCharacterIndex(start)
@editor.setSelectedBufferRange(new Range(caret, caret))
insertSnippet preprocessSnippet(value), @editor
@_saveSelection(utils.splitByLines(value).length - utils.splitByLines(oldValue).length)
value
getGrammar: ->
@editor.getGrammar().scopeName.toLowerCase()
# Returns the editor's syntax mode.
getSyntax: ->
scope = @getCurrentScope().join(' ')
return 'xsl' if ~scope.indexOf('xsl')
return 'jsx' if not /\bstring\b/.test(scope) && /\bsource\.(js|ts)x?\b/.test(scope)
sourceSyntax = scope.match(/\bsource\.([\w\-]+)/)?[0]
if not /\bstring\b/.test(scope) && sourceSyntax && resources.hasSyntax(sourceSyntax)
syntax = sourceSyntax;
else
# probe syntax based on current selector
m = scope.match(/\b(source|text)\.[\w\-\.]+/)
syntax = m?[0].split('.').reduceRight (result, token) ->
result or (token if resources.hasSyntax token)
, null
actionUtils.detectSyntax(@, syntax or 'html')
getCurrentScope: ->
range = @_selection.bufferRanges[@_selection.index]
@editor.scopeDescriptorForBufferPosition(range.start).getScopesArray()
# Returns the current output profile name
#
# See emmet.setupProfile for more information.
getProfileName: ->
return if @getCurrentScope().some((scope) -> /\bstring\.quoted\b/.test scope) then 'line' else actionUtils.detectProfile(@)
# Returns the current editor's file path
getFilePath: ->
# is there a better way to get this?
@editor.buffer.file.path