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 markableElements = require('./markable-elements')
32 MarkerContainer = require('./marker-container')
33 parsePrefs = require('./parse-prefs')
34 prefs = require('./prefs')
35 SelectionManager = require('./selection')
36 translate = require('./translate')
37 utils = require('./utils')
38 viewportUtils = require('./viewport')
40 {ContentClick} = Cu.import('resource:///modules/ContentClick.jsm', {})
41 {FORWARD, BACKWARD} = SelectionManager
43 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
49 commands.focus_location_bar = ({vim}) ->
50 vim.window.focusAndSelectUrlBar()
52 commands.focus_search_bar = ({vim, count}) ->
53 # The `.webSearch()` method opens a search engine in a tab if the search bar
54 # has been removed. Therefore we first check if it exists.
55 if vim.window.BrowserSearch.searchBar
56 vim.window.BrowserSearch.webSearch()
58 vim.notify(translate('notification.focus_search_bar.none'))
60 helper_paste_and_go = (props, {vim}) ->
61 {gURLBar} = vim.window
62 gURLBar.value = vim.window.readFromClipboard()
63 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
65 commands.paste_and_go = helper_paste_and_go.bind(null, null)
67 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
69 commands.copy_current_url = ({vim}) ->
70 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
71 vim.notify(translate('notification.copy_current_url.success'))
73 commands.go_up_path = ({vim, count}) ->
74 vim._run('go_up_path', {count})
76 commands.go_to_root = ({vim}) ->
77 vim._run('go_to_root')
79 commands.go_home = ({vim}) ->
80 vim.window.BrowserHome()
82 helper_go_history = (direction, {vim, count = 1}) ->
84 {SessionStore, gBrowser} = window
86 if (direction == 'back' and not gBrowser.canGoBack) or
87 (direction == 'forward' and not gBrowser.canGoForward)
88 vim.notify(translate("notification.history_#{direction}.limit"))
91 # `SessionStore.getSessionHistory()` (used below to support counts) starts
92 # lots of asynchronous tasks internally, which is a bit unreliable, it has
93 # turned out. The primary use of the `history_back` and `history_forward`
94 # commands is to go _one_ step back or forward, though, so those cases are
95 # optimized to use more reliable ways of going back and forward. Also, some
96 # extensions override the following functions, so calling them also gives
97 # better interoperability.
99 if direction == 'back'
102 window.BrowserForward()
105 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
106 {index} = sessionHistory
107 newIndex = index + count * (if direction == 'back' then -1 else 1)
108 newIndex = Math.max(newIndex, 0)
109 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
110 gBrowser.gotoIndex(newIndex)
113 commands.history_back = helper_go_history.bind(null, 'back')
115 commands.history_forward = helper_go_history.bind(null, 'forward')
117 commands.history_list = ({vim}) ->
118 menu = vim.window.document.getElementById('backForwardMenu')
119 utils.openPopup(menu)
120 if menu.childElementCount == 0
121 vim.notify(translate('notification.history_list.none'))
123 commands.reload = ({vim}) ->
124 vim.window.BrowserReload()
126 commands.reload_force = ({vim}) ->
127 vim.window.BrowserReloadSkipCache()
129 commands.reload_all = ({vim}) ->
130 vim.window.gBrowser.reloadAllTabs()
132 commands.reload_all_force = ({vim}) ->
133 for tab in vim.window.gBrowser.visibleTabs
134 gBrowser = tab.linkedBrowser
135 consts = gBrowser.webNavigation
136 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
137 gBrowser.reload(flags)
140 commands.stop = ({vim}) ->
141 vim.window.BrowserStop()
143 commands.stop_all = ({vim}) ->
144 for tab in vim.window.gBrowser.visibleTabs
145 tab.linkedBrowser.stop()
156 helper_scroll = (vim, event, args...) ->
158 method, type, directions, amounts
159 properties = null, adjustment = 0, name = 'scroll', extra = {}
162 elapsed = event.timeStamp - scrollData.lastRepeat
164 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
167 scrollData.lastRepeat = event.timeStamp
170 method, type, directions, amounts, properties, adjustment, extra
172 prefs.root.get('general.smoothScroll') and
173 prefs.root.get("general.smoothScroll.#{type}")
177 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
178 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
179 # scrolling command was invoked.
180 scrollData.nonce = nonce = {}
181 scrollData.springConstant ?= prefs.root.get(SPRING_CONSTANT_PREF)
183 SPRING_CONSTANT_PREF,
184 vim.options["smoothScroll.#{type}.spring-constant"]
187 vim.window.setTimeout((->
188 return unless scrollData.nonce == nonce
189 prefs.root.set(SPRING_CONSTANT_PREF, scrollData.springConstant)
190 scrollData.nonce = null
191 scrollData.springConstant = null
192 ), vim.options['scroll.reset_timeout'])
194 {isUIEvent = vim.isUIEvent(event)} = extra
195 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
196 if isUIEvent or helpScroll
197 activeElement = helpScroll or utils.getActiveElement(vim.window)
198 if vim._state.scrollableElements.has(activeElement) or helpScroll
199 viewportUtils.scroll(activeElement, options)
203 vim._run(name, options, reset)
206 helper_scrollByLinesX = (amount, {vim, event, count = 1}) ->
207 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
208 boost = if event.repeat then vim.options['scroll.horizontal_boost'] else 1
210 vim, event, 'scrollBy', 'lines', ['left'],
211 [amount * distance * boost * count * 5]
214 helper_scrollByLinesY = (amount, {vim, event, count = 1}) ->
215 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
216 boost = if event.repeat then vim.options['scroll.vertical_boost'] else 1
218 vim, event, 'scrollBy', 'lines', ['top'],
219 [amount * distance * boost * count * 20]
222 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
223 adjustment = vim.options["scroll.#{type}_page_adjustment"]
225 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
226 ['clientHeight'], adjustment
229 helper_scrollToX = (amount, {vim, event}) ->
230 helper_mark_last_scroll_position(vim)
232 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
235 helper_scrollToY = (amount, {vim, event}) ->
236 helper_mark_last_scroll_position(vim)
238 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
241 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
242 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
243 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
244 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
245 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
246 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
247 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
248 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
249 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
250 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
251 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
252 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
254 helper_mark_last_scroll_position = (vim) ->
255 keyStr = vim.options['scroll.last_position_mark']
256 vim._run('mark_scroll_position', {keyStr, notify: false, addToJumpList: true})
258 commands.mark_scroll_position = ({vim}) ->
259 vim._enterMode('marks', (keyStr) ->
260 vim._run('mark_scroll_position', {keyStr})
262 vim.notify(translate('notification.mark_scroll_position.enter'))
264 commands.scroll_to_mark = ({vim, event}) ->
265 vim._enterMode('marks', (keyStr) ->
266 lastPositionMark = vim.options['scroll.last_position_mark']
268 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
269 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
270 {keyStr, lastPositionMark, isUIEvent: false}
272 vim.hideNotification()
274 vim.notify(translate('notification.scroll_to_mark.enter'))
276 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
277 lastPositionMark = vim.options['scroll.last_position_mark']
279 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
280 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
281 {count, direction, lastPositionMark, isUIEvent: false}
284 commands.scroll_to_previous_position =
285 helper_scroll_to_position.bind(null, 'previous')
287 commands.scroll_to_next_position =
288 helper_scroll_to_position.bind(null, 'next')
292 commands.tab_new = ({vim}) ->
293 utils.nextTick(vim.window, ->
294 vim.window.BrowserOpenTab()
297 commands.tab_new_after_current = ({vim}) ->
299 newTabPosition = window.gBrowser.selectedTab._tPos + 1
300 utils.nextTick(window, ->
301 utils.listenOnce(window, 'TabOpen', (event) ->
302 newTab = event.originalTarget
303 window.gBrowser.moveTabTo(newTab, newTabPosition)
305 window.BrowserOpenTab()
308 commands.tab_duplicate = ({vim}) ->
309 {gBrowser} = vim.window
310 utils.nextTick(vim.window, ->
311 gBrowser.duplicateTab(gBrowser.selectedTab)
314 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
315 tabs = gBrowser.visibleTabs
316 {selectedTab} = gBrowser
318 currentIndex = tabs.indexOf(selectedTab)
319 absoluteIndex = currentIndex + relativeIndex
320 numTabsTotal = tabs.length
321 numPinnedTabs = gBrowser._numPinnedTabs
323 [numTabs, min] = switch
324 when not pinnedSeparate
326 when selectedTab.pinned
329 [numTabsTotal - numPinnedTabs, numPinnedTabs]
331 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
333 if (relativeIndex < 0 and currentIndex == min) or
334 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
335 if absoluteIndex < min
336 absoluteIndex += numTabs
337 else if absoluteIndex >= min + numTabs
338 absoluteIndex -= numTabs
340 absoluteIndex = Math.max(min, absoluteIndex)
341 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
345 helper_switch_tab = (direction, {vim, count = 1}) ->
346 {gBrowser} = vim.window
347 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
348 utils.nextTick(vim.window, ->
349 gBrowser.selectTabAtIndex(index)
352 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
354 commands.tab_select_next = helper_switch_tab.bind(null, +1)
356 helper_is_visited = (tab) ->
357 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
359 commands.tab_select_most_recent = ({vim, count = 1}) ->
360 {gBrowser} = vim.window
364 (tab) -> not tab.closing and helper_is_visited(tab)
365 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
366 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
368 gBrowser.selectedTab = tab
370 vim.notify(translate('notification.tab_select_most_recent.none'))
372 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
373 {gBrowser} = vim.window
377 (tab) -> not tab.closing and not helper_is_visited(tab)
378 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
379 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
381 gBrowser.selectedTab = tab
383 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
385 helper_move_tab = (direction, {vim, count = 1}) ->
386 {gBrowser} = vim.window
387 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
388 utils.nextTick(vim.window, ->
389 gBrowser.moveTabTo(gBrowser.selectedTab, index)
392 commands.tab_move_backward = helper_move_tab.bind(null, -1)
394 commands.tab_move_forward = helper_move_tab.bind(null, +1)
396 commands.tab_move_to_window = ({vim}) ->
397 {gBrowser} = vim.window
398 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
400 commands.tab_select_first = ({vim, count = 1}) ->
401 utils.nextTick(vim.window, ->
402 vim.window.gBrowser.selectTabAtIndex(count - 1)
405 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
406 firstNonPinned = vim.window.gBrowser._numPinnedTabs
407 utils.nextTick(vim.window, ->
408 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
411 commands.tab_select_last = ({vim, count = 1}) ->
412 utils.nextTick(vim.window, ->
413 vim.window.gBrowser.selectTabAtIndex(-count)
416 commands.tab_toggle_pinned = ({vim}) ->
417 currentTab = vim.window.gBrowser.selectedTab
419 vim.window.gBrowser.unpinTab(currentTab)
421 vim.window.gBrowser.pinTab(currentTab)
423 commands.tab_close = ({vim, count = 1}) ->
424 {gBrowser} = vim.window
425 return if gBrowser.selectedTab.pinned
426 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
427 utils.nextTick(vim.window, ->
428 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
429 gBrowser.removeTab(tab)
433 commands.tab_restore = ({vim, count = 1}) ->
434 utils.nextTick(vim.window, ->
435 for index in [0...count] by 1
436 restoredTab = vim.window.undoCloseTab()
437 if not restoredTab and index == 0
438 vim.notify(translate('notification.tab_restore.none'))
443 commands.tab_restore_list = ({vim}) ->
445 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
448 if fragment.childElementCount == 0
449 vim.notify(translate('notification.tab_restore.none'))
451 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
453 commands.tab_close_to_end = ({vim}) ->
454 {gBrowser} = vim.window
455 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
457 commands.tab_close_other = ({vim}) ->
458 {gBrowser} = vim.window
459 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
463 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
465 vim.markPageInteraction()
466 help.removeHelp(window)
468 markerContainer = new MarkerContainer({
470 hintChars: vim.options['hints.chars']
471 getComplementaryWrappers: (callback) ->
472 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
473 # `markerContainer.container` is `null`ed out when leaving Hints mode.
474 # If this callback is called after we’ve left Hints mode (and perhaps
475 # even entered it again), simply discard the result.
476 return unless markerContainer.container
477 if wrappers.length == 0
478 vim.notify(translate('notification.follow.none'))
479 callback({wrappers, viewport})
482 MarkerContainer.remove(window) # Better safe than sorry.
483 window.gBrowser.selectedBrowser.parentNode.appendChild(
484 markerContainer.container
487 chooseCallback = (marker, timesLeft, keyStr) ->
489 {type, href = null, elementIndex} = marker.wrapper
490 return callbackOverride({type, href, id: elementIndex, timesLeft})
492 return callback(marker, timesLeft, keyStr)
494 # Enter Hints mode immediately, with an empty set of markers. The user might
495 # press keys before any hints have been generated. Those keypresses should be
496 # handled in Hints mode, not Normal mode.
497 vim._enterMode('hints', {
498 markerContainer, count
499 callback: chooseCallback
500 matchText: vim.options['hints.match_text']
501 sleep: vim.options['hints.sleep']
504 injectHints = ({wrappers, viewport, pass}) ->
505 # See `getComplementaryWrappers` above.
506 return unless markerContainer.container
508 if wrappers.length == 0
509 if pass in ['single', 'second'] and markerContainer.markers.length == 0
510 vim.notify(translate('notification.follow.none'))
511 vim._enterMode('normal')
513 markerContainer.injectHints(wrappers, viewport, pass)
516 vim._run(name, {pass: 'second'}, injectHints)
518 vim._run(name, {pass: 'auto'}, injectHints)
520 helper_follow_clickable = (options, args) ->
523 callback = (marker, timesLeft, keyStr) ->
524 {inTab, inBackground} = options
525 {type, elementIndex} = marker.wrapper
526 isLast = (timesLeft == 1)
527 isLink = (type == 'link')
531 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
533 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
535 inBackground = not inBackground
541 inTab = false unless isLink
543 if type == 'text' or (isLink and not (inTab and inBackground))
546 vim._focusMarkerElement(elementIndex)
549 utils.nextTick(window, ->
550 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
551 # links using the mouse. Using that instead of simply
552 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
553 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
554 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
555 ContentClick.contentAreaClick({
556 href: marker.wrapper.href
557 shiftKey: not inBackground
560 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
565 # The point of “clicking” scrollable elements is focusing them (which is
566 # done above) so that scrolling commands may scroll them. Simulating a click
567 # here usually _unfocuses_ the element.
568 else if type != 'scrollable'
569 vim._run('click_marker_element', {
571 browserOffset: vim._getBrowserOffset()
572 preventTargetBlank: vim.options.prevent_target_blank
577 name = if options.inTab then 'follow_in_tab' else 'follow'
578 helper_follow({name, callback}, args)
581 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
583 commands.follow_in_tab =
584 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
586 commands.follow_in_focused_tab =
587 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
589 helper_follow_in_window = (options, args) ->
592 callback = (marker) ->
593 vim._focusMarkerElement(marker.wrapper.elementIndex)
594 {href} = marker.wrapper
595 vim.window.openLinkIn(href, 'window', options) if href
598 helper_follow({name: 'follow_in_tab', callback}, args)
600 commands.follow_in_window =
601 helper_follow_in_window.bind(null, {})
603 commands.follow_in_private_window =
604 helper_follow_in_window.bind(null, {private: true})
606 commands.follow_multiple = (args) ->
607 args.count = Infinity
608 commands.follow(args)
610 commands.follow_copy = (args) ->
613 callback = (marker) ->
614 property = switch marker.wrapper.type
619 when 'contenteditable', 'complementary'
621 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
624 helper_follow({name: 'follow_copy', callback}, args)
626 commands.follow_focus = (args) ->
629 callback = (marker) ->
630 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
633 helper_follow({name: 'follow_focus', callback}, args)
635 commands.open_context_menu = (args) ->
638 callback = (marker) ->
639 {type, elementIndex} = marker.wrapper
640 vim._run('click_marker_element', {
642 browserOffset: vim._getBrowserOffset()
646 helper_follow({name: 'follow_context', callback}, args)
648 commands.click_browser_element = ({vim}) ->
652 getButtonMenu = (element) ->
653 if element.localName == 'dropmarker' and
654 element.parentNode?.localName == 'toolbarbutton'
655 return element.parentNode.querySelector('menupopup')
659 filter = ({complementary}, element, getElementShape) ->
661 when vim._state.scrollableElements.has(element)
663 when getButtonMenu(element)
665 when utils.isFocusable(element) or
666 (element.onclick and element.localName != 'statuspanel')
670 type = if type then null else 'complementary'
674 # `getElementShape(element, -1)` is intentionally _not_ used in the
675 # `complementary` run, because it results in tons of useless hints for
676 # hidden context menus.
677 shape = getElementShape(element)
678 return unless shape.nonCoveredPoint
680 # The tabs and their close buttons as well as the tab bar scroll arrows get
681 # better hints, since switching or closing tabs is the most common use case
682 # for the `eb` command.
683 isTab = element.classList?.contains('tabbrowser-tab')
686 element.classList?.contains('tab-close-button') or
687 element.classList?.contains('scrollbutton-up') or
688 element.classList?.contains('scrollbutton-down')
690 length = markerElements.push(element)
692 type, shape, isTab, isPrioritized,
693 combinedArea: shape.area,
694 elementIndex: length - 1,
697 callback = (marker) ->
698 element = markerElements[marker.wrapper.elementIndex]
699 switch marker.wrapper.type
701 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
703 getButtonMenu(element).openPopup(
704 element.parentNode, # Anchor node.
705 'after_end', # Position.
707 false, # Isn’t a context menu.
708 true, # Allow the 'position' attribute to override the above position.
710 when 'clickable', 'complementary'
711 # VimFx’s own button won’t trigger unless the click is simulated in the
712 # next tick. This might be true for other buttons as well.
713 utils.nextTick(window, ->
714 utils.focusElement(element)
715 browserOffset = {x: window.screenX, y: window.screenY}
717 when element.localName == 'tab'
718 # Only 'mousedown' seems to be able to activate tabs.
719 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
720 when element.closest('tab')
721 # If `.click()` is used on a tab close button, its tab will be
722 # selected first, which might cause the selected tab to change.
723 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
725 # `.click()` seems to trigger more buttons (such as NoScript’s
726 # button and Firefox’s “hamburger” menu button) than simulating
729 utils.openDropdown(element)
733 wrappers = markableElements.find(
734 window, filter.bind(null, {complementary: false})
737 if wrappers.length > 0
738 viewport = viewportUtils.getWindowViewport(window)
740 markerContainer = new MarkerContainer({
742 hintChars: vim.options['hints.chars']
745 getComplementaryWrappers: (callback) ->
746 newWrappers = markableElements.find(
747 window, filter.bind(null, {complementary: true})
749 callback({wrappers: newWrappers, viewport})
751 MarkerContainer.remove(window) # Better safe than sorry.
752 markerContainer.container.classList.add('ui')
753 window.document.getElementById('browser-panel').appendChild(
754 markerContainer.container
757 [firstWrappers, secondWrappers] =
758 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
760 numChars = markerContainer.alphabet.length
761 numPrimary = markerContainer.primaryHintChars.length
762 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
765 for wrapper in firstWrappers
767 # Given the hint chars `abc de`, give the tabs weights so that the hints
768 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
769 # on. The rule is that the weight of a tab must be larger than the sum
770 # of all tabs with a longer hint. We start out at `1` and then use
771 # smaller and smaller fractions. This is to make sure that the tabs get
772 # consistent hints as the number of tabs or the size of the window
774 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
775 wrapper.combinedArea = 1 / numChars ** exponent
778 # Make sure that the tab close buttons and the tab bar scroll buttons
779 # come after all the tabs. Treating them all as the same size is fine.
780 # Their sum must be small enough in order not to affect the tab hints.
781 # It might look like using `0` is a good idea, but that results in
782 # increasingly worse hints the more tab close buttons there are.
783 wrapper.combinedArea = 1 / numChars ** numTabs
785 # Since most of the best hint characters might be used for the tabs, make
786 # sure that all other elements don’t get really bad hints. First, favor
787 # larger elements by sorting them. Then, give them all the same weight so
788 # that larger elements (such as the location bar, search bar, the web
789 # console input and other large areas in the devtools) don’t overpower the
790 # smaller ones. The usual “the larger the element, the better the hint” rule
791 # doesn’t really apply the same way for browser UI elements as in web pages.
792 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
793 for wrapper in secondWrappers
794 wrapper.combinedArea = 1
796 markerContainer.injectHints(firstWrappers, viewport, 'first')
797 markerContainer.injectHints(secondWrappers, viewport, 'second')
798 vim._enterMode('hints', {markerContainer, callback, matchText: false})
801 vim.notify(translate('notification.follow.none'))
803 helper_follow_pattern = (type, {vim}) ->
805 pattern_selector: vim.options.pattern_selector
806 pattern_attrs: vim.options.pattern_attrs
807 patterns: vim.options["#{type}_patterns"]
809 browserOffset = vim._getBrowserOffset()
810 vim._run('follow_pattern', {type, browserOffset, options})
812 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
814 commands.follow_next = helper_follow_pattern.bind(null, 'next')
816 commands.focus_text_input = ({vim, count}) ->
817 vim.markPageInteraction()
818 vim._run('focus_text_input', {count})
820 helper_follow_selectable = ({select}, args) ->
823 callback = (marker) ->
824 vim._run('element_text_select', {
825 elementIndex: marker.wrapper.elementIndex
829 vim._enterMode('caret', {select})
832 helper_follow({name: 'follow_selectable', callback}, args)
834 commands.element_text_caret =
835 helper_follow_selectable.bind(null, {select: false})
837 commands.element_text_select =
838 helper_follow_selectable.bind(null, {select: true})
840 commands.element_text_copy = (args) ->
843 callback = (marker) ->
844 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
847 helper_follow({name: 'follow_selectable', callback}, args)
849 helper_copy_marker_element = (vim, elementIndex, property) ->
850 if property == '_selection'
851 # Selecting the text and then copying that selection is better than copying
852 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
853 # and then includes those backticks in the compiled output (!), in hidden
854 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
855 # elements, text selection gives better whitespace than `.textContent`.
856 vim._run('element_text_select', {elementIndex, full: true}, ->
857 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
858 vim._run('clear_selection')
861 vim._run('copy_marker_element', {elementIndex, property})
870 helper_find_from_top_of_viewport = (vim, direction, callback) ->
871 if vim.options.find_from_top_of_viewport
872 vim._run('find_from_top_of_viewport', {direction}, ->
878 helper_find = ({highlight, linksOnly = false}, {vim}) ->
880 # Make sure to enter find mode here, since that’s where `findStorage.busy`
881 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
882 vim._enterMode('find')
885 helpSearchInput = help.getSearchInput(vim.window)
887 helpSearchInput.select()
890 # Important: Enter Find mode immediately. See `onInput` for Find mode.
891 findStorage.busy = true
892 vim._enterMode('find')
894 helper_mark_last_scroll_position(vim)
895 vim._run('mark_scroll_position', {
896 keyStr: vim.options['scroll.last_find_mark']
900 helper_find_from_top_of_viewport(vim, FORWARD, ->
901 return unless vim.mode == 'find'
902 findBar = vim.window.gBrowser.getFindBar()
904 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
905 findBar.startFind(mode)
906 utils.focusElement(findBar._findField, {select: true})
909 return unless highlightButton = findBar.getElement('highlight')
910 if highlightButton.checked != highlight
911 highlightButton.click()
914 commands.find = helper_find.bind(null, {highlight: false})
916 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
918 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
920 helper_find_again = (direction, {vim}) ->
921 return if findStorage.busy
923 findBar = vim.window.gBrowser.getFindBar()
924 if findStorage.lastSearchString.length == 0
925 vim.notify(translate('notification.find_again.none'))
928 findStorage.busy = true
930 helper_mark_last_scroll_position(vim)
931 helper_find_from_top_of_viewport(vim, direction, ->
932 findBar._findField.value = findStorage.lastSearchString
934 # `.onFindResult` is temporarily hacked to be able to know when the
935 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
936 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
938 originalOnFindResult = findBar.onFindResult
939 originalUpdateControlState = findBar.updateControlState
941 findBar.onFindResult = (data) ->
942 # Prevent the find bar from re-opening if there are no matches.
943 data.storeResult = false
944 findBar.onFindResult = originalOnFindResult
945 findBar.updateControlState = originalUpdateControlState
946 findBar.onFindResult(data)
949 findBar.updateControlState = (args...) ->
950 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
951 # matches here, so no need to take care of that in this case.
952 findBar.onFindResult = originalOnFindResult
953 findBar.updateControlState = originalUpdateControlState
954 findBar.updateControlState(args...)
958 message = findBar._findStatusDesc.textContent
959 vim.notify(message) if message
960 findStorage.busy = false
962 findBar.onFindAgainCommand(not direction)
965 commands.find_next = helper_find_again.bind(null, FORWARD)
967 commands.find_previous = helper_find_again.bind(null, BACKWARD)
971 commands.window_new = ({vim}) ->
972 vim.window.OpenBrowserWindow()
974 commands.window_new_private = ({vim}) ->
975 vim.window.OpenBrowserWindow({private: true})
977 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
978 type = if blacklist then 'blacklist' else 'explicit'
979 vim._enterMode('ignore', {type})
981 # Quote next keypress (pass it through to the page).
982 commands.quote = ({vim, count = 1}) ->
983 vim._enterMode('ignore', {type: 'explicit', count})
985 commands.enter_reader_view = ({vim}) ->
986 button = vim.window.document.getElementById('reader-mode-button')
987 if not button?.hidden
990 vim.notify(translate('notification.enter_reader_view.none'))
992 commands.reload_config_file = ({vim}) ->
993 vim._parent.emit('shutdown')
994 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
996 vim.notify(translate('notification.reload_config_file.none'))
998 vim.notify(translate('notification.reload_config_file.success'))
1000 vim.notify(translate('notification.reload_config_file.failure'))
1003 commands.edit_blacklist = ({vim}) ->
1004 url = vim.browser.currentURI.spec
1005 location = new vim.window.URL(url)
1006 newPattern = if location.host then "*#{location.host}*" else location.href
1008 blacklistString = prefs.get('blacklist')
1010 if vim._isBlacklisted(url)
1011 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1012 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1013 return vim.options.blacklist[index].test(url)
1015 newBlacklistString = "
1016 #{matching.join(delimiter)}\
1017 #{delimiter.repeat(7)}\
1018 #{nonMatching.join(delimiter)}
1020 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1022 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1023 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1026 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1031 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1032 return if input == null
1033 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1034 # and let the regular pref parsing take care of it.
1035 prefs.set('blacklist', input)
1036 vim._onLocationChange(url)
1039 commands.help = ({vim}) ->
1040 help.toggleHelp(vim.window, vim._parent)
1042 commands.dev = ({vim}) ->
1043 vim.window.DeveloperToolbar.show(true) # `true` to focus.
1045 commands.esc = ({vim}) ->
1047 vim.hideNotification()
1049 # Firefox does things differently when blurring the location bar, depending on
1050 # whether the autocomplete popup is open or not. To be consistent, always
1051 # close the autocomplete popup before blurring.
1052 vim.window.gURLBar.closePopup()
1054 utils.blurActiveBrowserElement(vim)
1055 vim.window.gBrowser.getFindBar().close()
1057 # Better safe than sorry.
1058 MarkerContainer.remove(vim.window)
1059 vim._parent.resetCaretBrowsing()
1061 # Calling `.hide()` when the toolbar is not open can destroy it for the rest
1062 # of the Firefox session. The code here is taken from the `.toggle()` method.
1063 {DeveloperToolbar} = vim.window
1064 if DeveloperToolbar.visible
1065 DeveloperToolbar.hide().catch(console.error)
1067 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1068 help.removeHelp(vim.window)
1070 vim._setFocusType('none') # Better safe than sorry.