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 config = require('./config')
30 help = require('./help')
31 hints = require('./hints')
32 prefs = require('./prefs')
33 translate = require('./l10n')
34 utils = require('./utils')
40 commands.focus_location_bar = ({vim}) ->
41 vim.window.focusAndSelectUrlBar()
43 commands.focus_search_bar = ({vim, count}) ->
44 # The `.webSearch()` method opens a search engine in a tab if the search bar
45 # has been removed. Therefore we first check if it exists.
46 if vim.window.BrowserSearch.searchBar
47 vim.window.BrowserSearch.webSearch()
49 vim.notify(translate('notification.focus_search_bar.none'))
51 helper_paste_and_go = (props, {vim}) ->
52 {gURLBar} = vim.window
53 gURLBar.value = vim.window.readFromClipboard()
54 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
56 commands.paste_and_go = helper_paste_and_go.bind(null, null)
58 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
60 commands.copy_current_url = ({vim}) ->
61 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
62 vim.notify(translate('notification.copy_current_url.success'))
64 commands.go_up_path = ({vim, count}) ->
65 vim._run('go_up_path', {count})
67 commands.go_to_root = ({vim}) ->
68 vim._run('go_to_root')
70 commands.go_home = ({vim}) ->
71 vim.window.BrowserHome()
73 helper_go_history = (direction, {vim, count = 1}) ->
75 {SessionStore, gBrowser} = window
77 if (direction == 'back' and not gBrowser.canGoBack) or
78 (direction == 'forward' and not gBrowser.canGoForward)
79 vim.notify(translate("notification.history_#{direction}.limit"))
82 # `SessionStore.getSessionHistory()` (used below to support counts) starts
83 # lots of asynchronous tasks internally, which is a bit unreliable, it has
84 # turned out. The primary use of the `history_back` and `history_forward`
85 # commands is to go _one_ step back or forward, though, so those cases are
86 # optimized to use more reliable ways of going back and forward. Also, some
87 # extensions override the following functions, so calling them also gives
88 # better interoperability.
90 if direction == 'back'
93 window.BrowserForward()
96 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
97 {index} = sessionHistory
98 newIndex = index + count * (if direction == 'back' then -1 else 1)
99 newIndex = Math.max(newIndex, 0)
100 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
101 gBrowser.gotoIndex(newIndex)
104 commands.history_back = helper_go_history.bind(null, 'back')
106 commands.history_forward = helper_go_history.bind(null, 'forward')
108 commands.history_list = ({vim}) ->
109 menu = vim.window.document.getElementById('backForwardMenu')
110 utils.openPopup(menu)
111 if menu.childElementCount == 0
112 vim.notify(translate('notification.history_list.none'))
114 commands.reload = ({vim}) ->
115 vim.window.BrowserReload()
117 commands.reload_force = ({vim}) ->
118 vim.window.BrowserReloadSkipCache()
120 commands.reload_all = ({vim}) ->
121 vim.window.gBrowser.reloadAllTabs()
123 commands.reload_all_force = ({vim}) ->
124 for tab in vim.window.gBrowser.visibleTabs
125 gBrowser = tab.linkedBrowser
126 consts = gBrowser.webNavigation
127 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
128 gBrowser.reload(flags)
131 commands.stop = ({vim}) ->
132 vim.window.BrowserStop()
134 commands.stop_all = ({vim}) ->
135 for tab in vim.window.gBrowser.visibleTabs
136 tab.linkedBrowser.stop()
141 helper_scroll = (vim, uiEvent, args...) ->
143 method, type, directions, amounts
144 properties = null, adjustment = 0, name = 'scroll'
147 method, type, directions, amounts, properties, adjustment
148 smooth: (prefs.root.get('general.smoothScroll') and
149 prefs.root.get("general.smoothScroll.#{type}"))
151 reset = prefs.root.tmp(
152 'layout.css.scroll-behavior.spring-constant',
153 vim.options["smoothScroll.#{type}.spring-constant"]
156 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
157 if uiEvent or helpScroll
158 activeElement = helpScroll or utils.getActiveElement(vim.window)
159 if vim._state.scrollableElements.has(activeElement) or helpScroll
160 utils.scroll(activeElement, options)
164 vim._run(name, options, reset)
167 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
168 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
169 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['left'],
170 [amount * distance * count * 5])
172 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
173 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
174 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['top'],
175 [amount * distance * count * 20])
177 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
178 adjustment = vim.options["scroll.#{type}_page_adjustment"]
179 helper_scroll(vim, uiEvent, 'scrollBy', 'pages', ['top'],
180 [amount * count], ['clientHeight'], adjustment)
182 helper_scrollToX = (amount, {vim, uiEvent}) ->
183 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['left'],
184 [amount], ['scrollLeftMax'])
185 helper_mark_last_scroll_position(vim)
187 helper_scrollToY = (amount, {vim, uiEvent}) ->
188 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['top'],
189 [amount], ['scrollTopMax'])
190 helper_mark_last_scroll_position(vim)
192 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
193 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
194 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
195 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
196 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
197 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
198 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
199 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
200 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
201 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
202 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
203 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
205 helper_mark_last_scroll_position = (vim) ->
206 keyStr = vim.options['scroll.last_position_mark']
207 vim._run('mark_scroll_position', {keyStr, notify: false})
209 commands.mark_scroll_position = ({vim}) ->
210 vim.enterMode('marks', (keyStr) -> vim._run('mark_scroll_position', {keyStr}))
211 vim.notify(translate('notification.mark_scroll_position.enter'))
213 commands.scroll_to_mark = ({vim}) ->
214 vim.enterMode('marks', (keyStr) ->
215 unless keyStr == vim.options['scroll.last_position_mark']
216 helper_mark_last_scroll_position(vim)
217 helper_scroll(vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
218 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark')
220 vim.notify(translate('notification.scroll_to_mark.enter'))
224 commands.tab_new = ({vim}) ->
225 utils.nextTick(vim.window, ->
226 vim.window.BrowserOpenTab()
229 commands.tab_new_after_current = ({vim}) ->
231 newTabPosition = window.gBrowser.selectedTab._tPos + 1
232 utils.nextTick(window, ->
233 utils.listenOnce(window, 'TabOpen', (event) ->
234 newTab = event.originalTarget
235 window.gBrowser.moveTabTo(newTab, newTabPosition)
237 window.BrowserOpenTab()
240 commands.tab_duplicate = ({vim}) ->
241 {gBrowser} = vim.window
242 utils.nextTick(vim.window, ->
243 gBrowser.duplicateTab(gBrowser.selectedTab)
246 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
247 tabs = gBrowser.visibleTabs
248 {selectedTab} = gBrowser
250 currentIndex = tabs.indexOf(selectedTab)
251 absoluteIndex = currentIndex + relativeIndex
252 numTabsTotal = tabs.length
253 numPinnedTabs = gBrowser._numPinnedTabs
255 [numTabs, min] = switch
256 when not pinnedSeparate
258 when selectedTab.pinned
261 [numTabsTotal - numPinnedTabs, numPinnedTabs]
263 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
265 if (relativeIndex < 0 and currentIndex == min) or
266 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
267 if absoluteIndex < min
268 absoluteIndex += numTabs
269 else if absoluteIndex >= min + numTabs
270 absoluteIndex -= numTabs
272 absoluteIndex = Math.max(min, absoluteIndex)
273 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
277 helper_switch_tab = (direction, {vim, count = 1}) ->
278 {gBrowser} = vim.window
279 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
280 utils.nextTick(vim.window, ->
281 gBrowser.selectTabAtIndex(index)
284 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
286 commands.tab_select_next = helper_switch_tab.bind(null, +1)
288 helper_is_visited = (tab) ->
289 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
291 commands.tab_select_most_recent = ({vim, count = 1}) ->
292 {gBrowser} = vim.window
296 (tab) -> not tab.closing and helper_is_visited(tab)
297 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
298 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
300 gBrowser.selectedTab = tab
302 vim.notify(translate('notification.tab_select_most_recent.none'))
304 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
305 {gBrowser} = vim.window
309 (tab) -> not tab.closing and not helper_is_visited(tab)
310 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
311 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
313 gBrowser.selectedTab = tab
315 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
317 helper_move_tab = (direction, {vim, count = 1}) ->
318 {gBrowser} = vim.window
319 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
320 utils.nextTick(vim.window, ->
321 gBrowser.moveTabTo(gBrowser.selectedTab, index)
324 commands.tab_move_backward = helper_move_tab.bind(null, -1)
326 commands.tab_move_forward = helper_move_tab.bind(null, +1)
328 commands.tab_move_to_window = ({vim}) ->
329 {gBrowser} = vim.window
330 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
332 commands.tab_select_first = ({vim, count = 1}) ->
333 utils.nextTick(vim.window, ->
334 vim.window.gBrowser.selectTabAtIndex(count - 1)
337 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
338 firstNonPinned = vim.window.gBrowser._numPinnedTabs
339 utils.nextTick(vim.window, ->
340 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
343 commands.tab_select_last = ({vim, count = 1}) ->
344 utils.nextTick(vim.window, ->
345 vim.window.gBrowser.selectTabAtIndex(-count)
348 commands.tab_toggle_pinned = ({vim}) ->
349 currentTab = vim.window.gBrowser.selectedTab
351 vim.window.gBrowser.unpinTab(currentTab)
353 vim.window.gBrowser.pinTab(currentTab)
355 commands.tab_close = ({vim, count = 1}) ->
356 {gBrowser} = vim.window
357 return if gBrowser.selectedTab.pinned
358 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
359 utils.nextTick(vim.window, ->
360 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
361 gBrowser.removeTab(tab)
365 commands.tab_restore = ({vim, count = 1}) ->
366 utils.nextTick(vim.window, ->
367 for index in [0...count] by 1
368 restoredTab = vim.window.undoCloseTab()
369 if not restoredTab and index == 0
370 vim.notify(translate('notification.tab_restore.none'))
375 commands.tab_restore_list = ({vim}) ->
377 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
380 if fragment.childElementCount == 0
381 vim.notify(translate('notification.tab_restore.none'))
383 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
385 commands.tab_close_to_end = ({vim}) ->
386 {gBrowser} = vim.window
387 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
389 commands.tab_close_other = ({vim}) ->
390 {gBrowser} = vim.window
391 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
395 helper_follow = (name, vim, callback, count = null) ->
396 vim.markPageInteraction()
397 help.removeHelp(vim.window)
399 # Enter hints mode immediately, with an empty set of markers. The user might
400 # press keys before the `vim._run` callback is invoked. Those key presses
401 # should be handled in hints mode, not normal mode.
403 storage = vim.enterMode('hints', initialMarkers, callback, count,
404 vim.options.hints_sleep)
406 vim._run(name, null, ({wrappers, viewport}) ->
407 # The user might have exited hints mode (and perhaps even entered it again)
408 # before this callback is invoked. If so, `storage.markers` has been
409 # cleared, or set to a new value. Only proceed if it is unchanged.
410 return unless storage.markers == initialMarkers
412 if wrappers.length > 0
413 {markers, markerMap} = hints.injectHints(vim.window, wrappers, viewport,
415 storage.markers = markers
416 storage.markerMap = markerMap
418 vim.notify(translate('notification.follow.none'))
419 vim.enterMode('normal')
422 helper_follow_clickable = (options, {vim, count = 1}) ->
423 callback = (marker, timesLeft, keyStr) ->
424 {inTab, inBackground} = options
425 {type, elementIndex} = marker.wrapper
426 isLast = (timesLeft == 1)
427 isLink = (type == 'link')
430 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
432 when keyStr.startsWith(vim.options.hints_toggle_in_background)
434 inBackground = not inBackground
440 inTab = false unless isLink
442 if type == 'text' or (isLink and not (inTab and inBackground))
445 vim._focusMarkerElement(elementIndex)
448 utils.nextTick(vim.window, ->
449 utils.openTab(vim.window, marker.wrapper.href, {
451 relatedToCurrent: true
455 vim._run('click_marker_element', {
457 preventTargetBlank: vim.options.prevent_target_blank
462 name = if options.inTab then 'follow_in_tab' else 'follow'
463 helper_follow(name, vim, callback, count)
466 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
468 commands.follow_in_tab =
469 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
471 commands.follow_in_focused_tab =
472 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
474 commands.follow_in_window = ({vim}) ->
475 callback = (marker) ->
476 vim._focusMarkerElement(marker.wrapper.elementIndex)
477 vim.window.openLinkIn(marker.wrapper.href, 'window', {})
478 helper_follow('follow_in_tab', vim, callback)
480 commands.follow_multiple = (args) ->
481 args.count = Infinity
482 commands.follow(args)
484 commands.follow_copy = ({vim}) ->
485 callback = (marker) ->
486 {elementIndex} = marker.wrapper
487 property = switch marker.wrapper.type
492 when 'contenteditable'
494 vim._run('copy_marker_element', {elementIndex, property})
495 helper_follow('follow_copy', vim, callback)
497 commands.follow_focus = ({vim}) ->
498 callback = (marker) ->
499 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
500 helper_follow('follow_focus', vim, callback)
502 commands.click_browser_element = ({vim}) ->
505 filter = (element, getElementShape) ->
506 document = element.ownerDocument
508 when vim._state.scrollableElements.has(element)
510 when utils.isFocusable(element) or
511 (element.onclick and element.localName != 'statuspanel')
514 return unless shape = getElementShape(element)
515 length = markerElements.push(element)
516 return {type, semantic: true, shape, elementIndex: length - 1}
518 callback = (marker) ->
519 element = markerElements[marker.wrapper.elementIndex]
520 switch marker.wrapper.type
522 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
525 if element.localName == 'tab'
529 utils.focusElement(element)
530 utils.simulateMouseEvents(element, sequence)
532 {wrappers, viewport} =
533 hints.getMarkableElementsAndViewport(vim.window, filter)
535 if wrappers.length > 0
536 {markers} = hints.injectHints(vim.window, wrappers, viewport, {
537 hint_chars: vim.options.hint_chars
540 vim.enterMode('hints', markers, callback)
542 vim.notify(translate('notification.follow.none'))
544 helper_follow_pattern = (type, {vim}) ->
546 pattern_selector: vim.options.pattern_selector
547 pattern_attrs: vim.options.pattern_attrs
548 patterns: vim.options["#{type}_patterns"]
550 vim._run('follow_pattern', {type, options})
552 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
554 commands.follow_next = helper_follow_pattern.bind(null, 'next')
556 commands.focus_text_input = ({vim, count}) ->
557 vim.markPageInteraction()
558 vim._run('focus_text_input', {count})
562 findStorage = {lastSearchString: ''}
564 helper_find = ({highlight, linksOnly = false}, {vim}) ->
565 helpSearchInput = help.getSearchInput(vim.window)
567 helpSearchInput.select()
570 helper_mark_last_scroll_position(vim)
571 findBar = vim.window.gBrowser.getFindBar()
573 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
574 findBar.startFind(mode)
575 utils.focusElement(findBar._findField, {select: true})
578 return unless highlightButton = findBar.getElement('highlight')
579 if highlightButton.checked != highlight
580 highlightButton.click()
582 commands.find = helper_find.bind(null, {highlight: false})
584 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
586 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
588 helper_find_again = (direction, {vim}) ->
589 findBar = vim.window.gBrowser.getFindBar()
590 if findStorage.lastSearchString.length == 0
591 vim.notify(translate('notification.find_again.none'))
593 helper_mark_last_scroll_position(vim)
594 findBar._findField.value = findStorage.lastSearchString
595 findBar.onFindAgainCommand(direction)
596 message = findBar._findStatusDesc.textContent
597 vim.notify(message) if message
599 commands.find_next = helper_find_again.bind(null, false)
601 commands.find_previous = helper_find_again.bind(null, true)
605 commands.window_new = ({vim}) ->
606 vim.window.OpenBrowserWindow()
608 commands.window_new_private = ({vim}) ->
609 vim.window.OpenBrowserWindow({private: true})
611 commands.enter_mode_ignore = ({vim}) ->
612 vim.enterMode('ignore', {type: 'explicit'})
614 # Quote next keypress (pass it through to the page).
615 commands.quote = ({vim, count = 1}) ->
616 vim.enterMode('ignore', {type: 'explicit', count})
618 commands.enter_reader_view = ({vim}) ->
619 button = vim.window.document.getElementById('reader-mode-button')
620 if not button?.hidden
623 vim.notify(translate('notification.enter_reader_view.none'))
625 commands.reload_config_file = ({vim}) ->
626 vim._parent.emit('shutdown')
627 config.load(vim._parent, (status) -> switch status
629 vim.notify(translate('notification.reload_config_file.none'))
631 vim.notify(translate('notification.reload_config_file.success'))
633 vim.notify(translate('notification.reload_config_file.failure'))
636 commands.help = ({vim}) ->
637 help.injectHelp(vim.window, vim._parent)
639 commands.dev = ({vim}) ->
640 vim.window.DeveloperToolbar.show(true) # `true` to focus.
642 commands.esc = ({vim}) ->
644 utils.blurActiveBrowserElement(vim)
645 vim.window.DeveloperToolbar.hide()
646 vim.window.gBrowser.getFindBar().close()
647 hints.removeHints(vim.window) # Better safe than sorry.
649 unless help.getSearchInput(vim.window)?.getAttribute('focused')
650 help.removeHelp(vim.window)