]> git.gir.st - VimFx.git/blob - extension/packages/commands.coffee
Change license to GPLv3
[VimFx.git] / extension / packages / commands.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014.
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 utils = require 'utils'
23 help = require 'help'
24 { _ } = require 'l10n'
25 { getPref
26 , getComplexPref
27 , setPref
28 , isPrefSet } = require 'prefs'
29
30 { classes: Cc, interfaces: Ci, utils: Cu } = Components
31
32 # “Selecting an element” means “focusing and selecting the text, if any, of an
33 # element”.
34
35 # Select the Address Bar.
36 command_focus = (vim) ->
37 # This function works even if the Address Bar has been removed.
38 vim.rootWindow.focusAndSelectUrlBar()
39
40 # Select the Search Bar.
41 command_focus_search = (vim) ->
42 # The `.webSearch()` method opens a search engine in a tab if the Search Bar
43 # has been removed. Therefore we first check if it exists.
44 if vim.rootWindow.BrowserSearch.searchBar
45 vim.rootWindow.BrowserSearch.webSearch()
46
47 helper_paste = (vim) ->
48 url = utils.readFromClipboard(vim.window)
49 postData = null
50 if not utils.isURL(url) and submission = utils.browserSearchSubmission(url)
51 url = submission.uri.spec
52 { postData } = submission
53 return {url, postData}
54
55 # Go to or search for the contents of the system clipboard.
56 command_paste = (vim) ->
57 { url, postData } = helper_paste(vim)
58 vim.rootWindow.gBrowser.loadURIWithFlags(url, null, null, null, postData)
59
60 # Go to or search for the contents of the system clipboard in a new tab.
61 command_paste_tab = (vim) ->
62 { url, postData } = helper_paste(vim)
63 vim.rootWindow.gBrowser.selectedTab =
64 vim.rootWindow.gBrowser.addTab(url, null, null, postData, null, false)
65
66 # Copy the URL or text of a marker element to the system clipboard.
67 command_marker_yank = (vim) ->
68 callback = (marker) ->
69 if url = marker.element.href
70 marker.element.focus()
71 utils.writeToClipboard(url)
72 else if utils.isTextInputElement(marker.element)
73 utils.writeToClipboard(marker.element.value)
74
75 vim.enterMode('hints', callback)
76
77 # Focus element.
78 command_marker_focus = (vim) ->
79 callback = (marker) -> marker.element.focus()
80
81 vim.enterMode('hints', callback)
82
83 # Copy the current URL to the system clipboard.
84 command_yank = (vim) ->
85 utils.writeToClipboard(vim.window.location.href)
86
87 # Reload the current tab, possibly from cache.
88 command_reload = (vim) ->
89 vim.rootWindow.BrowserReload()
90
91 # Reload the current tab, skipping cache.
92 command_reload_force = (vim) ->
93 vim.rootWindow.BrowserReloadSkipCache()
94
95 # Reload all tabs, possibly from cache.
96 command_reload_all = (vim) ->
97 vim.rootWindow.gBrowser.reloadAllTabs()
98
99 # Reload all tabs, skipping cache.
100 command_reload_all_force = (vim) ->
101 for tab in vim.rootWindow.gBrowser.visibleTabs
102 window = tab.linkedBrowser.contentWindow
103 window.location.reload(true)
104
105 # Stop loading the current tab.
106 command_stop = (vim) ->
107 vim.window.stop()
108
109 # Stop loading all tabs.
110 command_stop_all = (vim) ->
111 for tab in vim.rootWindow.gBrowser.visibleTabs
112 window = tab.linkedBrowser.contentWindow
113 window.stop()
114
115 # Scroll to the top of the page.
116 command_scroll_to_top = (vim) ->
117 vim.rootWindow.goDoCommand('cmd_scrollTop')
118
119 # Scroll to the bottom of the page.
120 command_scroll_to_bottom = (vim) ->
121 vim.rootWindow.goDoCommand('cmd_scrollBottom')
122
123 # Scroll down a bit.
124 command_scroll_down = (vim, event, count) ->
125 step = getPref('scroll_step_lines') * count
126 utils.simulateWheel(vim.window, 0, +step, utils.WHEEL_MODE_LINE)
127
128 # Scroll up a bit.
129 command_scroll_up = (vim, event, count) ->
130 step = getPref('scroll_step_lines') * count
131 utils.simulateWheel(vim.window, 0, -step, utils.WHEEL_MODE_LINE)
132
133 # Scroll left a bit.
134 command_scroll_left = (vim, event, count) ->
135 step = getPref('scroll_step_lines') * count
136 utils.simulateWheel(vim.window, -step, 0, utils.WHEEL_MODE_LINE)
137
138 # Scroll right a bit.
139 command_scroll_right = (vim, event, count) ->
140 step = getPref('scroll_step_lines') * count
141 utils.simulateWheel(vim.window, +step, 0, utils.WHEEL_MODE_LINE)
142
143 # Scroll down half a page.
144 command_scroll_half_page_down = (vim, event, count) ->
145 utils.simulateWheel(vim.window, 0, +0.5 * count, utils.WHEEL_MODE_PAGE)
146
147 # Scroll up half a page.
148 command_scroll_half_page_up = (vim, event, count) ->
149 utils.simulateWheel(vim.window, 0, -0.5 * count, utils.WHEEL_MODE_PAGE)
150
151 # Scroll down full a page.
152 command_scroll_page_down = (vim, event, count) ->
153 utils.simulateWheel(vim.window, 0, +1 * count, utils.WHEEL_MODE_PAGE)
154
155 # Scroll up full a page.
156 command_scroll_page_up = (vim, event, count) ->
157 utils.simulateWheel(vim.window, 0, -1 * count, utils.WHEEL_MODE_PAGE)
158
159 # Open a new tab and select the Address Bar.
160 command_open_tab = (vim) ->
161 vim.rootWindow.BrowserOpenTab()
162
163 absoluteTabIndex = (relativeIndex, gBrowser) ->
164 tabs = gBrowser.visibleTabs
165 { selectedTab } = gBrowser
166
167 currentIndex = tabs.indexOf(selectedTab)
168 absoluteIndex = currentIndex + relativeIndex
169 numTabs = tabs.length
170
171 wrap = (Math.abs(relativeIndex) == 1)
172 if wrap
173 absoluteIndex %%= numTabs
174 else
175 absoluteIndex = Math.max(0, absoluteIndex)
176 absoluteIndex = Math.min(absoluteIndex, numTabs - 1)
177
178 return absoluteIndex
179
180 helper_switch_tab = (direction, vim, event, count) ->
181 { gBrowser } = vim.rootWindow
182 gBrowser.selectTabAtIndex(absoluteTabIndex(direction * count, gBrowser))
183
184 # Switch to the previous tab.
185 command_tab_prev = helper_switch_tab.bind(undefined, -1)
186
187 # Switch to the next tab.
188 command_tab_next = helper_switch_tab.bind(undefined, +1)
189
190 helper_move_tab = (direction, vim, event, count) ->
191 { gBrowser } = vim.rootWindow
192 { selectedTab } = gBrowser
193 { pinned } = selectedTab
194
195 index = absoluteTabIndex(direction * count, gBrowser)
196
197 if index < gBrowser._numPinnedTabs
198 gBrowser.pinTab(selectedTab) unless pinned
199 else
200 gBrowser.unpinTab(selectedTab) if pinned
201
202 gBrowser.moveTabTo(selectedTab, index)
203
204 # Move the current tab backward.
205 command_tab_move_left = helper_move_tab.bind(undefined, -1)
206
207 # Move the current tab forward.
208 command_tab_move_right = helper_move_tab.bind(undefined, +1)
209
210 # Load the home page.
211 command_home = (vim) ->
212 vim.rootWindow.BrowserHome()
213
214 # Switch to the first tab.
215 command_tab_first = (vim) ->
216 vim.rootWindow.gBrowser.selectTabAtIndex(0)
217
218 # Switch to the first non-pinned tab.
219 command_tab_first_non_pinned = (vim) ->
220 firstNonPinned = vim.rootWindow.gBrowser._numPinnedTabs
221 vim.rootWindow.gBrowser.selectTabAtIndex(firstNonPinned)
222
223 # Switch to the last tab.
224 command_tab_last = (vim) ->
225 vim.rootWindow.gBrowser.selectTabAtIndex(-1)
226
227 # Close current tab.
228 command_close_tab = (vim, event, count) ->
229 { gBrowser } = vim.rootWindow
230 return if gBrowser.selectedTab.pinned
231 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
232 for tab in gBrowser.visibleTabs[currentIndex...(currentIndex + count)]
233 gBrowser.removeTab(tab)
234
235 # Restore last closed tab.
236 command_restore_tab = (vim, event, count) ->
237 vim.rootWindow.undoCloseTab() for [1..count]
238
239 helper_follow = ({ inTab, multiple }, vim, event, count) ->
240 callback = (matchedMarker, markers) ->
241 if matchedMarker.element.target == '_blank'
242 targetReset = matchedMarker.element.target
243 matchedMarker.element.target = ''
244
245 matchedMarker.element.focus()
246
247 _inTab = if count > 1 then true else inTab
248 utils.simulateClick(matchedMarker.element, {metaKey: _inTab, ctrlKey: _inTab})
249
250 matchedMarker.element.target = targetReset if targetReset
251
252 count -= 1
253 isEditable = utils.isElementEditable(matchedMarker.element)
254 if (multiple or count > 0) and not isEditable
255 # By not resetting immediately one is able to see the last char being
256 # matched, which gives some nice visual feedback that you've typed the
257 # right char.
258 vim.window.setTimeout((-> marker.reset() for marker in markers), 100)
259 return true
260
261 vim.enterMode('hints', callback)
262
263 # Follow links with hint markers.
264 command_follow = helper_follow.bind(undefined, {inTab: false})
265
266 # Follow links in a new Tab with hint markers.
267 command_follow_in_tab = helper_follow.bind(undefined, {inTab: true})
268
269 # Follow multiple links with hint markers.
270 command_follow_multiple = helper_follow.bind(undefined, {inTab: true, multiple: true})
271
272 helper_follow_pattern = do ->
273 # Search for the prev/next patterns in the following attributes of the
274 # element. `rel` should be kept as the first attribute, since the standard
275 # way of marking up prev/next links (`rel="prev"` and `rel="next"`) should be
276 # favored. Even though some of these attributes only allow a fixed set of
277 # keywords, we pattern-match them anyways since lots of sites don’t follow
278 # the spec and use the attributes arbitrarily.
279 attrs = ['rel', 'role', 'data-tooltip', 'aria-label']
280
281 return (type, vim) ->
282 links = utils.getMarkableElements(vim.window.document, {type: 'action'})
283 .filter(utils.isElementVisible)
284
285 patterns = utils.splitListString(getComplexPref("#{ type }_patterns"))
286
287 if matchingLink = utils.getBestPatternMatch(patterns, attrs, links)
288 utils.simulateClick(matchingLink, {metaKey: false, ctrlKey: false})
289
290 # Follow previous page.
291 command_follow_prev = helper_follow_pattern.bind(undefined, 'prev')
292
293 # Follow next page.
294 command_follow_next = helper_follow_pattern.bind(undefined, 'next')
295
296 # Go up one level in the URL hierarchy.
297 command_go_up_path = (vim, event, count) ->
298 { pathname } = vim.window.location
299 vim.window.location.pathname = pathname.replace(
300 /// (?: /[^/]+ ){1,#{ count }} /?$ ///, ''
301 )
302
303 # Go up to root of the URL hierarchy.
304 command_go_to_root = (vim) ->
305 vim.window.location.href = vim.window.location.origin
306
307 helper_go_history = (num, vim, event, count) ->
308 { index } = vim.rootWindow.getWebNavigation().sessionHistory
309 { history } = vim.window
310 num *= count
311 num = Math.max(num, -index)
312 num = Math.min(num, history.length - 1 - index)
313 return if num == 0
314 history.go(num)
315
316 # Go back in history.
317 command_back = helper_go_history.bind(undefined, -1)
318
319 # Go forward in history.
320 command_forward = helper_go_history.bind(undefined, +1)
321
322 findStorage = {lastSearchString: ''}
323
324 helper_find = (highlight, vim) ->
325 findBar = vim.rootWindow.gBrowser.getFindBar()
326
327 findBar.onFindCommand()
328 findBar._findField.focus()
329 findBar._findField.select()
330
331 return unless highlightButton = findBar.getElement('highlight')
332 if highlightButton.checked != highlight
333 highlightButton.click()
334
335 # Open the find bar, making sure that hightlighting is off.
336 command_find = helper_find.bind(undefined, false)
337
338 # Open the find bar, making sure that hightlighting is on.
339 command_find_hl = helper_find.bind(undefined, true)
340
341 helper_find_again = (direction, vim) ->
342 findBar = vim.rootWindow.gBrowser.getFindBar()
343 if findStorage.lastSearchString.length > 0
344 findBar._findField.value = findStorage.lastSearchString
345 findBar.onFindAgainCommand(direction)
346
347 # Search for the last pattern.
348 command_find_next = helper_find_again.bind(undefined, false)
349
350 # Search for the last pattern backwards.
351 command_find_prev = helper_find_again.bind(undefined, true)
352
353 # Enter insert mode.
354 command_insert_mode = (vim) ->
355 vim.enterMode('insert')
356
357 # Display the Help Dialog.
358 command_help = (vim) ->
359 help.injectHelp(vim.window.document, commands)
360
361 # Open and select the Developer Toolbar.
362 command_dev = (vim) ->
363 vim.rootWindow.DeveloperToolbar.show(true) # focus
364
365 command_Esc = (vim, event) ->
366 utils.blurActiveElement(vim.window)
367
368 # Blur active XUL control.
369 callback = -> event.originalTarget?.ownerDocument?.activeElement?.blur()
370 vim.window.setTimeout(callback, 0)
371
372 help.removeHelp(vim.window.document)
373
374 vim.rootWindow.DeveloperToolbar.hide()
375
376 vim.rootWindow.gBrowser.getFindBar().close()
377
378 vim.rootWindow.TabView.hide()
379
380
381 class Command
382 constructor: (@group, @name, @func, keys) ->
383 @defaultKeys = keys
384 if isPrefSet(@prefName('keys'))
385 try @keyValues = JSON.parse(getPref(@prefName('keys')))
386 else
387 @keyValues = keys
388
389 # Name of the preference for a given property.
390 prefName: (value) -> "commands.#{ @name }.#{ value }"
391
392 keys: (value) ->
393 if value is undefined
394 return @keyValues
395 else
396 @keyValues = value or @defaultKeyValues
397 setPref(@prefName('keys'), value and JSON.stringify(value))
398
399 help: -> _("help_command_#{ @name }")
400
401 commands = [
402 new Command('urls', 'focus', command_focus, ['o'])
403 new Command('urls', 'focus_search', command_focus_search, ['O'])
404 new Command('urls', 'paste', command_paste, ['p'])
405 new Command('urls', 'paste_tab', command_paste_tab, ['P'])
406 new Command('urls', 'marker_yank', command_marker_yank, ['y,f'])
407 new Command('urls', 'marker_focus', command_marker_focus, ['v,f'])
408 new Command('urls', 'yank', command_yank, ['y,y'])
409 new Command('urls', 'reload', command_reload, ['r'])
410 new Command('urls', 'reload_force', command_reload_force, ['R'])
411 new Command('urls', 'reload_all', command_reload_all, ['a,r'])
412 new Command('urls', 'reload_all_force', command_reload_all_force, ['a,R'])
413 new Command('urls', 'stop', command_stop, ['s'])
414 new Command('urls', 'stop_all', command_stop_all, ['a,s'])
415
416 new Command('nav', 'scroll_to_top', command_scroll_to_top , ['g,g'])
417 new Command('nav', 'scroll_to_bottom', command_scroll_to_bottom, ['G'])
418 new Command('nav', 'scroll_down', command_scroll_down, ['j'])
419 new Command('nav', 'scroll_up', command_scroll_up, ['k'])
420 new Command('nav', 'scroll_left', command_scroll_left, ['h'])
421 new Command('nav', 'scroll_right', command_scroll_right , ['l'])
422 new Command('nav', 'scroll_half_page_down', command_scroll_half_page_down, ['d'])
423 new Command('nav', 'scroll_half_page_up', command_scroll_half_page_up, ['u'])
424 new Command('nav', 'scroll_page_down', command_scroll_page_down, ['Space'])
425 new Command('nav', 'scroll_page_up', command_scroll_page_up, ['Shift-Space'])
426
427 new Command('tabs', 'open_tab', command_open_tab, ['t'])
428 new Command('tabs', 'tab_prev', command_tab_prev, ['J', 'g,T'])
429 new Command('tabs', 'tab_next', command_tab_next, ['K', 'g,t'])
430 new Command('tabs', 'tab_move_left', command_tab_move_left, ['g,J'])
431 new Command('tabs', 'tab_move_right', command_tab_move_right, ['g,K'])
432 new Command('tabs', 'home', command_home, ['g,h'])
433 new Command('tabs', 'tab_first', command_tab_first, ['g,H', 'g,0'])
434 new Command('tabs', 'tab_first_non_pinned', command_tab_first_non_pinned, ['g,^'])
435 new Command('tabs', 'tab_last', command_tab_last, ['g,L', 'g,$'])
436 new Command('tabs', 'close_tab', command_close_tab, ['x'])
437 new Command('tabs', 'restore_tab', command_restore_tab, ['X'])
438
439 new Command('browse', 'follow', command_follow, ['f'])
440 new Command('browse', 'follow_in_tab', command_follow_in_tab, ['F'])
441 new Command('browse', 'follow_multiple', command_follow_multiple, ['a,f'])
442 new Command('browse', 'follow_previous', command_follow_prev, ['['])
443 new Command('browse', 'follow_next', command_follow_next, [']'])
444 new Command('browse', 'go_up_path', command_go_up_path, ['g,u'])
445 new Command('browse', 'go_to_root', command_go_to_root, ['g,U'])
446 new Command('browse', 'back', command_back, ['H'])
447 new Command('browse', 'forward', command_forward, ['L'])
448
449 new Command('misc', 'find', command_find, ['/'])
450 new Command('misc', 'find_hl', command_find_hl, ['a,/'])
451 new Command('misc', 'find_next', command_find_next, ['n'])
452 new Command('misc', 'find_prev', command_find_prev, ['N'])
453 new Command('misc', 'insert_mode', command_insert_mode, ['i'])
454 new Command('misc', 'help', command_help, ['?'])
455 new Command('misc', 'dev', command_dev, [':'])
456
457 escapeCommand =
458 new Command('misc', 'Esc', command_Esc, ['Esc'])
459 ]
460
461 searchForMatchingCommand = (keys) ->
462 for index in [0...keys.length] by 1
463 str = keys[index..].join(',')
464 for command in commands
465 for key in command.keys()
466 # The following hack is a workaround for the issue where letter `c` is
467 # considered a start of command with control modifier `c-xxx`.
468 if "#{ key },".startsWith("#{ str },")
469 numbers = keys[0..index].join('').match(/[1-9]\d*/g)
470
471 # When letter `0` follows after a number, it is considered as number `0`
472 # instead of a valid command.
473 continue if key == '0' and numbers
474
475 count = parseInt(numbers[numbers.length - 1], 10) if numbers
476 count = if count > 1 then count else 1
477
478 return {match: true, exact: (key == str), command, count}
479
480 return {match: false}
481
482 isEscCommandKey = (keyStr) -> keyStr in escapeCommand.keys()
483
484 exports.commands = commands
485 exports.searchForMatchingCommand = searchForMatchingCommand
486 exports.isEscCommandKey = isEscCommandKey
487 exports.findStorage = findStorage
Imprint / Impressum