1 # This file defines all Normal mode commands. Commands that need to interact
2 # with web page content do so by running `vim._run(name)`, which invokes `name`
3 # in commands-frame.coffee.
5 # NOTE: Most tab related commands need to do their actual tab manipulations in
6 # the next tick (`utils.nextTick`) to work around bug 1200334.
8 config = require('./config')
9 help = require('./help')
10 markableElements = require('./markable-elements')
11 MarkerContainer = require('./marker-container')
12 parsePrefs = require('./parse-prefs')
13 prefs = require('./prefs')
14 SelectionManager = require('./selection')
15 translate = require('./translate')
16 utils = require('./utils')
17 viewportUtils = require('./viewport')
19 {FORWARD, BACKWARD} = SelectionManager
21 READER_VIEW_PREFIX = 'about:reader?url='
22 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
23 USER_CONTEXT_ID_ATTRIBUTE_NAME = 'usercontextid'
29 commands.focus_location_bar = ({vim}) ->
30 vim.window.gURLBar.select()
32 commands.focus_search_bar = ({vim, count}) ->
33 # The `.webSearch()` method opens a search engine in a tab if the search bar
34 # has been removed. Therefore we first check if it exists.
35 if vim.window.BrowserSearch.searchBar
36 vim.window.BrowserSearch.webSearch()
38 vim.notify(translate('notification.focus_search_bar.none'))
40 helper_paste_and_go = (props, {vim}) ->
41 {gURLBar} = vim.window
42 gURLBar.value = vim.window.readFromClipboard()
43 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
45 commands.paste_and_go = helper_paste_and_go.bind(null, null)
47 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
49 commands.copy_current_url = ({vim}) ->
50 url = vim.window.gBrowser.currentURI.spec
52 if url.startsWith(READER_VIEW_PREFIX)
53 decodeURIComponent(url[READER_VIEW_PREFIX.length..])
56 utils.writeToClipboard(adjustedUrl)
57 vim.notify(translate('notification.copy_current_url.success'))
59 commands.go_up_path = ({vim, count}) ->
60 vim._run('go_up_path', {count})
62 commands.go_to_root = ({vim}) ->
63 vim._run('go_to_root')
65 commands.go_home = ({vim}) ->
66 vim.window.BrowserHome()
68 helper_go_history = (direction, {vim, count = 1}) ->
70 {SessionStore, gBrowser} = window
72 if (direction == 'back' and not gBrowser.canGoBack) or
73 (direction == 'forward' and not gBrowser.canGoForward)
74 vim.notify(translate("notification.history_#{direction}.limit"))
77 # `SessionStore.getSessionHistory()` (used below to support counts) starts
78 # lots of asynchronous tasks internally, which is a bit unreliable, it has
79 # turned out. The primary use of the `history_back` and `history_forward`
80 # commands is to go _one_ step back or forward, though, so those cases are
81 # optimized to use more reliable ways of going back and forward. Also, some
82 # extensions override the following functions, so calling them also gives
83 # better interoperability.
85 if direction == 'back'
88 window.BrowserForward()
91 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
92 {index} = sessionHistory
93 newIndex = index + count * (if direction == 'back' then -1 else 1)
94 newIndex = Math.max(newIndex, 0)
95 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
96 gBrowser.gotoIndex(newIndex)
99 commands.history_back = helper_go_history.bind(null, 'back')
101 commands.history_forward = helper_go_history.bind(null, 'forward')
103 commands.history_list = ({vim}) ->
104 menu = vim.window.document.getElementById('backForwardMenu')
105 utils.openPopup(menu)
106 if menu.childElementCount == 0
107 vim.notify(translate('notification.history_list.none'))
109 commands.reload = ({vim}) ->
110 vim.window.BrowserReload()
112 commands.reload_force = ({vim}) ->
113 vim.window.BrowserReloadSkipCache()
115 commands.reload_all = ({vim}) ->
116 vim.window.gBrowser.reloadAllTabs()
118 commands.reload_all_force = ({vim}) ->
119 for tab in vim.window.gBrowser.visibleTabs
120 gBrowser = tab.linkedBrowser
121 consts = gBrowser.webNavigation
122 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
123 gBrowser.reload(flags)
126 commands.stop = ({vim}) ->
127 vim.window.BrowserStop()
129 commands.stop_all = ({vim}) ->
130 for tab in vim.window.gBrowser.visibleTabs
131 tab.linkedBrowser.stop()
142 helper_scroll = (vim, event, args...) ->
144 method, type, directions, amounts
145 properties = null, adjustment = 0, name = 'scroll', extra = {}
148 elapsed = event.timeStamp - scrollData.lastRepeat
150 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
153 scrollData.lastRepeat = event.timeStamp
156 method, type, directions, amounts, properties, adjustment, extra
158 prefs.root.get('general.smoothScroll') and
159 prefs.root.get("general.smoothScroll.#{type}")
163 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
164 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
165 # scrolling command was invoked.
166 scrollData.nonce = nonce = {}
167 scrollData.springConstant ?= prefs.root.get(SPRING_CONSTANT_PREF)
169 SPRING_CONSTANT_PREF,
170 vim.options["smoothScroll.#{type}.spring-constant"]
173 vim.window.setTimeout((->
174 return unless scrollData.nonce == nonce
175 prefs.root.set(SPRING_CONSTANT_PREF, scrollData.springConstant)
176 scrollData.nonce = null
177 scrollData.springConstant = null
178 ), vim.options['scroll.reset_timeout'])
180 {isUIEvent = vim.isUIEvent(event)} = extra
181 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
182 if isUIEvent or helpScroll
183 activeElement = helpScroll or utils.getActiveElement(vim.window)
184 if vim._state.scrollableElements.has(activeElement) or helpScroll
185 viewportUtils.scroll(activeElement, options)
189 vim._run(name, options, reset)
192 helper_scrollByLinesX = (amount, {vim, event, count = 1}) ->
193 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
194 boost = if event.repeat then vim.options['scroll.horizontal_boost'] else 1
196 vim, event, 'scrollBy', 'lines', ['left'],
197 [amount * distance * boost * count * 5]
200 helper_scrollByLinesY = (amount, {vim, event, count = 1}) ->
201 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
202 boost = if event.repeat then vim.options['scroll.vertical_boost'] else 1
204 vim, event, 'scrollBy', 'lines', ['top'],
205 [amount * distance * boost * count * 20]
208 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
209 adjustment = vim.options["scroll.#{type}_page_adjustment"]
211 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
212 ['clientHeight'], adjustment
215 helper_scrollToX = (amount, {vim, event}) ->
216 helper_mark_last_scroll_position(vim)
218 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
221 helper_scrollToY = (amount, {vim, event}) ->
222 helper_mark_last_scroll_position(vim)
224 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
227 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
228 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
229 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
230 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
231 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
232 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
233 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
234 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
235 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
236 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
237 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
238 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
240 helper_mark_last_scroll_position = (vim) ->
241 keyStr = vim.options['scroll.last_position_mark']
242 vim._run('mark_scroll_position', {keyStr, notify: false, addToJumpList: true})
244 commands.mark_scroll_position = ({vim}) ->
245 vim._enterMode('marks', (keyStr) ->
246 vim._run('mark_scroll_position', {keyStr})
248 vim.notify(translate('notification.mark_scroll_position.enter'))
250 commands.scroll_to_mark = ({vim, event}) ->
251 vim._enterMode('marks', (keyStr) ->
252 lastPositionMark = vim.options['scroll.last_position_mark']
254 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
255 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
256 {keyStr, lastPositionMark, isUIEvent: false}
258 vim.hideNotification()
260 vim.notify(translate('notification.scroll_to_mark.enter'))
262 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
263 lastPositionMark = vim.options['scroll.last_position_mark']
265 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
266 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
267 {count, direction, lastPositionMark, isUIEvent: false}
270 commands.scroll_to_previous_position =
271 helper_scroll_to_position.bind(null, 'previous')
273 commands.scroll_to_next_position =
274 helper_scroll_to_position.bind(null, 'next')
278 commands.tab_new = ({vim}) ->
279 utils.nextTick(vim.window, ->
280 vim.window.BrowserOpenTab()
283 commands.tab_new_after_current = ({vim}) ->
285 newTabPosition = window.gBrowser.selectedTab._tPos + 1
286 utils.nextTick(window, ->
287 utils.listenOnce(window, 'TabOpen', (event) ->
288 newTab = event.originalTarget
289 window.gBrowser.moveTabTo(newTab, newTabPosition)
291 window.BrowserOpenTab()
294 commands.tab_duplicate = ({vim}) ->
295 {gBrowser} = vim.window
296 utils.nextTick(vim.window, ->
297 gBrowser.duplicateTab(gBrowser.selectedTab)
300 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
301 tabs = gBrowser.visibleTabs
302 {selectedTab} = gBrowser
304 currentIndex = tabs.indexOf(selectedTab)
305 absoluteIndex = currentIndex + relativeIndex
306 numTabsTotal = tabs.length
307 numPinnedTabs = gBrowser._numPinnedTabs
309 [numTabs, min] = switch
310 when not pinnedSeparate
312 when selectedTab.pinned
315 [numTabsTotal - numPinnedTabs, numPinnedTabs]
317 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
319 if (relativeIndex < 0 and currentIndex == min) or
320 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
321 if absoluteIndex < min
322 absoluteIndex += numTabs
323 else if absoluteIndex >= min + numTabs
324 absoluteIndex -= numTabs
326 absoluteIndex = Math.max(min, absoluteIndex)
327 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
331 helper_switch_tab = (direction, {vim, count = 1}) ->
332 {gBrowser} = vim.window
333 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
334 utils.nextTick(vim.window, ->
335 gBrowser.selectTabAtIndex(index)
338 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
340 commands.tab_select_next = helper_switch_tab.bind(null, +1)
342 helper_is_visited = (tab) ->
343 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
345 commands.tab_select_most_recent = ({vim, count = 1}) ->
346 {gBrowser} = vim.window
348 Array.prototype.filter.call(
350 (tab) -> not tab.closing and helper_is_visited(tab)
351 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
352 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
354 gBrowser.selectedTab = tab
356 vim.notify(translate('notification.tab_select_most_recent.none'))
358 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
359 {gBrowser} = vim.window
361 Array.prototype.filter.call(
363 (tab) -> not tab.closing and not helper_is_visited(tab)
364 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
365 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
367 gBrowser.selectedTab = tab
369 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
371 helper_move_tab = (direction, {vim, count = 1}) ->
372 {gBrowser} = vim.window
373 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
374 utils.nextTick(vim.window, ->
375 gBrowser.moveTabTo(gBrowser.selectedTab, index)
378 commands.tab_move_backward = helper_move_tab.bind(null, -1)
380 commands.tab_move_forward = helper_move_tab.bind(null, +1)
382 commands.tab_move_to_window = ({vim}) ->
383 {gBrowser} = vim.window
384 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
386 commands.tab_select_first = ({vim, count = 1}) ->
387 utils.nextTick(vim.window, ->
388 vim.window.gBrowser.selectTabAtIndex(count - 1)
391 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
392 firstNonPinned = vim.window.gBrowser._numPinnedTabs
393 utils.nextTick(vim.window, ->
394 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
397 commands.tab_select_last = ({vim, count = 1}) ->
398 utils.nextTick(vim.window, ->
399 vim.window.gBrowser.selectTabAtIndex(-count)
402 commands.tab_toggle_pinned = ({vim}) ->
403 currentTab = vim.window.gBrowser.selectedTab
405 vim.window.gBrowser.unpinTab(currentTab)
407 vim.window.gBrowser.pinTab(currentTab)
409 commands.tab_close = ({vim, count = 1}) ->
410 {gBrowser} = vim.window
411 return if gBrowser.selectedTab.pinned
412 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
413 utils.nextTick(vim.window, ->
414 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
415 gBrowser.removeTab(tab)
419 commands.tab_restore = ({vim, count = 1}) ->
420 utils.nextTick(vim.window, ->
421 for index in [0...count] by 1
422 restoredTab = vim.window.undoCloseTab()
423 if not restoredTab and index == 0
424 vim.notify(translate('notification.tab_restore.none'))
429 commands.tab_restore_list = ({vim}) ->
431 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
434 if fragment.childElementCount == 0
435 vim.notify(translate('notification.tab_restore.none'))
437 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
439 commands.tab_close_to_end = ({vim}) ->
440 {gBrowser} = vim.window
441 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
443 commands.tab_close_other = ({vim}) ->
444 {gBrowser} = vim.window
445 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
449 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
451 vim.markPageInteraction()
452 help.removeHelp(window)
454 markerContainer = new MarkerContainer({
456 hintChars: vim.options['hints.chars']
457 getComplementaryWrappers: (callback) ->
458 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
459 # `markerContainer.container` is `null`ed out when leaving Hints mode.
460 # If this callback is called after we’ve left Hints mode (and perhaps
461 # even entered it again), simply discard the result.
462 return unless markerContainer.container
463 if wrappers.length == 0
464 vim.notify(translate('notification.follow.none'))
465 callback({wrappers, viewport})
468 MarkerContainer.remove(window) # Better safe than sorry.
469 window.gBrowser.selectedBrowser.parentNode.appendChild(
470 markerContainer.container
473 chooseCallback = (marker, timesLeft, keyStr) ->
475 {type, href = null, elementIndex} = marker.wrapper
476 return callbackOverride({type, href, id: elementIndex, timesLeft})
478 return callback(marker, timesLeft, keyStr)
480 # Enter Hints mode immediately, with an empty set of markers. The user might
481 # press keys before any hints have been generated. Those keypresses should be
482 # handled in Hints mode, not Normal mode.
483 vim._enterMode('hints', {
484 markerContainer, count
485 callback: chooseCallback
486 matchText: vim.options['hints.match_text']
487 sleep: vim.options['hints.sleep']
490 injectHints = ({wrappers, viewport, pass}) ->
491 # See `getComplementaryWrappers` above.
492 return unless markerContainer.container
494 if wrappers.length == 0
495 if pass in ['single', 'second'] and markerContainer.markers.length == 0
496 vim.notify(translate('notification.follow.none'))
497 vim._enterMode('normal')
499 markerContainer.injectHints(wrappers, viewport, pass)
502 vim._run(name, {pass: 'second'}, injectHints)
504 vim._run(name, {pass: 'auto'}, injectHints)
507 helper_add_user_context_id = (gBrowser, objectToAugment) ->
508 contextAttribute = gBrowser.selectedTab.attributes.getNamedItem(
509 USER_CONTEXT_ID_ATTRIBUTE_NAME)
511 # default has no context attribute so only set if it exists
513 objectToAugment.userContextId = contextAttribute.value
515 return objectToAugment
518 helper_follow_clickable = (options, args) ->
521 callback = (marker, timesLeft, keyStr) ->
522 {inTab, inBackground} = options
523 {type, elementIndex} = marker.wrapper
524 isLast = (timesLeft == 1)
525 isLink = (type == 'link')
529 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
531 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
533 inBackground = not inBackground
539 inTab = false unless isLink
541 if type == 'text' or (isLink and not (inTab and inBackground))
544 vim._focusMarkerElement(elementIndex)
547 utils.nextTick(window, ->
548 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
549 # links using the mouse. Using that instead of simply
550 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
551 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
552 referrerInfo = Cc['@mozilla.org/referrer-info;1']
553 .createInstance(Ci.nsIReferrerInfo)
554 referrerInfo.initWithDocument(window.document)
555 loadInBackground = prefs.root.get('browser.tabs.loadInBackground')
557 utils.contentAreaClick({
558 href: marker.wrapper.href
559 shiftKey: inBackground != loadInBackground
564 csp: window.document.csp
566 originAttributes: helper_add_user_context_id(
567 vim.browser.ownerGlobal.gBrowser,
568 window.document.nodePrincipal?.originAttributes ? {}
570 triggeringPrincipal: window.document.nodePrincipal
574 # The point of “clicking” scrollable elements is focusing them (which is
575 # done above) so that scrolling commands may scroll them. Simulating a click
576 # here usually _unfocuses_ the element.
577 else if type != 'scrollable'
578 vim._run('click_marker_element', {
580 browserOffset: vim._getBrowserOffset()
581 preventTargetBlank: vim.options.prevent_target_blank
586 name = if options.inTab then 'follow_in_tab' else 'follow'
587 helper_follow({name, callback}, args)
590 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
592 commands.follow_in_tab =
593 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
595 commands.follow_in_focused_tab =
596 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
598 helper_follow_in_window = (options, args) ->
601 callback = (marker) ->
602 vim._focusMarkerElement(marker.wrapper.elementIndex)
603 {href} = marker.wrapper
604 options.triggeringPrincipal = vim.window.document.nodePrincipal
605 options = helper_add_user_context_id(vim.window.gBrowser, options)
607 vim.window.openLinkIn(href, 'window', options) if href
610 helper_follow({name: 'follow_in_tab', callback}, args)
612 commands.follow_in_window =
613 helper_follow_in_window.bind(null, {})
615 commands.follow_in_private_window =
616 helper_follow_in_window.bind(null, {private: true})
618 commands.follow_multiple = (args) ->
619 args.count = Infinity
620 commands.follow(args)
622 commands.follow_copy = (args) ->
625 callback = (marker) ->
626 property = switch marker.wrapper.type
631 when 'contenteditable', 'complementary'
633 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
636 helper_follow({name: 'follow_copy', callback}, args)
638 commands.follow_focus = (args) ->
641 callback = (marker) ->
642 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
645 helper_follow({name: 'follow_focus', callback}, args)
647 commands.open_context_menu = (args) ->
650 callback = (marker) ->
651 {type, elementIndex} = marker.wrapper
652 vim._run('click_marker_element', {
654 browserOffset: vim._getBrowserOffset()
658 helper_follow({name: 'follow_context', callback}, args)
660 commands.click_browser_element = ({vim}) ->
664 getButtonMenu = (element) ->
665 if element.localName == 'dropmarker' and
666 element.parentNode?.localName == 'toolbarbutton'
667 return element.parentNode.querySelector('menupopup')
671 filter = ({complementary}, element, getElementShape) ->
673 when vim._state.scrollableElements.has(element)
675 when getButtonMenu(element)
677 when utils.isFocusable(element) or element.onclick
681 type = if type then null else 'complementary'
685 # `getElementShape(element, -1)` is intentionally _not_ used in the
686 # `complementary` run, because it results in tons of useless hints for
687 # hidden context menus.
688 shape = getElementShape(element)
689 return unless shape.nonCoveredPoint
691 # The tabs and their close buttons as well as the tab bar scroll arrows get
692 # better hints, since switching or closing tabs is the most common use case
693 # for the `eb` command.
694 isTab = element.classList?.contains('tabbrowser-tab')
697 element.classList?.contains('tab-close-button') or
698 element.classList?.contains('scrollbutton-up') or
699 element.classList?.contains('scrollbutton-down')
701 length = markerElements.push(element)
703 type, shape, isTab, isPrioritized,
704 combinedArea: shape.area,
705 elementIndex: length - 1,
708 callback = (marker) ->
709 element = markerElements[marker.wrapper.elementIndex]
710 switch marker.wrapper.type
712 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
714 getButtonMenu(element).openPopup(
715 element.parentNode, # Anchor node.
716 'after_end', # Position.
718 false, # Isn’t a context menu.
719 true, # Allow the 'position' attribute to override the above position.
721 when 'clickable', 'complementary'
722 # VimFx’s own button won’t trigger unless the click is simulated in the
723 # next tick. This might be true for other buttons as well.
724 utils.nextTick(window, ->
725 utils.focusElement(element)
726 browserOffset = {x: window.screenX, y: window.screenY}
728 when element.localName == 'tab'
729 # Only 'mousedown' seems to be able to activate tabs.
730 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
731 when element.closest('tab')
732 # If `.click()` is used on a tab close button, its tab will be
733 # selected first, which might cause the selected tab to change.
734 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
736 # `.click()` seems to trigger more buttons (such as NoScript’s
737 # button and Firefox’s “hamburger” menu button) than simulating
740 utils.openDropdown(element)
744 wrappers = markableElements.find(
745 window, filter.bind(null, {complementary: false})
748 if wrappers.length > 0
749 viewport = viewportUtils.getWindowViewport(window)
751 markerContainer = new MarkerContainer({
753 hintChars: vim.options['hints.chars']
756 getComplementaryWrappers: (callback) ->
757 newWrappers = markableElements.find(
758 window, filter.bind(null, {complementary: true})
760 callback({wrappers: newWrappers, viewport})
762 MarkerContainer.remove(window) # Better safe than sorry.
763 markerContainer.container.classList.add('ui')
764 mainWindow = window.document.body
765 mainWindow.insertBefore(
766 markerContainer.container,
767 mainWindow.firstChild
770 [firstWrappers, secondWrappers] =
771 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
773 numChars = markerContainer.alphabet.length
774 numPrimary = markerContainer.primaryHintChars.length
775 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
778 for wrapper in firstWrappers
780 # Given the hint chars `abc de`, give the tabs weights so that the hints
781 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
782 # on. The rule is that the weight of a tab must be larger than the sum
783 # of all tabs with a longer hint. We start out at `1` and then use
784 # smaller and smaller fractions. This is to make sure that the tabs get
785 # consistent hints as the number of tabs or the size of the window
787 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
788 wrapper.combinedArea = 1 / numChars ** exponent
791 # Make sure that the tab close buttons and the tab bar scroll buttons
792 # come after all the tabs. Treating them all as the same size is fine.
793 # Their sum must be small enough in order not to affect the tab hints.
794 # It might look like using `0` is a good idea, but that results in
795 # increasingly worse hints the more tab close buttons there are.
796 wrapper.combinedArea = 1 / numChars ** numTabs
798 # Since most of the best hint characters might be used for the tabs, make
799 # sure that all other elements don’t get really bad hints. First, favor
800 # larger elements by sorting them. Then, give them all the same weight so
801 # that larger elements (such as the location bar, search bar, the web
802 # console input and other large areas in the devtools) don’t overpower the
803 # smaller ones. The usual “the larger the element, the better the hint” rule
804 # doesn’t really apply the same way for browser UI elements as in web pages.
805 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
806 for wrapper in secondWrappers
807 wrapper.combinedArea = 1
809 markerContainer.injectHints(firstWrappers, viewport, 'first')
810 markerContainer.injectHints(secondWrappers, viewport, 'second')
811 vim._enterMode('hints', {markerContainer, callback, matchText: false})
814 vim.notify(translate('notification.follow.none'))
816 helper_follow_pattern = (type, {vim}) ->
818 pattern_selector: vim.options.pattern_selector
819 pattern_attrs: vim.options.pattern_attrs
820 patterns: vim.options["#{type}_patterns"]
822 browserOffset = vim._getBrowserOffset()
823 vim._run('follow_pattern', {type, browserOffset, options})
825 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
827 commands.follow_next = helper_follow_pattern.bind(null, 'next')
829 commands.focus_text_input = ({vim, count}) ->
830 vim.markPageInteraction()
831 vim._run('focus_text_input', {count})
833 helper_follow_selectable = ({select}, args) ->
836 callback = (marker) ->
837 vim._run('element_text_select', {
838 elementIndex: marker.wrapper.elementIndex
842 vim._enterMode('caret', {select})
845 helper_follow({name: 'follow_selectable', callback}, args)
847 commands.element_text_caret =
848 helper_follow_selectable.bind(null, {select: false})
850 commands.element_text_select =
851 helper_follow_selectable.bind(null, {select: true})
853 commands.element_text_copy = (args) ->
856 callback = (marker) ->
857 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
860 helper_follow({name: 'follow_selectable', callback}, args)
862 helper_copy_marker_element = (vim, elementIndex, property) ->
863 if property == '_selection'
864 # Selecting the text and then copying that selection is better than copying
865 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
866 # and then includes those backticks in the compiled output (!), in hidden
867 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
868 # elements, text selection gives better whitespace than `.textContent`.
869 vim._run('element_text_select', {elementIndex, full: true}, ->
870 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
871 vim._run('clear_selection')
874 vim._run('copy_marker_element', {elementIndex, property})
883 helper_find_from_top_of_viewport = (vim, direction, callback) ->
884 if vim.options.find_from_top_of_viewport
885 vim._run('find_from_top_of_viewport', {direction}, ->
891 helper_find = ({highlight, linksOnly = false}, {vim}) ->
893 # Make sure to enter find mode here, since that’s where `findStorage.busy`
894 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
895 vim._enterMode('find')
898 helpSearchInput = help.getSearchInput(vim.window)
900 helpSearchInput.select()
903 # Important: Enter Find mode immediately. See `onInput` for Find mode.
904 findStorage.busy = true
905 vim._enterMode('find')
907 helper_mark_last_scroll_position(vim)
908 vim._run('mark_scroll_position', {
909 keyStr: vim.options['scroll.last_find_mark']
913 helper_find_from_top_of_viewport(vim, FORWARD, ->
914 return unless vim.mode == 'find'
915 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
916 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
917 findBar.startFind(mode)
918 utils.focusElement(findBar._findField, {select: true})
921 return unless highlightButton = findBar.getElement('highlight')
922 if highlightButton.checked != highlight
923 highlightButton.click()
927 commands.find = helper_find.bind(null, {highlight: false})
929 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
931 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
933 helper_find_again = (direction, {vim}) ->
934 return if findStorage.busy
936 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
937 if findStorage.lastSearchString.length == 0
938 vim.notify(translate('notification.find_again.none'))
941 findStorage.busy = true
943 helper_mark_last_scroll_position(vim)
944 helper_find_from_top_of_viewport(vim, direction, ->
945 findBar._findField.value = findStorage.lastSearchString
947 # `.onFindResult` is temporarily hacked to be able to know when the
948 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
949 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
951 originalOnFindResult = findBar.onFindResult
952 originalUpdateControlState = findBar.updateControlState
954 findBar.onFindResult = (data) ->
955 # Prevent the find bar from re-opening if there are no matches.
956 data.storeResult = false
957 findBar.onFindResult = originalOnFindResult
958 findBar.updateControlState = originalUpdateControlState
959 findBar.onFindResult(data)
962 findBar.updateControlState = (args...) ->
963 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
964 # matches here, so no need to take care of that in this case.
965 findBar.onFindResult = originalOnFindResult
966 findBar.updateControlState = originalUpdateControlState
967 findBar.updateControlState(args...)
971 message = findBar._findStatusDesc.textContent
972 vim.notify(message) if message
973 findStorage.busy = false
975 findBar.onFindAgainCommand(not direction)
979 commands.find_next = helper_find_again.bind(null, FORWARD)
981 commands.find_previous = helper_find_again.bind(null, BACKWARD)
985 commands.window_new = ({vim}) ->
986 vim.window.OpenBrowserWindow()
988 commands.window_new_private = ({vim}) ->
989 vim.window.OpenBrowserWindow({private: true})
991 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
992 type = if blacklist then 'blacklist' else 'explicit'
993 vim._enterMode('ignore', {type})
995 # Quote next keypress (pass it through to the page).
996 commands.quote = ({vim, count = 1}) ->
997 vim._enterMode('ignore', {type: 'explicit', count})
999 commands.enter_reader_view = ({vim}) ->
1000 button = vim.window.document.getElementById('reader-mode-button')
1001 if not button?.hidden
1004 vim.notify(translate('notification.enter_reader_view.none'))
1006 commands.reload_config_file = ({vim}) ->
1007 vim._parent.emit('shutdown')
1008 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1010 vim.notify(translate('notification.reload_config_file.none'))
1012 vim.notify(translate('notification.reload_config_file.success'))
1014 vim.notify(translate('notification.reload_config_file.failure'))
1017 commands.edit_blacklist = ({vim}) ->
1018 url = vim.browser.currentURI.spec
1019 location = new vim.window.URL(url)
1020 newPattern = if location.host then "*#{location.host}*" else location.href
1022 blacklistString = prefs.get('blacklist')
1024 if vim._isBlacklisted(url)
1025 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1026 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1027 return vim.options.blacklist[index].test(url)
1029 newBlacklistString = "
1030 #{matching.join(delimiter)}\
1031 #{delimiter.repeat(7)}\
1032 #{nonMatching.join(delimiter)}
1034 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1036 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1037 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1040 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1045 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1046 return if input == null
1047 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1048 # and let the regular pref parsing take care of it.
1049 prefs.set('blacklist', input)
1050 vim._onLocationChange(url)
1053 commands.help = ({vim}) ->
1054 help.toggleHelp(vim.window, vim._parent)
1056 commands.esc = ({vim}) ->
1058 vim.hideNotification()
1060 # Firefox does things differently when blurring the location bar, depending on
1061 # whether the autocomplete popup is open or not. To be consistent, always
1062 # close the autocomplete popup before blurring.
1063 vim.window.gURLBar.view.close()
1065 utils.blurActiveBrowserElement(vim)
1066 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1068 # Better safe than sorry.
1069 MarkerContainer.remove(vim.window)
1070 vim._parent.resetCaretBrowsing()
1072 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1073 help.removeHelp(vim.window)
1075 vim._setFocusType('none') # Better safe than sorry.