]> git.gir.st - VimFx.git/blob - extension/lib/commands.coffee
Enable the `no_implicit_braces` CoffeeLint rule
[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 help = require('./help')
30 hints = require('./hints')
31 prefs = require('./prefs')
32 translate = require('./l10n')
33 utils = require('./utils')
34
35 commands = {}
36
37
38
39 commands.focus_location_bar = ({vim}) ->
40 vim.window.focusAndSelectUrlBar()
41
42 commands.focus_search_bar = ({vim, count}) ->
43 # The `.webSearch()` method opens a search engine in a tab if the search bar
44 # has been removed. Therefore we first check if it exists.
45 if vim.window.BrowserSearch.searchBar
46 vim.window.BrowserSearch.webSearch()
47
48 helper_paste_and_go = (props, {vim}) ->
49 {gURLBar} = vim.window
50 gURLBar.value = vim.window.readFromClipboard()
51 gURLBar.handleCommand(new vim.window.KeyboardEvent('keydown', props))
52
53 commands.paste_and_go = helper_paste_and_go.bind(null, null)
54
55 commands.paste_and_go_in_tab = helper_paste_and_go.bind(null, {altKey: true})
56
57 commands.copy_current_url = ({vim}) ->
58 utils.writeToClipboard(vim.window.gBrowser.currentURI.spec)
59 vim.notify(translate('notification.copy_current_url'))
60
61 commands.go_up_path = ({vim, count}) ->
62 vim._run('go_up_path', {count})
63
64 commands.go_to_root = ({vim}) ->
65 vim._run('go_to_root')
66
67 commands.go_home = ({vim}) ->
68 vim.window.BrowserHome()
69
70 helper_go_history = (direction, {vim, count = 1}) ->
71 {window} = vim
72 {SessionStore, gBrowser} = window
73
74 if (direction == 'back' and not gBrowser.canGoBack) or
75 (direction == 'forward' and not gBrowser.canGoForward)
76 vim.notify(translate("notification.history_#{direction}.limit"))
77 return
78
79 # `SessionStore.getSessionHistory()` (used below to support counts) starts
80 # lots of asynchronous tasks internally, which is a bit unreliable, it has
81 # turned out. The primary use of the `history_back` and `history_forward`
82 # commands is to go _one_ step back or forward, though, so those cases are
83 # optimized to use more reliable ways of going back and forward. Also, some
84 # extensions override the following functions, so calling them also gives
85 # better interoperability.
86 if count == 1
87 if direction == 'back'
88 window.BrowserBack()
89 else
90 window.BrowserForward()
91 return
92
93 SessionStore.getSessionHistory(gBrowser.selectedTab, (sessionHistory) ->
94 {index} = sessionHistory
95 newIndex = index + count * (if direction == 'back' then -1 else 1)
96 newIndex = Math.max(newIndex, 0)
97 newIndex = Math.min(newIndex, sessionHistory.entries.length - 1)
98 gBrowser.gotoIndex(newIndex)
99 )
100
101 commands.history_back = helper_go_history.bind(null, 'back')
102
103 commands.history_forward = helper_go_history.bind(null, 'forward')
104
105 commands.history_list = ({vim}) ->
106 menu = vim.window.document.getElementById('backForwardMenu')
107 utils.openPopup(menu)
108 if menu.childElementCount == 0
109 vim.notify(translate('notification.history_list.none'))
110
111 commands.reload = ({vim}) ->
112 vim.window.BrowserReload()
113
114 commands.reload_force = ({vim}) ->
115 vim.window.BrowserReloadSkipCache()
116
117 commands.reload_all = ({vim}) ->
118 vim.window.gBrowser.reloadAllTabs()
119
120 commands.reload_all_force = ({vim}) ->
121 for tab in vim.window.gBrowser.visibleTabs
122 gBrowser = tab.linkedBrowser
123 consts = gBrowser.webNavigation
124 flags = consts.LOAD_FLAGS_BYPASS_PROXY | consts.LOAD_FLAGS_BYPASS_CACHE
125 gBrowser.reload(flags)
126 return
127
128 commands.stop = ({vim}) ->
129 vim.window.BrowserStop()
130
131 commands.stop_all = ({vim}) ->
132 for tab in vim.window.gBrowser.visibleTabs
133 tab.linkedBrowser.stop()
134 return
135
136
137
138 helper_scroll = (vim, uiEvent, args...) ->
139 [
140 method, type, directions, amounts
141 properties = null, adjustment = 0, name = 'scroll'
142 ] = args
143 options = {
144 method, type, directions, amounts, properties, adjustment
145 smooth: (prefs.root.get('general.smoothScroll') and
146 prefs.root.get("general.smoothScroll.#{type}"))
147 }
148 reset = prefs.root.tmp(
149 'layout.css.scroll-behavior.spring-constant',
150 vim.options["smoothScroll.#{type}.spring-constant"]
151 )
152
153 helpScroll = help.getHelp(vim.window)?.querySelector('.wrapper')
154 if uiEvent or helpScroll
155 activeElement = helpScroll or utils.getActiveElement(vim.window)
156 if vim._state.scrollableElements.has(activeElement) or helpScroll
157 utils.scroll(activeElement, options)
158 reset()
159 return
160
161 vim._run(name, options, reset)
162
163
164 helper_scrollByLinesX = (amount, {vim, uiEvent, count = 1}) ->
165 distance = prefs.root.get('toolkit.scrollbox.horizontalScrollDistance')
166 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['left'],
167 [amount * distance * count * 5])
168
169 helper_scrollByLinesY = (amount, {vim, uiEvent, count = 1}) ->
170 distance = prefs.root.get('toolkit.scrollbox.verticalScrollDistance')
171 helper_scroll(vim, uiEvent, 'scrollBy', 'lines', ['top'],
172 [amount * distance * count * 20])
173
174 helper_scrollByPagesY = (amount, type, {vim, uiEvent, count = 1}) ->
175 adjustment = prefs.get("scroll.#{type}_page_adjustment")
176 helper_scroll(vim, uiEvent, 'scrollBy', 'pages', ['top'],
177 [amount * count], ['clientHeight'], adjustment)
178
179 helper_scrollToX = (amount, {vim, uiEvent}) ->
180 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['left'],
181 [amount], ['scrollLeftMax'])
182 helper_mark_last_scroll_position(vim)
183
184 helper_scrollToY = (amount, {vim, uiEvent}) ->
185 helper_scroll(vim, uiEvent, 'scrollTo', 'other', ['top'],
186 [amount], ['scrollTopMax'])
187 helper_mark_last_scroll_position(vim)
188
189 commands.scroll_left = helper_scrollByLinesX.bind(null, -1)
190 commands.scroll_right = helper_scrollByLinesX.bind(null, +1)
191 commands.scroll_down = helper_scrollByLinesY.bind(null, +1)
192 commands.scroll_up = helper_scrollByLinesY.bind(null, -1)
193 commands.scroll_page_down = helper_scrollByPagesY.bind(null, +1, 'full')
194 commands.scroll_page_up = helper_scrollByPagesY.bind(null, -1, 'full')
195 commands.scroll_half_page_down = helper_scrollByPagesY.bind(null, +0.5, 'half')
196 commands.scroll_half_page_up = helper_scrollByPagesY.bind(null, -0.5, 'half')
197 commands.scroll_to_top = helper_scrollToY.bind(null, 0)
198 commands.scroll_to_bottom = helper_scrollToY.bind(null, Infinity)
199 commands.scroll_to_left = helper_scrollToX.bind(null, 0)
200 commands.scroll_to_right = helper_scrollToX.bind(null, Infinity)
201
202 helper_mark_last_scroll_position = (vim) ->
203 keyStr = vim.options['scroll.last_position_mark']
204 vim._run('mark_scroll_position', {keyStr, notify: false})
205
206 commands.mark_scroll_position = ({vim}) ->
207 vim.enterMode('marks', (keyStr) -> vim._run('mark_scroll_position', {keyStr}))
208
209 commands.scroll_to_mark = ({vim}) ->
210 vim.enterMode('marks', (keyStr) ->
211 unless keyStr == vim.options['scroll.last_position_mark']
212 helper_mark_last_scroll_position(vim)
213 helper_scroll(vim, null, 'scrollTo', 'other', ['top', 'left'], keyStr,
214 ['scrollTopMax', 'scrollLeftMax'], 0, 'scroll_to_mark')
215 )
216
217
218
219 commands.tab_new = ({vim}) ->
220 utils.nextTick(vim.window, ->
221 vim.window.BrowserOpenTab()
222 )
223
224 commands.tab_duplicate = ({vim}) ->
225 {gBrowser} = vim.window
226 utils.nextTick(vim.window, ->
227 gBrowser.duplicateTab(gBrowser.selectedTab)
228 )
229
230 absoluteTabIndex = (relativeIndex, gBrowser, {pinnedSeparate}) ->
231 tabs = gBrowser.visibleTabs
232 {selectedTab} = gBrowser
233
234 currentIndex = tabs.indexOf(selectedTab)
235 absoluteIndex = currentIndex + relativeIndex
236 numTabsTotal = tabs.length
237 numPinnedTabs = gBrowser._numPinnedTabs
238
239 [numTabs, min] = switch
240 when not pinnedSeparate then [numTabsTotal, 0]
241 when selectedTab.pinned then [numPinnedTabs, 0]
242 else [numTabsTotal - numPinnedTabs, numPinnedTabs]
243
244 # Wrap _once_ if at one of the ends of the tab bar and cannot move in the
245 # current direction.
246 if (relativeIndex < 0 and currentIndex == min) or
247 (relativeIndex > 0 and currentIndex == min + numTabs - 1)
248 if absoluteIndex < min
249 absoluteIndex += numTabs
250 else if absoluteIndex >= min + numTabs
251 absoluteIndex -= numTabs
252
253 absoluteIndex = Math.max(min, absoluteIndex)
254 absoluteIndex = Math.min(absoluteIndex, min + numTabs - 1)
255
256 return absoluteIndex
257
258 helper_switch_tab = (direction, {vim, count = 1}) ->
259 {gBrowser} = vim.window
260 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: false})
261 utils.nextTick(vim.window, ->
262 gBrowser.selectTabAtIndex(index)
263 )
264
265 commands.tab_select_previous = helper_switch_tab.bind(null, -1)
266
267 commands.tab_select_next = helper_switch_tab.bind(null, +1)
268
269 commands.tab_select_most_recent = ({vim, count = 1}) ->
270 {gBrowser} = vim.window
271 tabsSorted = Array.filter(gBrowser.tabs, (tab) -> not tab.closing)
272 .sort((a, b) -> b.lastAccessed - a.lastAccessed)
273 mostRecentTab = tabsSorted[Math.min(count, tabsSorted.length - 1)]
274 gBrowser.selectedTab = mostRecentTab if mostRecentTab
275
276 helper_move_tab = (direction, {vim, count = 1}) ->
277 {gBrowser} = vim.window
278 index = absoluteTabIndex(direction * count, gBrowser, {pinnedSeparate: true})
279 utils.nextTick(vim.window, ->
280 gBrowser.moveTabTo(gBrowser.selectedTab, index)
281 )
282
283 commands.tab_move_backward = helper_move_tab.bind(null, -1)
284
285 commands.tab_move_forward = helper_move_tab.bind(null, +1)
286
287 commands.tab_move_to_window = ({vim}) ->
288 {gBrowser} = vim.window
289 gBrowser.replaceTabWithWindow(gBrowser.selectedTab)
290
291 commands.tab_select_first = ({vim, count = 1}) ->
292 utils.nextTick(vim.window, ->
293 vim.window.gBrowser.selectTabAtIndex(count - 1)
294 )
295
296 commands.tab_select_first_non_pinned = ({vim, count = 1}) ->
297 firstNonPinned = vim.window.gBrowser._numPinnedTabs
298 utils.nextTick(vim.window, ->
299 vim.window.gBrowser.selectTabAtIndex(firstNonPinned + count - 1)
300 )
301
302 commands.tab_select_last = ({vim, count = 1}) ->
303 utils.nextTick(vim.window, ->
304 vim.window.gBrowser.selectTabAtIndex(-count)
305 )
306
307 commands.tab_toggle_pinned = ({vim}) ->
308 currentTab = vim.window.gBrowser.selectedTab
309 if currentTab.pinned
310 vim.window.gBrowser.unpinTab(currentTab)
311 else
312 vim.window.gBrowser.pinTab(currentTab)
313
314 commands.tab_close = ({vim, count = 1}) ->
315 {gBrowser} = vim.window
316 return if gBrowser.selectedTab.pinned
317 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
318 utils.nextTick(vim.window, ->
319 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
320 gBrowser.removeTab(tab)
321 return
322 )
323
324 commands.tab_restore = ({vim, count = 1}) ->
325 utils.nextTick(vim.window, ->
326 for index in [0...count] by 1
327 restoredTab = vim.window.undoCloseTab()
328 if not restoredTab and index == 0
329 vim.notify(translate('notification.tab_restore.none'))
330 break
331 return
332 )
333
334 commands.tab_restore_list = ({vim}) ->
335 {window} = vim
336 fragment = window.RecentlyClosedTabsAndWindowsMenuUtils.getTabsFragment(
337 window, 'menuitem'
338 )
339 if fragment.childElementCount == 0
340 vim.notify(translate('notification.tab_restore.none'))
341 else
342 utils.openPopup(utils.injectTemporaryPopup(window.document, fragment))
343
344 commands.tab_close_to_end = ({vim}) ->
345 {gBrowser} = vim.window
346 gBrowser.removeTabsToTheEndFrom(gBrowser.selectedTab)
347
348 commands.tab_close_other = ({vim}) ->
349 {gBrowser} = vim.window
350 gBrowser.removeAllTabsBut(gBrowser.selectedTab)
351
352
353
354 helper_follow = (name, vim, callback, count = null) ->
355 vim.markPageInteraction()
356 help.removeHelp(vim.window)
357
358 # Enter hints mode immediately, with an empty set of markers. The user might
359 # press keys before the `vim._run` callback is invoked. Those key presses
360 # should be handled in hints mode, not normal mode.
361 initialMarkers = []
362 storage = vim.enterMode('hints', initialMarkers, callback, count,
363 vim.options.hints_sleep)
364
365 vim._run(name, null, ({wrappers, viewport}) ->
366 # The user might have exited hints mode (and perhaps even entered it again)
367 # before this callback is invoked. If so, `storage.markers` has been
368 # cleared, or set to a new value. Only proceed if it is unchanged.
369 return unless storage.markers == initialMarkers
370
371 if wrappers.length > 0
372 {markers, markerMap} = hints.injectHints(vim.window, wrappers, viewport,
373 vim.options)
374 storage.markers = markers
375 storage.markerMap = markerMap
376 else
377 vim.notify(translate('notification.follow.none'))
378 vim.enterMode('normal')
379 )
380
381 helper_follow_clickable = ({inTab, inBackground}, {vim, count = 1}) ->
382 callback = (marker, timesLeft, keyStr) ->
383 {type, elementIndex} = marker.wrapper
384 isLast = (timesLeft == 1)
385 isLink = (type == 'link')
386
387 switch
388 when keyStr.startsWith(vim.options.hints_toggle_in_tab)
389 inTab = not inTab
390 when keyStr.startsWith(vim.options.hints_toggle_in_background)
391 inTab = true
392 inBackground = not inBackground
393 else
394 unless isLast
395 inTab = true
396 inBackground = true
397
398 inTab = false unless isLink
399
400 if type == 'text' or (isLink and not (inTab and inBackground))
401 isLast = true
402
403 vim._focusMarkerElement(elementIndex)
404
405 if inTab
406 utils.nextTick(vim.window, ->
407 utils.openTab(vim.window, marker.wrapper.href, {
408 inBackground
409 relatedToCurrent: true
410 })
411 )
412 else
413 vim._run('click_marker_element', {
414 elementIndex, type
415 preventTargetBlank: vim.options.prevent_target_blank
416 })
417
418 return not isLast
419
420 name = if inTab then 'follow_in_tab' else 'follow'
421 helper_follow(name, vim, callback, count)
422
423 commands.follow =
424 helper_follow_clickable.bind(null, {inTab: false, inBackground: true})
425
426 commands.follow_in_tab =
427 helper_follow_clickable.bind(null, {inTab: true, inBackground: true})
428
429 commands.follow_in_focused_tab =
430 helper_follow_clickable.bind(null, {inTab: true, inBackground: false})
431
432 commands.follow_in_window = ({vim}) ->
433 callback = (marker) ->
434 vim._focusMarkerElement(marker.wrapper.elementIndex)
435 vim.window.openLinkIn(marker.wrapper.href, 'window', {})
436 helper_follow('follow_in_tab', vim, callback)
437
438 commands.follow_multiple = (args) ->
439 args.count = Infinity
440 commands.follow(args)
441
442 commands.follow_copy = ({vim}) ->
443 callback = (marker) ->
444 {elementIndex} = marker.wrapper
445 property = switch marker.wrapper.type
446 when 'link' then 'href'
447 when 'text' then 'value'
448 when 'contenteditable' then 'textContent'
449 vim._run('copy_marker_element', {elementIndex, property})
450 helper_follow('follow_copy', vim, callback)
451
452 commands.follow_focus = ({vim}) ->
453 callback = (marker) ->
454 vim._focusMarkerElement(marker.wrapper.elementIndex, {select: true})
455 return helper_follow('follow_focus', vim, callback)
456
457 commands.click_browser_element = ({vim}) ->
458 markerElements = []
459
460 filter = (element, getElementShape) ->
461 document = element.ownerDocument
462 type = switch
463 when vim._state.scrollableElements.has(element)
464 'scrollable'
465 when (element.tabIndex > -1 and
466 # `.localName` is `.nodeName` without `xul:` (if it exists).
467 not (element.localName.endsWith('box') and
468 element.localName != 'checkbox') and
469 element.localName not in ['tabs', 'menuitem', 'menuseparator']) or
470 element.onclick
471 'clickable'
472 return unless type
473 return unless shape = getElementShape(element)
474 length = markerElements.push(element)
475 return {type, semantic: true, shape, elementIndex: length - 1}
476
477 callback = (marker) ->
478 element = markerElements[marker.wrapper.elementIndex]
479 switch marker.wrapper.type
480 when 'scrollable'
481 utils.focusElement(element, {flag: 'FLAG_BYKEY'})
482 when 'clickable'
483 utils.focusElement(element)
484 utils.simulateMouseEvents(element, 'click')
485
486 {wrappers, viewport} =
487 hints.getMarkableElementsAndViewport(vim.window, filter)
488
489 if wrappers.length > 0
490 {markers} = hints.injectHints(vim.window, wrappers, viewport, {
491 hint_chars: vim.options.hint_chars
492 ui: true
493 })
494 vim.enterMode('hints', markers, callback)
495 else
496 vim.notify(translate('notification.follow.none'))
497
498 helper_follow_pattern = (type, {vim}) ->
499 options = {
500 pattern_selector: vim.options.pattern_selector
501 pattern_attrs: vim.options.pattern_attrs
502 patterns: vim.options["#{type}_patterns"]
503 }
504 vim._run('follow_pattern', {type, options})
505
506 commands.follow_previous = helper_follow_pattern.bind(null, 'prev')
507
508 commands.follow_next = helper_follow_pattern.bind(null, 'next')
509
510 commands.focus_text_input = ({vim, count}) ->
511 vim.markPageInteraction()
512 vim._run('focus_text_input', {count})
513
514
515
516 findStorage = {lastSearchString: ''}
517
518 helper_find = ({highlight, linksOnly = false}, {vim}) ->
519 helpSearchInput = help.getSearchInput(vim.window)
520 if helpSearchInput
521 helpSearchInput.select()
522 return
523
524 helper_mark_last_scroll_position(vim)
525 findBar = vim.window.gBrowser.getFindBar()
526
527 mode = if linksOnly then findBar.FIND_LINKS else findBar.FIND_NORMAL
528 findBar.startFind(mode)
529 utils.focusElement(findBar._findField, {select: true})
530
531 return if linksOnly
532 return unless highlightButton = findBar.getElement('highlight')
533 if highlightButton.checked != highlight
534 highlightButton.click()
535
536 commands.find = helper_find.bind(null, {highlight: false})
537
538 commands.find_highlight_all = helper_find.bind(null, {highlight: true})
539
540 commands.find_links_only = helper_find.bind(null, {linksOnly: true})
541
542 helper_find_again = (direction, {vim}) ->
543 findBar = vim.window.gBrowser.getFindBar()
544 if findStorage.lastSearchString.length == 0
545 vim.notify(translate('notification.find_again.none'))
546 return
547 helper_mark_last_scroll_position(vim)
548 findBar._findField.value = findStorage.lastSearchString
549 findBar.onFindAgainCommand(direction)
550 message = findBar._findStatusDesc.textContent
551 vim.notify(message) if message
552
553 commands.find_next = helper_find_again.bind(null, false)
554
555 commands.find_previous = helper_find_again.bind(null, true)
556
557
558
559 commands.window_new = ({vim}) ->
560 vim.window.OpenBrowserWindow()
561
562 commands.window_new_private = ({vim}) ->
563 vim.window.OpenBrowserWindow({private: true})
564
565 commands.enter_mode_ignore = ({vim}) ->
566 vim.enterMode('ignore')
567
568 # Quote next keypress (pass it through to the page).
569 commands.quote = ({vim, count = 1}) ->
570 vim.enterMode('ignore', count)
571
572 commands.enter_reader_view = ({vim}) ->
573 button = vim.window.document.getElementById('reader-mode-button')
574 if not button?.hidden
575 button.click()
576 else
577 vim.notify(translate('notification.enter_reader_view.none'))
578
579 commands.help = ({vim}) ->
580 help.injectHelp(vim.window, vim._parent)
581
582 commands.dev = ({vim}) ->
583 vim.window.DeveloperToolbar.show(true) # `true` to focus.
584
585 commands.esc = ({vim}) ->
586 vim._run('esc')
587 utils.blurActiveBrowserElement(vim)
588 vim.window.DeveloperToolbar.hide()
589 vim.window.gBrowser.getFindBar().close()
590 # TODO: Remove when Tab Groups have been removed.
591 vim.window.TabView?.hide()
592 hints.removeHints(vim.window) # Better safe than sorry.
593
594 unless help.getSearchInput(vim.window)?.getAttribute('focused')
595 help.removeHelp(vim.window)
596
597
598
599 module.exports = {
600 commands
601 findStorage
602 }
Imprint / Impressum