]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Fix the `'`, `g[` and `g]` commands crashing
[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 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')
39
40 {ContentClick} = Cu.import('resource:///modules/ContentClick.jsm', {})
41 {FORWARD, BACKWARD} = SelectionManager
42
43 SPRING_CONSTANT_PREF = 'layout.css.scroll-behavior.spring-constant'
44
45 commands = {}
46
47
48
49 commands.focus_location_bar = ({vim}) ->
50 vim.window.focusAndSelectUrlBar()
51
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()
57 else
58 vim.notify(translate('notification.focus_search_bar.none'))
59
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))
64
65 commands.paste_and_go = helper_paste_and_go.bind(null, null)
66
67 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
68
69 commands.copy_current_url = ({vim}) ->
70 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
71 vim.notify(translate('notification.copy_current_url.success'))
72
73 commands.go_up_path = ({vim, count}) ->
74 vim._run('go_up_path', {count})
75
76 commands.go_to_root = ({vim}) ->
77 vim._run('go_to_root')
78
79 commands.go_home = ({vim}) ->
80 vim.window.BrowserHome()
81
82 helper_go_history = (direction, {vim, count = 1}) ->
83 {window} = vim
84 {SessionStore, gBrowser} = window
85
86 if (direction == 'back' and not gBrowser.canGoBack) or
87 (direction == 'forward' and not gBrowser.canGoForward)
88 vim.notify(translate("notification.history_#{direction}.limit"))
89 return
90
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.
98 if count == 1
99 if direction == 'back'
100 window.BrowserBack()
101 else
102 window.BrowserForward()
103 return
104
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)
111 )
112
113 commands.history_back = helper_go_history.bind(null, 'back')
114
115 commands.history_forward = helper_go_history.bind(null, 'forward')
116
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'))
122
123 commands.reload = ({vim}) ->
124 vim.window.BrowserReload()
125
126 commands.reload_force = ({vim}) ->
127 vim.window.BrowserReloadSkipCache()
128
129 commands.reload_all = ({vim}) ->
130 vim.window.gBrowser.reloadAllTabs()
131
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)
138 return
139
140 commands.stop = ({vim}) ->
141 vim.window.BrowserStop()
142
143 commands.stop_all = ({vim}) ->
144 for tab in vim.window.gBrowser.visibleTabs
145 tab.linkedBrowser.stop()
146 return
147
148
149
150 scrollData = {
151 nonce: null
152 springConstant: null
153 lastRepeat: 0
154 }
155
156 helper_scroll = (vim, event, args...) ->
157 [
158 method, type, directions, amounts
159 properties = null, adjustment = 0, name = 'scroll', extra = {}
160 ] = args
161
162 elapsed = event.timeStamp - scrollData.lastRepeat
163
164 if event.repeat and elapsed < vim.options['scroll.repeat_timeout']
165 return
166
167 scrollData.lastRepeat = event.timeStamp
168
169 options = {
170 method, type, directions, amounts, properties, adjustment, extra
171 smooth: (
172 prefs.root.get('general.smoothScroll') and
173 prefs.root.get("general.smoothScroll.#{type}")
174 )
175 }
176
177 # Temporarily set Firefox’s “spring constant” pref to get the desired smooth
178 # scrolling speed. Reset it `reset_timeout` milliseconds after the last
179 # scrolling command was invoked.
180 scrollData.nonce = nonce = {}
181 scrollData.springConstant ?= prefs.root.get(SPRING_CONSTANT_PREF)
182 prefs.root.set(
183 SPRING_CONSTANT_PREF,
184 vim.options["smoothScroll.#{type}.spring-constant"]
185 )
186 reset = ->
187 vim.window.setTimeout((->
188 return unless scrollData.nonce == nonce
189 prefs.root.set(SPRING_CONSTANT_PREF, scrollData.springConstant)
190 scrollData.nonce = null
191 scrollData.springConstant = null
192 ), vim.options['scroll.reset_timeout'])
193
194 {isUIEvent = vim.isUIEvent(event)} = extra
195 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
196 if isUIEvent or helpScroll
197 activeElement = helpScroll or utils.getActiveElement(vim.window)
198 if vim._state.scrollableElements.has(activeElement) or helpScroll
199 viewportUtils.scroll(activeElement, options)
200 reset()
201 return
202
203 vim._run(name, options, reset)
204
205
206 helper_scrollByLinesX = (amount, {vim, event, count = 1}) ->
207 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
208 boost = if event.repeat then vim.options['scroll.horizontal_boost'] else 1
209 helper_scroll(
210 vim, event, 'scrollBy', 'lines', ['left'],
211 [amount * distance * boost * count * 5]
212 )
213
214 helper_scrollByLinesY = (amount, {vim, event, count = 1}) ->
215 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
216 boost = if event.repeat then vim.options['scroll.vertical_boost'] else 1
217 helper_scroll(
218 vim, event, 'scrollBy', 'lines', ['top'],
219 [amount * distance * boost * count * 20]
220 )
221
222 helper_scrollByPagesY = (amount, type, {vim, event, count = 1}) ->
223 adjustment = vim.options["scroll.#{type}_page_adjustment"]
224 helper_scroll(
225 vim, event, 'scrollBy', 'pages', ['top'], [amount * count],
226 ['clientHeight'], adjustment
227 )
228
229 helper_scrollToX = (amount, {vim, event}) ->
230 helper_mark_last_scroll_position(vim)
231 helper_scroll(
232 vim, event, 'scrollTo', 'other', ['left'], [amount], ['scrollLeftMax']
233 )
234
235 helper_scrollToY = (amount, {vim, event}) ->
236 helper_mark_last_scroll_position(vim)
237 helper_scroll(
238 vim, event, 'scrollTo', 'other', ['top'], [amount], ['scrollTopMax']
239 )
240
241 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
242 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
243 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
244 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
245 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
246 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
247 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
248 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
249 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
250 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
251 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
252 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
253
254 helper_mark_last_scroll_position = (vim) ->
255 keyStr = vim.options['scroll.last_position_mark']
256 vim._run('mark_scroll_position', {keyStr, notify: false, addToJumpList: true})
257
258 commands.mark_scroll_position = ({vim}) ->
259 vim._enterMode('marks', (keyStr) ->
260 vim._run('mark_scroll_position', {keyStr})
261 )
262 vim.notify(translate('notification.mark_scroll_position.enter'))
263
264 commands.scroll_to_mark = ({vim, event}) ->
265 vim._enterMode('marks', (keyStr) ->
266 lastPositionMark = vim.options['scroll.last_position_mark']
267 helper_scroll(
268 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
269 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_mark'
270 {keyStr, lastPositionMark, isUIEvent: false}
271 )
272 vim.hideNotification()
273 )
274 vim.notify(translate('notification.scroll_to_mark.enter'))
275
276 helper_scroll_to_position = (direction, {vim, event, count = 1}) ->
277 lastPositionMark = vim.options['scroll.last_position_mark']
278 helper_scroll(
279 vim, event, 'scrollTo', 'other', ['left', 'top'], [0, 0]
280 ['scrollLeftMax', 'scrollTopMax'], 0, 'scroll_to_position'
281 {count, direction, lastPositionMark, isUIEvent: false}
282 )
283
284 commands.scroll_to_previous_position =
285 helper_scroll_to_position.bind(null, 'previous')
286
287 commands.scroll_to_next_position =
288 helper_scroll_to_position.bind(null, 'next')
289
290
291
292 commands.tab_new = ({vim}) ->
293 utils.nextTick(vim.window, ->
294 vim.window.BrowserOpenTab()
295 )
296
297 commands.tab_new_after_current = ({vim}) ->
298 {window} = vim
299 newTabPosition = window.gBrowser.selectedTab._tPos + 1
300 utils.nextTick(window, ->
301 utils.listenOnce(window, 'TabOpen', (event) ->
302 newTab = event.originalTarget
303 window.gBrowser.moveTabTo(newTab, newTabPosition)
304 )
305 window.BrowserOpenTab()
306 )
307
308 commands.tab_duplicate = ({vim}) ->
309 {gBrowser} = vim.window
310 utils.nextTick(vim.window, ->
311 gBrowser.duplicateTab(gBrowser.selectedTab)
312 )
313
314 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
315 tabs = gBrowser.visibleTabs
316 {selectedTab} = gBrowser
317
318 currentIndex = tabs.indexOf(selectedTab)
319 absoluteIndex = currentIndex + relativeIndex
320 numTabsTotal = tabs.length
321 numPinnedTabs = gBrowser._numPinnedTabs
322
323 [numTabs, min] = switch
324 when not pinnedSeparate
325 [numTabsTotal, 0]
326 when selectedTab.pinned
327 [numPinnedTabs, 0]
328 else
329 [numTabsTotal - numPinnedTabs, numPinnedTabs]
330
331 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
332 # current direction.
333 if (relativeIndex < 0 and currentIndex == min) or
334 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
335 if absoluteIndex < min
336 absoluteIndex += numTabs
337 else if absoluteIndex >= min + numTabs
338 absoluteIndex -= numTabs
339
340 absoluteIndex = Math.max(min, absoluteIndex)
341 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
342
343 return absoluteIndex
344
345 helper_switch_tab = (direction, {vim, count = 1}) ->
346 {gBrowser} = vim.window
347 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
348 utils.nextTick(vim.window, ->
349 gBrowser.selectTabAtIndex(index)
350 )
351
352 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
353
354 commands.tab_select_next = helper_switch_tab.bind(null, +1)
355
356 helper_is_visited = (tab) ->
357 return tab.getAttribute('VimFx-visited') or not tab.getAttribute('unread')
358
359 commands.tab_select_most_recent = ({vim, count = 1}) ->
360 {gBrowser} = vim.window
361 tabsSorted =
362 Array.filter(
363 gBrowser.tabs,
364 (tab) -> not tab.closing and helper_is_visited(tab)
365 ).sort((a, b) -> b.lastAccessed - a.lastAccessed)[1..] # Remove current tab.
366 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
367 if tab
368 gBrowser.selectedTab = tab
369 else
370 vim.notify(translate('notification.tab_select_most_recent.none'))
371
372 commands.tab_select_oldest_unvisited = ({vim, count = 1}) ->
373 {gBrowser} = vim.window
374 tabsSorted =
375 Array.filter(
376 gBrowser.tabs,
377 (tab) -> not tab.closing and not helper_is_visited(tab)
378 ).sort((a, b) -> a.lastAccessed - b.lastAccessed)
379 tab = tabsSorted[Math.min(count - 1, tabsSorted.length - 1)]
380 if tab
381 gBrowser.selectedTab = tab
382 else
383 vim.notify(translate('notification.tab_select_oldest_unvisited.none'))
384
385 helper_move_tab = (direction, {vim, count = 1}) ->
386 {gBrowser} = vim.window
387 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
388 utils.nextTick(vim.window, ->
389 gBrowser.moveTabTo(gBrowser.selectedTab, index)
390 )
391
392 commands.tab_move_backward = helper_move_tab.bind(null, -1)
393
394 commands.tab_move_forward = helper_move_tab.bind(null, +1)
395
396 commands.tab_move_to_window = ({vim}) ->
397 {gBrowser} = vim.window
398 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
399
400 commands.tab_select_first = ({vim, count = 1}) ->
401 utils.nextTick(vim.window, ->
402 vim.window.gBrowser.selectTabAtIndex(count - 1)
403 )
404
405 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
406 firstNonPinned = vim.window.gBrowser._numPinnedTabs
407 utils.nextTick(vim.window, ->
408 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
409 )
410
411 commands.tab_select_last = ({vim, count = 1}) ->
412 utils.nextTick(vim.window, ->
413 vim.window.gBrowser.selectTabAtIndex(-count)
414 )
415
416 commands.tab_toggle_pinned = ({vim}) ->
417 currentTab = vim.window.gBrowser.selectedTab
418 if currentTab.pinned
419 vim.window.gBrowser.unpinTab(currentTab)
420 else
421 vim.window.gBrowser.pinTab(currentTab)
422
423 commands.tab_close = ({vim, count = 1}) ->
424 {gBrowser} = vim.window
425 return if gBrowser.selectedTab.pinned
426 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
427 utils.nextTick(vim.window, ->
428 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
429 gBrowser.removeTab(tab)
430 return
431 )
432
433 commands.tab_restore = ({vim, count = 1}) ->
434 utils.nextTick(vim.window, ->
435 for index in [0...count] by 1
436 restoredTab = vim.window.undoCloseTab()
437 if not restoredTab and index == 0
438 vim.notify(translate('notification.tab_restore.none'))
439 break
440 return
441 )
442
443 commands.tab_restore_list = ({vim}) ->
444 {window} = vim
445 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
446 window, 'menuitem'
447 )
448 if fragment.childElementCount == 0
449 vim.notify(translate('notification.tab_restore.none'))
450 else
451 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
452
453 commands.tab_close_to_end = ({vim}) ->
454 {gBrowser} = vim.window
455 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
456
457 commands.tab_close_other = ({vim}) ->
458 {gBrowser} = vim.window
459 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
460
461
462
463 helper_follow = ({name, callback}, {vim, count, callbackOverride = null}) ->
464 {window} = vim
465 vim.markPageInteraction()
466 help.removeHelp(window)
467
468 markerContainer = new MarkerContainer({
469 window
470 hintChars: vim.options['hints.chars']
471 getComplementaryWrappers: (callback) ->
472 vim._run(name, {pass: 'complementary'}, ({wrappers, viewport}) ->
473 # `markerContainer.container` is `null`ed out when leaving Hints mode.
474 # If this callback is called after we’ve left Hints mode (and perhaps
475 # even entered it again), simply discard the result.
476 return unless markerContainer.container
477 if wrappers.length == 0
478 vim.notify(translate('notification.follow.none'))
479 callback({wrappers, viewport})
480 )
481 })
482 MarkerContainer.remove(window) # Better safe than sorry.
483 window.gBrowser.selectedBrowser.parentNode.appendChild(
484 markerContainer.container
485 )
486
487 chooseCallback = (marker, timesLeft, keyStr) ->
488 if callbackOverride
489 {type, href = null, elementIndex} = marker.wrapper
490 return callbackOverride({type, href, id: elementIndex, timesLeft})
491 else
492 return callback(marker, timesLeft, keyStr)
493
494 # Enter Hints mode immediately, with an empty set of markers. The user might
495 # press keys before any hints have been generated. Those keypresses should be
496 # handled in Hints mode, not Normal mode.
497 vim._enterMode('hints', {
498 markerContainer, count
499 callback: chooseCallback
500 matchText: vim.options['hints.match_text']
501 sleep: vim.options['hints.sleep']
502 })
503
504 injectHints = ({wrappers, viewport, pass}) ->
505 # See `getComplementaryWrappers` above.
506 return unless markerContainer.container
507
508 if wrappers.length == 0
509 if pass in ['single', 'second'] and markerContainer.markers.length == 0
510 vim.notify(translate('notification.follow.none'))
511 vim._enterMode('normal')
512 else
513 markerContainer.injectHints(wrappers, viewport, pass)
514
515 if pass == 'first'
516 vim._run(name, {pass: 'second'}, injectHints)
517
518 vim._run(name, {pass: 'auto'}, injectHints)
519
520 helper_follow_clickable = (options, args) ->
521 {vim} = args
522
523 callback = (marker, timesLeft, keyStr) ->
524 {inTab, inBackground} = options
525 {type, elementIndex} = marker.wrapper
526 isLast = (timesLeft == 1)
527 isLink = (type == 'link')
528 {window} = vim
529
530 switch
531 when keyStr.startsWith(vim.options['hints.toggle_in_tab'])
532 inTab = not inTab
533 when keyStr.startsWith(vim.options['hints.toggle_in_background'])
534 inTab = true
535 inBackground = not inBackground
536 else
537 unless isLast
538 inTab = true
539 inBackground = true
540
541 inTab = false unless isLink
542
543 if type == 'text' or (isLink and not (inTab and inBackground))
544 isLast = true
545
546 vim._focusMarkerElement(elementIndex)
547
548 if inTab
549 utils.nextTick(window, ->
550 # `ContentClick.contentAreaClick` is what Firefox invokes when you click
551 # links using the mouse. Using that instead of simply
552 # `gBrowser.loadOneTab(url, options)` gives better interoperability with
553 # other add-ons, such as Tree Style Tab and BackTrack Tab History.
554 reset = prefs.root.tmp('browser.tabs.loadInBackground', true)
555 ContentClick.contentAreaClick({
556 href: marker.wrapper.href
557 shiftKey: not inBackground
558 ctrlKey: true
559 metaKey: true
560 originAttributes: window.document.nodePrincipal?.originAttributes ? {}
561 }, vim.browser)
562 reset()
563 )
564
565 # The point of “clicking” scrollable elements is focusing them (which is
566 # done above) so that scrolling commands may scroll them. Simulating a click
567 # here usually _unfocuses_ the element.
568 else if type != 'scrollable'
569 vim._run('click_marker_element', {
570 elementIndex, type
571 browserOffset: vim._getBrowserOffset()
572 preventTargetBlank: vim.options.prevent_target_blank
573 })
574
575 return not isLast
576
577 name = if options.inTab then 'follow_in_tab' else 'follow'
578 helper_follow({name, callback}, args)
579
580 commands.follow =
581 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
582
583 commands.follow_in_tab =
584 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
585
586 commands.follow_in_focused_tab =
587 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
588
589 helper_follow_in_window = (options, args) ->
590 {vim} = args
591
592 callback = (marker) ->
593 vim._focusMarkerElement(marker.wrapper.elementIndex)
594 {href} = marker.wrapper
595 vim.window.openLinkIn(href, 'window', options) if href
596 return false
597
598 helper_follow({name: 'follow_in_tab', callback}, args)
599
600 commands.follow_in_window =
601 helper_follow_in_window.bind(null, {})
602
603 commands.follow_in_private_window =
604 helper_follow_in_window.bind(null, {private: true})
605
606 commands.follow_multiple = (args) ->
607 args.count = Infinity
608 commands.follow(args)
609
610 commands.follow_copy = (args) ->
611 {vim} = args
612
613 callback = (marker) ->
614 property = switch marker.wrapper.type
615 when 'link'
616 'href'
617 when 'text'
618 'value'
619 when 'contenteditable', 'complementary'
620 '_selection'
621 helper_copy_marker_element(vim, marker.wrapper.elementIndex, property)
622 return false
623
624 helper_follow({name: 'follow_copy', callback}, args)
625
626 commands.follow_focus = (args) ->
627 {vim} = args
628
629 callback = (marker) ->
630 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
631 return false
632
633 helper_follow({name: 'follow_focus', callback}, args)
634
635 commands.open_context_menu = (args) ->
636 {vim} = args
637
638 callback = (marker) ->
639 {type, elementIndex} = marker.wrapper
640 vim._run('click_marker_element', {
641 elementIndex, type
642 browserOffset: vim._getBrowserOffset()
643 })
644 return false
645
646 helper_follow({name: 'follow_context', callback}, args)
647
648 commands.click_browser_element = ({vim}) ->
649 {window} = vim
650 markerElements = []
651
652 getButtonMenu = (element) ->
653 if element.localName == 'dropmarker' and
654 element.parentNode?.localName == 'toolbarbutton'
655 return element.parentNode.querySelector('menupopup')
656 else
657 return null
658
659 filter = ({complementary}, element, getElementShape) ->
660 type = switch
661 when vim._state.scrollableElements.has(element)
662 'scrollable'
663 when getButtonMenu(element)
664 'dropmarker'
665 when utils.isFocusable(element) or
666 (element.onclick and element.localName != 'statuspanel')
667 'clickable'
668
669 if complementary
670 type = if type then null else 'complementary'
671
672 return unless type
673
674 # `getElementShape(element, -1)` is intentionally _not_ used in the
675 # `complementary` run, because it results in tons of useless hints for
676 # hidden context menus.
677 shape = getElementShape(element)
678 return unless shape.nonCoveredPoint
679
680 # The tabs and their close buttons as well as the tab bar scroll arrows get
681 # better hints, since switching or closing tabs is the most common use case
682 # for the `eb` command.
683 isTab = element.classList?.contains('tabbrowser-tab')
684 isPrioritized =
685 isTab or
686 element.classList?.contains('tab-close-button') or
687 element.classList?.contains('scrollbutton-up') or
688 element.classList?.contains('scrollbutton-down')
689
690 length = markerElements.push(element)
691 return {
692 type, shape, isTab, isPrioritized,
693 combinedArea: shape.area,
694 elementIndex: length - 1,
695 }
696
697 callback = (marker) ->
698 element = markerElements[marker.wrapper.elementIndex]
699 switch marker.wrapper.type
700 when 'scrollable'
701 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
702 when 'dropmarker'
703 getButtonMenu(element).openPopup(
704 element.parentNode, # Anchor node.
705 'after_end', # Position.
706 0, 0, # Offset.
707 false, # Isn’t a context menu.
708 true, # Allow the 'position' attribute to override the above position.
709 )
710 when 'clickable', 'complementary'
711 # VimFx’s own button won’t trigger unless the click is simulated in the
712 # next tick. This might be true for other buttons as well.
713 utils.nextTick(window, ->
714 utils.focusElement(element)
715 browserOffset = {x: window.screenX, y: window.screenY}
716 switch
717 when element.localName == 'tab'
718 # Only 'mousedown' seems to be able to activate tabs.
719 utils.simulateMouseEvents(element, ['mousedown'], browserOffset)
720 when element.closest('tab')
721 # If `.click()` is used on a tab close button, its tab will be
722 # selected first, which might cause the selected tab to change.
723 utils.simulateMouseEvents(element, 'click-xul', browserOffset)
724 else
725 # `.click()` seems to trigger more buttons (such as NoScript’s
726 # button and Firefox’s “hamburger” menu button) than simulating
727 # 'click-xul'.
728 element.click()
729 utils.openDropdown(element)
730 )
731 return false
732
733 wrappers = markableElements.find(
734 window, filter.bind(null, {complementary: false})
735 )
736
737 if wrappers.length > 0
738 viewport = viewportUtils.getWindowViewport(window)
739
740 markerContainer = new MarkerContainer({
741 window
742 hintChars: vim.options['hints.chars']
743 adjustZoom: false
744 minWeightDiff: 0
745 getComplementaryWrappers: (callback) ->
746 newWrappers = markableElements.find(
747 window, filter.bind(null, {complementary: true})
748 )
749 callback({wrappers: newWrappers, viewport})
750 })
751 MarkerContainer.remove(window) # Better safe than sorry.
752 markerContainer.container.classList.add('ui')
753 window.document.getElementById('browser-panel').appendChild(
754 markerContainer.container
755 )
756
757 [firstWrappers, secondWrappers] =
758 utils.partition(wrappers, (wrapper) -> wrapper.isPrioritized)
759
760 numChars = markerContainer.alphabet.length
761 numPrimary = markerContainer.primaryHintChars.length
762 numTabs = firstWrappers.filter(({isTab}) -> isTab).length
763 index = 0
764
765 for wrapper in firstWrappers
766 if wrapper.isTab
767 # Given the hint chars `abc de`, give the tabs weights so that the hints
768 # consistently become `a b ca cb cc cd cea ceb cec ced ceea ceeb` and so
769 # on. The rule is that the weight of a tab must be larger than the sum
770 # of all tabs with a longer hint. We start out at `1` and then use
771 # smaller and smaller fractions. This is to make sure that the tabs get
772 # consistent hints as the number of tabs or the size of the window
773 # changes.
774 exponent = (index - numPrimary + 1) // (numChars - 1) + 1
775 wrapper.combinedArea = 1 / numChars ** exponent
776 index += 1
777 else
778 # Make sure that the tab close buttons and the tab bar scroll buttons
779 # come after all the tabs. Treating them all as the same size is fine.
780 # Their sum must be small enough in order not to affect the tab hints.
781 # It might look like using `0` is a good idea, but that results in
782 # increasingly worse hints the more tab close buttons there are.
783 wrapper.combinedArea = 1 / numChars ** numTabs
784
785 # Since most of the best hint characters might be used for the tabs, make
786 # sure that all other elements don’t get really bad hints. First, favor
787 # larger elements by sorting them. Then, give them all the same weight so
788 # that larger elements (such as the location bar, search bar, the web
789 # console input and other large areas in the devtools) don’t overpower the
790 # smaller ones. The usual “the larger the element, the better the hint” rule
791 # doesn’t really apply the same way for browser UI elements as in web pages.
792 secondWrappers.sort((a, b) -> b.combinedArea - a.combinedArea)
793 for wrapper in secondWrappers
794 wrapper.combinedArea = 1
795
796 markerContainer.injectHints(firstWrappers, viewport, 'first')
797 markerContainer.injectHints(secondWrappers, viewport, 'second')
798 vim._enterMode('hints', {markerContainer, callback, matchText: false})
799
800 else
801 vim.notify(translate('notification.follow.none'))
802
803 helper_follow_pattern = (type, {vim}) ->
804 options = {
805 pattern_selector: vim.options.pattern_selector
806 pattern_attrs: vim.options.pattern_attrs
807 patterns: vim.options["#{type}_patterns"]
808 }
809 browserOffset = vim._getBrowserOffset()
810 vim._run('follow_pattern', {type, browserOffset, options})
811
812 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
813
814 commands.follow_next = helper_follow_pattern.bind(null, 'next')
815
816 commands.focus_text_input = ({vim, count}) ->
817 vim.markPageInteraction()
818 vim._run('focus_text_input', {count})
819
820 helper_follow_selectable = ({select}, args) ->
821 {vim} = args
822
823 callback = (marker) ->
824 vim._run('element_text_select', {
825 elementIndex: marker.wrapper.elementIndex
826 full: select
827 scroll: select
828 })
829 vim._enterMode('caret', {select})
830 return false
831
832 helper_follow({name: 'follow_selectable', callback}, args)
833
834 commands.element_text_caret =
835 helper_follow_selectable.bind(null, {select: false})
836
837 commands.element_text_select =
838 helper_follow_selectable.bind(null, {select: true})
839
840 commands.element_text_copy = (args) ->
841 {vim} = args
842
843 callback = (marker) ->
844 helper_copy_marker_element(vim, marker.wrapper.elementIndex, '_selection')
845 return false
846
847 helper_follow({name: 'follow_selectable', callback}, args)
848
849 helper_copy_marker_element = (vim, elementIndex, property) ->
850 if property == '_selection'
851 # Selecting the text and then copying that selection is better than copying
852 # `.textContent`. Slack uses markdown-style backtick syntax for code spans
853 # and then includes those backticks in the compiled output (!), in hidden
854 # `<span>`s, so `.textContent` would copy those too. In `contenteditable`
855 # elements, text selection gives better whitespace than `.textContent`.
856 vim._run('element_text_select', {elementIndex, full: true}, ->
857 vim.window.goDoCommand('cmd_copy') # See `caret.copy_selection_and_exit`.
858 vim._run('clear_selection')
859 )
860 else
861 vim._run('copy_marker_element', {elementIndex, property})
862
863
864
865 findStorage = {
866 lastSearchString: ''
867 busy: false
868 }
869
870 helper_find_from_top_of_viewport = (vim, direction, callback) ->
871 if vim.options.find_from_top_of_viewport
872 vim._run('find_from_top_of_viewport', {direction}, ->
873 callback()
874 )
875 else
876 callback()
877
878 helper_find = ({highlight, linksOnly = false}, {vim}) ->
879 if findStorage.busy
880 # Make sure to enter find mode here, since that’s where `findStorage.busy`
881 # is reset to `false` again. Otherwise we can get stuck in the “busy” state.
882 vim._enterMode('find')
883 return
884
885 helpSearchInput = help.getSearchInput(vim.window)
886 if helpSearchInput
887 helpSearchInput.select()
888 return
889
890 # Important: Enter Find mode immediately. See `onInput` for Find mode.
891 findStorage.busy = true
892 vim._enterMode('find')
893
894 helper_mark_last_scroll_position(vim)
895 vim._run('mark_scroll_position', {
896 keyStr: vim.options['scroll.last_find_mark']
897 notify: false
898 })
899
900 helper_find_from_top_of_viewport(vim, FORWARD, ->
901 return unless vim.mode == 'find'
902 findBar = vim.window.gBrowser.getFindBar()
903
904 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
905 findBar.startFind(mode)
906 utils.focusElement(findBar._findField, {select: true})
907
908 return if linksOnly
909 return unless highlightButton = findBar.getElement('highlight')
910 if highlightButton.checked != highlight
911 highlightButton.click()
912 )
913
914 commands.find = helper_find.bind(null, {highlight: false})
915
916 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
917
918 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
919
920 helper_find_again = (direction, {vim}) ->
921 return if findStorage.busy
922
923 findBar = vim.window.gBrowser.getFindBar()
924 if findStorage.lastSearchString.length == 0
925 vim.notify(translate('notification.find_again.none'))
926 return
927
928 findStorage.busy = true
929
930 helper_mark_last_scroll_position(vim)
931 helper_find_from_top_of_viewport(vim, direction, ->
932 findBar._findField.value = findStorage.lastSearchString
933
934 # `.onFindResult` is temporarily hacked to be able to know when the
935 # asynchronous `.onFindAgainCommand` is done. When PDFs are shown using
936 # PDF.js, `.updateControlState` is called instead of `.onFindResult`, so
937 # hack that one too.
938 originalOnFindResult = findBar.onFindResult
939 originalUpdateControlState = findBar.updateControlState
940
941 findBar.onFindResult = (data) ->
942 # Prevent the find bar from re-opening if there are no matches.
943 data.storeResult = false
944 findBar.onFindResult = originalOnFindResult
945 findBar.updateControlState = originalUpdateControlState
946 findBar.onFindResult(data)
947 callback()
948
949 findBar.updateControlState = (args...) ->
950 # Firefox inconsistently _doesn’t_ re-open the find bar if there are no
951 # matches here, so no need to take care of that in this case.
952 findBar.onFindResult = originalOnFindResult
953 findBar.updateControlState = originalUpdateControlState
954 findBar.updateControlState(args...)
955 callback()
956
957 callback = ->
958 message = findBar._findStatusDesc.textContent
959 vim.notify(message) if message
960 findStorage.busy = false
961
962 findBar.onFindAgainCommand(not direction)
963 )
964
965 commands.find_next = helper_find_again.bind(null, FORWARD)
966
967 commands.find_previous = helper_find_again.bind(null, BACKWARD)
968
969
970
971 commands.window_new = ({vim}) ->
972 vim.window.OpenBrowserWindow()
973
974 commands.window_new_private = ({vim}) ->
975 vim.window.OpenBrowserWindow({private: true})
976
977 commands.enter_mode_ignore = ({vim, blacklist = false}) ->
978 type = if blacklist then 'blacklist' else 'explicit'
979 vim._enterMode('ignore', {type})
980
981 # Quote next keypress (pass it through to the page).
982 commands.quote = ({vim, count = 1}) ->
983 vim._enterMode('ignore', {type: 'explicit', count})
984
985 commands.enter_reader_view = ({vim}) ->
986 button = vim.window.document.getElementById('reader-mode-button')
987 if not button?.hidden
988 button.click()
989 else
990 vim.notify(translate('notification.enter_reader_view.none'))
991
992 commands.reload_config_file = ({vim}) ->
993 vim._parent.emit('shutdown')
994 config.load(vim._parent, {allowDeprecated: false}, (status) -> switch status
995 when null
996 vim.notify(translate('notification.reload_config_file.none'))
997 when true
998 vim.notify(translate('notification.reload_config_file.success'))
999 else
1000 vim.notify(translate('notification.reload_config_file.failure'))
1001 )
1002
1003 commands.edit_blacklist = ({vim}) ->
1004 url = vim.browser.currentURI.spec
1005 location = new vim.window.URL(url)
1006 newPattern = if location.host then "*#{location.host}*" else location.href
1007 delimiter = ' '
1008 blacklistString = prefs.get('blacklist')
1009
1010 if vim._isBlacklisted(url)
1011 blacklist = parsePrefs.parseSpaceDelimitedString(blacklistString).parsed
1012 [matching, nonMatching] = utils.partition(blacklist, (string, index) ->
1013 return vim.options.blacklist[index].test(url)
1014 )
1015 newBlacklistString = "
1016 #{matching.join(delimiter)}\
1017 #{delimiter.repeat(7)}\
1018 #{nonMatching.join(delimiter)}
1019 "
1020 extraMessage = translate('pref.blacklist.extra.is_blacklisted')
1021 else
1022 newBlacklistString = "#{newPattern}#{delimiter}#{blacklistString}"
1023 extraMessage = translate('pref.blacklist.extra.added', newPattern)
1024
1025 message = """
1026 #{translate('pref.blacklist.title')}: #{translate('pref.blacklist.desc')}
1027
1028 #{extraMessage}
1029 """
1030
1031 vim._modal('prompt', [message, newBlacklistString.trim()], (input) ->
1032 return if input == null
1033 # Just set the blacklist as if the user had typed it in the Add-ons Manager,
1034 # and let the regular pref parsing take care of it.
1035 prefs.set('blacklist', input)
1036 vim._onLocationChange(url)
1037 )
1038
1039 commands.help = ({vim}) ->
1040 help.toggleHelp(vim.window, vim._parent)
1041
1042 commands.dev = ({vim}) ->
1043 vim.window.DeveloperToolbar.show(true) # `true` to focus.
1044
1045 commands.esc = ({vim}) ->
1046 vim._run('esc')
1047 vim.hideNotification()
1048
1049 # Firefox does things differently when blurring the location bar, depending on
1050 # whether the autocomplete popup is open or not. To be consistent, always
1051 # close the autocomplete popup before blurring.
1052 vim.window.gURLBar.closePopup()
1053
1054 utils.blurActiveBrowserElement(vim)
1055 vim.window.gBrowser.getFindBar().close()
1056
1057 # Better safe than sorry.
1058 MarkerContainer.remove(vim.window)
1059 vim._parent.resetCaretBrowsing()
1060
1061 # Calling `.hide()` when the toolbar is not open can destroy it for the rest
1062 # of the Firefox session. The code here is taken from the `.toggle()` method.
1063 {DeveloperToolbar} = vim.window
1064 if DeveloperToolbar.visible
1065 DeveloperToolbar.hide().catch(console.error)
1066
1067 unless help.getSearchInput(vim.window)?.getAttribute('focused')
1068 help.removeHelp(vim.window)
1069
1070 vim._setFocusType('none') # Better safe than sorry.
1071
1072
1073
1074 module.exports = {
1075 commands
1076 findStorage
1077 }
Imprint / Impressum