]> git.gir.st - VimFx.git/blob - extension/lib/modes.coffee
Properly suppress keys and notifications in all modes
[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, matchText} = storage
234 changed = false
235 visibleMarkers = null
236
237 switch match.type
238 when 'full'
239 match.command.run(Object.assign({match}, args))
240
241 when 'none', 'count'
242 # Make sure notifications for counts aren’t shown.
243 vim._refreshPersistentNotification()
244
245 {char, isHintChar} = hintsMode.getChar(match, storage)
246 return true unless char
247
248 return true if storage.isMatched.byText and not isHintChar
249
250 visibleMarkers = markerContainer.addChar(char, isHintChar)
251 storage.isMatched = hintsMode.isMatched(visibleMarkers, markerContainer)
252
253 if (storage.isMatched.byHint and isHintChar) or
254 (storage.isMatched.byText and not isHintChar and
255 vim.options['hints.auto_activate'])
256 hintsMode.activateMatch(
257 vim, storage, match, visibleMarkers, callback
258 )
259
260 unless isHintChar
261 vim._parent.ignoreKeyEventsUntilTime =
262 Date.now() + vim.options['hints.timeout']
263
264 return true
265
266 }, {
267 exit: ({vim}) ->
268 vim._enterMode('normal')
269
270 activate_highlighted: ({vim, storage, match}) ->
271 {markerContainer: {markers, highlightedMarkers}, callback} = storage
272 return if highlightedMarkers.length == 0
273
274 for marker in markers when marker.visible
275 marker.hide() unless marker in highlightedMarkers
276
277 hintsMode.activateMatch(
278 vim, storage, match, highlightedMarkers, callback
279 )
280
281 rotate_markers_forward: ({storage}) ->
282 storage.markerContainer.rotateOverlapping(true)
283
284 rotate_markers_backward: ({storage}) ->
285 storage.markerContainer.rotateOverlapping(false)
286
287 delete_char: ({storage}) ->
288 {markerContainer} = storage
289 visibleMarkers = markerContainer.deleteChar()
290 storage.isMatched =
291 hintsMode.isMatched(visibleMarkers or [], markerContainer)
292
293 increase_count: ({storage}) ->
294 storage.count += 1
295 # Uncomment this line if you want to use `gulp hints.html`!
296 # utils.writeToClipboard(storage.markerContainer.container.outerHTML)
297
298 toggle_complementary: ({storage}) ->
299 storage.markerContainer.toggleComplementary()
300 })
301
302
303
304 mode('ignore', {
305 onEnter: ({vim, storage}, {count = null, type = null} = {}) ->
306 storage.count = count
307
308 # Keep last `.type` if no type was given. This is useful when returning to
309 # Ignore mode after runnning the `unquote` command.
310 if type
311 storage.type = type
312 else
313 storage.type ?= 'explicit'
314
315 onLeave: ({vim, storage}) ->
316 unless storage.count? or storage.type == 'focusType'
317 vim._run('blur_active_element')
318
319 onInput: (args, match) ->
320 {vim, storage} = args
321 args.count = 1
322
323 switch storage.count
324 when null
325 switch match.type
326 when 'full'
327 match.command.run(args)
328 return true
329 when 'partial'
330 return true
331
332 # Make sure notifications for counts aren’t shown.
333 vim.hideNotification()
334 return false
335
336 when 1
337 vim._enterMode('normal')
338
339 else
340 storage.count -= 1
341
342 return false
343
344 }, {
345 exit: ({vim, storage}) ->
346 storage.type = null
347 vim._enterMode('normal')
348
349 unquote: ({vim}) ->
350 vim._enterMode('normal', {returnTo: 'ignore'})
351 })
352
353
354
355 mode('find', {
356 onEnter: ->
357
358 onLeave: ({vim}) ->
359 findBar = vim.window.gBrowser.getFindBar()
360 findStorage.lastSearchString = findBar._findField.value
361 findStorage.busy = false
362
363 onInput: (args, match) ->
364 {vim} = args
365 switch
366 when match.type == 'full'
367 args.findBar = args.vim.window.gBrowser.getFindBar()
368 match.command.run(args)
369 return true
370 when match.type == 'partial'
371 return true
372 when vim.focusType != 'findbar'
373 # If we’re in Find mode but the find bar input hasn’t been focused yet,
374 # suppress all input, because we don’t want to trigger Firefox commands,
375 # such as `/` (which opens the Quick Find bar). This happens when
376 # `helper_find_from_top_of_viewport` is slow, or when _Firefox_ is slow,
377 # for example to due to heavy page loading. The following URL is a good
378 # stress test: <https://html.spec.whatwg.org/>
379 findStorage.busy = true
380 return true
381 else
382 # At this point we know for sure that the find bar is not busy anymore.
383 findStorage.busy = false
384 return false
385
386 }, {
387 exit: ({vim, findBar}) ->
388 vim._enterMode('normal')
389 findBar.close()
390 })
391
392
393
394 mode('marks', {
395 onEnter: ({vim, storage}, callback) ->
396 storage.callback = callback
397 storage.timeoutId = vim.window.setTimeout((->
398 vim.hideNotification()
399 vim._enterMode('normal')
400 ), vim.options.timeout)
401
402 onLeave: ({vim, storage}) ->
403 storage.callback = null
404 vim.window.clearTimeout(storage.timeoutId) if storage.timeoutId?
405 storage.timeoutId = null
406
407 onInput: (args, match) ->
408 {vim, storage} = args
409 switch match.type
410 when 'full'
411 match.command.run(args)
412 when 'none', 'count'
413 storage.callback(match.keyStr)
414 vim._enterMode('normal')
415 return true
416
417 }, {
418 exit: ({vim}) ->
419 vim.hideNotification()
420 vim._enterMode('normal')
421 })
Imprint / Impressum