1 utils = require 'utils'
7 , isPrefSet } = require 'prefs'
9 { classes: Cc, interfaces: Ci, utils: Cu } = Components
11 # “Selecting an element” means “focusing and selecting the text, if any, of an
14 # Select the Address Bar.
15 command_focus = (vim) ->
16 # This function works even if the Address Bar has been removed.
17 vim.rootWindow.focusAndSelectUrlBar()
19 # Select the Search Bar.
20 command_focus_search = (vim) ->
21 # The `.webSearch()` method opens a search engine in a tab if the Search Bar
22 # has been removed. Therefore we first check if it exists.
23 if vim.rootWindow.BrowserSearch.searchBar
24 vim.rootWindow.BrowserSearch.webSearch()
26 helper_paste = (vim) ->
27 url = utils.readFromClipboard(vim.window)
29 if not utils.isURL(url) and submission = utils.browserSearchSubmission(url)
30 url = submission.uri.spec
31 { postData } = submission
32 return {url, postData}
34 # Go to or search for the contents of the system clipboard.
35 command_paste = (vim) ->
36 { url, postData } = helper_paste(vim)
37 vim.rootWindow.gBrowser.loadURIWithFlags(url, null, null, null, postData)
39 # Go to or search for the contents of the system clipboard in a new tab.
40 command_paste_tab = (vim) ->
41 { url, postData } = helper_paste(vim)
42 vim.rootWindow.gBrowser.selectedTab =
43 vim.rootWindow.gBrowser.addTab(url, null, null, postData, null, false)
45 # Copy the URL or text of a marker element to the system clipboard.
46 command_marker_yank = (vim) ->
47 callback = (marker) ->
48 if url = marker.element.href
49 marker.element.focus()
50 utils.writeToClipboard(url)
51 else if utils.isTextInputElement(marker.element)
52 utils.writeToClipboard(marker.element.value)
54 vim.enterMode('hints', callback)
57 command_marker_focus = (vim) ->
58 callback = (marker) -> marker.element.focus()
60 vim.enterMode('hints', callback)
62 # Copy the current URL to the system clipboard.
63 command_yank = (vim) ->
64 utils.writeToClipboard(vim.window.location.href)
66 # Reload the current tab, possibly from cache.
67 command_reload = (vim) ->
68 vim.rootWindow.BrowserReload()
70 # Reload the current tab, skipping cache.
71 command_reload_force = (vim) ->
72 vim.rootWindow.BrowserReloadSkipCache()
74 # Reload all tabs, possibly from cache.
75 command_reload_all = (vim) ->
76 vim.rootWindow.gBrowser.reloadAllTabs()
78 # Reload all tabs, skipping cache.
79 command_reload_all_force = (vim) ->
80 for tab in vim.rootWindow.gBrowser.visibleTabs
81 window = tab.linkedBrowser.contentWindow
82 window.location.reload(true)
84 # Stop loading the current tab.
85 command_stop = (vim) ->
88 # Stop loading all tabs.
89 command_stop_all = (vim) ->
90 for tab in vim.rootWindow.gBrowser.visibleTabs
91 window = tab.linkedBrowser.contentWindow
94 # Scroll to the top of the page.
95 command_scroll_to_top = (vim) ->
96 vim.rootWindow.goDoCommand('cmd_scrollTop')
98 # Scroll to the bottom of the page.
99 command_scroll_to_bottom = (vim) ->
100 vim.rootWindow.goDoCommand('cmd_scrollBottom')
103 command_scroll_down = (vim, event, count) ->
104 step = getPref('scroll_step_lines') * count
105 utils.simulateWheel(vim.window, 0, +step, utils.WHEEL_MODE_LINE)
108 command_scroll_up = (vim, event, count) ->
109 step = getPref('scroll_step_lines') * count
110 utils.simulateWheel(vim.window, 0, -step, utils.WHEEL_MODE_LINE)
113 command_scroll_left = (vim, event, count) ->
114 step = getPref('scroll_step_lines') * count
115 utils.simulateWheel(vim.window, -step, 0, utils.WHEEL_MODE_LINE)
117 # Scroll right a bit.
118 command_scroll_right = (vim, event, count) ->
119 step = getPref('scroll_step_lines') * count
120 utils.simulateWheel(vim.window, +step, 0, utils.WHEEL_MODE_LINE)
122 # Scroll down half a page.
123 command_scroll_half_page_down = (vim, event, count) ->
124 utils.simulateWheel(vim.window, 0, +0.5 * count, utils.WHEEL_MODE_PAGE)
126 # Scroll up half a page.
127 command_scroll_half_page_up = (vim, event, count) ->
128 utils.simulateWheel(vim.window, 0, -0.5 * count, utils.WHEEL_MODE_PAGE)
130 # Scroll down full a page.
131 command_scroll_page_down = (vim, event, count) ->
132 utils.simulateWheel(vim.window, 0, +1 * count, utils.WHEEL_MODE_PAGE)
134 # Scroll up full a page.
135 command_scroll_page_up = (vim, event, count) ->
136 utils.simulateWheel(vim.window, 0, -1 * count, utils.WHEEL_MODE_PAGE)
138 # Open a new tab and select the Address Bar.
139 command_open_tab = (vim) ->
140 vim.rootWindow.BrowserOpenTab()
142 helper_switch_tab = (direction, vim, event, count) ->
143 gBrowser = vim.rootWindow.gBrowser
146 gBrowser.tabContainer.advanceSelectedTab(direction, wrap = true)
148 currentIndex = gBrowser.visibleTabs.indexOf(gBrowser.selectedTab)
150 targetIndex = currentIndex + count * direction
151 targetIndex = Math.max(0, targetIndex)
152 targetIndex = Math.min(targetIndex, gBrowser.visibleTabs.length - 1)
154 gBrowser.selectTabAtIndex(targetIndex)
156 # Switch to the previous tab.
157 command_tab_prev = helper_switch_tab.bind(undefined, -1)
159 # Switch to the next tab.
160 command_tab_next = helper_switch_tab.bind(undefined, +1)
162 # Move the current tab backward.
163 command_tab_move_left = (vim) ->
164 { gBrowser } = vim.rootWindow
165 lastIndex = gBrowser.tabContainer.selectedIndex
166 gBrowser.moveTabBackward()
167 if gBrowser.tabContainer.selectedIndex == lastIndex
168 gBrowser.moveTabToEnd()
170 # Move the current tab forward.
171 command_tab_move_right = (vim) ->
172 { gBrowser } = vim.rootWindow
173 lastIndex = gBrowser.tabContainer.selectedIndex
174 gBrowser.moveTabForward()
175 if gBrowser.tabContainer.selectedIndex == lastIndex
176 gBrowser.moveTabToStart()
178 # Load the home page.
179 command_home = (vim) ->
180 vim.rootWindow.BrowserHome()
182 # Switch to the first tab.
183 command_tab_first = (vim) ->
184 vim.rootWindow.gBrowser.selectTabAtIndex(0)
186 # Switch to the last tab.
187 command_tab_last = (vim) ->
188 vim.rootWindow.gBrowser.selectTabAtIndex(-1)
191 command_close_tab = (vim) ->
192 unless vim.rootWindow.gBrowser.selectedTab.pinned
193 vim.rootWindow.gBrowser.removeCurrentTab()
195 # Restore last closed tab.
196 command_restore_tab = (vim) ->
197 vim.rootWindow.undoCloseTab()
199 helper_follow = ({ inTab, multiple }, vim) ->
200 callback = (matchedMarker, markers) ->
201 if matchedMarker.element.target == '_blank'
202 targetReset = matchedMarker.element.target
203 matchedMarker.element.target = ''
205 matchedMarker.element.focus()
206 utils.simulateClick(matchedMarker.element, {metaKey: inTab, ctrlKey: inTab})
208 matchedMarker.element.target = targetReset if targetReset
210 isEditable = utils.isElementEditable(matchedMarker.element)
211 if multiple and not isEditable
212 # By not resetting immediately one is able to see the last char being
213 # matched, which gives some nice visual feedback that you've typed the
215 vim.window.setTimeout((-> marker.reset() for marker in markers), 100)
218 vim.enterMode('hints', callback)
220 # Follow links with hint markers.
221 command_follow = helper_follow.bind(undefined, {inTab: false})
223 # Follow links in a new Tab with hint markers.
224 command_follow_in_tab = helper_follow.bind(undefined, {inTab: true})
226 # Follow multiple links with hint markers.
227 command_follow_multiple = helper_follow.bind(undefined, {inTab: true, multiple: true})
229 helper_follow_pattern = do ->
230 # Search for the prev/next patterns in the following attributes of the
231 # element. `rel` should be kept as the first attribute, since the standard
232 # way of marking up prev/next links (`rel="prev"` and `rel="next"`) should be
233 # favored. Even though some of these attributes only allow a fixed set of
234 # keywords, we pattern-match them anyways since lots of sites don’t follow
235 # the spec and use the attributes arbitrarily.
236 attrs = ['rel', 'role', 'data-tooltip', 'aria-label']
238 return (type, vim) ->
239 links = utils.getMarkableElements(vim.window.document, {type: 'action'})
240 .filter(utils.isElementVisible)
242 patterns = utils.splitListString(getComplexPref("#{ type }_patterns"))
244 if matchingLink = utils.getBestPatternMatch(patterns, attrs, links)
245 utils.simulateClick(matchingLink, {metaKey: false, ctrlKey: false})
247 # Follow previous page.
248 command_follow_prev = helper_follow_pattern.bind(undefined, 'prev')
251 command_follow_next = helper_follow_pattern.bind(undefined, 'next')
253 # Go up one level in the URL hierarchy.
254 command_go_up_path = (vim) ->
255 path = vim.window.location.pathname
256 vim.window.location.pathname = path.replace(/// / [^/]+ /?$ ///, '')
258 # Go up to root of the URL hierarchy.
259 command_go_to_root = (vim) ->
260 vim.window.location.href = vim.window.location.origin
262 # Go back in history.
263 command_back = (vim) ->
264 vim.rootWindow.BrowserBack()
266 # Go forward in history.
267 command_forward = (vim) ->
268 vim.rootWindow.BrowserForward()
270 findStorage = {lastSearchString: ''}
272 helper_find = (highlight, vim) ->
273 findBar = vim.rootWindow.gBrowser.getFindBar()
275 findBar.onFindCommand()
276 findBar._findField.focus()
277 findBar._findField.select()
279 return unless highlightButton = findBar.getElement('highlight')
280 if highlightButton.checked != highlight
281 highlightButton.click()
283 # Open the find bar, making sure that hightlighting is off.
284 command_find = helper_find.bind(undefined, false)
286 # Open the find bar, making sure that hightlighting is on.
287 command_find_hl = helper_find.bind(undefined, true)
289 helper_find_again = (direction, vim) ->
290 findBar = vim.rootWindow.gBrowser.getFindBar()
291 if findStorage.lastSearchString.length > 0
292 findBar._findField.value = findStorage.lastSearchString
293 findBar.onFindAgainCommand(direction)
295 # Search for the last pattern.
296 command_find_next = helper_find_again.bind(undefined, false)
298 # Search for the last pattern backwards.
299 command_find_prev = helper_find_again.bind(undefined, true)
302 command_insert_mode = (vim) ->
303 vim.enterMode('insert')
305 # Display the Help Dialog.
306 command_help = (vim) ->
307 help.injectHelp(vim.window.document, commands)
309 # Open and select the Developer Toolbar.
310 command_dev = (vim) ->
311 vim.rootWindow.DeveloperToolbar.show(true) # focus
313 command_Esc = (vim, event) ->
314 utils.blurActiveElement(vim.window)
316 # Blur active XUL control.
317 callback = -> event.originalTarget?.ownerDocument?.activeElement?.blur()
318 vim.window.setTimeout(callback, 0)
320 help.removeHelp(vim.window.document)
322 vim.rootWindow.DeveloperToolbar.hide()
324 vim.rootWindow.gBrowser.getFindBar().close()
326 vim.rootWindow.TabView.hide()
330 constructor: (@group, @name, @func, keys) ->
332 if isPrefSet(@prefName('keys'))
333 try @keyValues = JSON.parse(getPref(@prefName('keys')))
337 # Name of the preference for a given property.
338 prefName: (value) -> "commands.#{ @name }.#{ value }"
341 if value is undefined
344 @keyValues = value or @defaultKeyValues
345 setPref(@prefName('keys'), value and JSON.stringify(value))
347 help: -> _("help_command_#{ @name }")
350 new Command('urls', 'focus', command_focus, ['o'])
351 new Command('urls', 'focus_search', command_focus_search, ['O'])
352 new Command('urls', 'paste', command_paste, ['p'])
353 new Command('urls', 'paste_tab', command_paste_tab, ['P'])
354 new Command('urls', 'marker_yank', command_marker_yank, ['y,f'])
355 new Command('urls', 'marker_focus', command_marker_focus, ['v,f'])
356 new Command('urls', 'yank', command_yank, ['y,y'])
357 new Command('urls', 'reload', command_reload, ['r'])
358 new Command('urls', 'reload_force', command_reload_force, ['R'])
359 new Command('urls', 'reload_all', command_reload_all, ['a,r'])
360 new Command('urls', 'reload_all_force', command_reload_all_force, ['a,R'])
361 new Command('urls', 'stop', command_stop, ['s'])
362 new Command('urls', 'stop_all', command_stop_all, ['a,s'])
364 new Command('nav', 'scroll_to_top', command_scroll_to_top , ['g,g'])
365 new Command('nav', 'scroll_to_bottom', command_scroll_to_bottom, ['G'])
366 new Command('nav', 'scroll_down', command_scroll_down, ['j', 'c-e'])
367 new Command('nav', 'scroll_up', command_scroll_up, ['k', 'c-y'])
368 new Command('nav', 'scroll_left', command_scroll_left, ['h'])
369 new Command('nav', 'scroll_right', command_scroll_right , ['l'])
370 new Command('nav', 'scroll_half_page_down', command_scroll_half_page_down, ['d'])
371 new Command('nav', 'scroll_half_page_up', command_scroll_half_page_up, ['u'])
372 new Command('nav', 'scroll_page_down', command_scroll_page_down, ['c-f'])
373 new Command('nav', 'scroll_page_up', command_scroll_page_up, ['c-b'])
375 new Command('tabs', 'open_tab', command_open_tab, ['t'])
376 new Command('tabs', 'tab_prev', command_tab_prev, ['J', 'g,T'])
377 new Command('tabs', 'tab_next', command_tab_next, ['K', 'g,t'])
378 new Command('tabs', 'tab_move_left', command_tab_move_left, ['c-J'])
379 new Command('tabs', 'tab_move_right', command_tab_move_right, ['c-K'])
380 new Command('tabs', 'home', command_home, ['g,h'])
381 new Command('tabs', 'tab_first', command_tab_first, ['g,H', 'g,^'])
382 new Command('tabs', 'tab_last', command_tab_last, ['g,L', 'g,$'])
383 new Command('tabs', 'close_tab', command_close_tab, ['x'])
384 new Command('tabs', 'restore_tab', command_restore_tab, ['X'])
386 new Command('browse', 'follow', command_follow, ['f'])
387 new Command('browse', 'follow_in_tab', command_follow_in_tab, ['F'])
388 new Command('browse', 'follow_multiple', command_follow_multiple, ['a,f'])
389 new Command('browse', 'follow_previous', command_follow_prev, ['['])
390 new Command('browse', 'follow_next', command_follow_next, [']'])
391 new Command('browse', 'go_up_path', command_go_up_path, ['g,u'])
392 new Command('browse', 'go_to_root', command_go_to_root, ['g,U'])
393 new Command('browse', 'back', command_back, ['H'])
394 new Command('browse', 'forward', command_forward, ['L'])
396 new Command('misc', 'find', command_find, ['/'])
397 new Command('misc', 'find_hl', command_find_hl, ['a,/'])
398 new Command('misc', 'find_next', command_find_next, ['n'])
399 new Command('misc', 'find_prev', command_find_prev, ['N'])
400 new Command('misc', 'insert_mode', command_insert_mode, ['i'])
401 new Command('misc', 'help', command_help, ['?'])
402 new Command('misc', 'dev', command_dev, [':'])
405 new Command('misc', 'Esc', command_Esc, ['Esc'])
408 searchForMatchingCommand = (keys) ->
409 for index in [0...keys.length] by 1
410 str = keys[index..].join(',')
411 for command in commands
412 for key in command.keys()
413 # The following hack is a workaround for the issue where letter `c` is
414 # considered a start of command with control modifier `c-xxx`.
415 if "#{ key },".startsWith("#{ str },")
416 numbers = keys[0..index].join('').match(/[1-9]\d*/g)
418 # When letter `0` follows after a number, it is considered as number `0`
419 # instead of a valid command.
420 continue if key == '0' and numbers
422 count = parseInt(numbers[numbers.length - 1], 10) if numbers
423 count = if count > 1 then count else 1
425 return {match: true, exact: (key == str), command, count}
427 return {match: false}
429 isEscCommandKey = (keyStr) -> keyStr in escapeCommand.keys()
431 exports.commands = commands
432 exports.searchForMatchingCommand = searchForMatchingCommand
433 exports.isEscCommandKey = isEscCommandKey
434 exports.findStorage = findStorage