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