2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
4 # Copyright Wang Zhuochun 2013, 2014.
6 # This file is part of VimFx.
8 # VimFx is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # VimFx is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
22 # This file defines all Normal mode commands. Commands that need to interact
23 # with web page content do so by running `vim._run(name)`, which invokes `name`
24 # in commands-frame.coffee.
26 # NOTE: Most tab related commands need to do their actual tab manipulations in
27 # the next tick (`utils.nextTick`) to work around bug 1200334.
29 config = require('./config')
30 help = require('./help')
31 markableElements = require('./markable-elements')
32 MarkerContainer = require('./marker-container')
33 prefs = require('./prefs')
34 SelectionManager = require('./selection')
35 translate = require('./translate')
36 utils = require('./utils')
37 viewportUtils = require('./viewport')
39 {ContentClick} = Cu.import('resource:///modules/ContentClick.jsm', {})
40 {FORWARD, BACKWARD} = SelectionManager
42 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
48 commands.focus_location_bar = ({vim}) ->
49 vim.window.focusAndSelectUrlBar()
51 commands.focus_search_bar = ({vim, count}) ->
52 # The `.webSearch()` method opens a search engine in a tab if the search bar
53 # has been removed. Therefore we first check if it exists.
54 if vim.window.BrowserSearch.searchBar
55 vim.window.BrowserSearch.webSearch()
57 vim.notify(translate('notification.focus_search_bar.none'))
59 helper_paste_and_go = (props, {vim}) ->
60 {gURLBar} = vim.window
61 gURLBar.value = vim.window.readFromClipboard()
62 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
64 commands.paste_and_go = helper_paste_and_go.bind(null, null)
66 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
68 commands.copy_current_url = ({vim}) ->
69 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
70 vim.notify(translate('notification.copy_current_url.success'))
72 commands.go_up_path = ({vim, count}) ->
73 vim._run('go_up_path', {count})
75 commands.go_to_root = ({vim}) ->
76 vim._run('go_to_root')
78 commands.go_home = ({vim}) ->
79 vim.window.BrowserHome()
81 helper_go_history = (direction, {vim, count = 1}) ->
83 {SessionStore, gBrowser} = window
85 if (direction == 'back' and not gBrowser.canGoBack) or
86 (direction == 'forward' and not gBrowser.canGoForward)
87 vim.notify(translate("notification.history_#{direction}.limit"))
90 # `SessionStore.getSessionHistory()` (used below to support counts) starts
91 # lots of asynchronous tasks internally, which is a bit unreliable, it has
92 # turned out. The primary use of the `history_back` and `history_forward`
93 # commands is to go _one_ step back or forward, though, so those cases are
94 # optimized to use more reliable ways of going back and forward. Also, some
95 # extensions override the following functions, so calling them also gives
96 # better interoperability.
98 if direction == 'back'
101 window.BrowserForward()
104 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
105 {index} = sessionHistory
106 newIndex = index + count * (if direction == 'back' then -1 else 1)
107 newIndex = Math.max(newIndex, 0)
108 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
109 gBrowser.gotoIndex(newIndex)
112 commands.history_back = helper_go_history.bind(null, 'back')
114 commands.history_forward = helper_go_history.bind(null, 'forward')
116 commands.history_list = ({vim}) ->
117 menu = vim.window.document.getElementById('backForwardMenu')
118 utils.openPopup(menu)
119 if menu.childElementCount == 0
120 vim.notify(translate('notification.history_list.none'))
122 commands.reload = ({vim}) ->
123 vim.window.BrowserReload()
125 commands.reload_force = ({vim}) ->
126 vim.window.BrowserReloadSkipCache()
128 commands.reload_all = ({vim}) ->
129 vim.window.gBrowser.reloadAllTabs()
131 commands.reload_all_force = ({vim}) ->
132 for tab in vim.window.gBrowser.visibleTabs
133 gBrowser = tab.linkedBrowser
134 consts = gBrowser.webNavigation
135 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
136 gBrowser.reload(flags)
139 commands.stop = ({vim}) ->
140 vim.window.BrowserStop()
142 commands.stop_all = ({vim}) ->
143 for tab in vim.window.gBrowser.visibleTabs
144 tab.linkedBrowser.stop()
154 helper_scroll = (vim, uiEvent, args...) ->
156 method, type, directions, amounts
157 properties = null, adjustment = 0, name = 'scroll'
160 method, type, directions, amounts, properties, adjustment
162 prefs.root.get('general.smoothScroll') and
163 prefs.root.get("general.smoothScroll.#{type}")
167 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
168 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
169 # scrolling command was invoked.
170 springConstant.nonce = nonce = {}
171 springConstant.value ?= prefs.root.get(SPRING_CONSTANT_PREF)
173 SPRING_CONSTANT_PREF,
174 vim.options["smoothScroll.#{type}.spring-constant"]
177 vim.window.setTimeout((->
178 return unless springConstant.nonce == nonce
179 prefs.root.set(SPRING_CONSTANT_PREF, springConstant.value)
180 springConstant.nonce = null
181 springConstant.value = null
182 ), vim.options['scroll.reset_timeout'])
184 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
185 if uiEvent or helpScroll
186 activeElement = helpScroll or utils.getActiveElement(vim.window)
187 if vim._state.scrollableElements.has(activeElement) or helpScroll
188 viewportUtils.scroll(activeElement, options)
192 vim._run(name, options, reset)
195 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
196 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
198 vim, uiEvent, 'scrollBy', 'lines', ['left'], [amount * distance * count * 5]
201 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
202 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
204 vim, uiEvent, 'scrollBy', 'lines', ['top'], [amount * distance * count * 20]
207 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
208 adjustment = vim.options["scroll.#{type}_page_adjustment"]
210 vim, uiEvent, 'scrollBy', 'pages', ['top'], [amount * count],
211 ['clientHeight'], adjustment
214 helper_scrollToX = (amount, {vim, uiEvent}) ->
215 helper_mark_last_scroll_position(vim)
217 vim, uiEvent, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
220 helper_scrollToY = (amount, {vim, uiEvent}) ->
221 helper_mark_last_scroll_position(vim)
223 vim, uiEvent, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
226 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
227 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
228 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
229 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
230 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
231 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
232 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
233 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
234 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
235 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
236 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
237 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
239 helper_mark_last_scroll_position = (vim) ->
240 keyStr = vim.options['scroll.last_position_mark']
241 vim._run('mark_scroll_position', {keyStr, notify: false})
243 commands.mark_scroll_position = ({vim}) ->
244 vim._enterMode('marks', (keyStr) ->
245 vim._run('mark_scroll_position', {keyStr})
247 vim.notify(translate('notification.mark_scroll_position.enter'))
249 commands.scroll_to_mark = ({vim}) ->
250 vim._enterMode('marks', (keyStr) ->
251 unless keyStr == vim.options['scroll.last_position_mark']
252 helper_mark_last_scroll_position(vim)
254 vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
255 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark'
258 vim.notify(translate('notification.scroll_to_mark.enter'))
262 commands.tab_new = ({vim}) ->
263 utils.nextTick(vim.window, ->
264 vim.window.BrowserOpenTab()
267 commands.tab_new_after_current = ({vim}) ->
269 newTabPosition = window.gBrowser.selectedTab._tPos + 1
270 utils.nextTick(window, ->
271 utils.listenOnce(window, 'TabOpen', (event) ->
272 newTab = event.originalTarget
273 window.gBrowser.moveTabTo(newTab, newTabPosition)
275 window.BrowserOpenTab()
278 commands.tab_duplicate = ({vim}) ->
279 {gBrowser} = vim.window
280 utils.nextTick(vim.window, ->
281 gBrowser.duplicateTab(gBrowser.selectedTab)
284 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
285 tabs = gBrowser.visibleTabs
286 {selectedTab} = gBrowser
288 currentIndex = tabs.indexOf(selectedTab)
289 absoluteIndex = currentIndex + relativeIndex
290 numTabsTotal = tabs.length
291 numPinnedTabs = gBrowser._numPinnedTabs
293 [numTabs, min] = switch
294 when not pinnedSeparate
296 when selectedTab.pinned
299 [numTabsTotal - numPinnedTabs, numPinnedTabs]
301 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
303 if (relativeIndex < 0 and currentIndex == min) or
304 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
305 if absoluteIndex < min
306 absoluteIndex += numTabs
307 else if absoluteIndex >= min + numTabs
308 absoluteIndex -= numTabs
310 absoluteIndex = Math.max(min, absoluteIndex)
311 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
315 helper_switch_tab = (direction, {vim, count = 1}) ->
316 {gBrowser} = vim.window
317 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
318 utils.nextTick(vim.window, ->
319 gBrowser.selectTabAtIndex(index)
322 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
324 commands.tab_select_next = helper_switch_tab.bind(null, +1)
326 helper_is_visited = (tab) ->
327 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
329 commands.tab_select_most_recent = ({vim, count = 1}) ->
330 {gBrowser} = vim.window
334 (tab) -> not tab.closing and helper_is_visited(tab)
335 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
336 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
338 gBrowser.selectedTab = tab
340 vim.notify(translate('notification.tab_select_most_recent.none'))
342 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
343 {gBrowser} = vim.window
347 (tab) -> not tab.closing and not helper_is_visited(tab)
348 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
349 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
351 gBrowser.selectedTab = tab
353 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
355 helper_move_tab = (direction, {vim, count = 1}) ->
356 {gBrowser} = vim.window
357 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
358 utils.nextTick(vim.window, ->
359 gBrowser.moveTabTo(gBrowser.selectedTab, index)
362 commands.tab_move_backward = helper_move_tab.bind(null, -1)
364 commands.tab_move_forward = helper_move_tab.bind(null, +1)
366 commands.tab_move_to_window = ({vim}) ->
367 {gBrowser} = vim.window
368 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
370 commands.tab_select_first = ({vim, count = 1}) ->
371 utils.nextTick(vim.window, ->
372 vim.window.gBrowser.selectTabAtIndex(count - 1)
375 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
376 firstNonPinned = vim.window.gBrowser._numPinnedTabs
377 utils.nextTick(vim.window, ->
378 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
381 commands.tab_select_last = ({vim, count = 1}) ->
382 utils.nextTick(vim.window, ->
383 vim.window.gBrowser.selectTabAtIndex(-count)
386 commands.tab_toggle_pinned = ({vim}) ->
387 currentTab = vim.window.gBrowser.selectedTab
389 vim.window.gBrowser.unpinTab(currentTab)
391 vim.window.gBrowser.pinTab(currentTab)
393 commands.tab_close = ({vim, count = 1}) ->
394 {gBrowser} = vim.window
395 return if gBrowser.selectedTab.pinned
396 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
397 utils.nextTick(vim.window, ->
398 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
399 gBrowser.removeTab(tab)
403 commands.tab_restore = ({vim, count = 1}) ->
404 utils.nextTick(vim.window, ->
405 for index in [0...count] by 1
406 restoredTab = vim.window.undoCloseTab()
407 if not restoredTab and index == 0
408 vim.notify(translate('notification.tab_restore.none'))
413 commands.tab_restore_list = ({vim}) ->
415 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
418 if fragment.childElementCount == 0
419 vim.notify(translate('notification.tab_restore.none'))
421 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
423 commands.tab_close_to_end = ({vim}) ->
424 {gBrowser} = vim.window
425 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
427 commands.tab_close_other = ({vim}) ->
428 {gBrowser} = vim.window
429 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
433 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
435 vim.markPageInteraction()
436 help.removeHelp(window)
438 markerContainer = new MarkerContainer({
440 hintChars: vim.options.hint_chars
441 getComplementaryWrappers: (callback) ->
442 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
443 # `markerContainer.container` is `null`ed out when leaving Hints mode.
444 # If this callback is called after we’ve left Hints mode (and perhaps
445 # even entered it again), simply discard the result.
446 return unless markerContainer.container
447 if wrappers.length == 0
448 vim.notify(translate('notification.follow.none'))
449 callback({wrappers, viewport})
452 MarkerContainer.remove(window) # Better safe than sorry.
453 window.gBrowser.selectedBrowser.parentNode.appendChild(
454 markerContainer.container
457 chooseCallback = (marker, timesLeft, keyStr) ->
459 {type, href = null, elementIndex} = marker.wrapper
460 return callbackOverride({type, href, id: elementIndex, timesLeft})
462 return callback(marker, timesLeft, keyStr)
464 # Enter Hints mode immediately, with an empty set of markers. The user might
465 # press keys before any hints have been generated. Those key presses should be
466 # handled in Hints mode, not Normal mode.
467 vim._enterMode('hints', {
468 markerContainer, count
469 callback: chooseCallback
470 sleep: vim.options.hints_sleep
473 injectHints = ({wrappers, viewport, pass}) ->
474 # See `getComplementaryWrappers` above.
475 return unless markerContainer.container
477 if wrappers.length == 0
478 if pass in ['single', 'second'] and markerContainer.markers.length == 0
479 vim.notify(translate('notification.follow.none'))
480 vim._enterMode('normal')
482 markerContainer.injectHints(wrappers, viewport, pass)
485 vim._run(name, {pass: 'second'}, injectHints)
487 vim._run(name, {pass: 'auto'}, injectHints)
489 helper_follow_clickable = (options, args) ->
492 callback = (marker, timesLeft, keyStr) ->
493 {inTab, inBackground} = options
494 {type, elementIndex} = marker.wrapper
495 isLast = (timesLeft == 1)
496 isLink = (type == 'link')
500 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
502 when keyStr.startsWith(vim.options.hints_toggle_in_background)
504 inBackground = not inBackground
510 inTab = false unless isLink
512 if type == 'text' or (isLink and not (inTab and inBackground))
515 vim._focusMarkerElement(elementIndex)
518 utils.nextTick(window, ->
519 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
520 # links using the mouse. Using that instead of simply
521 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
522 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
523 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
524 ContentClick.contentAreaClick({
525 href: marker.wrapper.href
526 shiftKey: not inBackground
529 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
534 vim._run('click_marker_element', {
536 preventTargetBlank: vim.options.prevent_target_blank
541 name = if options.inTab then 'follow_in_tab' else 'follow'
542 helper_follow({name, callback}, args)
545 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
547 commands.follow_in_tab =
548 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
550 commands.follow_in_focused_tab =
551 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
553 commands.follow_in_window = (args) ->
556 callback = (marker) ->
557 vim._focusMarkerElement(marker.wrapper.elementIndex)
558 {href} = marker.wrapper
559 vim.window.openLinkIn(href, 'window', {}) if href
562 helper_follow({name: 'follow_in_tab', callback}, args)
564 commands.follow_multiple = (args) ->
565 args.count = Infinity
566 commands.follow(args)
568 commands.follow_copy = (args) ->
571 callback = (marker) ->
572 property = switch marker.wrapper.type
577 when 'contenteditable', 'complementary'
579 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
582 helper_follow({name: 'follow_copy', callback}, args)
584 commands.follow_focus = (args) ->
587 callback = (marker) ->
588 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
591 helper_follow({name: 'follow_focus', callback}, args)
593 commands.click_browser_element = ({vim}) ->
597 getButtonMenu = (element) ->
598 if element.localName == 'dropmarker' and
599 element.parentNode?.localName == 'toolbarbutton'
600 return element.parentNode.querySelector('menupopup')
604 filter = ({complementary}, element, getElementShape) ->
606 when vim._state.scrollableElements.has(element)
608 when getButtonMenu(element)
610 when utils.isFocusable(element) or
611 (element.onclick and element.localName != 'statuspanel')
615 type = if type then null else 'complementary'
619 # `getElementShape(element, -1)` is intentionally _not_ used in the
620 # `complementary` run, because it results in tons of useless hints for
621 # hidden context menus.
622 shape = getElementShape(element)
623 return unless shape.nonCoveredPoint
625 length = markerElements.push(element)
626 return {type, shape, elementIndex: length - 1}
628 callback = (marker) ->
629 element = markerElements[marker.wrapper.elementIndex]
630 switch marker.wrapper.type
632 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
634 getButtonMenu(element).openPopup(
635 element.parentNode, # Anchor node.
636 'after_end', # Position.
638 false, # Isn’t a context menu.
639 true, # Allow the 'position' attribute to override the above position.
641 when 'clickable', 'complementary'
642 # VimFx’s own button won’t trigger unless the click is simulated in the
643 # next tick. This might be true for other buttons as well.
644 utils.nextTick(window, ->
645 utils.focusElement(element)
647 when element.localName == 'tab'
648 # Only 'mousedown' seems to be able to activate tabs.
649 utils.simulateMouseEvents(element, ['mousedown'])
650 when element.closest('tab')
651 # If `.click()` is used on a tab close button, its tab will be
652 # selected first, which might cause the selected tab to change.
653 utils.simulateMouseEvents(element, 'click-xul')
655 # `.click()` seems to trigger more buttons (such as NoScript’s
656 # button and Firefox’s “hamburger” menu button) than simulating
659 utils.openDropdown(element)
663 wrappers = markableElements.find(
664 window, filter.bind(null, {complementary: false})
667 if wrappers.length > 0
668 viewport = viewportUtils.getWindowViewport(window)
670 markerContainer = new MarkerContainer({
672 hintChars: vim.options.hint_chars
674 getComplementaryWrappers: (callback) ->
675 newWrappers = markableElements.find(
676 window, filter.bind(null, {complementary: true})
678 callback({wrappers: newWrappers, viewport})
680 MarkerContainer.remove(window) # Better safe than sorry.
681 markerContainer.container.classList.add('ui')
682 window.document.getElementById('browser-panel').appendChild(
683 markerContainer.container
686 markerContainer.injectHints(wrappers, viewport, 'single')
687 vim._enterMode('hints', {markerContainer, callback})
690 vim.notify(translate('notification.follow.none'))
692 helper_follow_pattern = (type, {vim}) ->
694 pattern_selector: vim.options.pattern_selector
695 pattern_attrs: vim.options.pattern_attrs
696 patterns: vim.options["#{type}_patterns"]
698 vim._run('follow_pattern', {type, options})
700 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
702 commands.follow_next = helper_follow_pattern.bind(null, 'next')
704 commands.focus_text_input = ({vim, count}) ->
705 vim.markPageInteraction()
706 vim._run('focus_text_input', {count})
708 helper_follow_selectable = ({select}, args) ->
711 callback = (marker) ->
712 vim._run('element_text_select', {
713 elementIndex: marker.wrapper.elementIndex
717 vim._enterMode('caret', {select})
720 helper_follow({name: 'follow_selectable', callback}, args)
722 commands.element_text_caret =
723 helper_follow_selectable.bind(null, {select: false})
725 commands.element_text_select =
726 helper_follow_selectable.bind(null, {select: true})
728 commands.element_text_copy = (args) ->
731 callback = (marker) ->
732 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
735 helper_follow({name: 'follow_selectable', callback}, args)
737 helper_copy_marker_element = (vim, elementIndex, property) ->
738 if property == '_selection'
739 # Selecting the text and then copying that selection is better than copying
740 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
741 # and then includes those backticks in the compiled output (!), in hidden
742 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
743 # elements, text selection gives better whitespace than `.textContent`.
744 vim._run('element_text_select', {elementIndex, full: true}, ->
745 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
746 vim._run('clear_selection')
749 vim._run('copy_marker_element', {elementIndex, property})
758 helper_find_from_top_of_viewport = (vim, direction, callback) ->
759 return if findStorage.busy
760 if vim.options.find_from_top_of_viewport
761 findStorage.busy = true
762 vim._run('find_from_top_of_viewport', {direction}, ->
763 findStorage.busy = false
769 helper_find = ({highlight, linksOnly = false}, {vim}) ->
770 helpSearchInput = help.getSearchInput(vim.window)
772 helpSearchInput.select()
775 # In case `helper_find_from_top_of_viewport` is slow, make sure that keys
776 # pressed before the find bar input is focsued doesn’t trigger commands.
777 vim._enterMode('find')
779 helper_mark_last_scroll_position(vim)
780 helper_find_from_top_of_viewport(vim, FORWARD, ->
781 return unless vim.mode == 'find'
782 findBar = vim.window.gBrowser.getFindBar()
784 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
785 findBar.startFind(mode)
786 utils.focusElement(findBar._findField, {select: true})
789 return unless highlightButton = findBar.getElement('highlight')
790 if highlightButton.checked != highlight
791 highlightButton.click()
794 commands.find = helper_find.bind(null, {highlight: false})
796 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
798 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
800 helper_find_again = (direction, {vim}) ->
801 findBar = vim.window.gBrowser.getFindBar()
802 if findStorage.lastSearchString.length == 0
803 vim.notify(translate('notification.find_again.none'))
806 helper_mark_last_scroll_position(vim)
807 helper_find_from_top_of_viewport(vim, direction, ->
808 findBar._findField.value = findStorage.lastSearchString
810 # Temporarily hack `.onFindResult` to be able to know when the asynchronous
811 # `.onFindAgainCommand` is done.
812 originalOnFindResult = findBar.onFindResult
813 findBar.onFindResult = (data) ->
814 # Prevent the find bar from re-opening if there are no matches.
815 data.storeResult = false
816 findBar.onFindResult = originalOnFindResult
817 findBar.onFindResult(data)
818 message = findBar._findStatusDesc.textContent
819 vim.notify(message) if message
821 findBar.onFindAgainCommand(not direction)
824 commands.find_next = helper_find_again.bind(null, FORWARD)
826 commands.find_previous = helper_find_again.bind(null, BACKWARD)
830 commands.window_new = ({vim}) ->
831 vim.window.OpenBrowserWindow()
833 commands.window_new_private = ({vim}) ->
834 vim.window.OpenBrowserWindow({private: true})
836 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
837 type = if blacklist then 'blacklist' else 'explicit'
838 vim._enterMode('ignore', {type})
840 # Quote next keypress (pass it through to the page).
841 commands.quote = ({vim, count = 1}) ->
842 vim._enterMode('ignore', {type: 'explicit', count})
844 commands.enter_reader_view = ({vim}) ->
845 button = vim.window.document.getElementById('reader-mode-button')
846 if not button?.hidden
849 vim.notify(translate('notification.enter_reader_view.none'))
851 commands.reload_config_file = ({vim}) ->
852 vim._parent.emit('shutdown')
853 config.load(vim._parent, (status) -> switch status
855 vim.notify(translate('notification.reload_config_file.none'))
857 vim.notify(translate('notification.reload_config_file.success'))
859 vim.notify(translate('notification.reload_config_file.failure'))
862 commands.help = ({vim}) ->
863 help.toggleHelp(vim.window, vim._parent)
865 commands.dev = ({vim}) ->
866 vim.window.DeveloperToolbar.show(true) # `true` to focus.
868 commands.esc = ({vim}) ->
870 utils.blurActiveBrowserElement(vim)
871 vim.window.gBrowser.getFindBar().close()
872 MarkerContainer.remove(vim.window) # Better safe than sorry.
874 # Calling `.hide()` when the toolbar is not open can destroy it for the rest
875 # of the Firefox session. The code here is taken from the `.toggle()` method.
876 {DeveloperToolbar} = vim.window
877 if DeveloperToolbar.visible
878 DeveloperToolbar.hide().catch(console.error)
880 unless help.getSearchInput(vim.window)?.getAttribute('focused')
881 help.removeHelp(vim.window)
883 vim._setFocusType('none') # Better safe than sorry.