]> git.gir.st - VimFx.git/blob - extension/lib/modes.coffee
Remove unnecessary variables in modes.coffee
[VimFx.git] / extension / lib / modes.coffee
1 ###
2 # Copyright Simon Lydell 2014, 2015, 2016.
3 #
4 # This file is part of VimFx.
5 #
6 # VimFx is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # VimFx is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
18 ###
19
20 # This file defines VimFx’s modes, and their respective commands. The Normal
21 # mode commands are defined in commands.coffee, though.
22
23 {commands, findStorage} = require('./commands')
24 defaults = require('./defaults')
25 help = require('./help')
26 hintsMode = require('./hints-mode')
27 prefs = require('./prefs')
28 SelectionManager = require('./selection')
29 translate = require('./translate')
30 utils = require('./utils')
31
32 {FORWARD, BACKWARD} = SelectionManager
33 CARET_BROWSING_PREF = 'accessibility.browsewithcaret'
34
35 # Helper to create modes in a DRY way.
36 mode = (modeName, obj, commands = null) ->
37 obj.name = translate("mode.#{modeName}")
38 obj.order = defaults.mode_order[modeName]
39 obj.commands = {}
40 for commandName, fn of commands
41 pref = "mode.#{modeName}.#{commandName}"
42 obj.commands[commandName] = {
43 pref: defaults.BRANCH + pref
44 run: fn
45 category: defaults.categoryMap[pref]
46 description: translate(pref)
47 order: defaults.command_order[pref]
48 }
49 exports[modeName] = obj
50
51
52
53 mode('normal', {
54 onEnter: ({vim, storage}, {returnTo = null} = {}) ->
55 if returnTo
56 storage.returnTo = returnTo
57 else if storage.returnTo
58 vim._enterMode(storage.returnTo)
59 storage.returnTo = null
60
61 onLeave: ({vim}) ->
62 vim._run('clear_inputs')
63
64 onInput: (args, match) ->
65 {vim, storage, uiEvent} = args
66 {keyStr} = match
67
68 vim.hideNotification() if match.type in ['none', 'full']
69
70 if match.type == 'none' or
71 (match.likelyConflict and not match.specialKeys['<force>'])
72 match.discard()
73 if storage.returnTo
74 vim._enterMode(storage.returnTo)
75 storage.returnTo = null
76 # If you press `aa` (and `a` is a prefix key, but there’s no `aa`
77 # shortcut), don’t pass the second `a` to the page.
78 return not match.toplevel
79
80 if match.type == 'full'
81 match.command.run(args)
82
83 # If the command changed the mode, wait until coming back from that mode
84 # before switching to `storage.returnTo` if any (see `onEnter` above).
85 if storage.returnTo and vim.mode == 'normal'
86 vim._enterMode(storage.returnTo)
87 storage.returnTo = null
88
89 # At this point the match is either full, partial or part of a count. Then
90 # we always want to suppress, except for one case: The Escape key.
91 return true unless keyStr == '<escape>'
92
93 # Passing Escape through allows for stopping the loading of the page and
94 # closing many custom dialogs (and perhaps other things; Escape is a very
95 # commonly used key).
96 if uiEvent
97 # In browser UI the biggest reasons are allowing to reset the location bar
98 # when blurring it, and closing dialogs such as the “bookmark this page”
99 # dialog (<c-d>). However, an exception is made for the devtools (<c-K>).
100 # There, trying to unfocus the devtools using Escape would annoyingly
101 # open the split console.
102 return utils.isDevtoolsElement(uiEvent.originalTarget)
103 else
104 # In web pages content, an exception is made if an element that VimFx
105 # cares about is focused. That allows for blurring an input in a custom
106 # dialog without closing the dialog too.
107 return vim.focusType != 'none'
108
109 # Note that this special handling of Escape is only used in Normal mode.
110 # There are two reasons we might suppress it in other modes. If some custom
111 # dialog of a website is open, we should be able to cancel hint markers on
112 # it without closing it. Secondly, otherwise cancelling hint markers on
113 # Google causes its search bar to be focused.
114
115 }, commands)
116
117
118
119 helper_move_caret = (method, direction, {vim, storage, count = 1}) ->
120 vim._run('move_caret', {
121 method, direction, select: storage.select
122 count: if method == 'intraLineMove' then 1 else count
123 })
124
125 mode('caret', {
126 onEnter: ({vim, storage}, {select = false} = {}) ->
127 storage.select = select
128 storage.caretBrowsingPref = prefs.root.get(CARET_BROWSING_PREF)
129 prefs.root.set(CARET_BROWSING_PREF, true)
130 vim._run('enable_caret')
131
132 listener = ->
133 return unless newVim = vim._parent.getCurrentVim(vim.window)
134 prefs.root.set(
135 CARET_BROWSING_PREF,
136 if newVim.mode == 'caret' then true else storage.caretBrowsingPref
137 )
138 vim._parent.on('TabSelect', listener)
139 storage.removeListener = -> vim._parent.off('TabSelect', listener)
140
141 onLeave: ({vim, storage}) ->
142 prefs.root.set(CARET_BROWSING_PREF, storage.caretBrowsingPref)
143 vim._run('clear_selection')
144 storage.removeListener?()
145 storage.removeListener = null
146
147 onInput: (args, match) ->
148 args.vim.hideNotification()
149 switch match.type
150 when 'full'
151 match.command.run(args)
152 return true
153 when 'partial', 'count'
154 return true
155 return false
156
157 }, {
158 # coffeelint: disable=colon_assignment_spacing
159 move_left: helper_move_caret.bind(null, 'characterMove', BACKWARD)
160 move_right: helper_move_caret.bind(null, 'characterMove', FORWARD)
161 move_down: helper_move_caret.bind(null, 'lineMove', FORWARD)
162 move_up: helper_move_caret.bind(null, 'lineMove', BACKWARD)
163 move_word_left: helper_move_caret.bind(null, 'wordMoveAdjusted', BACKWARD)
164 move_word_right: helper_move_caret.bind(null, 'wordMoveAdjusted', FORWARD)
165 move_to_line_start: helper_move_caret.bind(null, 'intraLineMove', BACKWARD)
166 move_to_line_end: helper_move_caret.bind(null, 'intraLineMove', FORWARD)
167 # coffeelint: enable=colon_assignment_spacing
168
169 toggle_selection: ({vim, storage}) ->
170 storage.select = not storage.select
171 if storage.select
172 vim.notify(translate('notification.toggle_selection.enter'))
173 else
174 vim._run('collapse_selection')
175
176 toggle_selection_direction: ({vim}) ->
177 vim._run('toggle_selection_direction')
178
179 copy_selection_and_exit: ({vim}) ->
180 vim._run('get_selection', null, (selection) ->
181 # If the selection consists of newlines only, it _looks_ as if the
182 # selection is collapsed, so don’t try to copy it in that case.
183 if /^\n*$/.test(selection)
184 vim.notify(translate('notification.copy_selection_and_exit.none'))
185 else
186 # Trigger this copying command instead of putting `selection` into the
187 # clipboard, since `window.getSelection().toString()` sadly collapses
188 # whitespace in `<pre>` elements.
189 vim.window.goDoCommand('cmd_copy')
190 vim._enterMode('normal')
191 )
192
193 exit: ({vim}) ->
194 vim._enterMode('normal')
195 })
196
197
198
199 mode('hints', {
200 onEnter: ({vim, storage}, options) ->
201 {
202 markerContainer, callback, matchText = true, count = 1, sleep = -1
203 } = options
204 storage.markerContainer = markerContainer
205 storage.callback = callback
206 storage.matchText = matchText
207 storage.count = count
208 storage.isMatched = {byText: false, byHint: false}
209 storage.skipOnLeaveCleanup = false
210
211 if matchText
212 markerContainer.visualFeedbackUpdater =
213 hintsMode.updateVisualFeedback.bind(null, vim)
214 vim._run('clear_selection')
215
216 if sleep >= 0
217 storage.clearInterval = utils.interval(vim.window, sleep, (next) ->
218 if markerContainer.markers.length == 0
219 next()
220 return
221 vim._send('getMarkableElementsMovements', null, (diffs) ->
222 for {dx, dy}, index in diffs when not (dx == 0 and dy == 0)
223 markerContainer.markerMap[index].updatePosition(dx, dy)
224 next()
225 )
226 )
227
228 onLeave: ({vim, storage}) ->
229 hintsMode.cleanup(vim, storage) unless storage.skipOnLeaveCleanup
230
231 onInput: (args, match) ->
232 {vim, storage} = args
233 {markerContainer, callback} = storage
234
235 switch match.type
236 when 'full'
237 match.command.run(Object.assign({match}, args))
238
239 when 'none', 'count'
240 # Make sure notifications for counts aren’t shown.
241 vim._refreshPersistentNotification()
242
243 {char, isHintChar} = hintsMode.getChar(match, storage)
244 return true unless char
245
246 return true if storage.isMatched.byText and not isHintChar
247
248 visibleMarkers = markerContainer.addChar(char, isHintChar)
249 storage.isMatched = hintsMode.isMatched(visibleMarkers, markerContainer)
250
251 if (storage.isMatched.byHint and isHintChar) or
252 (storage.isMatched.byText and not isHintChar and
253 vim.options['hints.auto_activate'])
254 hintsMode.activateMatch(
255 vim, storage, match, visibleMarkers, callback
256 )
257
258 unless isHintChar
259 vim._parent.ignoreKeyEventsUntilTime =
260 Date.now() + vim.options['hints.timeout']
261
262 return true
263
264 }, {
265 exit: ({vim}) ->
266 vim._enterMode('normal')
267
268 activate_highlighted: ({vim, storage, match}) ->
269 {markerContainer: {markers, highlightedMarkers}, callback} = storage
270 return if highlightedMarkers.length == 0
271
272 for marker in markers when marker.visible
273 marker.hide() unless marker in highlightedMarkers
274
275 hintsMode.activateMatch(
276 vim, storage, match, highlightedMarkers, callback
277 )
278
279 rotate_markers_forward: ({storage}) ->
280 storage.markerContainer.rotateOverlapping(true)
281
282 rotate_markers_backward: ({storage}) ->
283 storage.markerContainer.rotateOverlapping(false)
284
285 delete_char: ({storage}) ->
286 {markerContainer} = storage
287 visibleMarkers = markerContainer.deleteChar()
288 storage.isMatched =
289 hintsMode.isMatched(visibleMarkers or [], markerContainer)
290
291 increase_count: ({storage}) ->
292 storage.count += 1
293 # Uncomment this line if you want to use `gulp hints.html`!
294 # utils.writeToClipboard(storage.markerContainer.container.outerHTML)
295
296 toggle_complementary: ({storage}) ->
297 storage.markerContainer.toggleComplementary()
298 })
299
300
301
302 mode('ignore', {
303 onEnter: ({vim, storage}, {count = null, type = null} = {}) ->
304 storage.count = count
305
306 # Keep last `.type` if no type was given. This is useful when returning to
307 # Ignore mode after runnning the `unquote` command.
308 if type
309 storage.type = type
310 else
311 storage.type ?= 'explicit'
312
313 onLeave: ({vim, storage}) ->
314 unless storage.count? or storage.type == 'focusType'
315 vim._run('blur_active_element')
316
317 onInput: (args, match) ->
318 {vim, storage} = args
319 args.count = 1
320
321 switch storage.count
322 when null
323 switch match.type
324 when 'full'
325 match.command.run(args)
326 return true
327 when 'partial'
328 return true
329
330 # Make sure notifications for counts aren’t shown.
331 vim.hideNotification()
332 return false
333
334 when 1
335 vim._enterMode('normal')
336
337 else
338 storage.count -= 1
339
340 return false
341
342 }, {
343 exit: ({vim, storage}) ->
344 storage.type = null
345 vim._enterMode('normal')
346
347 unquote: ({vim}) ->
348 vim._enterMode('normal', {returnTo: 'ignore'})
349 })
350
351
352
353 mode('find', {
354 onEnter: ->
355
356 onLeave: ({vim}) ->
357 findBar = vim.window.gBrowser.getFindBar()
358 findStorage.lastSearchString = findBar._findField.value
359 findStorage.busy = false
360
361 onInput: (args, match) ->
362 {vim} = args
363 switch
364 when match.type == 'full'
365 args.findBar = args.vim.window.gBrowser.getFindBar()
366 match.command.run(args)
367 return true
368 when match.type == 'partial'
369 return true
370 when vim.focusType != 'findbar'
371 # If we’re in Find mode but the find bar input hasn’t been focused yet,
372 # suppress all input, because we don’t want to trigger Firefox commands,
373 # such as `/` (which opens the Quick Find bar). This happens when
374 # `helper_find_from_top_of_viewport` is slow, or when _Firefox_ is slow,
375 # for example to due to heavy page loading. The following URL is a good
376 # stress test: <https://html.spec.whatwg.org/>
377 findStorage.busy = true
378 return true
379 else
380 # At this point we know for sure that the find bar is not busy anymore.
381 findStorage.busy = false
382 return false
383
384 }, {
385 exit: ({vim, findBar}) ->
386 vim._enterMode('normal')
387 findBar.close()
388 })
389
390
391
392 mode('marks', {
393 onEnter: ({vim, storage}, callback) ->
394 storage.callback = callback
395 storage.timeoutId = vim.window.setTimeout((->
396 vim.hideNotification()
397 vim._enterMode('normal')
398 ), vim.options.timeout)
399
400 onLeave: ({vim, storage}) ->
401 storage.callback = null
402 vim.window.clearTimeout(storage.timeoutId) if storage.timeoutId?
403 storage.timeoutId = null
404
405 onInput: (args, match) ->
406 {vim, storage} = args
407 switch match.type
408 when 'full'
409 match.command.run(args)
410 when 'none', 'count'
411 storage.callback(match.keyStr)
412 vim._enterMode('normal')
413 return true
414
415 }, {
416 exit: ({vim}) ->
417 vim.hideNotification()
418 vim._enterMode('normal')
419 })
Imprint / Impressum