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 {PlacesUIUtils} = Cu.import('resource:///modules/PlacesUIUtils.jsm', {})
20 {PrivateBrowsingUtils} =
21 Cu.import('resource://gre/modules/PrivateBrowsingUtils.jsm', {})
22 {E10SUtils} = Cu.import('resource://gre/modules/E10SUtils.jsm', {})
23 {FORWARD, BACKWARD} = SelectionManager
25 READER_VIEW_PREFIX = 'about:reader?url='
26 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
32 commands.focus_location_bar = ({vim}) ->
34 vim.window.gURLBar.select() # fx76+
36 vim.window.focusAndSelectUrlBar()
38 commands.focus_search_bar = ({vim, count}) ->
39 # The `.webSearch()` method opens a search engine in a tab if the search bar
40 # has been removed. Therefore we first check if it exists.
41 if vim.window.BrowserSearch.searchBar
42 vim.window.BrowserSearch.webSearch()
44 vim.notify(translate('notification.focus_search_bar.none'))
46 helper_paste_and_go = (props, {vim}) ->
47 {gURLBar} = vim.window
48 gURLBar.value = vim.window.readFromClipboard()
49 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
51 commands.paste_and_go = helper_paste_and_go.bind(null, null)
53 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
55 commands.copy_current_url = ({vim}) ->
56 url = vim.window.gBrowser.currentURI.spec
58 if url.startsWith(READER_VIEW_PREFIX)
59 decodeURIComponent(url[READER_VIEW_PREFIX.length..])
62 utils.writeToClipboard(adjustedUrl)
63 vim.notify(translate('notification.copy_current_url.success'))
65 commands.go_up_path = ({vim, count}) ->
66 vim._run('go_up_path', {count})
68 commands.go_to_root = ({vim}) ->
69 vim._run('go_to_root')
71 commands.go_home = ({vim}) ->
72 vim.window.BrowserHome()
74 helper_go_history = (direction, {vim, count = 1}) ->
76 {SessionStore, gBrowser} = window
78 if (direction == 'back' and not gBrowser.canGoBack) or
79 (direction == 'forward' and not gBrowser.canGoForward)
80 vim.notify(translate("notification.history_#{direction}.limit"))
83 # `SessionStore.getSessionHistory()` (used below to support counts) starts
84 # lots of asynchronous tasks internally, which is a bit unreliable, it has
85 # turned out. The primary use of the `history_back` and `history_forward`
86 # commands is to go _one_ step back or forward, though, so those cases are
87 # optimized to use more reliable ways of going back and forward. Also, some
88 # extensions override the following functions, so calling them also gives
89 # better interoperability.
91 if direction == 'back'
94 window.BrowserForward()
97 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
98 {index} = sessionHistory
99 newIndex = index + count * (if direction == 'back' then -1 else 1)
100 newIndex = Math.max(newIndex, 0)
101 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
102 gBrowser.gotoIndex(newIndex)
105 commands.history_back = helper_go_history.bind(null, 'back')
107 commands.history_forward = helper_go_history.bind(null, 'forward')
109 commands.history_list = ({vim}) ->
110 menu = vim.window.document.getElementById('backForwardMenu')
111 utils.openPopup(menu)
112 if menu.childElementCount == 0
113 vim.notify(translate('notification.history_list.none'))
115 commands.reload = ({vim}) ->
116 vim.window.BrowserReload()
118 commands.reload_force = ({vim}) ->
119 vim.window.BrowserReloadSkipCache()
121 commands.reload_all = ({vim}) ->
122 vim.window.gBrowser.reloadAllTabs()
124 commands.reload_all_force = ({vim}) ->
125 for tab in vim.window.gBrowser.visibleTabs
126 gBrowser = tab.linkedBrowser
127 consts = gBrowser.webNavigation
128 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
129 gBrowser.reload(flags)
132 commands.stop = ({vim}) ->
133 vim.window.BrowserStop()
135 commands.stop_all = ({vim}) ->
136 for tab in vim.window.gBrowser.visibleTabs
137 tab.linkedBrowser.stop()
148 helper_scroll = (vim, event, args...) ->
150 method, type, directions, amounts
151 properties = null, adjustment = 0, name = 'scroll', extra = {}
154 elapsed = event.timeStamp - scrollData.lastRepeat
156 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
159 scrollData.lastRepeat = event.timeStamp
162 method, type, directions, amounts, properties, adjustment, extra
164 prefs.root.get('general.smoothScroll') and
165 prefs.root.get("general.smoothScroll.#{type}")
169 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
170 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
171 # scrolling command was invoked.
172 scrollData.nonce = nonce = {}
173 scrollData.springConstant ?= prefs.root.get(SPRING_CONSTANT_PREF)
175 SPRING_CONSTANT_PREF,
176 vim.options["smoothScroll.#{type}.spring-constant"]
179 vim.window.setTimeout((->
180 return unless scrollData.nonce == nonce
181 prefs.root.set(SPRING_CONSTANT_PREF, scrollData.springConstant)
182 scrollData.nonce = null
183 scrollData.springConstant = null
184 ), vim.options['scroll.reset_timeout'])
186 {isUIEvent = vim.isUIEvent(event)} = extra
187 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
188 if isUIEvent or helpScroll
189 activeElement = helpScroll or utils.getActiveElement(vim.window)
190 if vim._state.scrollableElements.has(activeElement) or helpScroll
191 viewportUtils.scroll(activeElement, options)
195 vim._run(name, options, reset)
198 helper_scrollByLinesX = (amount, {vim, event, count = 1}) ->
199 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
200 boost = if event.repeat then vim.options['scroll.horizontal_boost'] else 1
202 vim, event, 'scrollBy', 'lines', ['left'],
203 [amount * distance * boost * count * 5]
206 helper_scrollByLinesY = (amount, {vim, event, count = 1}) ->
207 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
208 boost = if event.repeat then vim.options['scroll.vertical_boost'] else 1
210 vim, event, 'scrollBy', 'lines', ['top'],
211 [amount * distance * boost * count * 20]
214 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
215 adjustment = vim.options["scroll.#{type}_page_adjustment"]
217 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
218 ['clientHeight'], adjustment
221 helper_scrollToX = (amount, {vim, event}) ->
222 helper_mark_last_scroll_position(vim)
224 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
227 helper_scrollToY = (amount, {vim, event}) ->
228 helper_mark_last_scroll_position(vim)
230 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
233 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
234 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
235 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
236 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
237 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
238 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
239 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
240 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
241 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
242 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
243 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
244 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
246 helper_mark_last_scroll_position = (vim) ->
247 keyStr = vim.options['scroll.last_position_mark']
248 vim._run('mark_scroll_position', {keyStr, notify: false, addToJumpList: true})
250 commands.mark_scroll_position = ({vim}) ->
251 vim._enterMode('marks', (keyStr) ->
252 vim._run('mark_scroll_position', {keyStr})
254 vim.notify(translate('notification.mark_scroll_position.enter'))
256 commands.scroll_to_mark = ({vim, event}) ->
257 vim._enterMode('marks', (keyStr) ->
258 lastPositionMark = vim.options['scroll.last_position_mark']
260 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
261 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
262 {keyStr, lastPositionMark, isUIEvent: false}
264 vim.hideNotification()
266 vim.notify(translate('notification.scroll_to_mark.enter'))
268 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
269 lastPositionMark = vim.options['scroll.last_position_mark']
271 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
272 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
273 {count, direction, lastPositionMark, isUIEvent: false}
276 commands.scroll_to_previous_position =
277 helper_scroll_to_position.bind(null, 'previous')
279 commands.scroll_to_next_position =
280 helper_scroll_to_position.bind(null, 'next')
284 commands.tab_new = ({vim}) ->
285 utils.nextTick(vim.window, ->
286 vim.window.BrowserOpenTab()
289 commands.tab_new_after_current = ({vim}) ->
291 newTabPosition = window.gBrowser.selectedTab._tPos + 1
292 utils.nextTick(window, ->
293 utils.listenOnce(window, 'TabOpen', (event) ->
294 newTab = event.originalTarget
295 window.gBrowser.moveTabTo(newTab, newTabPosition)
297 window.BrowserOpenTab()
300 commands.tab_duplicate = ({vim}) ->
301 {gBrowser} = vim.window
302 utils.nextTick(vim.window, ->
303 gBrowser.duplicateTab(gBrowser.selectedTab)
306 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
307 tabs = gBrowser.visibleTabs
308 {selectedTab} = gBrowser
310 currentIndex = tabs.indexOf(selectedTab)
311 absoluteIndex = currentIndex + relativeIndex
312 numTabsTotal = tabs.length
313 numPinnedTabs = gBrowser._numPinnedTabs
315 [numTabs, min] = switch
316 when not pinnedSeparate
318 when selectedTab.pinned
321 [numTabsTotal - numPinnedTabs, numPinnedTabs]
323 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
325 if (relativeIndex < 0 and currentIndex == min) or
326 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
327 if absoluteIndex < min
328 absoluteIndex += numTabs
329 else if absoluteIndex >= min + numTabs
330 absoluteIndex -= numTabs
332 absoluteIndex = Math.max(min, absoluteIndex)
333 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
337 helper_switch_tab = (direction, {vim, count = 1}) ->
338 {gBrowser} = vim.window
339 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
340 utils.nextTick(vim.window, ->
341 gBrowser.selectTabAtIndex(index)
344 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
346 commands.tab_select_next = helper_switch_tab.bind(null, +1)
348 helper_is_visited = (tab) ->
349 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
351 commands.tab_select_most_recent = ({vim, count = 1}) ->
352 {gBrowser} = vim.window
354 Array.prototype.filter.call(
356 (tab) -> not tab.closing and helper_is_visited(tab)
357 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
358 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
360 gBrowser.selectedTab = tab
362 vim.notify(translate('notification.tab_select_most_recent.none'))
364 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
365 {gBrowser} = vim.window
367 Array.prototype.filter.call(
369 (tab) -> not tab.closing and not helper_is_visited(tab)
370 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
371 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
373 gBrowser.selectedTab = tab
375 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
377 helper_move_tab = (direction, {vim, count = 1}) ->
378 {gBrowser} = vim.window
379 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
380 utils.nextTick(vim.window, ->
381 gBrowser.moveTabTo(gBrowser.selectedTab, index)
384 commands.tab_move_backward = helper_move_tab.bind(null, -1)
386 commands.tab_move_forward = helper_move_tab.bind(null, +1)
388 commands.tab_move_to_window = ({vim}) ->
389 {gBrowser} = vim.window
390 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
392 commands.tab_select_first = ({vim, count = 1}) ->
393 utils.nextTick(vim.window, ->
394 vim.window.gBrowser.selectTabAtIndex(count - 1)
397 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
398 firstNonPinned = vim.window.gBrowser._numPinnedTabs
399 utils.nextTick(vim.window, ->
400 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
403 commands.tab_select_last = ({vim, count = 1}) ->
404 utils.nextTick(vim.window, ->
405 vim.window.gBrowser.selectTabAtIndex(-count)
408 commands.tab_toggle_pinned = ({vim}) ->
409 currentTab = vim.window.gBrowser.selectedTab
411 vim.window.gBrowser.unpinTab(currentTab)
413 vim.window.gBrowser.pinTab(currentTab)
415 commands.tab_close = ({vim, count = 1}) ->
416 {gBrowser} = vim.window
417 return if gBrowser.selectedTab.pinned
418 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
419 utils.nextTick(vim.window, ->
420 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
421 gBrowser.removeTab(tab)
425 commands.tab_restore = ({vim, count = 1}) ->
426 utils.nextTick(vim.window, ->
427 for index in [0...count] by 1
428 restoredTab = vim.window.undoCloseTab()
429 if not restoredTab and index == 0
430 vim.notify(translate('notification.tab_restore.none'))
435 commands.tab_restore_list = ({vim}) ->
437 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
440 if fragment.childElementCount == 0
441 vim.notify(translate('notification.tab_restore.none'))
443 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
445 commands.tab_close_to_end = ({vim}) ->
446 {gBrowser} = vim.window
447 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
449 commands.tab_close_other = ({vim}) ->
450 {gBrowser} = vim.window
451 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
455 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
457 vim.markPageInteraction()
458 help.removeHelp(window)
460 markerContainer = new MarkerContainer({
462 hintChars: vim.options['hints.chars']
463 getComplementaryWrappers: (callback) ->
464 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
465 # `markerContainer.container` is `null`ed out when leaving Hints mode.
466 # If this callback is called after we’ve left Hints mode (and perhaps
467 # even entered it again), simply discard the result.
468 return unless markerContainer.container
469 if wrappers.length == 0
470 vim.notify(translate('notification.follow.none'))
471 callback({wrappers, viewport})
474 MarkerContainer.remove(window) # Better safe than sorry.
475 window.gBrowser.selectedBrowser.parentNode.appendChild(
476 markerContainer.container
479 chooseCallback = (marker, timesLeft, keyStr) ->
481 {type, href = null, elementIndex} = marker.wrapper
482 return callbackOverride({type, href, id: elementIndex, timesLeft})
484 return callback(marker, timesLeft, keyStr)
486 # Enter Hints mode immediately, with an empty set of markers. The user might
487 # press keys before any hints have been generated. Those keypresses should be
488 # handled in Hints mode, not Normal mode.
489 vim._enterMode('hints', {
490 markerContainer, count
491 callback: chooseCallback
492 matchText: vim.options['hints.match_text']
493 sleep: vim.options['hints.sleep']
496 injectHints = ({wrappers, viewport, pass}) ->
497 # See `getComplementaryWrappers` above.
498 return unless markerContainer.container
500 if wrappers.length == 0
501 if pass in ['single', 'second'] and markerContainer.markers.length == 0
502 vim.notify(translate('notification.follow.none'))
503 vim._enterMode('normal')
505 markerContainer.injectHints(wrappers, viewport, pass)
508 vim._run(name, {pass: 'second'}, injectHints)
510 vim._run(name, {pass: 'auto'}, injectHints)
512 helper_follow_clickable = (options, args) ->
515 callback = (marker, timesLeft, keyStr) ->
516 {inTab, inBackground} = options
517 {type, elementIndex} = marker.wrapper
518 isLast = (timesLeft == 1)
519 isLink = (type == 'link')
523 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
525 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
527 inBackground = not inBackground
533 inTab = false unless isLink
535 if type == 'text' or (isLink and not (inTab and inBackground))
538 vim._focusMarkerElement(elementIndex)
541 contentAreaClick = (json, browser) ->
542 # Note this function is shortened from the same-named one currently in
543 # mozilla-central/browser/actors/ClickHandlerParent.jsm. Keep in sync!
544 window = browser.ownerGlobal
546 charset: browser.characterSet,
547 referrerInfo: E10SUtils.deserializeReferrerInfo(json.referrerInfo),
548 allowMixedContent: json.allowMixedContent,
549 isContentWindowPrivate: json.isContentWindowPrivate,
550 originPrincipal: json.originPrincipal,
551 originStoragePrincipal: json.originStoragePrincipal,
552 triggeringPrincipal: json.triggeringPrincipal,
553 csp: if json.csp then E10SUtils.deserializeCSP(json.csp) else null,
554 frameOuterWindowID: json.frameOuterWindowID,
555 allowInheritPrincipal: true,
557 if json.originAttributes.userContextId
558 params.userContextId = json.originAttributes.userContextId
559 try if not PrivateBrowsingUtils.isWindowPrivate(window)
560 PlacesUIUtils.markPageAsFollowedLink(json.href)
561 window.openLinkIn(json.href, window.whereToOpenLink(json), params)
563 utils.nextTick(window, ->
564 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
565 # links using the mouse. Using that instead of simply
566 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
567 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
568 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
570 href: marker.wrapper.href
571 shiftKey: not inBackground
574 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
575 triggeringPrincipal: window.document.nodePrincipal
580 # The point of “clicking” scrollable elements is focusing them (which is
581 # done above) so that scrolling commands may scroll them. Simulating a click
582 # here usually _unfocuses_ the element.
583 else if type != 'scrollable'
584 vim._run('click_marker_element', {
586 browserOffset: vim._getBrowserOffset()
587 preventTargetBlank: vim.options.prevent_target_blank
592 name = if options.inTab then 'follow_in_tab' else 'follow'
593 helper_follow({name, callback}, args)
596 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
598 commands.follow_in_tab =
599 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
601 commands.follow_in_focused_tab =
602 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
604 helper_follow_in_window = (options, args) ->
607 callback = (marker) ->
608 vim._focusMarkerElement(marker.wrapper.elementIndex)
609 {href} = marker.wrapper
610 vim.window.openLinkIn(href, 'window', options) if href
613 helper_follow({name: 'follow_in_tab', callback}, args)
615 commands.follow_in_window =
616 helper_follow_in_window.bind(null, {})
618 commands.follow_in_private_window =
619 helper_follow_in_window.bind(null, {private: true})
621 commands.follow_multiple = (args) ->
622 args.count = Infinity
623 commands.follow(args)
625 commands.follow_copy = (args) ->
628 callback = (marker) ->
629 property = switch marker.wrapper.type
634 when 'contenteditable', 'complementary'
636 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
639 helper_follow({name: 'follow_copy', callback}, args)
641 commands.follow_focus = (args) ->
644 callback = (marker) ->
645 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
648 helper_follow({name: 'follow_focus', callback}, args)
650 commands.open_context_menu = (args) ->
653 callback = (marker) ->
654 {type, elementIndex} = marker.wrapper
655 vim._run('click_marker_element', {
657 browserOffset: vim._getBrowserOffset()
661 helper_follow({name: 'follow_context', callback}, args)
663 commands.click_browser_element = ({vim}) ->
667 getButtonMenu = (element) ->
668 if element.localName == 'dropmarker' and
669 element.parentNode?.localName == 'toolbarbutton'
670 return element.parentNode.querySelector('menupopup')
674 filter = ({complementary}, element, getElementShape) ->
676 when vim._state.scrollableElements.has(element)
678 when getButtonMenu(element)
680 when utils.isFocusable(element) or element.onclick
684 type = if type then null else 'complementary'
688 # `getElementShape(element, -1)` is intentionally _not_ used in the
689 # `complementary` run, because it results in tons of useless hints for
690 # hidden context menus.
691 shape = getElementShape(element)
692 return unless shape.nonCoveredPoint
694 # The tabs and their close buttons as well as the tab bar scroll arrows get
695 # better hints, since switching or closing tabs is the most common use case
696 # for the `eb` command.
697 isTab = element.classList?.contains('tabbrowser-tab')
700 element.classList?.contains('tab-close-button') or
701 element.classList?.contains('scrollbutton-up') or
702 element.classList?.contains('scrollbutton-down')
704 length = markerElements.push(element)
706 type, shape, isTab, isPrioritized,
707 combinedArea: shape.area,
708 elementIndex: length - 1,
711 callback = (marker) ->
712 element = markerElements[marker.wrapper.elementIndex]
713 switch marker.wrapper.type
715 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
717 getButtonMenu(element).openPopup(
718 element.parentNode, # Anchor node.
719 'after_end', # Position.
721 false, # Isn’t a context menu.
722 true, # Allow the 'position' attribute to override the above position.
724 when 'clickable', 'complementary'
725 # VimFx’s own button won’t trigger unless the click is simulated in the
726 # next tick. This might be true for other buttons as well.
727 utils.nextTick(window, ->
728 utils.focusElement(element)
729 browserOffset = {x: window.screenX, y: window.screenY}
731 when element.localName == 'tab'
732 # Only 'mousedown' seems to be able to activate tabs.
733 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
734 when element.closest('tab')
735 # If `.click()` is used on a tab close button, its tab will be
736 # selected first, which might cause the selected tab to change.
737 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
739 # `.click()` seems to trigger more buttons (such as NoScript’s
740 # button and Firefox’s “hamburger” menu button) than simulating
743 utils.openDropdown(element)
747 wrappers = markableElements.find(
748 window, filter.bind(null, {complementary: false})
751 if wrappers.length > 0
752 viewport = viewportUtils.getWindowViewport(window)
754 markerContainer = new MarkerContainer({
756 hintChars: vim.options['hints.chars']
759 getComplementaryWrappers: (callback) ->
760 newWrappers = markableElements.find(
761 window, filter.bind(null, {complementary: true})
763 callback({wrappers: newWrappers, viewport})
765 MarkerContainer.remove(window) # Better safe than sorry.
766 markerContainer.container.classList.add('ui')
767 mainWindow = window.document.body or
768 window.document.getElementById('main-window') # fallback <fx72
769 mainWindow.insertBefore(
770 markerContainer.container,
771 mainWindow.firstChild
774 [firstWrappers, secondWrappers] =
775 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
777 numChars = markerContainer.alphabet.length
778 numPrimary = markerContainer.primaryHintChars.length
779 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
782 for wrapper in firstWrappers
784 # Given the hint chars `abc de`, give the tabs weights so that the hints
785 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
786 # on. The rule is that the weight of a tab must be larger than the sum
787 # of all tabs with a longer hint. We start out at `1` and then use
788 # smaller and smaller fractions. This is to make sure that the tabs get
789 # consistent hints as the number of tabs or the size of the window
791 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
792 wrapper.combinedArea = 1 / numChars ** exponent
795 # Make sure that the tab close buttons and the tab bar scroll buttons
796 # come after all the tabs. Treating them all as the same size is fine.
797 # Their sum must be small enough in order not to affect the tab hints.
798 # It might look like using `0` is a good idea, but that results in
799 # increasingly worse hints the more tab close buttons there are.
800 wrapper.combinedArea = 1 / numChars ** numTabs
802 # Since most of the best hint characters might be used for the tabs, make
803 # sure that all other elements don’t get really bad hints. First, favor
804 # larger elements by sorting them. Then, give them all the same weight so
805 # that larger elements (such as the location bar, search bar, the web
806 # console input and other large areas in the devtools) don’t overpower the
807 # smaller ones. The usual “the larger the element, the better the hint” rule
808 # doesn’t really apply the same way for browser UI elements as in web pages.
809 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
810 for wrapper in secondWrappers
811 wrapper.combinedArea = 1
813 markerContainer.injectHints(firstWrappers, viewport, 'first')
814 markerContainer.injectHints(secondWrappers, viewport, 'second')
815 vim._enterMode('hints', {markerContainer, callback, matchText: false})
818 vim.notify(translate('notification.follow.none'))
820 helper_follow_pattern = (type, {vim}) ->
822 pattern_selector: vim.options.pattern_selector
823 pattern_attrs: vim.options.pattern_attrs
824 patterns: vim.options["#{type}_patterns"]
826 browserOffset = vim._getBrowserOffset()
827 vim._run('follow_pattern', {type, browserOffset, options})
829 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
831 commands.follow_next = helper_follow_pattern.bind(null, 'next')
833 commands.focus_text_input = ({vim, count}) ->
834 vim.markPageInteraction()
835 vim._run('focus_text_input', {count})
837 helper_follow_selectable = ({select}, args) ->
840 callback = (marker) ->
841 vim._run('element_text_select', {
842 elementIndex: marker.wrapper.elementIndex
846 vim._enterMode('caret', {select})
849 helper_follow({name: 'follow_selectable', callback}, args)
851 commands.element_text_caret =
852 helper_follow_selectable.bind(null, {select: false})
854 commands.element_text_select =
855 helper_follow_selectable.bind(null, {select: true})
857 commands.element_text_copy = (args) ->
860 callback = (marker) ->
861 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
864 helper_follow({name: 'follow_selectable', callback}, args)
866 helper_copy_marker_element = (vim, elementIndex, property) ->
867 if property == '_selection'
868 # Selecting the text and then copying that selection is better than copying
869 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
870 # and then includes those backticks in the compiled output (!), in hidden
871 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
872 # elements, text selection gives better whitespace than `.textContent`.
873 vim._run('element_text_select', {elementIndex, full: true}, ->
874 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
875 vim._run('clear_selection')
878 vim._run('copy_marker_element', {elementIndex, property})
887 helper_find_from_top_of_viewport = (vim, direction, callback) ->
888 if vim.options.find_from_top_of_viewport
889 vim._run('find_from_top_of_viewport', {direction}, ->
895 helper_find = ({highlight, linksOnly = false}, {vim}) ->
897 # Make sure to enter find mode here, since that’s where `findStorage.busy`
898 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
899 vim._enterMode('find')
902 helpSearchInput = help.getSearchInput(vim.window)
904 helpSearchInput.select()
907 # Important: Enter Find mode immediately. See `onInput` for Find mode.
908 findStorage.busy = true
909 vim._enterMode('find')
911 helper_mark_last_scroll_position(vim)
912 vim._run('mark_scroll_position', {
913 keyStr: vim.options['scroll.last_find_mark']
917 helper_find_from_top_of_viewport(vim, FORWARD, ->
918 return unless vim.mode == 'find'
919 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
920 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
921 findBar.startFind(mode)
922 utils.focusElement(findBar._findField, {select: true})
925 return unless highlightButton = findBar.getElement('highlight')
926 if highlightButton.checked != highlight
927 highlightButton.click()
931 commands.find = helper_find.bind(null, {highlight: false})
933 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
935 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
937 helper_find_again = (direction, {vim}) ->
938 return if findStorage.busy
940 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
941 if findStorage.lastSearchString.length == 0
942 vim.notify(translate('notification.find_again.none'))
945 findStorage.busy = true
947 helper_mark_last_scroll_position(vim)
948 helper_find_from_top_of_viewport(vim, direction, ->
949 findBar._findField.value = findStorage.lastSearchString
951 # `.onFindResult` is temporarily hacked to be able to know when the
952 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
953 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
955 originalOnFindResult = findBar.onFindResult
956 originalUpdateControlState = findBar.updateControlState
958 findBar.onFindResult = (data) ->
959 # Prevent the find bar from re-opening if there are no matches.
960 data.storeResult = false
961 findBar.onFindResult = originalOnFindResult
962 findBar.updateControlState = originalUpdateControlState
963 findBar.onFindResult(data)
966 findBar.updateControlState = (args...) ->
967 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
968 # matches here, so no need to take care of that in this case.
969 findBar.onFindResult = originalOnFindResult
970 findBar.updateControlState = originalUpdateControlState
971 findBar.updateControlState(args...)
975 message = findBar._findStatusDesc.textContent
976 vim.notify(message) if message
977 findStorage.busy = false
979 findBar.onFindAgainCommand(not direction)
983 commands.find_next = helper_find_again.bind(null, FORWARD)
985 commands.find_previous = helper_find_again.bind(null, BACKWARD)
989 commands.window_new = ({vim}) ->
990 vim.window.OpenBrowserWindow()
992 commands.window_new_private = ({vim}) ->
993 vim.window.OpenBrowserWindow({private: true})
995 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
996 type = if blacklist then 'blacklist' else 'explicit'
997 vim._enterMode('ignore', {type})
999 # Quote next keypress (pass it through to the page).
1000 commands.quote = ({vim, count = 1}) ->
1001 vim._enterMode('ignore', {type: 'explicit', count})
1003 commands.enter_reader_view = ({vim}) ->
1004 button = vim.window.document.getElementById('reader-mode-button')
1005 if not button?.hidden
1008 vim.notify(translate('notification.enter_reader_view.none'))
1010 commands.reload_config_file = ({vim}) ->
1011 vim._parent.emit('shutdown')
1012 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1014 vim.notify(translate('notification.reload_config_file.none'))
1016 vim.notify(translate('notification.reload_config_file.success'))
1018 vim.notify(translate('notification.reload_config_file.failure'))
1021 commands.edit_blacklist = ({vim}) ->
1022 url = vim.browser.currentURI.spec
1023 location = new vim.window.URL(url)
1024 newPattern = if location.host then "*#{location.host}*" else location.href
1026 blacklistString = prefs.get('blacklist')
1028 if vim._isBlacklisted(url)
1029 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1030 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1031 return vim.options.blacklist[index].test(url)
1033 newBlacklistString = "
1034 #{matching.join(delimiter)}\
1035 #{delimiter.repeat(7)}\
1036 #{nonMatching.join(delimiter)}
1038 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1040 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1041 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1044 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1049 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1050 return if input == null
1051 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1052 # and let the regular pref parsing take care of it.
1053 prefs.set('blacklist', input)
1054 vim._onLocationChange(url)
1057 commands.help = ({vim}) ->
1058 help.toggleHelp(vim.window, vim._parent)
1060 commands.esc = ({vim}) ->
1062 vim.hideNotification()
1064 # Firefox does things differently when blurring the location bar, depending on
1065 # whether the autocomplete popup is open or not. To be consistent, always
1066 # close the autocomplete popup before blurring.
1067 vim.window.gURLBar.view.close()
1069 utils.blurActiveBrowserElement(vim)
1070 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1072 # Better safe than sorry.
1073 MarkerContainer.remove(vim.window)
1074 vim._parent.resetCaretBrowsing()
1076 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1077 help.removeHelp(vim.window)
1079 vim._setFocusType('none') # Better safe than sorry.