]> git.gir.st - VimFx.git/blob - extension/lib/modes.coffee
Correctly suppress keys between `/` and find bar focus
[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 if match.type == 'full'
150 match.command.run(args)
151 return true
152 return false
153
154 }, {
155 # coffeelint: disable=colon_assignment_spacing
156 move_left: helper_move_caret.bind(null, 'characterMove', BACKWARD)
157 move_right: helper_move_caret.bind(null, 'characterMove', FORWARD)
158 move_down: helper_move_caret.bind(null, 'lineMove', FORWARD)
159 move_up: helper_move_caret.bind(null, 'lineMove', BACKWARD)
160 move_word_left: helper_move_caret.bind(null, 'wordMoveAdjusted', BACKWARD)
161 move_word_right: helper_move_caret.bind(null, 'wordMoveAdjusted', FORWARD)
162 move_to_line_start: helper_move_caret.bind(null, 'intraLineMove', BACKWARD)
163 move_to_line_end: helper_move_caret.bind(null, 'intraLineMove', FORWARD)
164 # coffeelint: enable=colon_assignment_spacing
165
166 toggle_selection: ({vim, storage}) ->
167 storage.select = not storage.select
168 if storage.select
169 vim.notify(translate('notification.toggle_selection.enter'))
170 else
171 vim._run('collapse_selection')
172
173 toggle_selection_direction: ({vim}) ->
174 vim._run('toggle_selection_direction')
175
176 copy_selection_and_exit: ({vim}) ->
177 vim._run('get_selection', null, (selection) ->
178 # If the selection consists of newlines only, it _looks_ as if the
179 # selection is collapsed, so don’t try to copy it in that case.
180 if /^\n*$/.test(selection)
181 vim.notify(translate('notification.copy_selection_and_exit.none'))
182 else
183 # Trigger this copying command instead of putting `selection` into the
184 # clipboard, since `window.getSelection().toString()` sadly collapses
185 # whitespace in `<pre>` elements.
186 vim.window.goDoCommand('cmd_copy')
187 vim._enterMode('normal')
188 )
189
190 exit: ({vim}) ->
191 vim._enterMode('normal')
192 })
193
194
195
196 mode('hints', {
197 onEnter: ({vim, storage}, options) ->
198 {
199 markerContainer, callback, matchText = true, count = 1, sleep = -1
200 } = options
201 storage.markerContainer = markerContainer
202 storage.callback = callback
203 storage.matchText = matchText
204 storage.count = count
205 storage.skipOnLeaveCleanup = false
206
207 if matchText
208 markerContainer.visualFeedbackUpdater =
209 hintsMode.updateVisualFeedback.bind(null, vim)
210 vim._run('clear_selection')
211
212 if sleep >= 0
213 storage.clearInterval = utils.interval(vim.window, sleep, (next) ->
214 if markerContainer.markers.length == 0
215 next()
216 return
217 vim._send('getMarkableElementsMovements', null, (diffs) ->
218 for {dx, dy}, index in diffs when not (dx == 0 and dy == 0)
219 markerContainer.markerMap[index].updatePosition(dx, dy)
220 next()
221 )
222 )
223
224 onLeave: ({vim, storage}) ->
225 hintsMode.cleanup(vim, storage) unless storage.skipOnLeaveCleanup
226
227 onInput: (args, match) ->
228 {vim, storage} = args
229 {markerContainer, callback, matchText} = storage
230 changed = false
231 visibleMarkers = null
232
233 if match.type == 'full'
234 match.command.run(Object.assign({match}, args))
235
236 else
237 {char, isHintChar} = hintsMode.getChar(match, storage)
238 return true unless char
239
240 visibleMarkers = markerContainer.addChar(char, isHintChar)
241
242 if (vim.options['hints.auto_activate'] or isHintChar) and
243 new Set(visibleMarkers.map((marker) -> marker.hint)).size == 1
244 hintsMode.activateMatch(
245 vim, storage, match, visibleMarkers, callback
246 )
247
248 unless isHintChar
249 vim._parent.ignoreKeyEventsUntilTime =
250 Date.now() + vim.options['hints.timeout']
251
252 return true
253
254 }, {
255 exit: ({vim}) ->
256 vim._enterMode('normal')
257
258 activate_highlighted: ({vim, storage, match}) ->
259 {markerContainer: {markers, highlightedMarkers}, callback} = storage
260 return if highlightedMarkers.length == 0
261
262 for marker in markers when marker.visible
263 marker.hide() unless marker in highlightedMarkers
264
265 hintsMode.activateMatch(
266 vim, storage, match, highlightedMarkers, callback
267 )
268
269 rotate_markers_forward: ({storage}) ->
270 storage.markerContainer.rotateOverlapping(true)
271
272 rotate_markers_backward: ({storage}) ->
273 storage.markerContainer.rotateOverlapping(false)
274
275 delete_char: ({storage}) ->
276 storage.markerContainer.deleteChar()
277
278 increase_count: ({storage}) ->
279 storage.count += 1
280 # Uncomment this line if you want to use `gulp hints.html`!
281 # utils.writeToClipboard(storage.markerContainer.container.outerHTML)
282
283 toggle_complementary: ({storage}) ->
284 storage.markerContainer.toggleComplementary()
285 })
286
287
288
289 mode('ignore', {
290 onEnter: ({vim, storage}, {count = null, type = null} = {}) ->
291 storage.count = count
292
293 # Keep last `.type` if no type was given. This is useful when returning to
294 # Ignore mode after runnning the `unquote` command.
295 if type
296 storage.type = type
297 else
298 storage.type ?= 'explicit'
299
300 onLeave: ({vim, storage}) ->
301 unless storage.count? or storage.type == 'focusType'
302 vim._run('blur_active_element')
303
304 onInput: (args, match) ->
305 {vim, storage} = args
306 args.count = 1
307 switch storage.count
308 when null
309 if match.type == 'full'
310 match.command.run(args)
311 return true
312 when 1
313 vim._enterMode('normal')
314 else
315 storage.count -= 1
316 return false
317
318 }, {
319 exit: ({vim, storage}) ->
320 storage.type = null
321 vim._enterMode('normal')
322 unquote: ({vim}) ->
323 vim._enterMode('normal', {returnTo: 'ignore'})
324 })
325
326
327
328 mode('find', {
329 onEnter: ->
330
331 onLeave: ({vim}) ->
332 findBar = vim.window.gBrowser.getFindBar()
333 findStorage.lastSearchString = findBar._findField.value
334 findStorage.busy = false
335
336 onInput: (args, match) ->
337 {vim} = args
338 switch
339 when match.type == 'full'
340 args.findBar = args.vim.window.gBrowser.getFindBar()
341 match.command.run(args)
342 return true
343 when vim.focusType != 'findbar'
344 # If we’re in Find mode but the find bar input hasn’t been focused yet,
345 # suppress all input, because we don’t want to trigger Firefox commands,
346 # such as `/` (which opens the Quick Find bar). This happens when
347 # `helper_find_from_top_of_viewport` is slow, or when _Firefox_ is slow,
348 # for example to due to heavy page loading. The following URL is a good
349 # stress test: <https://html.spec.whatwg.org/>
350 findStorage.busy = true
351 return true
352 else
353 # At this point we know for sure that the find bar is not busy anymore.
354 findStorage.busy = false
355 return false
356
357 }, {
358 exit: ({vim, findBar}) ->
359 vim._enterMode('normal')
360 findBar.close()
361 })
362
363
364
365 mode('marks', {
366 onEnter: ({vim, storage}, callback) ->
367 storage.callback = callback
368 storage.timeoutId = vim.window.setTimeout((->
369 vim.hideNotification()
370 vim._enterMode('normal')
371 ), vim.options.timeout)
372
373 onLeave: ({vim, storage}) ->
374 storage.callback = null
375 vim.window.clearTimeout(storage.timeoutId) if storage.timeoutId?
376 storage.timeoutId = null
377
378 onInput: (args, match) ->
379 {vim, storage} = args
380 if match.type == 'full'
381 match.command.run(args)
382 else
383 storage.callback(match.keyStr)
384 vim._enterMode('normal')
385 return true
386 }, {
387 exit: ({vim}) ->
388 vim.hideNotification()
389 vim._enterMode('normal')
390 })
Imprint / Impressum