]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Use strings instead of functions in the `modes` object
[VimFx.git] / extension / lib / commands.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
4 # Copyright Wang Zhuochun 2013, 2014.
5 #
6 # This file is part of VimFx.
7 #
8 # VimFx is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # VimFx is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
20 ###
21
22 # This file defines all Normal mode commands. Commands that need to interact
23 # with web page content do so by running `vim._run(name)`, which invokes `name`
24 # in commands-frame.coffee.
25
26 # NOTE: Most tab related commands need to do their actual tab manipulations in
27 # the next tick (`utils.nextTick`) to work around bug 1200334.
28
29 help = require('./help')
30 hints = require('./hints')
31 prefs = require('./prefs')
32 translate = require('./l10n')
33 utils = require('./utils')
34
35 commands = {}
36
37
38
39 commands.focus_location_bar = ({vim}) ->
40 vim.window.focusAndSelectUrlBar()
41
42 commands.focus_search_bar = ({vim, count}) ->
43 # The `.webSearch()` method opens a search engine in a tab if the search bar
44 # has been removed. Therefore we first check if it exists.
45 if vim.window.BrowserSearch.searchBar
46 vim.window.BrowserSearch.webSearch()
47
48 helper_paste_and_go = (props, {vim}) ->
49 {gURLBar} = vim.window
50 gURLBar.value = vim.window.readFromClipboard()
51 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
52
53 commands.paste_and_go = helper_paste_and_go.bind(null, null)
54
55 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
56
57 commands.copy_current_url = ({vim}) ->
58 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
59 vim.notify(translate('notification.copy_current_url'))
60
61 commands.go_up_path = ({vim, count}) ->
62 vim._run('go_up_path', {count})
63
64 commands.go_to_root = ({vim}) ->
65 vim._run('go_to_root')
66
67 commands.go_home = ({vim}) ->
68 vim.window.BrowserHome()
69
70 helper_go_history = (direction, {vim, count = 1}) ->
71 {SessionStore, gBrowser} = vim.window
72
73 # TODO: When Firefox 43 is released, only use the `.getSessionHistory`
74 # version and bump the minimum Firefox version.
75 if SessionStore.getSessionHistory
76 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
77 {index} = sessionHistory
78 newIndex = index + count * (if direction == 'back' then -1 else 1)
79 newIndex = Math.max(newIndex, 0)
80 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
81 if newIndex == index
82 vim.notify(translate("notification.history_#{direction}.limit"))
83 else
84 gBrowser.gotoIndex(newIndex)
85 )
86 else
87 # Until then, fall back to a no-count version.
88 if direction == 'back' then gBrowser.goBack() else gBrowser.goForward()
89
90 commands.history_back = helper_go_history.bind(null, 'back')
91
92 commands.history_forward = helper_go_history.bind(null, 'forward')
93
94 commands.history_list = ({vim}) ->
95 menu = vim.window.document.getElementById('backForwardMenu')
96 utils.openPopup(menu)
97 vim.notify(translate('notification.history_list.none')) unless menu.open
98
99 commands.reload = ({vim}) ->
100 vim.window.BrowserReload()
101
102 commands.reload_force = ({vim}) ->
103 vim.window.BrowserReloadSkipCache()
104
105 commands.reload_all = ({vim}) ->
106 vim.window.gBrowser.reloadAllTabs()
107
108 commands.reload_all_force = ({vim}) ->
109 for tab in vim.window.gBrowser.visibleTabs
110 gBrowser = tab.linkedBrowser
111 consts = gBrowser.webNavigation
112 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
113 gBrowser.reload(flags)
114 return
115
116 commands.stop = ({vim}) ->
117 vim.window.BrowserStop()
118
119 commands.stop_all = ({vim}) ->
120 for tab in vim.window.gBrowser.visibleTabs
121 tab.linkedBrowser.stop()
122 return
123
124
125
126 helper_scroll = (vim, uiEvent, args...) ->
127 [
128 method, type, directions, amounts
129 properties = null, adjustment = 0, name = 'scroll'
130 ] = args
131 options = {
132 method, type, directions, amounts, properties, adjustment
133 smooth: (prefs.root.get('general.smoothScroll') and
134 prefs.root.get("general.smoothScroll.#{type}"))
135 }
136 reset = prefs.root.tmp(
137 'layout.css.scroll-behavior.spring-constant',
138 vim.options["smoothScroll.#{type}.spring-constant"]
139 )
140
141 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
142 if uiEvent or helpScroll
143 activeElement = helpScroll or utils.getActiveElement(vim.window)
144 if vim._state.scrollableElements.has(activeElement) or helpScroll
145 utils.scroll(activeElement, options)
146 reset()
147 return
148
149 vim._run(name, options, reset)
150
151
152 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
153 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
154 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['left'],
155 [amount * distance * count * 5])
156
157 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
158 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
159 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['top'],
160 [amount * distance * count * 20])
161
162 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
163 adjustment = prefs.get("scroll.#{type}_page_adjustment")
164 helper_scroll(vim, uiEvent, 'scrollBy', 'pages', ['top'],
165 [amount * count], ['clientHeight'], adjustment)
166
167 helper_scrollToX = (amount, {vim, uiEvent}) ->
168 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['left'],
169 [amount], ['scrollLeftMax'])
170 helper_mark_last_scroll_position(vim)
171
172 helper_scrollToY = (amount, {vim, uiEvent}) ->
173 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['top'],
174 [amount], ['scrollTopMax'])
175 helper_mark_last_scroll_position(vim)
176
177 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
178 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
179 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
180 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
181 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
182 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
183 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
184 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
185 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
186 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
187 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
188 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
189
190 helper_mark_last_scroll_position = (vim) ->
191 keyStr = vim.options['scroll.last_position_mark']
192 vim._run('mark_scroll_position', {keyStr, notify: false})
193
194 commands.mark_scroll_position = ({vim}) ->
195 vim.enterMode('marks', (keyStr) -> vim._run('mark_scroll_position', {keyStr}))
196
197 commands.scroll_to_mark = ({vim}) ->
198 vim.enterMode('marks', (keyStr) ->
199 unless keyStr == vim.options['scroll.last_position_mark']
200 helper_mark_last_scroll_position(vim)
201 helper_scroll(vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
202 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark')
203 )
204
205
206
207 commands.tab_new = ({vim}) ->
208 utils.nextTick(vim.window, ->
209 vim.window.BrowserOpenTab()
210 )
211
212 commands.tab_duplicate = ({vim}) ->
213 {gBrowser} = vim.window
214 utils.nextTick(vim.window, ->
215 gBrowser.duplicateTab(gBrowser.selectedTab)
216 )
217
218 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
219 tabs = gBrowser.visibleTabs
220 {selectedTab} = gBrowser
221
222 currentIndex = tabs.indexOf(selectedTab)
223 absoluteIndex = currentIndex + relativeIndex
224 numTabsTotal = tabs.length
225 numPinnedTabs = gBrowser._numPinnedTabs
226
227 [numTabs, min] = switch
228 when not pinnedSeparate then [numTabsTotal, 0]
229 when selectedTab.pinned then [numPinnedTabs, 0]
230 else [numTabsTotal - numPinnedTabs, numPinnedTabs]
231
232 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
233 # current direction.
234 if (relativeIndex < 0 and currentIndex == min) or
235 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
236 if absoluteIndex < min
237 absoluteIndex += numTabs
238 else if absoluteIndex >= min + numTabs
239 absoluteIndex -= numTabs
240
241 absoluteIndex = Math.max(min, absoluteIndex)
242 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
243
244 return absoluteIndex
245
246 helper_switch_tab = (direction, {vim, count = 1}) ->
247 {gBrowser} = vim.window
248 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
249 utils.nextTick(vim.window, ->
250 gBrowser.selectTabAtIndex(index)
251 )
252
253 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
254
255 commands.tab_select_next = helper_switch_tab.bind(null, +1)
256
257 commands.tab_select_most_recent = ({vim, count = 1}) ->
258 {gBrowser} = vim.window
259 tabsSorted = Array.filter(gBrowser.tabs, (tab) -> not tab.closing)
260 .sort((a, b) -> b.lastAccessed - a.lastAccessed)
261 mostRecentTab = tabsSorted[Math.min(count, tabsSorted.length - 1)]
262 gBrowser.selectedTab = mostRecentTab if mostRecentTab
263
264 helper_move_tab = (direction, {vim, count = 1}) ->
265 {gBrowser} = vim.window
266 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
267 utils.nextTick(vim.window, ->
268 gBrowser.moveTabTo(gBrowser.selectedTab, index)
269 )
270
271 commands.tab_move_backward = helper_move_tab.bind(null, -1)
272
273 commands.tab_move_forward = helper_move_tab.bind(null, +1)
274
275 commands.tab_move_to_window = ({vim}) ->
276 {gBrowser} = vim.window
277 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
278
279 commands.tab_select_first = ({vim, count = 1}) ->
280 utils.nextTick(vim.window, ->
281 vim.window.gBrowser.selectTabAtIndex(count - 1)
282 )
283
284 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
285 firstNonPinned = vim.window.gBrowser._numPinnedTabs
286 utils.nextTick(vim.window, ->
287 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
288 )
289
290 commands.tab_select_last = ({vim, count = 1}) ->
291 utils.nextTick(vim.window, ->
292 vim.window.gBrowser.selectTabAtIndex(-count)
293 )
294
295 commands.tab_toggle_pinned = ({vim}) ->
296 currentTab = vim.window.gBrowser.selectedTab
297 if currentTab.pinned
298 vim.window.gBrowser.unpinTab(currentTab)
299 else
300 vim.window.gBrowser.pinTab(currentTab)
301
302 commands.tab_close = ({vim, count = 1}) ->
303 {gBrowser} = vim.window
304 return if gBrowser.selectedTab.pinned
305 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
306 utils.nextTick(vim.window, ->
307 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
308 gBrowser.removeTab(tab)
309 return
310 )
311
312 commands.tab_restore = ({vim, count = 1}) ->
313 utils.nextTick(vim.window, ->
314 for index in [0...count] by 1
315 restoredTab = vim.window.undoCloseTab()
316 if not restoredTab and index == 0
317 vim.notify(translate('notification.tab_restore.none'))
318 break
319 return
320 )
321
322 commands.tab_restore_list = ({vim}) ->
323 {window} = vim
324 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
325 window, 'menuitem'
326 )
327 if fragment.childElementCount == 0
328 vim.notify(translate('notification.tab_restore.none'))
329 else
330 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
331
332 commands.tab_close_to_end = ({vim}) ->
333 {gBrowser} = vim.window
334 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
335
336 commands.tab_close_other = ({vim}) ->
337 {gBrowser} = vim.window
338 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
339
340
341
342 helper_follow = (name, vim, callback, count = null) ->
343 vim.markPageInteraction()
344 help.removeHelp(vim.window)
345
346 # Enter hints mode immediately, with an empty set of markers. The user might
347 # press keys before the `vim._run` callback is invoked. Those key presses
348 # should be handled in hints mode, not normal mode.
349 initialMarkers = []
350 storage = vim.enterMode('hints', initialMarkers, callback, count)
351
352 vim._run(name, null, ({wrappers, viewport}) ->
353 # The user might have exited hints mode (and perhaps even entered it again)
354 # before this callback is invoked. If so, `storage.markers` has been
355 # cleared, or set to a new value. Only proceed if it is unchanged.
356 return unless storage.markers == initialMarkers
357
358 if wrappers.length > 0
359 {markers, markerMap} = hints.injectHints(vim.window, wrappers, viewport,
360 vim.options)
361 storage.markers = markers
362 storage.markerMap = markerMap
363 else
364 vim.notify(translate('notification.follow.none'))
365 vim.enterMode('normal')
366 )
367
368 helper_follow_clickable = ({inTab, inBackground}, {vim, count = 1}) ->
369 callback = (marker, timesLeft, keyStr) ->
370 {type, elementIndex} = marker.wrapper
371 isLast = (timesLeft == 1)
372 isLink = (type == 'link')
373
374 switch
375 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
376 inTab = not inTab
377 when keyStr.startsWith(vim.options.hints_toggle_in_background)
378 inTab = true
379 inBackground = not inBackground
380 else
381 unless isLast
382 inTab = true
383 inBackground = true
384
385 inTab = false unless isLink
386
387 if type == 'text' or (isLink and not (inTab and inBackground))
388 isLast = true
389
390 vim._focusMarkerElement(elementIndex)
391
392 if inTab
393 utils.nextTick(vim.window, ->
394 utils.openTab(vim.window, marker.wrapper.href, {
395 inBackground
396 relatedToCurrent: true
397 })
398 )
399 else
400 vim._run('click_marker_element', {
401 elementIndex, type
402 preventTargetBlank: vim.options.prevent_target_blank
403 })
404
405 return not isLast
406
407 name = if inTab then 'follow_in_tab' else 'follow'
408 helper_follow(name, vim, callback, count)
409
410 commands.follow =
411 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
412
413 commands.follow_in_tab =
414 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
415
416 commands.follow_in_focused_tab =
417 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
418
419 commands.follow_in_window = ({vim}) ->
420 callback = (marker) ->
421 vim._focusMarkerElement(marker.wrapper.elementIndex)
422 vim.window.openLinkIn(marker.wrapper.href, 'window', {})
423 helper_follow('follow_in_tab', vim, callback)
424
425 commands.follow_multiple = (args) ->
426 args.count = Infinity
427 commands.follow(args)
428
429 commands.follow_copy = ({vim}) ->
430 callback = (marker) ->
431 {elementIndex} = marker.wrapper
432 property = switch marker.wrapper.type
433 when 'link' then 'href'
434 when 'text' then 'value'
435 when 'contenteditable' then 'textContent'
436 vim._run('copy_marker_element', {elementIndex, property})
437 helper_follow('follow_copy', vim, callback)
438
439 commands.follow_focus = ({vim}) ->
440 callback = (marker) ->
441 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
442 return helper_follow('follow_focus', vim, callback)
443
444 commands.click_browser_element = ({vim}) ->
445 markerElements = []
446
447 filter = (element, getElementShape) ->
448 document = element.ownerDocument
449 type = switch
450 when vim._state.scrollableElements.has(element)
451 'scrollable'
452 when (element.tabIndex > -1 and
453 # `.localName` is `.nodeName` without `xul:` (if it exists).
454 not (element.localName.endsWith('box') and
455 element.localName != 'checkbox') and
456 element.localName not in ['tabs', 'menuitem', 'menuseparator']) or
457 element.onclick
458 'clickable'
459 return unless type
460 return unless shape = getElementShape(element)
461 length = markerElements.push(element)
462 return {type, semantic: true, shape, elementIndex: length - 1}
463
464 callback = (marker) ->
465 element = markerElements[marker.wrapper.elementIndex]
466 switch marker.wrapper.type
467 when 'scrollable'
468 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
469 when 'clickable'
470 utils.focusElement(element)
471 utils.simulateMouseEvents(element, 'click')
472
473 {wrappers, viewport} =
474 hints.getMarkableElementsAndViewport(vim.window, filter)
475
476 if wrappers.length > 0
477 {markers} = hints.injectHints(vim.window, wrappers, viewport, {
478 hint_chars: vim.options.hint_chars
479 ui: true
480 })
481 vim.enterMode('hints', markers, callback)
482 else
483 vim.notify(translate('notification.follow.none'))
484
485 helper_follow_pattern = (type, {vim}) ->
486 options =
487 pattern_selector: vim.options.pattern_selector
488 pattern_attrs: vim.options.pattern_attrs
489 patterns: vim.options["#{type}_patterns"]
490 vim._run('follow_pattern', {type, options})
491
492 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
493
494 commands.follow_next = helper_follow_pattern.bind(null, 'next')
495
496 commands.focus_text_input = ({vim, count}) ->
497 vim.markPageInteraction()
498 vim._run('focus_text_input', {count})
499
500
501
502 findStorage = {lastSearchString: ''}
503
504 helper_find = ({highlight, linksOnly = false}, {vim}) ->
505 helpSearchInput = help.getSearchInput(vim.window)
506 if helpSearchInput
507 helpSearchInput.select()
508 return
509
510 helper_mark_last_scroll_position(vim)
511 findBar = vim.window.gBrowser.getFindBar()
512
513 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
514 findBar.startFind(mode)
515 utils.focusElement(findBar._findField, {select: true})
516
517 return if linksOnly
518 return unless highlightButton = findBar.getElement('highlight')
519 if highlightButton.checked != highlight
520 highlightButton.click()
521
522 commands.find = helper_find.bind(null, {highlight: false})
523
524 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
525
526 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
527
528 helper_find_again = (direction, {vim}) ->
529 findBar = vim.window.gBrowser.getFindBar()
530 if findStorage.lastSearchString.length == 0
531 vim.notify(translate('notification.find_again.none'))
532 return
533 helper_mark_last_scroll_position(vim)
534 findBar._findField.value = findStorage.lastSearchString
535 findBar.onFindAgainCommand(direction)
536 message = findBar._findStatusDesc.textContent
537 vim.notify(message) if message
538
539 commands.find_next = helper_find_again.bind(null, false)
540
541 commands.find_previous = helper_find_again.bind(null, true)
542
543
544
545 commands.window_new = ({vim}) ->
546 vim.window.OpenBrowserWindow()
547
548 commands.window_new_private = ({vim}) ->
549 vim.window.OpenBrowserWindow({private: true})
550
551 commands.enter_mode_ignore = ({vim}) ->
552 vim.enterMode('ignore')
553
554 # Quote next keypress (pass it through to the page).
555 commands.quote = ({vim, count = 1}) ->
556 vim.enterMode('ignore', count)
557
558 commands.enter_reader_view = ({vim}) ->
559 button = vim.window.document.getElementById('reader-mode-button')
560 if not button?.hidden
561 button.click()
562 else
563 vim.notify(translate('notification.enter_reader_view.none'))
564
565 commands.help = ({vim}) ->
566 help.injectHelp(vim.window, vim._parent)
567
568 commands.dev = ({vim}) ->
569 vim.window.DeveloperToolbar.show(true) # `true` to focus.
570
571 commands.esc = ({vim}) ->
572 vim._run('esc')
573 utils.blurActiveBrowserElement(vim)
574 vim.window.DeveloperToolbar.hide()
575 vim.window.gBrowser.getFindBar().close()
576 # TODO: Remove when Tab Groups have been removed.
577 vim.window.TabView?.hide()
578 hints.removeHints(vim.window) # Better safe than sorry.
579
580 unless help.getSearchInput(vim.window)?.getAttribute('focused')
581 help.removeHelp(vim.window)
582
583
584
585 module.exports = {
586 commands
587 findStorage
588 }
Imprint / Impressum