]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Speed up and refactor Hints mode
[VimFx.git] / extension / lib / commands.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
4 # Copyright Wang Zhuochun 2013, 2014.
5 #
6 # This file is part of VimFx.
7 #
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.
12 #
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.
17 #
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/>.
20 ###
21
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.
25
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.
28
29 config = require('./config')
30 help = require('./help')
31 MarkerContainer = require('./marker-container')
32 markableElements = require('./markable-elements')
33 prefs = require('./prefs')
34 translate = require('./l10n')
35 utils = require('./utils')
36 SelectionManager = require('./selection')
37 viewportUtils = require('./viewport')
38
39 {ContentClick} = Cu.import('resource:///modules/ContentClick.jsm', {})
40 {FORWARD, BACKWARD} = SelectionManager
41
42 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
43
44 commands = {}
45
46
47
48 commands.focus_location_bar = ({vim}) ->
49 vim.window.focusAndSelectUrlBar()
50
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()
56 else
57 vim.notify(translate('notification.focus_search_bar.none'))
58
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))
63
64 commands.paste_and_go = helper_paste_and_go.bind(null, null)
65
66 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
67
68 commands.copy_current_url = ({vim}) ->
69 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
70 vim.notify(translate('notification.copy_current_url.success'))
71
72 commands.go_up_path = ({vim, count}) ->
73 vim._run('go_up_path', {count})
74
75 commands.go_to_root = ({vim}) ->
76 vim._run('go_to_root')
77
78 commands.go_home = ({vim}) ->
79 vim.window.BrowserHome()
80
81 helper_go_history = (direction, {vim, count = 1}) ->
82 {window} = vim
83 {SessionStore, gBrowser} = window
84
85 if (direction == 'back' and not gBrowser.canGoBack) or
86 (direction == 'forward' and not gBrowser.canGoForward)
87 vim.notify(translate("notification.history_#{direction}.limit"))
88 return
89
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.
97 if count == 1
98 if direction == 'back'
99 window.BrowserBack()
100 else
101 window.BrowserForward()
102 return
103
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)
110 )
111
112 commands.history_back = helper_go_history.bind(null, 'back')
113
114 commands.history_forward = helper_go_history.bind(null, 'forward')
115
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'))
121
122 commands.reload = ({vim}) ->
123 vim.window.BrowserReload()
124
125 commands.reload_force = ({vim}) ->
126 vim.window.BrowserReloadSkipCache()
127
128 commands.reload_all = ({vim}) ->
129 vim.window.gBrowser.reloadAllTabs()
130
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)
137 return
138
139 commands.stop = ({vim}) ->
140 vim.window.BrowserStop()
141
142 commands.stop_all = ({vim}) ->
143 for tab in vim.window.gBrowser.visibleTabs
144 tab.linkedBrowser.stop()
145 return
146
147
148
149 springConstant = {
150 nonce: null
151 value: null
152 }
153
154 helper_scroll = (vim, uiEvent, args...) ->
155 [
156 method, type, directions, amounts
157 properties = null, adjustment = 0, name = 'scroll'
158 ] = args
159 options = {
160 method, type, directions, amounts, properties, adjustment
161 smooth: (
162 prefs.root.get('general.smoothScroll') and
163 prefs.root.get("general.smoothScroll.#{type}")
164 )
165 }
166
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)
172 prefs.root.set(
173 SPRING_CONSTANT_PREF,
174 vim.options["smoothScroll.#{type}.spring-constant"]
175 )
176 reset = ->
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'])
183
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)
189 reset()
190 return
191
192 vim._run(name, options, reset)
193
194
195 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
196 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
197 helper_scroll(
198 vim, uiEvent, 'scrollBy', 'lines', ['left'], [amount * distance * count * 5]
199 )
200
201 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
202 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
203 helper_scroll(
204 vim, uiEvent, 'scrollBy', 'lines', ['top'], [amount * distance * count * 20]
205 )
206
207 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
208 adjustment = vim.options["scroll.#{type}_page_adjustment"]
209 helper_scroll(
210 vim, uiEvent, 'scrollBy', 'pages', ['top'], [amount * count],
211 ['clientHeight'], adjustment
212 )
213
214 helper_scrollToX = (amount, {vim, uiEvent}) ->
215 helper_mark_last_scroll_position(vim)
216 helper_scroll(
217 vim, uiEvent, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
218 )
219
220 helper_scrollToY = (amount, {vim, uiEvent}) ->
221 helper_mark_last_scroll_position(vim)
222 helper_scroll(
223 vim, uiEvent, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
224 )
225
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)
238
239 helper_mark_last_scroll_position = (vim) ->
240 keyStr = vim.options['scroll.last_position_mark']
241 vim._run('mark_scroll_position', {keyStr, notify: false})
242
243 commands.mark_scroll_position = ({vim}) ->
244 vim.enterMode('marks', (keyStr) -> vim._run('mark_scroll_position', {keyStr}))
245 vim.notify(translate('notification.mark_scroll_position.enter'))
246
247 commands.scroll_to_mark = ({vim}) ->
248 vim.enterMode('marks', (keyStr) ->
249 unless keyStr == vim.options['scroll.last_position_mark']
250 helper_mark_last_scroll_position(vim)
251 helper_scroll(
252 vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
253 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark'
254 )
255 )
256 vim.notify(translate('notification.scroll_to_mark.enter'))
257
258
259
260 commands.tab_new = ({vim}) ->
261 utils.nextTick(vim.window, ->
262 vim.window.BrowserOpenTab()
263 )
264
265 commands.tab_new_after_current = ({vim}) ->
266 {window} = vim
267 newTabPosition = window.gBrowser.selectedTab._tPos + 1
268 utils.nextTick(window, ->
269 utils.listenOnce(window, 'TabOpen', (event) ->
270 newTab = event.originalTarget
271 window.gBrowser.moveTabTo(newTab, newTabPosition)
272 )
273 window.BrowserOpenTab()
274 )
275
276 commands.tab_duplicate = ({vim}) ->
277 {gBrowser} = vim.window
278 utils.nextTick(vim.window, ->
279 gBrowser.duplicateTab(gBrowser.selectedTab)
280 )
281
282 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
283 tabs = gBrowser.visibleTabs
284 {selectedTab} = gBrowser
285
286 currentIndex = tabs.indexOf(selectedTab)
287 absoluteIndex = currentIndex + relativeIndex
288 numTabsTotal = tabs.length
289 numPinnedTabs = gBrowser._numPinnedTabs
290
291 [numTabs, min] = switch
292 when not pinnedSeparate
293 [numTabsTotal, 0]
294 when selectedTab.pinned
295 [numPinnedTabs, 0]
296 else
297 [numTabsTotal - numPinnedTabs, numPinnedTabs]
298
299 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
300 # current direction.
301 if (relativeIndex < 0 and currentIndex == min) or
302 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
303 if absoluteIndex < min
304 absoluteIndex += numTabs
305 else if absoluteIndex >= min + numTabs
306 absoluteIndex -= numTabs
307
308 absoluteIndex = Math.max(min, absoluteIndex)
309 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
310
311 return absoluteIndex
312
313 helper_switch_tab = (direction, {vim, count = 1}) ->
314 {gBrowser} = vim.window
315 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
316 utils.nextTick(vim.window, ->
317 gBrowser.selectTabAtIndex(index)
318 )
319
320 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
321
322 commands.tab_select_next = helper_switch_tab.bind(null, +1)
323
324 helper_is_visited = (tab) ->
325 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
326
327 commands.tab_select_most_recent = ({vim, count = 1}) ->
328 {gBrowser} = vim.window
329 tabsSorted =
330 Array.filter(
331 gBrowser.tabs,
332 (tab) -> not tab.closing and helper_is_visited(tab)
333 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
334 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
335 if tab
336 gBrowser.selectedTab = tab
337 else
338 vim.notify(translate('notification.tab_select_most_recent.none'))
339
340 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
341 {gBrowser} = vim.window
342 tabsSorted =
343 Array.filter(
344 gBrowser.tabs,
345 (tab) -> not tab.closing and not helper_is_visited(tab)
346 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
347 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
348 if tab
349 gBrowser.selectedTab = tab
350 else
351 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
352
353 helper_move_tab = (direction, {vim, count = 1}) ->
354 {gBrowser} = vim.window
355 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
356 utils.nextTick(vim.window, ->
357 gBrowser.moveTabTo(gBrowser.selectedTab, index)
358 )
359
360 commands.tab_move_backward = helper_move_tab.bind(null, -1)
361
362 commands.tab_move_forward = helper_move_tab.bind(null, +1)
363
364 commands.tab_move_to_window = ({vim}) ->
365 {gBrowser} = vim.window
366 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
367
368 commands.tab_select_first = ({vim, count = 1}) ->
369 utils.nextTick(vim.window, ->
370 vim.window.gBrowser.selectTabAtIndex(count - 1)
371 )
372
373 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
374 firstNonPinned = vim.window.gBrowser._numPinnedTabs
375 utils.nextTick(vim.window, ->
376 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
377 )
378
379 commands.tab_select_last = ({vim, count = 1}) ->
380 utils.nextTick(vim.window, ->
381 vim.window.gBrowser.selectTabAtIndex(-count)
382 )
383
384 commands.tab_toggle_pinned = ({vim}) ->
385 currentTab = vim.window.gBrowser.selectedTab
386 if currentTab.pinned
387 vim.window.gBrowser.unpinTab(currentTab)
388 else
389 vim.window.gBrowser.pinTab(currentTab)
390
391 commands.tab_close = ({vim, count = 1}) ->
392 {gBrowser} = vim.window
393 return if gBrowser.selectedTab.pinned
394 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
395 utils.nextTick(vim.window, ->
396 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
397 gBrowser.removeTab(tab)
398 return
399 )
400
401 commands.tab_restore = ({vim, count = 1}) ->
402 utils.nextTick(vim.window, ->
403 for index in [0...count] by 1
404 restoredTab = vim.window.undoCloseTab()
405 if not restoredTab and index == 0
406 vim.notify(translate('notification.tab_restore.none'))
407 break
408 return
409 )
410
411 commands.tab_restore_list = ({vim}) ->
412 {window} = vim
413 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
414 window, 'menuitem'
415 )
416 if fragment.childElementCount == 0
417 vim.notify(translate('notification.tab_restore.none'))
418 else
419 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
420
421 commands.tab_close_to_end = ({vim}) ->
422 {gBrowser} = vim.window
423 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
424
425 commands.tab_close_other = ({vim}) ->
426 {gBrowser} = vim.window
427 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
428
429
430
431 helper_follow = (name, vim, callback, count = null) ->
432 {window} = vim
433 vim.markPageInteraction()
434 help.removeHelp(window)
435
436 markerContainer = new MarkerContainer({
437 window
438 hintChars: vim.options.hint_chars
439 getComplementaryWrappers: (callback) ->
440 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
441 # `markerContainer.container` is `null`ed out when leaving Hints mode.
442 # If this callback is called after we’ve left Hints mode (and perhaps
443 # even entered it again), simply discard the result.
444 return unless markerContainer.container
445 if wrappers.length == 0
446 vim.notify(translate('notification.follow.none'))
447 callback({wrappers, viewport})
448 )
449 })
450 MarkerContainer.remove(window) # Better safe than sorry.
451 window.gBrowser.selectedBrowser.parentNode.appendChild(
452 markerContainer.container
453 )
454
455 # Enter Hints mode immediately, with an empty set of markers. The user might
456 # press keys before any hints have been generated. Those key presses should be
457 # handled in Hints mode, not Normal mode.
458 vim.enterMode('hints', {
459 markerContainer, callback, count
460 sleep: vim.options.hints_sleep
461 })
462
463 injectHints = ({wrappers, viewport, pass}) ->
464 # See `getComplementaryWrappers` above.
465 return unless markerContainer.container
466
467 if wrappers.length == 0
468 if pass in ['single', 'second'] and markerContainer.markers.length == 0
469 vim.notify(translate('notification.follow.none'))
470 vim.enterMode('normal')
471 else
472 markerContainer.injectHints(wrappers, viewport, pass)
473
474 if pass == 'first'
475 vim._run(name, {pass: 'second'}, injectHints)
476
477 vim._run(name, {pass: 'auto'}, injectHints)
478
479 helper_follow_clickable = (options, {vim, count = 1}) ->
480 callback = (marker, timesLeft, keyStr) ->
481 {inTab, inBackground} = options
482 {type, elementIndex} = marker.wrapper
483 isLast = (timesLeft == 1)
484 isLink = (type == 'link')
485
486 switch
487 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
488 inTab = not inTab
489 when keyStr.startsWith(vim.options.hints_toggle_in_background)
490 inTab = true
491 inBackground = not inBackground
492 else
493 unless isLast
494 inTab = true
495 inBackground = true
496
497 inTab = false unless isLink
498
499 if type == 'text' or (isLink and not (inTab and inBackground))
500 isLast = true
501
502 vim._focusMarkerElement(elementIndex)
503
504 if inTab
505 utils.nextTick(vim.window, ->
506 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
507 # links using the mouse. Using that instead of simply
508 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
509 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
510 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
511 ContentClick.contentAreaClick({
512 href: marker.wrapper.href
513 shiftKey: not inBackground
514 ctrlKey: true
515 metaKey: true
516 }, vim.browser)
517 reset()
518 )
519 else
520 vim._run('click_marker_element', {
521 elementIndex, type
522 preventTargetBlank: vim.options.prevent_target_blank
523 })
524
525 return not isLast
526
527 name = if options.inTab then 'follow_in_tab' else 'follow'
528 helper_follow(name, vim, callback, count)
529
530 commands.follow =
531 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
532
533 commands.follow_in_tab =
534 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
535
536 commands.follow_in_focused_tab =
537 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
538
539 commands.follow_in_window = ({vim}) ->
540 callback = (marker) ->
541 vim._focusMarkerElement(marker.wrapper.elementIndex)
542 {href} = marker.wrapper
543 vim.window.openLinkIn(href, 'window', {}) if href
544 return false
545 helper_follow('follow_in_tab', vim, callback)
546
547 commands.follow_multiple = (args) ->
548 args.count = Infinity
549 commands.follow(args)
550
551 commands.follow_copy = ({vim}) ->
552 callback = (marker) ->
553 property = switch marker.wrapper.type
554 when 'link'
555 'href'
556 when 'text'
557 'value'
558 when 'contenteditable', 'complementary'
559 '_selection'
560 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
561 return false
562 helper_follow('follow_copy', vim, callback)
563
564 commands.follow_focus = ({vim}) ->
565 callback = (marker) ->
566 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
567 return false
568 helper_follow('follow_focus', vim, callback)
569
570 commands.click_browser_element = ({vim}) ->
571 {window} = vim
572 markerElements = []
573
574 filter = ({complementary}, element, getElementShape) ->
575 type = switch
576 when vim._state.scrollableElements.has(element)
577 'scrollable'
578 when utils.isFocusable(element) or
579 (element.onclick and element.localName != 'statuspanel')
580 'clickable'
581
582 if complementary
583 type = if type then null else 'complementary'
584
585 return unless type
586 return unless shape = getElementShape(element)
587 length = markerElements.push(element)
588 return {type, shape, elementIndex: length - 1}
589
590 callback = (marker) ->
591 element = markerElements[marker.wrapper.elementIndex]
592 switch marker.wrapper.type
593 when 'scrollable'
594 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
595 when 'clickable', 'complementary'
596 sequence =
597 if element.localName == 'tab'
598 ['mousedown']
599 else
600 'click-xul'
601 utils.focusElement(element)
602 utils.simulateMouseEvents(element, sequence)
603 return false
604
605 wrappers = markableElements.find(
606 window, filter.bind(null, {complementary: false})
607 )
608
609 if wrappers.length > 0
610 viewport = viewportUtils.getWindowViewport(window)
611
612 markerContainer = new MarkerContainer({
613 window
614 hintChars: vim.options.hint_chars
615 adjustZoom: false
616 getComplementaryWrappers: (callback) ->
617 newWrappers = markableElements.find(
618 window, filter.bind(null, {complementary: true})
619 )
620 callback({wrappers: newWrappers, viewport})
621 })
622 MarkerContainer.remove(window) # Better safe than sorry.
623 markerContainer.container.classList.add('ui')
624 window.document.getElementById('browser-panel').appendChild(
625 markerContainer.container
626 )
627
628 markerContainer.injectHints(wrappers, viewport, 'single')
629 vim.enterMode('hints', {markerContainer, callback})
630
631 else
632 vim.notify(translate('notification.follow.none'))
633
634 helper_follow_pattern = (type, {vim}) ->
635 options = {
636 pattern_selector: vim.options.pattern_selector
637 pattern_attrs: vim.options.pattern_attrs
638 patterns: vim.options["#{type}_patterns"]
639 }
640 vim._run('follow_pattern', {type, options})
641
642 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
643
644 commands.follow_next = helper_follow_pattern.bind(null, 'next')
645
646 commands.focus_text_input = ({vim, count}) ->
647 vim.markPageInteraction()
648 vim._run('focus_text_input', {count})
649
650 helper_follow_selectable = ({select}, {vim}) ->
651 callback = (marker) ->
652 vim._run('element_text_select', {
653 elementIndex: marker.wrapper.elementIndex
654 full: select
655 scroll: select
656 })
657 vim.enterMode('caret', select)
658 return false
659 helper_follow('follow_selectable', vim, callback)
660
661 commands.element_text_caret =
662 helper_follow_selectable.bind(null, {select: false})
663
664 commands.element_text_select =
665 helper_follow_selectable.bind(null, {select: true})
666
667 commands.element_text_copy = ({vim}) ->
668 callback = (marker) ->
669 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
670 return false
671 helper_follow('follow_selectable', vim, callback)
672
673 helper_copy_marker_element = (vim, elementIndex, property) ->
674 if property == '_selection'
675 # Selecting the text and then copying that selection is better than copying
676 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
677 # and then includes those backticks in the compiled output (!), in hidden
678 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
679 # elements, text selection gives better whitespace than `.textContent`.
680 vim._run('element_text_select', {elementIndex, full: true}, ->
681 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
682 vim._run('clear_selection')
683 )
684 else
685 vim._run('copy_marker_element', {elementIndex, property})
686
687
688
689 findStorage = {lastSearchString: ''}
690
691 helper_find_from_top_of_viewport = (vim, direction, callback) ->
692 if vim.options.find_from_top_of_viewport
693 vim._run('find_from_top_of_viewport', {direction}, callback)
694 else
695 callback()
696
697 helper_find = ({highlight, linksOnly = false}, {vim}) ->
698 helpSearchInput = help.getSearchInput(vim.window)
699 if helpSearchInput
700 helpSearchInput.select()
701 return
702
703 helper_mark_last_scroll_position(vim)
704 helper_find_from_top_of_viewport(vim, FORWARD, ->
705 findBar = vim.window.gBrowser.getFindBar()
706
707 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
708 findBar.startFind(mode)
709 utils.focusElement(findBar._findField, {select: true})
710
711 return if linksOnly
712 return unless highlightButton = findBar.getElement('highlight')
713 if highlightButton.checked != highlight
714 highlightButton.click()
715 )
716
717 commands.find = helper_find.bind(null, {highlight: false})
718
719 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
720
721 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
722
723 helper_find_again = (direction, {vim}) ->
724 findBar = vim.window.gBrowser.getFindBar()
725 if findStorage.lastSearchString.length == 0
726 vim.notify(translate('notification.find_again.none'))
727 return
728
729 helper_mark_last_scroll_position(vim)
730 helper_find_from_top_of_viewport(vim, direction, ->
731 findBar._findField.value = findStorage.lastSearchString
732 findBar.onFindAgainCommand(not direction)
733 message = findBar._findStatusDesc.textContent
734 vim.notify(message) if message
735 )
736
737 commands.find_next = helper_find_again.bind(null, FORWARD)
738
739 commands.find_previous = helper_find_again.bind(null, BACKWARD)
740
741
742
743 commands.window_new = ({vim}) ->
744 vim.window.OpenBrowserWindow()
745
746 commands.window_new_private = ({vim}) ->
747 vim.window.OpenBrowserWindow({private: true})
748
749 commands.enter_mode_ignore = ({vim}) ->
750 vim.enterMode('ignore', {type: 'explicit'})
751
752 # Quote next keypress (pass it through to the page).
753 commands.quote = ({vim, count = 1}) ->
754 vim.enterMode('ignore', {type: 'explicit', count})
755
756 commands.enter_reader_view = ({vim}) ->
757 button = vim.window.document.getElementById('reader-mode-button')
758 if not button?.hidden
759 button.click()
760 else
761 vim.notify(translate('notification.enter_reader_view.none'))
762
763 commands.reload_config_file = ({vim}) ->
764 vim._parent.emit('shutdown')
765 config.load(vim._parent, (status) -> switch status
766 when null
767 vim.notify(translate('notification.reload_config_file.none'))
768 when true
769 vim.notify(translate('notification.reload_config_file.success'))
770 else
771 vim.notify(translate('notification.reload_config_file.failure'))
772 )
773
774 commands.help = ({vim}) ->
775 help.injectHelp(vim.window, vim._parent)
776
777 commands.dev = ({vim}) ->
778 vim.window.DeveloperToolbar.show(true) # `true` to focus.
779
780 commands.esc = ({vim}) ->
781 vim._run('esc')
782 utils.blurActiveBrowserElement(vim)
783 vim.window.gBrowser.getFindBar().close()
784 MarkerContainer.remove(vim.window) # Better safe than sorry.
785
786 # Calling `.hide()` when the toolbar is not open can destroy it for the rest
787 # of the Firefox session. The code here is taken from the `.toggle()` method.
788 {DeveloperToolbar} = vim.window
789 if DeveloperToolbar.visible
790 DeveloperToolbar.hide().catch(console.error)
791
792 unless help.getSearchInput(vim.window)?.getAttribute('focused')
793 help.removeHelp(vim.window)
794
795
796
797 module.exports = {
798 commands
799 findStorage
800 }
Imprint / Impressum