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'
27 USER_CONTEXT_ID_ATTRIBUTE_NAME = 'usercontextid'
33 commands.focus_location_bar = ({vim}) ->
35 vim.window.gURLBar.select() # fx76+
37 vim.window.focusAndSelectUrlBar()
39 commands.focus_search_bar = ({vim, count}) ->
40 # The `.webSearch()` method opens a search engine in a tab if the search bar
41 # has been removed. Therefore we first check if it exists.
42 if vim.window.BrowserSearch.searchBar
43 vim.window.BrowserSearch.webSearch()
45 vim.notify(translate('notification.focus_search_bar.none'))
47 helper_paste_and_go = (props, {vim}) ->
48 {gURLBar} = vim.window
49 gURLBar.value = vim.window.readFromClipboard()
50 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
52 commands.paste_and_go = helper_paste_and_go.bind(null, null)
54 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
56 commands.copy_current_url = ({vim}) ->
57 url = vim.window.gBrowser.currentURI.spec
59 if url.startsWith(READER_VIEW_PREFIX)
60 decodeURIComponent(url[READER_VIEW_PREFIX.length..])
63 utils.writeToClipboard(adjustedUrl)
64 vim.notify(translate('notification.copy_current_url.success'))
66 commands.go_up_path = ({vim, count}) ->
67 vim._run('go_up_path', {count})
69 commands.go_to_root = ({vim}) ->
70 vim._run('go_to_root')
72 commands.go_home = ({vim}) ->
73 vim.window.BrowserHome()
75 helper_go_history = (direction, {vim, count = 1}) ->
77 {SessionStore, gBrowser} = window
79 if (direction == 'back' and not gBrowser.canGoBack) or
80 (direction == 'forward' and not gBrowser.canGoForward)
81 vim.notify(translate("notification.history_#{direction}.limit"))
84 # `SessionStore.getSessionHistory()` (used below to support counts) starts
85 # lots of asynchronous tasks internally, which is a bit unreliable, it has
86 # turned out. The primary use of the `history_back` and `history_forward`
87 # commands is to go _one_ step back or forward, though, so those cases are
88 # optimized to use more reliable ways of going back and forward. Also, some
89 # extensions override the following functions, so calling them also gives
90 # better interoperability.
92 if direction == 'back'
95 window.BrowserForward()
98 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
99 {index} = sessionHistory
100 newIndex = index + count * (if direction == 'back' then -1 else 1)
101 newIndex = Math.max(newIndex, 0)
102 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
103 gBrowser.gotoIndex(newIndex)
106 commands.history_back = helper_go_history.bind(null, 'back')
108 commands.history_forward = helper_go_history.bind(null, 'forward')
110 commands.history_list = ({vim}) ->
111 menu = vim.window.document.getElementById('backForwardMenu')
112 utils.openPopup(menu)
113 if menu.childElementCount == 0
114 vim.notify(translate('notification.history_list.none'))
116 commands.reload = ({vim}) ->
117 vim.window.BrowserReload()
119 commands.reload_force = ({vim}) ->
120 vim.window.BrowserReloadSkipCache()
122 commands.reload_all = ({vim}) ->
123 vim.window.gBrowser.reloadAllTabs()
125 commands.reload_all_force = ({vim}) ->
126 for tab in vim.window.gBrowser.visibleTabs
127 gBrowser = tab.linkedBrowser
128 consts = gBrowser.webNavigation
129 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
130 gBrowser.reload(flags)
133 commands.stop = ({vim}) ->
134 vim.window.BrowserStop()
136 commands.stop_all = ({vim}) ->
137 for tab in vim.window.gBrowser.visibleTabs
138 tab.linkedBrowser.stop()
149 helper_scroll = (vim, event, args...) ->
151 method, type, directions, amounts
152 properties = null, adjustment = 0, name = 'scroll', extra = {}
155 elapsed = event.timeStamp - scrollData.lastRepeat
157 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
160 scrollData.lastRepeat = event.timeStamp
163 method, type, directions, amounts, properties, adjustment, extra
165 prefs.root.get('general.smoothScroll') and
166 prefs.root.get("general.smoothScroll.#{type}")
170 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
171 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
172 # scrolling command was invoked.
173 scrollData.nonce = nonce = {}
174 scrollData.springConstant ?= prefs.root.get(SPRING_CONSTANT_PREF)
176 SPRING_CONSTANT_PREF,
177 vim.options["smoothScroll.#{type}.spring-constant"]
180 vim.window.setTimeout((->
181 return unless scrollData.nonce == nonce
182 prefs.root.set(SPRING_CONSTANT_PREF, scrollData.springConstant)
183 scrollData.nonce = null
184 scrollData.springConstant = null
185 ), vim.options['scroll.reset_timeout'])
187 {isUIEvent = vim.isUIEvent(event)} = extra
188 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
189 if isUIEvent or helpScroll
190 activeElement = helpScroll or utils.getActiveElement(vim.window)
191 if vim._state.scrollableElements.has(activeElement) or helpScroll
192 viewportUtils.scroll(activeElement, options)
196 vim._run(name, options, reset)
199 helper_scrollByLinesX = (amount, {vim, event, count = 1}) ->
200 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
201 boost = if event.repeat then vim.options['scroll.horizontal_boost'] else 1
203 vim, event, 'scrollBy', 'lines', ['left'],
204 [amount * distance * boost * count * 5]
207 helper_scrollByLinesY = (amount, {vim, event, count = 1}) ->
208 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
209 boost = if event.repeat then vim.options['scroll.vertical_boost'] else 1
211 vim, event, 'scrollBy', 'lines', ['top'],
212 [amount * distance * boost * count * 20]
215 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
216 adjustment = vim.options["scroll.#{type}_page_adjustment"]
218 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
219 ['clientHeight'], adjustment
222 helper_scrollToX = (amount, {vim, event}) ->
223 helper_mark_last_scroll_position(vim)
225 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
228 helper_scrollToY = (amount, {vim, event}) ->
229 helper_mark_last_scroll_position(vim)
231 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
234 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
235 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
236 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
237 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
238 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
239 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
240 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
241 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
242 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
243 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
244 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
245 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
247 helper_mark_last_scroll_position = (vim) ->
248 keyStr = vim.options['scroll.last_position_mark']
249 vim._run('mark_scroll_position', {keyStr, notify: false, addToJumpList: true})
251 commands.mark_scroll_position = ({vim}) ->
252 vim._enterMode('marks', (keyStr) ->
253 vim._run('mark_scroll_position', {keyStr})
255 vim.notify(translate('notification.mark_scroll_position.enter'))
257 commands.scroll_to_mark = ({vim, event}) ->
258 vim._enterMode('marks', (keyStr) ->
259 lastPositionMark = vim.options['scroll.last_position_mark']
261 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
262 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
263 {keyStr, lastPositionMark, isUIEvent: false}
265 vim.hideNotification()
267 vim.notify(translate('notification.scroll_to_mark.enter'))
269 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
270 lastPositionMark = vim.options['scroll.last_position_mark']
272 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
273 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
274 {count, direction, lastPositionMark, isUIEvent: false}
277 commands.scroll_to_previous_position =
278 helper_scroll_to_position.bind(null, 'previous')
280 commands.scroll_to_next_position =
281 helper_scroll_to_position.bind(null, 'next')
285 commands.tab_new = ({vim}) ->
286 utils.nextTick(vim.window, ->
287 vim.window.BrowserOpenTab()
290 commands.tab_new_after_current = ({vim}) ->
292 newTabPosition = window.gBrowser.selectedTab._tPos + 1
293 utils.nextTick(window, ->
294 utils.listenOnce(window, 'TabOpen', (event) ->
295 newTab = event.originalTarget
296 window.gBrowser.moveTabTo(newTab, newTabPosition)
298 window.BrowserOpenTab()
301 commands.tab_duplicate = ({vim}) ->
302 {gBrowser} = vim.window
303 utils.nextTick(vim.window, ->
304 gBrowser.duplicateTab(gBrowser.selectedTab)
307 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
308 tabs = gBrowser.visibleTabs
309 {selectedTab} = gBrowser
311 currentIndex = tabs.indexOf(selectedTab)
312 absoluteIndex = currentIndex + relativeIndex
313 numTabsTotal = tabs.length
314 numPinnedTabs = gBrowser._numPinnedTabs
316 [numTabs, min] = switch
317 when not pinnedSeparate
319 when selectedTab.pinned
322 [numTabsTotal - numPinnedTabs, numPinnedTabs]
324 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
326 if (relativeIndex < 0 and currentIndex == min) or
327 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
328 if absoluteIndex < min
329 absoluteIndex += numTabs
330 else if absoluteIndex >= min + numTabs
331 absoluteIndex -= numTabs
333 absoluteIndex = Math.max(min, absoluteIndex)
334 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
338 helper_switch_tab = (direction, {vim, count = 1}) ->
339 {gBrowser} = vim.window
340 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
341 utils.nextTick(vim.window, ->
342 gBrowser.selectTabAtIndex(index)
345 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
347 commands.tab_select_next = helper_switch_tab.bind(null, +1)
349 helper_is_visited = (tab) ->
350 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
352 commands.tab_select_most_recent = ({vim, count = 1}) ->
353 {gBrowser} = vim.window
355 Array.prototype.filter.call(
357 (tab) -> not tab.closing and helper_is_visited(tab)
358 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
359 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
361 gBrowser.selectedTab = tab
363 vim.notify(translate('notification.tab_select_most_recent.none'))
365 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
366 {gBrowser} = vim.window
368 Array.prototype.filter.call(
370 (tab) -> not tab.closing and not helper_is_visited(tab)
371 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
372 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
374 gBrowser.selectedTab = tab
376 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
378 helper_move_tab = (direction, {vim, count = 1}) ->
379 {gBrowser} = vim.window
380 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
381 utils.nextTick(vim.window, ->
382 gBrowser.moveTabTo(gBrowser.selectedTab, index)
385 commands.tab_move_backward = helper_move_tab.bind(null, -1)
387 commands.tab_move_forward = helper_move_tab.bind(null, +1)
389 commands.tab_move_to_window = ({vim}) ->
390 {gBrowser} = vim.window
391 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
393 commands.tab_select_first = ({vim, count = 1}) ->
394 utils.nextTick(vim.window, ->
395 vim.window.gBrowser.selectTabAtIndex(count - 1)
398 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
399 firstNonPinned = vim.window.gBrowser._numPinnedTabs
400 utils.nextTick(vim.window, ->
401 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
404 commands.tab_select_last = ({vim, count = 1}) ->
405 utils.nextTick(vim.window, ->
406 vim.window.gBrowser.selectTabAtIndex(-count)
409 commands.tab_toggle_pinned = ({vim}) ->
410 currentTab = vim.window.gBrowser.selectedTab
412 vim.window.gBrowser.unpinTab(currentTab)
414 vim.window.gBrowser.pinTab(currentTab)
416 commands.tab_close = ({vim, count = 1}) ->
417 {gBrowser} = vim.window
418 return if gBrowser.selectedTab.pinned
419 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
420 utils.nextTick(vim.window, ->
421 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
422 gBrowser.removeTab(tab)
426 commands.tab_restore = ({vim, count = 1}) ->
427 utils.nextTick(vim.window, ->
428 for index in [0...count] by 1
429 restoredTab = vim.window.undoCloseTab()
430 if not restoredTab and index == 0
431 vim.notify(translate('notification.tab_restore.none'))
436 commands.tab_restore_list = ({vim}) ->
438 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
441 if fragment.childElementCount == 0
442 vim.notify(translate('notification.tab_restore.none'))
444 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
446 commands.tab_close_to_end = ({vim}) ->
447 {gBrowser} = vim.window
448 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
450 commands.tab_close_other = ({vim}) ->
451 {gBrowser} = vim.window
452 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
456 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
458 vim.markPageInteraction()
459 help.removeHelp(window)
461 markerContainer = new MarkerContainer({
463 hintChars: vim.options['hints.chars']
464 getComplementaryWrappers: (callback) ->
465 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
466 # `markerContainer.container` is `null`ed out when leaving Hints mode.
467 # If this callback is called after we’ve left Hints mode (and perhaps
468 # even entered it again), simply discard the result.
469 return unless markerContainer.container
470 if wrappers.length == 0
471 vim.notify(translate('notification.follow.none'))
472 callback({wrappers, viewport})
475 MarkerContainer.remove(window) # Better safe than sorry.
476 window.gBrowser.selectedBrowser.parentNode.appendChild(
477 markerContainer.container
480 chooseCallback = (marker, timesLeft, keyStr) ->
482 {type, href = null, elementIndex} = marker.wrapper
483 return callbackOverride({type, href, id: elementIndex, timesLeft})
485 return callback(marker, timesLeft, keyStr)
487 # Enter Hints mode immediately, with an empty set of markers. The user might
488 # press keys before any hints have been generated. Those keypresses should be
489 # handled in Hints mode, not Normal mode.
490 vim._enterMode('hints', {
491 markerContainer, count
492 callback: chooseCallback
493 matchText: vim.options['hints.match_text']
494 sleep: vim.options['hints.sleep']
497 injectHints = ({wrappers, viewport, pass}) ->
498 # See `getComplementaryWrappers` above.
499 return unless markerContainer.container
501 if wrappers.length == 0
502 if pass in ['single', 'second'] and markerContainer.markers.length == 0
503 vim.notify(translate('notification.follow.none'))
504 vim._enterMode('normal')
506 markerContainer.injectHints(wrappers, viewport, pass)
509 vim._run(name, {pass: 'second'}, injectHints)
511 vim._run(name, {pass: 'auto'}, injectHints)
514 helper_add_user_context_id = (gBrowser, objectToAugment) ->
515 contextAttribute = gBrowser.selectedTab.attributes.getNamedItem(
516 USER_CONTEXT_ID_ATTRIBUTE_NAME)
518 # default has no context attribute so only set if it exists
520 objectToAugment.userContextId = contextAttribute.value
522 return objectToAugment
525 helper_follow_clickable = (options, args) ->
528 callback = (marker, timesLeft, keyStr) ->
529 {inTab, inBackground} = options
530 {type, elementIndex} = marker.wrapper
531 isLast = (timesLeft == 1)
532 isLink = (type == 'link')
536 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
538 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
540 inBackground = not inBackground
546 inTab = false unless isLink
548 if type == 'text' or (isLink and not (inTab and inBackground))
551 vim._focusMarkerElement(elementIndex)
554 contentAreaClick = (json, browser) ->
555 # Note this function is shortened from the same-named one currently in
556 # mozilla-central/browser/actors/ClickHandlerParent.jsm. Keep in sync!
557 window = browser.ownerGlobal
559 charset: browser.characterSet,
560 referrerInfo: E10SUtils.deserializeReferrerInfo(json.referrerInfo),
561 allowMixedContent: json.allowMixedContent, # <=fx88
562 isContentWindowPrivate: json.isContentWindowPrivate,
563 originPrincipal: json.originPrincipal,
564 originStoragePrincipal: json.originStoragePrincipal,
565 triggeringPrincipal: json.triggeringPrincipal,
566 csp: if json.csp then E10SUtils.deserializeCSP(json.csp) else null,
567 frameOuterWindowID: json.frameOuterWindowID, # <=fx79
568 frameID: json.frameID, # >=fx80
569 allowInheritPrincipal: true,
571 if json.originAttributes.userContextId
572 params.userContextId = json.originAttributes.userContextId
573 try if not PrivateBrowsingUtils.isWindowPrivate(window)
574 PlacesUIUtils.markPageAsFollowedLink(json.href)
575 window.openLinkIn(json.href, window.whereToOpenLink(json), params)
577 utils.nextTick(window, ->
578 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
579 # links using the mouse. Using that instead of simply
580 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
581 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
582 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
584 href: marker.wrapper.href
585 shiftKey: not inBackground
588 originAttributes: helper_add_user_context_id(
589 vim.browser.ownerGlobal.gBrowser,
590 window.document.nodePrincipal?.originAttributes ? {}
592 triggeringPrincipal: window.document.nodePrincipal
597 # The point of “clicking” scrollable elements is focusing them (which is
598 # done above) so that scrolling commands may scroll them. Simulating a click
599 # here usually _unfocuses_ the element.
600 else if type != 'scrollable'
601 vim._run('click_marker_element', {
603 browserOffset: vim._getBrowserOffset()
604 preventTargetBlank: vim.options.prevent_target_blank
609 name = if options.inTab then 'follow_in_tab' else 'follow'
610 helper_follow({name, callback}, args)
613 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
615 commands.follow_in_tab =
616 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
618 commands.follow_in_focused_tab =
619 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
621 helper_follow_in_window = (options, args) ->
624 callback = (marker) ->
625 vim._focusMarkerElement(marker.wrapper.elementIndex)
626 {href} = marker.wrapper
627 options.triggeringPrincipal = vim.window.document.nodePrincipal
628 options = helper_add_user_context_id(vim.window.gBrowser, options)
630 vim.window.openLinkIn(href, 'window', options) if href
633 helper_follow({name: 'follow_in_tab', callback}, args)
635 commands.follow_in_window =
636 helper_follow_in_window.bind(null, {})
638 commands.follow_in_private_window =
639 helper_follow_in_window.bind(null, {private: true})
641 commands.follow_multiple = (args) ->
642 args.count = Infinity
643 commands.follow(args)
645 commands.follow_copy = (args) ->
648 callback = (marker) ->
649 property = switch marker.wrapper.type
654 when 'contenteditable', 'complementary'
656 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
659 helper_follow({name: 'follow_copy', callback}, args)
661 commands.follow_focus = (args) ->
664 callback = (marker) ->
665 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
668 helper_follow({name: 'follow_focus', callback}, args)
670 commands.open_context_menu = (args) ->
673 callback = (marker) ->
674 {type, elementIndex} = marker.wrapper
675 vim._run('click_marker_element', {
677 browserOffset: vim._getBrowserOffset()
681 helper_follow({name: 'follow_context', callback}, args)
683 commands.click_browser_element = ({vim}) ->
687 getButtonMenu = (element) ->
688 if element.localName == 'dropmarker' and
689 element.parentNode?.localName == 'toolbarbutton'
690 return element.parentNode.querySelector('menupopup')
694 filter = ({complementary}, element, getElementShape) ->
696 when vim._state.scrollableElements.has(element)
698 when getButtonMenu(element)
700 when utils.isFocusable(element) or element.onclick
704 type = if type then null else 'complementary'
708 # `getElementShape(element, -1)` is intentionally _not_ used in the
709 # `complementary` run, because it results in tons of useless hints for
710 # hidden context menus.
711 shape = getElementShape(element)
712 return unless shape.nonCoveredPoint
714 # The tabs and their close buttons as well as the tab bar scroll arrows get
715 # better hints, since switching or closing tabs is the most common use case
716 # for the `eb` command.
717 isTab = element.classList?.contains('tabbrowser-tab')
720 element.classList?.contains('tab-close-button') or
721 element.classList?.contains('scrollbutton-up') or
722 element.classList?.contains('scrollbutton-down')
724 length = markerElements.push(element)
726 type, shape, isTab, isPrioritized,
727 combinedArea: shape.area,
728 elementIndex: length - 1,
731 callback = (marker) ->
732 element = markerElements[marker.wrapper.elementIndex]
733 switch marker.wrapper.type
735 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
737 getButtonMenu(element).openPopup(
738 element.parentNode, # Anchor node.
739 'after_end', # Position.
741 false, # Isn’t a context menu.
742 true, # Allow the 'position' attribute to override the above position.
744 when 'clickable', 'complementary'
745 # VimFx’s own button won’t trigger unless the click is simulated in the
746 # next tick. This might be true for other buttons as well.
747 utils.nextTick(window, ->
748 utils.focusElement(element)
749 browserOffset = {x: window.screenX, y: window.screenY}
751 when element.localName == 'tab'
752 # Only 'mousedown' seems to be able to activate tabs.
753 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
754 when element.closest('tab')
755 # If `.click()` is used on a tab close button, its tab will be
756 # selected first, which might cause the selected tab to change.
757 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
759 # `.click()` seems to trigger more buttons (such as NoScript’s
760 # button and Firefox’s “hamburger” menu button) than simulating
763 utils.openDropdown(element)
767 wrappers = markableElements.find(
768 window, filter.bind(null, {complementary: false})
771 if wrappers.length > 0
772 viewport = viewportUtils.getWindowViewport(window)
774 markerContainer = new MarkerContainer({
776 hintChars: vim.options['hints.chars']
779 getComplementaryWrappers: (callback) ->
780 newWrappers = markableElements.find(
781 window, filter.bind(null, {complementary: true})
783 callback({wrappers: newWrappers, viewport})
785 MarkerContainer.remove(window) # Better safe than sorry.
786 markerContainer.container.classList.add('ui')
787 mainWindow = window.document.body or
788 window.document.getElementById('main-window') # fallback <fx72
789 mainWindow.insertBefore(
790 markerContainer.container,
791 mainWindow.firstChild
794 [firstWrappers, secondWrappers] =
795 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
797 numChars = markerContainer.alphabet.length
798 numPrimary = markerContainer.primaryHintChars.length
799 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
802 for wrapper in firstWrappers
804 # Given the hint chars `abc de`, give the tabs weights so that the hints
805 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
806 # on. The rule is that the weight of a tab must be larger than the sum
807 # of all tabs with a longer hint. We start out at `1` and then use
808 # smaller and smaller fractions. This is to make sure that the tabs get
809 # consistent hints as the number of tabs or the size of the window
811 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
812 wrapper.combinedArea = 1 / numChars ** exponent
815 # Make sure that the tab close buttons and the tab bar scroll buttons
816 # come after all the tabs. Treating them all as the same size is fine.
817 # Their sum must be small enough in order not to affect the tab hints.
818 # It might look like using `0` is a good idea, but that results in
819 # increasingly worse hints the more tab close buttons there are.
820 wrapper.combinedArea = 1 / numChars ** numTabs
822 # Since most of the best hint characters might be used for the tabs, make
823 # sure that all other elements don’t get really bad hints. First, favor
824 # larger elements by sorting them. Then, give them all the same weight so
825 # that larger elements (such as the location bar, search bar, the web
826 # console input and other large areas in the devtools) don’t overpower the
827 # smaller ones. The usual “the larger the element, the better the hint” rule
828 # doesn’t really apply the same way for browser UI elements as in web pages.
829 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
830 for wrapper in secondWrappers
831 wrapper.combinedArea = 1
833 markerContainer.injectHints(firstWrappers, viewport, 'first')
834 markerContainer.injectHints(secondWrappers, viewport, 'second')
835 vim._enterMode('hints', {markerContainer, callback, matchText: false})
838 vim.notify(translate('notification.follow.none'))
840 helper_follow_pattern = (type, {vim}) ->
842 pattern_selector: vim.options.pattern_selector
843 pattern_attrs: vim.options.pattern_attrs
844 patterns: vim.options["#{type}_patterns"]
846 browserOffset = vim._getBrowserOffset()
847 vim._run('follow_pattern', {type, browserOffset, options})
849 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
851 commands.follow_next = helper_follow_pattern.bind(null, 'next')
853 commands.focus_text_input = ({vim, count}) ->
854 vim.markPageInteraction()
855 vim._run('focus_text_input', {count})
857 helper_follow_selectable = ({select}, args) ->
860 callback = (marker) ->
861 vim._run('element_text_select', {
862 elementIndex: marker.wrapper.elementIndex
866 vim._enterMode('caret', {select})
869 helper_follow({name: 'follow_selectable', callback}, args)
871 commands.element_text_caret =
872 helper_follow_selectable.bind(null, {select: false})
874 commands.element_text_select =
875 helper_follow_selectable.bind(null, {select: true})
877 commands.element_text_copy = (args) ->
880 callback = (marker) ->
881 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
884 helper_follow({name: 'follow_selectable', callback}, args)
886 helper_copy_marker_element = (vim, elementIndex, property) ->
887 if property == '_selection'
888 # Selecting the text and then copying that selection is better than copying
889 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
890 # and then includes those backticks in the compiled output (!), in hidden
891 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
892 # elements, text selection gives better whitespace than `.textContent`.
893 vim._run('element_text_select', {elementIndex, full: true}, ->
894 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
895 vim._run('clear_selection')
898 vim._run('copy_marker_element', {elementIndex, property})
907 helper_find_from_top_of_viewport = (vim, direction, callback) ->
908 if vim.options.find_from_top_of_viewport
909 vim._run('find_from_top_of_viewport', {direction}, ->
915 helper_find = ({highlight, linksOnly = false}, {vim}) ->
917 # Make sure to enter find mode here, since that’s where `findStorage.busy`
918 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
919 vim._enterMode('find')
922 helpSearchInput = help.getSearchInput(vim.window)
924 helpSearchInput.select()
927 # Important: Enter Find mode immediately. See `onInput` for Find mode.
928 findStorage.busy = true
929 vim._enterMode('find')
931 helper_mark_last_scroll_position(vim)
932 vim._run('mark_scroll_position', {
933 keyStr: vim.options['scroll.last_find_mark']
937 helper_find_from_top_of_viewport(vim, FORWARD, ->
938 return unless vim.mode == 'find'
939 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
940 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
941 findBar.startFind(mode)
942 utils.focusElement(findBar._findField, {select: true})
945 return unless highlightButton = findBar.getElement('highlight')
946 if highlightButton.checked != highlight
947 highlightButton.click()
951 commands.find = helper_find.bind(null, {highlight: false})
953 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
955 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
957 helper_find_again = (direction, {vim}) ->
958 return if findStorage.busy
960 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
961 if findStorage.lastSearchString.length == 0
962 vim.notify(translate('notification.find_again.none'))
965 findStorage.busy = true
967 helper_mark_last_scroll_position(vim)
968 helper_find_from_top_of_viewport(vim, direction, ->
969 findBar._findField.value = findStorage.lastSearchString
971 # `.onFindResult` is temporarily hacked to be able to know when the
972 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
973 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
975 originalOnFindResult = findBar.onFindResult
976 originalUpdateControlState = findBar.updateControlState
978 findBar.onFindResult = (data) ->
979 # Prevent the find bar from re-opening if there are no matches.
980 data.storeResult = false
981 findBar.onFindResult = originalOnFindResult
982 findBar.updateControlState = originalUpdateControlState
983 findBar.onFindResult(data)
986 findBar.updateControlState = (args...) ->
987 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
988 # matches here, so no need to take care of that in this case.
989 findBar.onFindResult = originalOnFindResult
990 findBar.updateControlState = originalUpdateControlState
991 findBar.updateControlState(args...)
995 message = findBar._findStatusDesc.textContent
996 vim.notify(message) if message
997 findStorage.busy = false
999 findBar.onFindAgainCommand(not direction)
1003 commands.find_next = helper_find_again.bind(null, FORWARD)
1005 commands.find_previous = helper_find_again.bind(null, BACKWARD)
1009 commands.window_new = ({vim}) ->
1010 vim.window.OpenBrowserWindow()
1012 commands.window_new_private = ({vim}) ->
1013 vim.window.OpenBrowserWindow({private: true})
1015 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
1016 type = if blacklist then 'blacklist' else 'explicit'
1017 vim._enterMode('ignore', {type})
1019 # Quote next keypress (pass it through to the page).
1020 commands.quote = ({vim, count = 1}) ->
1021 vim._enterMode('ignore', {type: 'explicit', count})
1023 commands.enter_reader_view = ({vim}) ->
1024 button = vim.window.document.getElementById('reader-mode-button')
1025 if not button?.hidden
1028 vim.notify(translate('notification.enter_reader_view.none'))
1030 commands.reload_config_file = ({vim}) ->
1031 vim._parent.emit('shutdown')
1032 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1034 vim.notify(translate('notification.reload_config_file.none'))
1036 vim.notify(translate('notification.reload_config_file.success'))
1038 vim.notify(translate('notification.reload_config_file.failure'))
1041 commands.edit_blacklist = ({vim}) ->
1042 url = vim.browser.currentURI.spec
1043 location = new vim.window.URL(url)
1044 newPattern = if location.host then "*#{location.host}*" else location.href
1046 blacklistString = prefs.get('blacklist')
1048 if vim._isBlacklisted(url)
1049 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1050 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1051 return vim.options.blacklist[index].test(url)
1053 newBlacklistString = "
1054 #{matching.join(delimiter)}\
1055 #{delimiter.repeat(7)}\
1056 #{nonMatching.join(delimiter)}
1058 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1060 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1061 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1064 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1069 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1070 return if input == null
1071 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1072 # and let the regular pref parsing take care of it.
1073 prefs.set('blacklist', input)
1074 vim._onLocationChange(url)
1077 commands.help = ({vim}) ->
1078 help.toggleHelp(vim.window, vim._parent)
1080 commands.esc = ({vim}) ->
1082 vim.hideNotification()
1084 # Firefox does things differently when blurring the location bar, depending on
1085 # whether the autocomplete popup is open or not. To be consistent, always
1086 # close the autocomplete popup before blurring.
1087 vim.window.gURLBar.view.close()
1089 utils.blurActiveBrowserElement(vim)
1090 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1092 # Better safe than sorry.
1093 MarkerContainer.remove(vim.window)
1094 vim._parent.resetCaretBrowsing()
1096 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1097 help.removeHelp(vim.window)
1099 vim._setFocusType('none') # Better safe than sorry.