2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
4 # Copyright Wang Zhuochun 2013, 2014.
6 # This file is part of VimFx.
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.
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.
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/>.
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.
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.
29 help = require('./help')
30 hints = require('./hints')
31 prefs = require('./prefs')
32 translate = require('./l10n')
33 utils = require('./utils')
39 commands.focus_location_bar = ({vim}) ->
40 vim.window.focusAndSelectUrlBar()
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()
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))
53 commands.paste_and_go = helper_paste_and_go.bind(null, null)
55 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
57 commands.copy_current_url = ({vim}) ->
58 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
59 vim.notify(translate('notification.copy_current_url'))
61 commands.go_up_path = ({vim, count}) ->
62 vim._run('go_up_path', {count})
64 commands.go_to_root = ({vim}) ->
65 vim._run('go_to_root')
67 commands.go_home = ({vim}) ->
68 vim.window.BrowserHome()
70 helper_go_history = (direction, {vim, count = 1}) ->
72 {SessionStore, gBrowser} = window
74 if (direction == 'back' and not gBrowser.canGoBack) or
75 (direction == 'forward' and not gBrowser.canGoForward)
76 vim.notify(translate("notification.history_#{direction}.limit"))
79 # `SessionStore.getSessionHistory()` (used below to support counts) starts
80 # lots of asynchronous tasks internally, which is a bit unreliable, it has
81 # turned out. The primary use of the `history_back` and `history_forward`
82 # commands is to go _one_ step back or forward, though, so those cases are
83 # optimized to use more reliable ways of going back and forward. Also, some
84 # extensions override the following functions, so calling them also gives
85 # better interoperability.
87 if direction == 'back'
90 window.BrowserForward()
93 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
94 {index} = sessionHistory
95 newIndex = index + count * (if direction == 'back' then -1 else 1)
96 newIndex = Math.max(newIndex, 0)
97 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
98 gBrowser.gotoIndex(newIndex)
101 commands.history_back = helper_go_history.bind(null, 'back')
103 commands.history_forward = helper_go_history.bind(null, 'forward')
105 commands.history_list = ({vim}) ->
106 menu = vim.window.document.getElementById('backForwardMenu')
107 utils.openPopup(menu)
108 if menu.childElementCount == 0
109 vim.notify(translate('notification.history_list.none'))
111 commands.reload = ({vim}) ->
112 vim.window.BrowserReload()
114 commands.reload_force = ({vim}) ->
115 vim.window.BrowserReloadSkipCache()
117 commands.reload_all = ({vim}) ->
118 vim.window.gBrowser.reloadAllTabs()
120 commands.reload_all_force = ({vim}) ->
121 for tab in vim.window.gBrowser.visibleTabs
122 gBrowser = tab.linkedBrowser
123 consts = gBrowser.webNavigation
124 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
125 gBrowser.reload(flags)
128 commands.stop = ({vim}) ->
129 vim.window.BrowserStop()
131 commands.stop_all = ({vim}) ->
132 for tab in vim.window.gBrowser.visibleTabs
133 tab.linkedBrowser.stop()
138 helper_scroll = (vim, uiEvent, args...) ->
140 method, type, directions, amounts
141 properties = null, adjustment = 0, name = 'scroll'
144 method, type, directions, amounts, properties, adjustment
145 smooth: (prefs.root.get('general.smoothScroll') and
146 prefs.root.get("general.smoothScroll.#{type}"))
148 reset = prefs.root.tmp(
149 'layout.css.scroll-behavior.spring-constant',
150 vim.options["smoothScroll.#{type}.spring-constant"]
153 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
154 if uiEvent or helpScroll
155 activeElement = helpScroll or utils.getActiveElement(vim.window)
156 if vim._state.scrollableElements.has(activeElement) or helpScroll
157 utils.scroll(activeElement, options)
161 vim._run(name, options, reset)
164 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
165 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
166 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['left'],
167 [amount * distance * count * 5])
169 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
170 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
171 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['top'],
172 [amount * distance * count * 20])
174 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
175 adjustment = prefs.get("scroll.#{type}_page_adjustment")
176 helper_scroll(vim, uiEvent, 'scrollBy', 'pages', ['top'],
177 [amount * count], ['clientHeight'], adjustment)
179 helper_scrollToX = (amount, {vim, uiEvent}) ->
180 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['left'],
181 [amount], ['scrollLeftMax'])
182 helper_mark_last_scroll_position(vim)
184 helper_scrollToY = (amount, {vim, uiEvent}) ->
185 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['top'],
186 [amount], ['scrollTopMax'])
187 helper_mark_last_scroll_position(vim)
189 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
190 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
191 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
192 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
193 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
194 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
195 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
196 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
197 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
198 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
199 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
200 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
202 helper_mark_last_scroll_position = (vim) ->
203 keyStr = vim.options['scroll.last_position_mark']
204 vim._run('mark_scroll_position', {keyStr, notify: false})
206 commands.mark_scroll_position = ({vim}) ->
207 vim.enterMode('marks', (keyStr) -> vim._run('mark_scroll_position', {keyStr}))
209 commands.scroll_to_mark = ({vim}) ->
210 vim.enterMode('marks', (keyStr) ->
211 unless keyStr == vim.options['scroll.last_position_mark']
212 helper_mark_last_scroll_position(vim)
213 helper_scroll(vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
214 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark')
219 commands.tab_new = ({vim}) ->
220 utils.nextTick(vim.window, ->
221 vim.window.BrowserOpenTab()
224 commands.tab_duplicate = ({vim}) ->
225 {gBrowser} = vim.window
226 utils.nextTick(vim.window, ->
227 gBrowser.duplicateTab(gBrowser.selectedTab)
230 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
231 tabs = gBrowser.visibleTabs
232 {selectedTab} = gBrowser
234 currentIndex = tabs.indexOf(selectedTab)
235 absoluteIndex = currentIndex + relativeIndex
236 numTabsTotal = tabs.length
237 numPinnedTabs = gBrowser._numPinnedTabs
239 [numTabs, min] = switch
240 when not pinnedSeparate
242 when selectedTab.pinned
245 [numTabsTotal - numPinnedTabs, numPinnedTabs]
247 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
249 if (relativeIndex < 0 and currentIndex == min) or
250 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
251 if absoluteIndex < min
252 absoluteIndex += numTabs
253 else if absoluteIndex >= min + numTabs
254 absoluteIndex -= numTabs
256 absoluteIndex = Math.max(min, absoluteIndex)
257 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
261 helper_switch_tab = (direction, {vim, count = 1}) ->
262 {gBrowser} = vim.window
263 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
264 utils.nextTick(vim.window, ->
265 gBrowser.selectTabAtIndex(index)
268 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
270 commands.tab_select_next = helper_switch_tab.bind(null, +1)
272 commands.tab_select_most_recent = ({vim, count = 1}) ->
273 {gBrowser} = vim.window
274 tabsSorted = Array.filter(gBrowser.tabs, (tab) -> not tab.closing)
275 .sort((a, b) -> b.lastAccessed - a.lastAccessed)
276 mostRecentTab = tabsSorted[Math.min(count, tabsSorted.length - 1)]
277 gBrowser.selectedTab = mostRecentTab if mostRecentTab
279 helper_move_tab = (direction, {vim, count = 1}) ->
280 {gBrowser} = vim.window
281 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
282 utils.nextTick(vim.window, ->
283 gBrowser.moveTabTo(gBrowser.selectedTab, index)
286 commands.tab_move_backward = helper_move_tab.bind(null, -1)
288 commands.tab_move_forward = helper_move_tab.bind(null, +1)
290 commands.tab_move_to_window = ({vim}) ->
291 {gBrowser} = vim.window
292 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
294 commands.tab_select_first = ({vim, count = 1}) ->
295 utils.nextTick(vim.window, ->
296 vim.window.gBrowser.selectTabAtIndex(count - 1)
299 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
300 firstNonPinned = vim.window.gBrowser._numPinnedTabs
301 utils.nextTick(vim.window, ->
302 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
305 commands.tab_select_last = ({vim, count = 1}) ->
306 utils.nextTick(vim.window, ->
307 vim.window.gBrowser.selectTabAtIndex(-count)
310 commands.tab_toggle_pinned = ({vim}) ->
311 currentTab = vim.window.gBrowser.selectedTab
313 vim.window.gBrowser.unpinTab(currentTab)
315 vim.window.gBrowser.pinTab(currentTab)
317 commands.tab_close = ({vim, count = 1}) ->
318 {gBrowser} = vim.window
319 return if gBrowser.selectedTab.pinned
320 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
321 utils.nextTick(vim.window, ->
322 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
323 gBrowser.removeTab(tab)
327 commands.tab_restore = ({vim, count = 1}) ->
328 utils.nextTick(vim.window, ->
329 for index in [0...count] by 1
330 restoredTab = vim.window.undoCloseTab()
331 if not restoredTab and index == 0
332 vim.notify(translate('notification.tab_restore.none'))
337 commands.tab_restore_list = ({vim}) ->
339 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
342 if fragment.childElementCount == 0
343 vim.notify(translate('notification.tab_restore.none'))
345 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
347 commands.tab_close_to_end = ({vim}) ->
348 {gBrowser} = vim.window
349 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
351 commands.tab_close_other = ({vim}) ->
352 {gBrowser} = vim.window
353 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
357 helper_follow = (name, vim, callback, count = null) ->
358 vim.markPageInteraction()
359 help.removeHelp(vim.window)
361 # Enter hints mode immediately, with an empty set of markers. The user might
362 # press keys before the `vim._run` callback is invoked. Those key presses
363 # should be handled in hints mode, not normal mode.
365 storage = vim.enterMode('hints', initialMarkers, callback, count,
366 vim.options.hints_sleep)
368 vim._run(name, null, ({wrappers, viewport}) ->
369 # The user might have exited hints mode (and perhaps even entered it again)
370 # before this callback is invoked. If so, `storage.markers` has been
371 # cleared, or set to a new value. Only proceed if it is unchanged.
372 return unless storage.markers == initialMarkers
374 if wrappers.length > 0
375 {markers, markerMap} = hints.injectHints(vim.window, wrappers, viewport,
377 storage.markers = markers
378 storage.markerMap = markerMap
380 vim.notify(translate('notification.follow.none'))
381 vim.enterMode('normal')
384 helper_follow_clickable = ({inTab, inBackground}, {vim, count = 1}) ->
385 callback = (marker, timesLeft, keyStr) ->
386 {type, elementIndex} = marker.wrapper
387 isLast = (timesLeft == 1)
388 isLink = (type == 'link')
391 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
393 when keyStr.startsWith(vim.options.hints_toggle_in_background)
395 inBackground = not inBackground
401 inTab = false unless isLink
403 if type == 'text' or (isLink and not (inTab and inBackground))
406 vim._focusMarkerElement(elementIndex)
409 utils.nextTick(vim.window, ->
410 utils.openTab(vim.window, marker.wrapper.href, {
412 relatedToCurrent: true
416 vim._run('click_marker_element', {
418 preventTargetBlank: vim.options.prevent_target_blank
423 name = if inTab then 'follow_in_tab' else 'follow'
424 helper_follow(name, vim, callback, count)
427 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
429 commands.follow_in_tab =
430 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
432 commands.follow_in_focused_tab =
433 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
435 commands.follow_in_window = ({vim}) ->
436 callback = (marker) ->
437 vim._focusMarkerElement(marker.wrapper.elementIndex)
438 vim.window.openLinkIn(marker.wrapper.href, 'window', {})
439 helper_follow('follow_in_tab', vim, callback)
441 commands.follow_multiple = (args) ->
442 args.count = Infinity
443 commands.follow(args)
445 commands.follow_copy = ({vim}) ->
446 callback = (marker) ->
447 {elementIndex} = marker.wrapper
448 property = switch marker.wrapper.type
453 when 'contenteditable'
455 vim._run('copy_marker_element', {elementIndex, property})
456 helper_follow('follow_copy', vim, callback)
458 commands.follow_focus = ({vim}) ->
459 callback = (marker) ->
460 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
461 return helper_follow('follow_focus', vim, callback)
463 commands.click_browser_element = ({vim}) ->
466 filter = (element, getElementShape) ->
467 document = element.ownerDocument
469 when vim._state.scrollableElements.has(element)
471 when (element.tabIndex > -1 and
472 # `.localName` is `.nodeName` without `xul:` (if it exists).
473 not (element.localName.endsWith('box') and
474 element.localName != 'checkbox') and
475 element.localName not in ['tabs', 'menuitem', 'menuseparator']) or
479 return unless shape = getElementShape(element)
480 length = markerElements.push(element)
481 return {type, semantic: true, shape, elementIndex: length - 1}
483 callback = (marker) ->
484 element = markerElements[marker.wrapper.elementIndex]
485 switch marker.wrapper.type
487 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
489 utils.focusElement(element)
490 utils.simulateMouseEvents(element, 'click')
492 {wrappers, viewport} =
493 hints.getMarkableElementsAndViewport(vim.window, filter)
495 if wrappers.length > 0
496 {markers} = hints.injectHints(vim.window, wrappers, viewport, {
497 hint_chars: vim.options.hint_chars
500 vim.enterMode('hints', markers, callback)
502 vim.notify(translate('notification.follow.none'))
504 helper_follow_pattern = (type, {vim}) ->
506 pattern_selector: vim.options.pattern_selector
507 pattern_attrs: vim.options.pattern_attrs
508 patterns: vim.options["#{type}_patterns"]
510 vim._run('follow_pattern', {type, options})
512 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
514 commands.follow_next = helper_follow_pattern.bind(null, 'next')
516 commands.focus_text_input = ({vim, count}) ->
517 vim.markPageInteraction()
518 vim._run('focus_text_input', {count})
522 findStorage = {lastSearchString: ''}
524 helper_find = ({highlight, linksOnly = false}, {vim}) ->
525 helpSearchInput = help.getSearchInput(vim.window)
527 helpSearchInput.select()
530 helper_mark_last_scroll_position(vim)
531 findBar = vim.window.gBrowser.getFindBar()
533 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
534 findBar.startFind(mode)
535 utils.focusElement(findBar._findField, {select: true})
538 return unless highlightButton = findBar.getElement('highlight')
539 if highlightButton.checked != highlight
540 highlightButton.click()
542 commands.find = helper_find.bind(null, {highlight: false})
544 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
546 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
548 helper_find_again = (direction, {vim}) ->
549 findBar = vim.window.gBrowser.getFindBar()
550 if findStorage.lastSearchString.length == 0
551 vim.notify(translate('notification.find_again.none'))
553 helper_mark_last_scroll_position(vim)
554 findBar._findField.value = findStorage.lastSearchString
555 findBar.onFindAgainCommand(direction)
556 message = findBar._findStatusDesc.textContent
557 vim.notify(message) if message
559 commands.find_next = helper_find_again.bind(null, false)
561 commands.find_previous = helper_find_again.bind(null, true)
565 commands.window_new = ({vim}) ->
566 vim.window.OpenBrowserWindow()
568 commands.window_new_private = ({vim}) ->
569 vim.window.OpenBrowserWindow({private: true})
571 commands.enter_mode_ignore = ({vim}) ->
572 vim.enterMode('ignore')
574 # Quote next keypress (pass it through to the page).
575 commands.quote = ({vim, count = 1}) ->
576 vim.enterMode('ignore', count)
578 commands.enter_reader_view = ({vim}) ->
579 button = vim.window.document.getElementById('reader-mode-button')
580 if not button?.hidden
583 vim.notify(translate('notification.enter_reader_view.none'))
585 commands.help = ({vim}) ->
586 help.injectHelp(vim.window, vim._parent)
588 commands.dev = ({vim}) ->
589 vim.window.DeveloperToolbar.show(true) # `true` to focus.
591 commands.esc = ({vim}) ->
593 utils.blurActiveBrowserElement(vim)
594 vim.window.DeveloperToolbar.hide()
595 vim.window.gBrowser.getFindBar().close()
596 # TODO: Remove when Tab Groups have been removed.
597 vim.window.TabView?.hide()
598 hints.removeHints(vim.window) # Better safe than sorry.
600 unless help.getSearchInput(vim.window)?.getAttribute('focused')
601 help.removeHelp(vim.window)