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 parsePrefs = require('./parse-prefs')
34 prefs = require('./prefs')
35 SelectionManager = require('./selection')
36 translate = require('./translate')
37 utils = require('./utils')
38 viewportUtils = require('./viewport')
40 {ContentClick} = Cu.import('resource:///modules/ContentClick.jsm', {})
41 {FORWARD, BACKWARD} = SelectionManager
43 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
49 commands.focus_location_bar = ({vim}) ->
50 vim.window.focusAndSelectUrlBar()
52 commands.focus_search_bar = ({vim, count}) ->
53 # The `.webSearch()` method opens a search engine in a tab if the search bar
54 # has been removed. Therefore we first check if it exists.
55 if vim.window.BrowserSearch.searchBar
56 vim.window.BrowserSearch.webSearch()
58 vim.notify(translate('notification.focus_search_bar.none'))
60 helper_paste_and_go = (props, {vim}) ->
61 {gURLBar} = vim.window
62 gURLBar.value = vim.window.readFromClipboard()
63 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
65 commands.paste_and_go = helper_paste_and_go.bind(null, null)
67 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
69 commands.copy_current_url = ({vim}) ->
70 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
71 vim.notify(translate('notification.copy_current_url.success'))
73 commands.go_up_path = ({vim, count}) ->
74 vim._run('go_up_path', {count})
76 commands.go_to_root = ({vim}) ->
77 vim._run('go_to_root')
79 commands.go_home = ({vim}) ->
80 vim.window.BrowserHome()
82 helper_go_history = (direction, {vim, count = 1}) ->
84 {SessionStore, gBrowser} = window
86 if (direction == 'back' and not gBrowser.canGoBack) or
87 (direction == 'forward' and not gBrowser.canGoForward)
88 vim.notify(translate("notification.history_#{direction}.limit"))
91 # `SessionStore.getSessionHistory()` (used below to support counts) starts
92 # lots of asynchronous tasks internally, which is a bit unreliable, it has
93 # turned out. The primary use of the `history_back` and `history_forward`
94 # commands is to go _one_ step back or forward, though, so those cases are
95 # optimized to use more reliable ways of going back and forward. Also, some
96 # extensions override the following functions, so calling them also gives
97 # better interoperability.
99 if direction == 'back'
102 window.BrowserForward()
105 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
106 {index} = sessionHistory
107 newIndex = index + count * (if direction == 'back' then -1 else 1)
108 newIndex = Math.max(newIndex, 0)
109 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
110 gBrowser.gotoIndex(newIndex)
113 commands.history_back = helper_go_history.bind(null, 'back')
115 commands.history_forward = helper_go_history.bind(null, 'forward')
117 commands.history_list = ({vim}) ->
118 menu = vim.window.document.getElementById('backForwardMenu')
119 utils.openPopup(menu)
120 if menu.childElementCount == 0
121 vim.notify(translate('notification.history_list.none'))
123 commands.reload = ({vim}) ->
124 vim.window.BrowserReload()
126 commands.reload_force = ({vim}) ->
127 vim.window.BrowserReloadSkipCache()
129 commands.reload_all = ({vim}) ->
130 vim.window.gBrowser.reloadAllTabs()
132 commands.reload_all_force = ({vim}) ->
133 for tab in vim.window.gBrowser.visibleTabs
134 gBrowser = tab.linkedBrowser
135 consts = gBrowser.webNavigation
136 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
137 gBrowser.reload(flags)
140 commands.stop = ({vim}) ->
141 vim.window.BrowserStop()
143 commands.stop_all = ({vim}) ->
144 for tab in vim.window.gBrowser.visibleTabs
145 tab.linkedBrowser.stop()
155 helper_scroll = (vim, uiEvent, args...) ->
157 method, type, directions, amounts
158 properties = null, adjustment = 0, name = 'scroll'
161 method, type, directions, amounts, properties, adjustment
163 prefs.root.get('general.smoothScroll') and
164 prefs.root.get("general.smoothScroll.#{type}")
168 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
169 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
170 # scrolling command was invoked.
171 springConstant.nonce = nonce = {}
172 springConstant.value ?= prefs.root.get(SPRING_CONSTANT_PREF)
174 SPRING_CONSTANT_PREF,
175 vim.options["smoothScroll.#{type}.spring-constant"]
178 vim.window.setTimeout((->
179 return unless springConstant.nonce == nonce
180 prefs.root.set(SPRING_CONSTANT_PREF, springConstant.value)
181 springConstant.nonce = null
182 springConstant.value = null
183 ), vim.options['scroll.reset_timeout'])
185 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
186 if uiEvent or helpScroll
187 activeElement = helpScroll or utils.getActiveElement(vim.window)
188 if vim._state.scrollableElements.has(activeElement) or helpScroll
189 viewportUtils.scroll(activeElement, options)
193 vim._run(name, options, reset)
196 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
197 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
199 vim, uiEvent, 'scrollBy', 'lines', ['left'], [amount * distance * count * 5]
202 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
203 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
205 vim, uiEvent, 'scrollBy', 'lines', ['top'], [amount * distance * count * 20]
208 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
209 adjustment = vim.options["scroll.#{type}_page_adjustment"]
211 vim, uiEvent, 'scrollBy', 'pages', ['top'], [amount * count],
212 ['clientHeight'], adjustment
215 helper_scrollToX = (amount, {vim, uiEvent}) ->
216 helper_mark_last_scroll_position(vim)
218 vim, uiEvent, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
221 helper_scrollToY = (amount, {vim, uiEvent}) ->
222 helper_mark_last_scroll_position(vim)
224 vim, uiEvent, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
227 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
228 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
229 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
230 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
231 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
232 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
233 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
234 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
235 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
236 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
237 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
238 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
240 helper_mark_last_scroll_position = (vim) ->
241 keyStr = vim.options['scroll.last_position_mark']
242 vim._run('mark_scroll_position', {keyStr, notify: false})
244 commands.mark_scroll_position = ({vim}) ->
245 vim._enterMode('marks', (keyStr) ->
246 vim._run('mark_scroll_position', {keyStr})
248 vim.notify(translate('notification.mark_scroll_position.enter'))
250 commands.scroll_to_mark = ({vim}) ->
251 vim._enterMode('marks', (keyStr) ->
252 unless keyStr == vim.options['scroll.last_position_mark']
253 helper_mark_last_scroll_position(vim)
255 vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
256 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark'
259 vim.notify(translate('notification.scroll_to_mark.enter'))
263 commands.tab_new = ({vim}) ->
264 utils.nextTick(vim.window, ->
265 vim.window.BrowserOpenTab()
268 commands.tab_new_after_current = ({vim}) ->
270 newTabPosition = window.gBrowser.selectedTab._tPos + 1
271 utils.nextTick(window, ->
272 utils.listenOnce(window, 'TabOpen', (event) ->
273 newTab = event.originalTarget
274 window.gBrowser.moveTabTo(newTab, newTabPosition)
276 window.BrowserOpenTab()
279 commands.tab_duplicate = ({vim}) ->
280 {gBrowser} = vim.window
281 utils.nextTick(vim.window, ->
282 gBrowser.duplicateTab(gBrowser.selectedTab)
285 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
286 tabs = gBrowser.visibleTabs
287 {selectedTab} = gBrowser
289 currentIndex = tabs.indexOf(selectedTab)
290 absoluteIndex = currentIndex + relativeIndex
291 numTabsTotal = tabs.length
292 numPinnedTabs = gBrowser._numPinnedTabs
294 [numTabs, min] = switch
295 when not pinnedSeparate
297 when selectedTab.pinned
300 [numTabsTotal - numPinnedTabs, numPinnedTabs]
302 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
304 if (relativeIndex < 0 and currentIndex == min) or
305 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
306 if absoluteIndex < min
307 absoluteIndex += numTabs
308 else if absoluteIndex >= min + numTabs
309 absoluteIndex -= numTabs
311 absoluteIndex = Math.max(min, absoluteIndex)
312 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
316 helper_switch_tab = (direction, {vim, count = 1}) ->
317 {gBrowser} = vim.window
318 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
319 utils.nextTick(vim.window, ->
320 gBrowser.selectTabAtIndex(index)
323 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
325 commands.tab_select_next = helper_switch_tab.bind(null, +1)
327 helper_is_visited = (tab) ->
328 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
330 commands.tab_select_most_recent = ({vim, count = 1}) ->
331 {gBrowser} = vim.window
335 (tab) -> not tab.closing and helper_is_visited(tab)
336 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
337 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
339 gBrowser.selectedTab = tab
341 vim.notify(translate('notification.tab_select_most_recent.none'))
343 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
344 {gBrowser} = vim.window
348 (tab) -> not tab.closing and not helper_is_visited(tab)
349 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
350 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
352 gBrowser.selectedTab = tab
354 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
356 helper_move_tab = (direction, {vim, count = 1}) ->
357 {gBrowser} = vim.window
358 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
359 utils.nextTick(vim.window, ->
360 gBrowser.moveTabTo(gBrowser.selectedTab, index)
363 commands.tab_move_backward = helper_move_tab.bind(null, -1)
365 commands.tab_move_forward = helper_move_tab.bind(null, +1)
367 commands.tab_move_to_window = ({vim}) ->
368 {gBrowser} = vim.window
369 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
371 commands.tab_select_first = ({vim, count = 1}) ->
372 utils.nextTick(vim.window, ->
373 vim.window.gBrowser.selectTabAtIndex(count - 1)
376 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
377 firstNonPinned = vim.window.gBrowser._numPinnedTabs
378 utils.nextTick(vim.window, ->
379 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
382 commands.tab_select_last = ({vim, count = 1}) ->
383 utils.nextTick(vim.window, ->
384 vim.window.gBrowser.selectTabAtIndex(-count)
387 commands.tab_toggle_pinned = ({vim}) ->
388 currentTab = vim.window.gBrowser.selectedTab
390 vim.window.gBrowser.unpinTab(currentTab)
392 vim.window.gBrowser.pinTab(currentTab)
394 commands.tab_close = ({vim, count = 1}) ->
395 {gBrowser} = vim.window
396 return if gBrowser.selectedTab.pinned
397 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
398 utils.nextTick(vim.window, ->
399 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
400 gBrowser.removeTab(tab)
404 commands.tab_restore = ({vim, count = 1}) ->
405 utils.nextTick(vim.window, ->
406 for index in [0...count] by 1
407 restoredTab = vim.window.undoCloseTab()
408 if not restoredTab and index == 0
409 vim.notify(translate('notification.tab_restore.none'))
414 commands.tab_restore_list = ({vim}) ->
416 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
419 if fragment.childElementCount == 0
420 vim.notify(translate('notification.tab_restore.none'))
422 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
424 commands.tab_close_to_end = ({vim}) ->
425 {gBrowser} = vim.window
426 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
428 commands.tab_close_other = ({vim}) ->
429 {gBrowser} = vim.window
430 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
434 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
436 vim.markPageInteraction()
437 help.removeHelp(window)
439 markerContainer = new MarkerContainer({
441 hintChars: vim.options['hints.chars']
442 getComplementaryWrappers: (callback) ->
443 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
444 # `markerContainer.container` is `null`ed out when leaving Hints mode.
445 # If this callback is called after we’ve left Hints mode (and perhaps
446 # even entered it again), simply discard the result.
447 return unless markerContainer.container
448 if wrappers.length == 0
449 vim.notify(translate('notification.follow.none'))
450 callback({wrappers, viewport})
453 MarkerContainer.remove(window) # Better safe than sorry.
454 window.gBrowser.selectedBrowser.parentNode.appendChild(
455 markerContainer.container
458 chooseCallback = (marker, timesLeft, keyStr) ->
460 {type, href = null, elementIndex} = marker.wrapper
461 return callbackOverride({type, href, id: elementIndex, timesLeft})
463 return callback(marker, timesLeft, keyStr)
465 # Enter Hints mode immediately, with an empty set of markers. The user might
466 # press keys before any hints have been generated. Those key presses should be
467 # handled in Hints mode, not Normal mode.
468 vim._enterMode('hints', {
469 markerContainer, count
470 callback: chooseCallback
471 matchText: vim.options['hints.match_text']
472 sleep: vim.options['hints.sleep']
475 injectHints = ({wrappers, viewport, pass}) ->
476 # See `getComplementaryWrappers` above.
477 return unless markerContainer.container
479 if wrappers.length == 0
480 if pass in ['single', 'second'] and markerContainer.markers.length == 0
481 vim.notify(translate('notification.follow.none'))
482 vim._enterMode('normal')
484 markerContainer.injectHints(wrappers, viewport, pass)
487 vim._run(name, {pass: 'second'}, injectHints)
489 vim._run(name, {pass: 'auto'}, injectHints)
491 helper_follow_clickable = (options, args) ->
494 callback = (marker, timesLeft, keyStr) ->
495 {inTab, inBackground} = options
496 {type, elementIndex} = marker.wrapper
497 isLast = (timesLeft == 1)
498 isLink = (type == 'link')
502 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
504 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
506 inBackground = not inBackground
512 inTab = false unless isLink
514 if type == 'text' or (isLink and not (inTab and inBackground))
517 vim._focusMarkerElement(elementIndex)
520 utils.nextTick(window, ->
521 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
522 # links using the mouse. Using that instead of simply
523 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
524 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
525 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
526 ContentClick.contentAreaClick({
527 href: marker.wrapper.href
528 shiftKey: not inBackground
531 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
536 vim._run('click_marker_element', {
538 browserOffset: vim._getBrowserOffset()
539 preventTargetBlank: vim.options.prevent_target_blank
544 name = if options.inTab then 'follow_in_tab' else 'follow'
545 helper_follow({name, callback}, args)
548 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
550 commands.follow_in_tab =
551 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
553 commands.follow_in_focused_tab =
554 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
556 helper_follow_in_window = (options, args) ->
559 callback = (marker) ->
560 vim._focusMarkerElement(marker.wrapper.elementIndex)
561 {href} = marker.wrapper
562 vim.window.openLinkIn(href, 'window', options) if href
565 helper_follow({name: 'follow_in_tab', callback}, args)
567 commands.follow_in_window =
568 helper_follow_in_window.bind(null, {})
570 commands.follow_in_private_window =
571 helper_follow_in_window.bind(null, {private: true})
573 commands.follow_multiple = (args) ->
574 args.count = Infinity
575 commands.follow(args)
577 commands.follow_copy = (args) ->
580 callback = (marker) ->
581 property = switch marker.wrapper.type
586 when 'contenteditable', 'complementary'
588 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
591 helper_follow({name: 'follow_copy', callback}, args)
593 commands.follow_focus = (args) ->
596 callback = (marker) ->
597 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
600 helper_follow({name: 'follow_focus', callback}, args)
602 commands.open_context_menu = (args) ->
605 callback = (marker) ->
606 {type, elementIndex} = marker.wrapper
607 vim._run('click_marker_element', {
609 browserOffset: vim._getBrowserOffset()
613 helper_follow({name: 'follow_context', callback}, args)
615 commands.click_browser_element = ({vim}) ->
619 getButtonMenu = (element) ->
620 if element.localName == 'dropmarker' and
621 element.parentNode?.localName == 'toolbarbutton'
622 return element.parentNode.querySelector('menupopup')
626 filter = ({complementary}, element, getElementShape) ->
628 when vim._state.scrollableElements.has(element)
630 when getButtonMenu(element)
632 when utils.isFocusable(element) or
633 (element.onclick and element.localName != 'statuspanel')
637 type = if type then null else 'complementary'
641 # `getElementShape(element, -1)` is intentionally _not_ used in the
642 # `complementary` run, because it results in tons of useless hints for
643 # hidden context menus.
644 shape = getElementShape(element)
645 return unless shape.nonCoveredPoint
647 length = markerElements.push(element)
648 return {type, shape, elementIndex: length - 1}
650 callback = (marker) ->
651 element = markerElements[marker.wrapper.elementIndex]
652 switch marker.wrapper.type
654 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
656 getButtonMenu(element).openPopup(
657 element.parentNode, # Anchor node.
658 'after_end', # Position.
660 false, # Isn’t a context menu.
661 true, # Allow the 'position' attribute to override the above position.
663 when 'clickable', 'complementary'
664 # VimFx’s own button won’t trigger unless the click is simulated in the
665 # next tick. This might be true for other buttons as well.
666 utils.nextTick(window, ->
667 utils.focusElement(element)
668 browserOffset = {x: window.screenX, y: window.screenY}
670 when element.localName == 'tab'
671 # Only 'mousedown' seems to be able to activate tabs.
672 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
673 when element.closest('tab')
674 # If `.click()` is used on a tab close button, its tab will be
675 # selected first, which might cause the selected tab to change.
676 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
678 # `.click()` seems to trigger more buttons (such as NoScript’s
679 # button and Firefox’s “hamburger” menu button) than simulating
682 utils.openDropdown(element)
686 wrappers = markableElements.find(
687 window, filter.bind(null, {complementary: false})
690 if wrappers.length > 0
691 viewport = viewportUtils.getWindowViewport(window)
694 utils.removeDuplicateChars(vim.options['hints.chars'].toLowerCase())
695 markerContainer = new MarkerContainer({
699 getComplementaryWrappers: (callback) ->
700 newWrappers = markableElements.find(
701 window, filter.bind(null, {complementary: true})
703 callback({wrappers: newWrappers, viewport})
705 MarkerContainer.remove(window) # Better safe than sorry.
706 markerContainer.container.classList.add('ui')
707 window.document.getElementById('browser-panel').appendChild(
708 markerContainer.container
711 markerContainer.injectHints(wrappers, viewport, 'single')
712 vim._enterMode('hints', {markerContainer, callback, matchText: false})
715 vim.notify(translate('notification.follow.none'))
717 helper_follow_pattern = (type, {vim}) ->
719 pattern_selector: vim.options.pattern_selector
720 pattern_attrs: vim.options.pattern_attrs
721 patterns: vim.options["#{type}_patterns"]
723 browserOffset = vim._getBrowserOffset()
724 vim._run('follow_pattern', {type, browserOffset, options})
726 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
728 commands.follow_next = helper_follow_pattern.bind(null, 'next')
730 commands.focus_text_input = ({vim, count}) ->
731 vim.markPageInteraction()
732 vim._run('focus_text_input', {count})
734 helper_follow_selectable = ({select}, args) ->
737 callback = (marker) ->
738 vim._run('element_text_select', {
739 elementIndex: marker.wrapper.elementIndex
743 vim._enterMode('caret', {select})
746 helper_follow({name: 'follow_selectable', callback}, args)
748 commands.element_text_caret =
749 helper_follow_selectable.bind(null, {select: false})
751 commands.element_text_select =
752 helper_follow_selectable.bind(null, {select: true})
754 commands.element_text_copy = (args) ->
757 callback = (marker) ->
758 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
761 helper_follow({name: 'follow_selectable', callback}, args)
763 helper_copy_marker_element = (vim, elementIndex, property) ->
764 if property == '_selection'
765 # Selecting the text and then copying that selection is better than copying
766 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
767 # and then includes those backticks in the compiled output (!), in hidden
768 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
769 # elements, text selection gives better whitespace than `.textContent`.
770 vim._run('element_text_select', {elementIndex, full: true}, ->
771 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
772 vim._run('clear_selection')
775 vim._run('copy_marker_element', {elementIndex, property})
784 helper_find_from_top_of_viewport = (vim, direction, callback) ->
785 if vim.options.find_from_top_of_viewport
786 vim._run('find_from_top_of_viewport', {direction}, ->
792 helper_find = ({highlight, linksOnly = false}, {vim}) ->
794 # Make sure to enter find mode here, since that’s where `findStorage.busy`
795 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
796 vim._enterMode('find')
799 helpSearchInput = help.getSearchInput(vim.window)
801 helpSearchInput.select()
804 # Important: Enter Find mode immediately. See `onInput` for Find mode.
805 findStorage.busy = true
806 vim._enterMode('find')
808 helper_mark_last_scroll_position(vim)
809 helper_find_from_top_of_viewport(vim, FORWARD, ->
810 return unless vim.mode == 'find'
811 findBar = vim.window.gBrowser.getFindBar()
813 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
814 findBar.startFind(mode)
815 utils.focusElement(findBar._findField, {select: true})
818 return unless highlightButton = findBar.getElement('highlight')
819 if highlightButton.checked != highlight
820 highlightButton.click()
823 commands.find = helper_find.bind(null, {highlight: false})
825 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
827 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
829 helper_find_again = (direction, {vim}) ->
830 return if findStorage.busy
832 findBar = vim.window.gBrowser.getFindBar()
833 if findStorage.lastSearchString.length == 0
834 vim.notify(translate('notification.find_again.none'))
837 findStorage.busy = true
839 helper_mark_last_scroll_position(vim)
840 helper_find_from_top_of_viewport(vim, direction, ->
841 findBar._findField.value = findStorage.lastSearchString
843 # Temporarily hack `.onFindResult` to be able to know when the asynchronous
844 # `.onFindAgainCommand` is done.
845 originalOnFindResult = findBar.onFindResult
846 findBar.onFindResult = (data) ->
847 # Prevent the find bar from re-opening if there are no matches.
848 data.storeResult = false
849 findBar.onFindResult = originalOnFindResult
850 findBar.onFindResult(data)
851 message = findBar._findStatusDesc.textContent
852 vim.notify(message) if message
853 findStorage.busy = false
855 findBar.onFindAgainCommand(not direction)
858 commands.find_next = helper_find_again.bind(null, FORWARD)
860 commands.find_previous = helper_find_again.bind(null, BACKWARD)
864 commands.window_new = ({vim}) ->
865 vim.window.OpenBrowserWindow()
867 commands.window_new_private = ({vim}) ->
868 vim.window.OpenBrowserWindow({private: true})
870 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
871 type = if blacklist then 'blacklist' else 'explicit'
872 vim._enterMode('ignore', {type})
874 # Quote next keypress (pass it through to the page).
875 commands.quote = ({vim, count = 1}) ->
876 vim._enterMode('ignore', {type: 'explicit', count})
878 commands.enter_reader_view = ({vim}) ->
879 button = vim.window.document.getElementById('reader-mode-button')
880 if not button?.hidden
883 vim.notify(translate('notification.enter_reader_view.none'))
885 commands.reload_config_file = ({vim}) ->
886 vim._parent.emit('shutdown')
887 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
889 vim.notify(translate('notification.reload_config_file.none'))
891 vim.notify(translate('notification.reload_config_file.success'))
893 vim.notify(translate('notification.reload_config_file.failure'))
896 commands.edit_blacklist = ({vim}) ->
897 url = vim.browser.currentURI.spec
898 location = new vim.window.URL(url)
899 domain = location.host or location.href
900 newPattern = "*#{domain}*"
902 blacklistString = prefs.get('blacklist')
904 if vim._isBlacklisted(url)
905 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
906 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
907 return vim.options.blacklist[index].test(url)
909 newBlacklistString = "
910 #{matching.join(delimiter)}\
911 #{delimiter.repeat(7)}\
912 #{nonMatching.join(delimiter)}
914 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
916 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
917 extraMessage = translate('pref.blacklist.extra.added', newPattern)
920 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
925 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
926 return if input == null
927 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
928 # and let the regular pref parsing take care of it.
929 prefs.set('blacklist', input)
930 vim._onLocationChange(url)
933 commands.help = ({vim}) ->
934 help.toggleHelp(vim.window, vim._parent)
936 commands.dev = ({vim}) ->
937 vim.window.DeveloperToolbar.show(true) # `true` to focus.
939 commands.esc = ({vim}) ->
941 vim.hideNotification()
942 utils.blurActiveBrowserElement(vim)
943 vim.window.gBrowser.getFindBar().close()
944 MarkerContainer.remove(vim.window) # Better safe than sorry.
946 # Calling `.hide()` when the toolbar is not open can destroy it for the rest
947 # of the Firefox session. The code here is taken from the `.toggle()` method.
948 {DeveloperToolbar} = vim.window
949 if DeveloperToolbar.visible
950 DeveloperToolbar.hide().catch(console.error)
952 unless help.getSearchInput(vim.window)?.getAttribute('focused')
953 help.removeHelp(vim.window)
955 vim._setFocusType('none') # Better safe than sorry.