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, # <=fx79
555 frameID: json.frameID, # >=fx80
556 allowInheritPrincipal: true,
558 if json.originAttributes.userContextId
559 params.userContextId = json.originAttributes.userContextId
560 try if not PrivateBrowsingUtils.isWindowPrivate(window)
561 PlacesUIUtils.markPageAsFollowedLink(json.href)
562 window.openLinkIn(json.href, window.whereToOpenLink(json), params)
564 utils.nextTick(window, ->
565 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
566 # links using the mouse. Using that instead of simply
567 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
568 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
569 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
571 href: marker.wrapper.href
572 shiftKey: not inBackground
575 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
576 triggeringPrincipal: window.document.nodePrincipal
581 # The point of “clicking” scrollable elements is focusing them (which is
582 # done above) so that scrolling commands may scroll them. Simulating a click
583 # here usually _unfocuses_ the element.
584 else if type != 'scrollable'
585 vim._run('click_marker_element', {
587 browserOffset: vim._getBrowserOffset()
588 preventTargetBlank: vim.options.prevent_target_blank
593 name = if options.inTab then 'follow_in_tab' else 'follow'
594 helper_follow({name, callback}, args)
597 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
599 commands.follow_in_tab =
600 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
602 commands.follow_in_focused_tab =
603 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
605 helper_follow_in_window = (options, args) ->
608 callback = (marker) ->
609 vim._focusMarkerElement(marker.wrapper.elementIndex)
610 {href} = marker.wrapper
611 options.triggeringPrincipal = vim.window.document.nodePrincipal
612 vim.window.openLinkIn(href, 'window', options) if href
615 helper_follow({name: 'follow_in_tab', callback}, args)
617 commands.follow_in_window =
618 helper_follow_in_window.bind(null, {})
620 commands.follow_in_private_window =
621 helper_follow_in_window.bind(null, {private: true})
623 commands.follow_multiple = (args) ->
624 args.count = Infinity
625 commands.follow(args)
627 commands.follow_copy = (args) ->
630 callback = (marker) ->
631 property = switch marker.wrapper.type
636 when 'contenteditable', 'complementary'
638 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
641 helper_follow({name: 'follow_copy', callback}, args)
643 commands.follow_focus = (args) ->
646 callback = (marker) ->
647 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
650 helper_follow({name: 'follow_focus', callback}, args)
652 commands.open_context_menu = (args) ->
655 callback = (marker) ->
656 {type, elementIndex} = marker.wrapper
657 vim._run('click_marker_element', {
659 browserOffset: vim._getBrowserOffset()
663 helper_follow({name: 'follow_context', callback}, args)
665 commands.click_browser_element = ({vim}) ->
669 getButtonMenu = (element) ->
670 if element.localName == 'dropmarker' and
671 element.parentNode?.localName == 'toolbarbutton'
672 return element.parentNode.querySelector('menupopup')
676 filter = ({complementary}, element, getElementShape) ->
678 when vim._state.scrollableElements.has(element)
680 when getButtonMenu(element)
682 when utils.isFocusable(element) or element.onclick
686 type = if type then null else 'complementary'
690 # `getElementShape(element, -1)` is intentionally _not_ used in the
691 # `complementary` run, because it results in tons of useless hints for
692 # hidden context menus.
693 shape = getElementShape(element)
694 return unless shape.nonCoveredPoint
696 # The tabs and their close buttons as well as the tab bar scroll arrows get
697 # better hints, since switching or closing tabs is the most common use case
698 # for the `eb` command.
699 isTab = element.classList?.contains('tabbrowser-tab')
702 element.classList?.contains('tab-close-button') or
703 element.classList?.contains('scrollbutton-up') or
704 element.classList?.contains('scrollbutton-down')
706 length = markerElements.push(element)
708 type, shape, isTab, isPrioritized,
709 combinedArea: shape.area,
710 elementIndex: length - 1,
713 callback = (marker) ->
714 element = markerElements[marker.wrapper.elementIndex]
715 switch marker.wrapper.type
717 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
719 getButtonMenu(element).openPopup(
720 element.parentNode, # Anchor node.
721 'after_end', # Position.
723 false, # Isn’t a context menu.
724 true, # Allow the 'position' attribute to override the above position.
726 when 'clickable', 'complementary'
727 # VimFx’s own button won’t trigger unless the click is simulated in the
728 # next tick. This might be true for other buttons as well.
729 utils.nextTick(window, ->
730 utils.focusElement(element)
731 browserOffset = {x: window.screenX, y: window.screenY}
733 when element.localName == 'tab'
734 # Only 'mousedown' seems to be able to activate tabs.
735 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
736 when element.closest('tab')
737 # If `.click()` is used on a tab close button, its tab will be
738 # selected first, which might cause the selected tab to change.
739 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
741 # `.click()` seems to trigger more buttons (such as NoScript’s
742 # button and Firefox’s “hamburger” menu button) than simulating
745 utils.openDropdown(element)
749 wrappers = markableElements.find(
750 window, filter.bind(null, {complementary: false})
753 if wrappers.length > 0
754 viewport = viewportUtils.getWindowViewport(window)
756 markerContainer = new MarkerContainer({
758 hintChars: vim.options['hints.chars']
761 getComplementaryWrappers: (callback) ->
762 newWrappers = markableElements.find(
763 window, filter.bind(null, {complementary: true})
765 callback({wrappers: newWrappers, viewport})
767 MarkerContainer.remove(window) # Better safe than sorry.
768 markerContainer.container.classList.add('ui')
769 mainWindow = window.document.body or
770 window.document.getElementById('main-window') # fallback <fx72
771 mainWindow.insertBefore(
772 markerContainer.container,
773 mainWindow.firstChild
776 [firstWrappers, secondWrappers] =
777 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
779 numChars = markerContainer.alphabet.length
780 numPrimary = markerContainer.primaryHintChars.length
781 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
784 for wrapper in firstWrappers
786 # Given the hint chars `abc de`, give the tabs weights so that the hints
787 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
788 # on. The rule is that the weight of a tab must be larger than the sum
789 # of all tabs with a longer hint. We start out at `1` and then use
790 # smaller and smaller fractions. This is to make sure that the tabs get
791 # consistent hints as the number of tabs or the size of the window
793 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
794 wrapper.combinedArea = 1 / numChars ** exponent
797 # Make sure that the tab close buttons and the tab bar scroll buttons
798 # come after all the tabs. Treating them all as the same size is fine.
799 # Their sum must be small enough in order not to affect the tab hints.
800 # It might look like using `0` is a good idea, but that results in
801 # increasingly worse hints the more tab close buttons there are.
802 wrapper.combinedArea = 1 / numChars ** numTabs
804 # Since most of the best hint characters might be used for the tabs, make
805 # sure that all other elements don’t get really bad hints. First, favor
806 # larger elements by sorting them. Then, give them all the same weight so
807 # that larger elements (such as the location bar, search bar, the web
808 # console input and other large areas in the devtools) don’t overpower the
809 # smaller ones. The usual “the larger the element, the better the hint” rule
810 # doesn’t really apply the same way for browser UI elements as in web pages.
811 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
812 for wrapper in secondWrappers
813 wrapper.combinedArea = 1
815 markerContainer.injectHints(firstWrappers, viewport, 'first')
816 markerContainer.injectHints(secondWrappers, viewport, 'second')
817 vim._enterMode('hints', {markerContainer, callback, matchText: false})
820 vim.notify(translate('notification.follow.none'))
822 helper_follow_pattern = (type, {vim}) ->
824 pattern_selector: vim.options.pattern_selector
825 pattern_attrs: vim.options.pattern_attrs
826 patterns: vim.options["#{type}_patterns"]
828 browserOffset = vim._getBrowserOffset()
829 vim._run('follow_pattern', {type, browserOffset, options})
831 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
833 commands.follow_next = helper_follow_pattern.bind(null, 'next')
835 commands.focus_text_input = ({vim, count}) ->
836 vim.markPageInteraction()
837 vim._run('focus_text_input', {count})
839 helper_follow_selectable = ({select}, args) ->
842 callback = (marker) ->
843 vim._run('element_text_select', {
844 elementIndex: marker.wrapper.elementIndex
848 vim._enterMode('caret', {select})
851 helper_follow({name: 'follow_selectable', callback}, args)
853 commands.element_text_caret =
854 helper_follow_selectable.bind(null, {select: false})
856 commands.element_text_select =
857 helper_follow_selectable.bind(null, {select: true})
859 commands.element_text_copy = (args) ->
862 callback = (marker) ->
863 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
866 helper_follow({name: 'follow_selectable', callback}, args)
868 helper_copy_marker_element = (vim, elementIndex, property) ->
869 if property == '_selection'
870 # Selecting the text and then copying that selection is better than copying
871 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
872 # and then includes those backticks in the compiled output (!), in hidden
873 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
874 # elements, text selection gives better whitespace than `.textContent`.
875 vim._run('element_text_select', {elementIndex, full: true}, ->
876 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
877 vim._run('clear_selection')
880 vim._run('copy_marker_element', {elementIndex, property})
889 helper_find_from_top_of_viewport = (vim, direction, callback) ->
890 if vim.options.find_from_top_of_viewport
891 vim._run('find_from_top_of_viewport', {direction}, ->
897 helper_find = ({highlight, linksOnly = false}, {vim}) ->
899 # Make sure to enter find mode here, since that’s where `findStorage.busy`
900 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
901 vim._enterMode('find')
904 helpSearchInput = help.getSearchInput(vim.window)
906 helpSearchInput.select()
909 # Important: Enter Find mode immediately. See `onInput` for Find mode.
910 findStorage.busy = true
911 vim._enterMode('find')
913 helper_mark_last_scroll_position(vim)
914 vim._run('mark_scroll_position', {
915 keyStr: vim.options['scroll.last_find_mark']
919 helper_find_from_top_of_viewport(vim, FORWARD, ->
920 return unless vim.mode == 'find'
921 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
922 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
923 findBar.startFind(mode)
924 utils.focusElement(findBar._findField, {select: true})
927 return unless highlightButton = findBar.getElement('highlight')
928 if highlightButton.checked != highlight
929 highlightButton.click()
933 commands.find = helper_find.bind(null, {highlight: false})
935 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
937 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
939 helper_find_again = (direction, {vim}) ->
940 return if findStorage.busy
942 utils.getFindBar(vim.window.gBrowser).then((findBar) ->
943 if findStorage.lastSearchString.length == 0
944 vim.notify(translate('notification.find_again.none'))
947 findStorage.busy = true
949 helper_mark_last_scroll_position(vim)
950 helper_find_from_top_of_viewport(vim, direction, ->
951 findBar._findField.value = findStorage.lastSearchString
953 # `.onFindResult` is temporarily hacked to be able to know when the
954 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
955 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
957 originalOnFindResult = findBar.onFindResult
958 originalUpdateControlState = findBar.updateControlState
960 findBar.onFindResult = (data) ->
961 # Prevent the find bar from re-opening if there are no matches.
962 data.storeResult = false
963 findBar.onFindResult = originalOnFindResult
964 findBar.updateControlState = originalUpdateControlState
965 findBar.onFindResult(data)
968 findBar.updateControlState = (args...) ->
969 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
970 # matches here, so no need to take care of that in this case.
971 findBar.onFindResult = originalOnFindResult
972 findBar.updateControlState = originalUpdateControlState
973 findBar.updateControlState(args...)
977 message = findBar._findStatusDesc.textContent
978 vim.notify(message) if message
979 findStorage.busy = false
981 findBar.onFindAgainCommand(not direction)
985 commands.find_next = helper_find_again.bind(null, FORWARD)
987 commands.find_previous = helper_find_again.bind(null, BACKWARD)
991 commands.window_new = ({vim}) ->
992 vim.window.OpenBrowserWindow()
994 commands.window_new_private = ({vim}) ->
995 vim.window.OpenBrowserWindow({private: true})
997 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
998 type = if blacklist then 'blacklist' else 'explicit'
999 vim._enterMode('ignore', {type})
1001 # Quote next keypress (pass it through to the page).
1002 commands.quote = ({vim, count = 1}) ->
1003 vim._enterMode('ignore', {type: 'explicit', count})
1005 commands.enter_reader_view = ({vim}) ->
1006 button = vim.window.document.getElementById('reader-mode-button')
1007 if not button?.hidden
1010 vim.notify(translate('notification.enter_reader_view.none'))
1012 commands.reload_config_file = ({vim}) ->
1013 vim._parent.emit('shutdown')
1014 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
1016 vim.notify(translate('notification.reload_config_file.none'))
1018 vim.notify(translate('notification.reload_config_file.success'))
1020 vim.notify(translate('notification.reload_config_file.failure'))
1023 commands.edit_blacklist = ({vim}) ->
1024 url = vim.browser.currentURI.spec
1025 location = new vim.window.URL(url)
1026 newPattern = if location.host then "*#{location.host}*" else location.href
1028 blacklistString = prefs.get('blacklist')
1030 if vim._isBlacklisted(url)
1031 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1032 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1033 return vim.options.blacklist[index].test(url)
1035 newBlacklistString = "
1036 #{matching.join(delimiter)}\
1037 #{delimiter.repeat(7)}\
1038 #{nonMatching.join(delimiter)}
1040 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1042 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1043 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1046 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1051 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1052 return if input == null
1053 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1054 # and let the regular pref parsing take care of it.
1055 prefs.set('blacklist', input)
1056 vim._onLocationChange(url)
1059 commands.help = ({vim}) ->
1060 help.toggleHelp(vim.window, vim._parent)
1062 commands.esc = ({vim}) ->
1064 vim.hideNotification()
1066 # Firefox does things differently when blurring the location bar, depending on
1067 # whether the autocomplete popup is open or not. To be consistent, always
1068 # close the autocomplete popup before blurring.
1069 vim.window.gURLBar.view.close()
1071 utils.blurActiveBrowserElement(vim)
1072 utils.getFindBar(vim.window.gBrowser).then((findBar) -> findBar.close())
1074 # Better safe than sorry.
1075 MarkerContainer.remove(vim.window)
1076 vim._parent.resetCaretBrowsing()
1078 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1079 help.removeHelp(vim.window)
1081 vim._setFocusType('none') # Better safe than sorry.