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