]> git.gir.st - VimFx.git/blob - documentation/api.md
Merge branch 'master' into develop
[VimFx.git] / documentation / api.md
1 <!--
2 This is part of the VimFx documentation.
3 Copyright Simon Lydell 2015.
4 See the file README.md for copying conditions.
5 -->
6
7 # Public API
8
9 VimFx has a public API. It is intended to be used by users who would like to
10 write a so-called [config file].
11
12 Some parts of the API is also intended to be used by authors who would like to
13 extend VimFx.
14
15
16 ## Getting the API
17
18 ```js
19 let {classes: Cc, interfaces: Ci, utils: Cu} = Components
20 Cu.import('resource://gre/modules/Services.jsm')
21 let apiPref = 'extensions.VimFx.api_url'
22 let apiUrl = Services.prefs.getComplexValue(apiPref, Ci.nsISupportsString).data
23 Cu.import(apiUrl, {}).getAPI(vimfx => {
24
25 // Do things with the `vimfx` object here.
26
27 })
28 ```
29
30 You might also want to take a look at the [config file bootstrap.js
31 example][bootstrap.js].
32
33 Note that the callback passed to `getAPI` is called once every time VimFx starts
34 up, not once per Firefox session! This means that if you update VimFx (or
35 disable and then enable it), the callback is re-run with the new version.
36
37
38 ## API
39
40 The following sub-sections assume that you store VimFx’s public API in a
41 variable called `vimfx`.
42
43 ### `vimfx.get(pref)`, `vimfx.getDefault(pref)` and `vimfx.set(pref, value)`
44
45 Gets or sets the (default) value of the VimFx pref `pref`.
46
47 You can see all prefs in [defaults.coffee], or by opening [about:config] and
48 filtering by `extensions.vimfx`. Note that you can also access the [special
49 options], which may not be accessed in [about:config], using `vimfx.get()` and
50 `vimfx.set()`—in fact, this is the _only_ way of accessing those options.
51
52 #### `vimfx.get(pref)`
53
54 Gets the value of the VimFx pref `pref`.
55
56 ```js
57 // Get the value of the Hint chars option:
58 vimfx.get('hint_chars')
59 // Get all keyboard shortcuts (as a string) for the `f` command:
60 vimfx.get('mode.normal.follow')
61 ```
62
63 #### `vimfx.getDefault(pref)`
64
65 Gets the default value of the VimFx pref `pref`.
66
67 Useful when you wish to extend a default, rather than replacing it. See below.
68
69 #### `vimfx.set(pref, value)`
70
71 Sets the value of the VimFx pref `pref` to `value`.
72
73 ```js
74 // Set the value of the Hint chars option:
75 vimfx.set('hint_chars', 'abcdefghijklmnopqrstuvwxyz')
76 // Add yet a keyboard shortcut for the `f` command:
77 vimfx.set('mode.normal.follow', vimfx.getDefault('mode.normal.follow') + ' e')
78 ```
79
80 When extending a pref (as in the second example above), be sure to use
81 `vimfx.getDefault` rather than `vimfx.get`. Otherwise you get a multiplying
82 effect. In the above example, after starting Firefox a few times the pref would
83 be `f e e e e`. Also, if you find that example very verbose: Remember that
84 you’re using a programming language! Write a small helper function that suits
85 your needs.
86
87 Note: If you produce conflicting keyboard shortcuts, the order of your code does
88 not matter. The command that comes first in VimFx’s settings page in the Add-ons
89 Manager (and in the help dialog) gets the shortcut; the other one(s) do(es) not.
90 See the notes about order in [mode object], [category object] and [command
91 object] for more information about order.
92
93 ```js
94 // Even though we set the shortcut for focusing the search bar last, the command
95 // for focusing the location bar “wins”, because it comes first in VimFx’s
96 // settings page in the Add-ons Manager.
97 vimfx.set('mode.normal.focus_location_bar', 'ö')
98 vimfx.set('mode.normal.focus_search_bar', 'ö')
99
100 // Swapping their orders also swaps the “winner”.
101 let {commands} = vimfx.modes.normal
102 ;[commands.focus_location_bar.order, commands.focus_search_bar.order] =
103 [commands.focus_search_bar.order, commands.focus_location_bar.order]
104 ```
105
106 ### `vimfx.addCommand(options, fn)`
107
108 Creates a new command.
109
110 **Note:** This should only be used by config file users, not by extension
111 authors who wish to extend VimFx. They should add commands manually to
112 [`vimfx.modes`] instead.
113
114 `options`:
115
116 - name: `String`. The name used when accessing the command via
117 `vimfx.modes[options.mode].commands[options.name]`. It is also used for the
118 pref used to store the shortcuts for the command:
119 `` `custom.mode.${options.mode}.${options.name}` ``.
120 - description: `String`. Shown in the help dialog and VimFx’s settings page in
121 the Add-ons Manager.
122 - mode: `String`. Defaults to `'normal'`. The mode to add the command to. The
123 value has to be one of the keys of [`vimfx.modes`].
124 - category: `String`. Defaults to `'misc'` for Normal mode and `''`
125 (uncategorized) otherwise. The category to add the command to. The
126 value has to be one of the keys of [`vimfx.get('categories')`][categories].
127 - order: `Number`. Defaults to putting the command at the end of the category.
128 The first of the default commands has the order `100` and then they increase
129 by `100` per command. This allows to put new commands between two already
130 existing ones.
131
132 `fn` is called when the command is activated. See the [onInput] documentation
133 below for more information.
134
135 Note that you have to give the new command a shortcut in VimFx’s settings page
136 in the Add-ons Manager or set one using `vimfx.set()` to able to use the new
137 command.
138
139 ```js
140 vimfx.addCommand({
141 name: 'hello',
142 description: 'Log Hello World',
143 }, => {
144 console.log('Hello World!')
145 })
146 // Optional:
147 vimfx.set('custom.mode.normal.hello', 'gö')
148 ```
149
150 ### `vimfx.addOptionOverrides(...rules)` and `vimfx.addKeyOverrides(...rules)`
151
152 These methods take any number of arguments. Each argument is a rule. The rules
153 are added in order. The methods may be run multiple times.
154
155 A rule is an `Array` of length 2:
156
157 1. The first item is a function that returns `true` if the rule should be
158 applied and `false` if not. This is called the matching function.
159 2. The second item is the value that should be used if the rule is applied. This
160 is called the override.
161
162 The rules are tried in the same order they were added. When a matching rule is
163 found it is applied. No more rules will be applied.
164
165 #### `vimfx.addOptionOverrides(...rules)`
166
167 The rules are matched any time the value of a VimFx pref is needed.
168
169 The matching function receives a [location object].
170
171 The override is an object whose keys are VimFx pref names and whose values
172 override the pref in question. The values should be formatted as in an [options
173 object].
174
175 ```js
176 vimfx.addOptionOverrides(
177 [ ({hostname, pathname, hash}) =>
178 `${hostname}${pathname}${hash}` === 'google.com/',
179 {prevent_autofocus: false}
180 ]
181 )
182 ```
183
184 #### `vimfx.addKeyOverrides(...rules)`
185
186 The rules are matched any time you press a key that is not part of the tail of a
187 multi-key shortcut.
188
189 The matching function receives a [location object] as well as the current
190 mode name (one of the keys of [`vimfx.modes`]).
191
192 The override is an array of keys which should not activate VimFx commands but be
193 sent to the page.
194
195 This allows to disable commands on specific sites. To _add_ commands on specific
196 sites, add them globally and then disable them on all _other_ sites.
197
198 ```js
199 vimfx.addKeyOverrides(
200 [ location => location.hostname === 'facebook.com',
201 ['j', 'k']
202 ]
203 )
204 ```
205
206 ### `vimfx.on(eventName, listener)`
207
208 Runs `listener(data)` when `eventName` is fired.
209
210 #### The `locationChange` event
211
212 Occurs when opening a new tab, navigating to a new URL or refreshing the page,
213 causing a full page load. The data passed to listeners is an object with the
214 following properties:
215
216 - vim: The current [vim object].
217 - location: A [location object].
218
219 This can be used to enter a different mode by default on some pages (which can
220 be used to replace the blacklist option).
221
222 ```js
223 vimfx.on('locationChange', ({vim, location}) => {
224 if (location.hostname === 'example.com') {
225 vim.enterMode('ignore')
226 }
227 })
228 ```
229
230 #### The `notification` and `hideNotification` events
231
232 The `notification` event occurs when `vim.notify(message)` is called, and means
233 that `message` should be displayed to the user.
234
235 The `hideNotification` event occurs when the `vim.hideNotification()` is called,
236 and means that the current notification is requested to be hidden.
237
238 The data passed to listeners is an object with the following properties:
239
240 - vim: The current [vim object].
241 - message: The message that should be notified. Only for the `notification`
242 event.
243
244 Both of these events are emitted even if the [`notifications_enabled`] option is
245 disabled, allowing you to display notifications in any way you want.
246
247 #### The `modeChange` event
248
249 Occurs whenever the current mode in any tab changes. The initial entering of the
250 default mode in new tabs also counts as a mode change. The data passed to
251 listeners is the current [vim object].
252
253 ```js
254 vimfx.on('modeChange', vim => {
255 let mode = vimfx.modes[vim.mode].name()
256 vim.notify(`Entering mode: ${mode}`)
257 })
258 ```
259
260 #### The `TabSelect` event
261
262 Occurs whenever any tab in any window is selected. This is also fired when
263 Firefox starts for the currently selected tab. The data passed to listeners is
264 the `event` object passed to the standard Firefox [TabSelect] event.
265
266 ### The `modeDisplayChange` event
267
268 This is basically a combination of the `modeChange` and the `TabSelect` events.
269 The event is useful for knowing when to update UI showing the current mode. The
270 data passed to listeners is the current [vim object].
271
272 (VimFx itself uses this event to update the toolbar [button], by setting
273 `#main-window[vimfx-mode]` to the current mode. You may use this with custom
274 [styling].)
275
276 #### The `focusTypeChange` event
277
278 Occurs when focusing or blurring any element. The data passed to listeners is an
279 object with the following properties:
280
281 - vim: The current [vim object].
282 - focusType: A string similar to `match.focus` of a [match object], with the
283 following differences:
284
285 - The current pressed key is _not_ taken into account, because focus and blur
286 events have no current key.
287 - The value is never `null` or `'other'`, but `'none'` instead.
288
289 (VimFx itself uses this event to update the toolbar [button], by setting
290 `#main-window[vimfx-focus-type]` to the current focus type. You may use this
291 with custom [styling].)
292
293
294
295 ### `vimfx.modes`
296
297 An object whose keys are mode names and whose values are [mode object]s.
298
299 This is a very low-level part of the API. It allows to:
300
301 - Access all commands and run them. This is the only thing that a config file
302 user needs it for.
303
304 ```js
305 let {commands} = vimfx.modes.normal
306 // Inside a custom command:
307 commands.tab_new.run(args)
308 ```
309
310 - Adding new commands. This is intended to be used by extension authors who wish
311 to extend VimFx, not config file users. They should use the
312 `vimfx.addCommand()` helper instead.
313
314 ```js
315 vimfx.modes.normal.commands.new_command = {
316 pref: 'extensions.my_extension.mode.normal.new_command',
317 category: 'misc',
318 order: 10000,
319 description: () => translate('mode.normal.new_command'),
320 run: args => console.log('New command! args:', args)
321 }
322 ```
323
324 - Adding new modes. This is intended to be used by extension authors who wish to
325 extend VimFx, not config file users.
326
327 ```js
328 vimfx.modes.new_mode = {
329 name: () => translate('mode.new_mode'),
330 order: 10000,
331 commands: {},
332 onEnter(args) {},
333 onLeave(args) {},
334 onInput(args, match) {
335 if (match.type === 'full') {
336 match.command.run(args)
337 }
338 return (match.type !== 'none')
339 },
340 }
341 ```
342
343 Have a look at [modes.coffee] and [commands.coffee] for more information.
344
345 ### `vimfx.get('categories')`
346
347 An object whose keys are category names and whose values are [category object]s.
348
349 ```js
350 let categories = vimfx.get('categories')
351
352 // Add a new category.
353 categories.custom = {
354 name: () => 'Custom commands',
355 order: 10000,
356 }
357
358 // Swap the order of the Location and Tabs categories.
359 ;[commands.focus_location_bar.order, categories.tabs.order] =
360 [categories.tabs.order, commands.focus_location_bar.order]
361 ```
362
363 ### Mode object
364
365 A mode is an object with the follwing properties:
366
367 - name(): `Function`. Returns a human readable name of the mode used in the help
368 dialog and VimFx’s settings page in the Add-ons Manager.
369 - order: `Number`. The first of the default modes has the order `100` and then
370 they increase by `100` per mode. This allows to put new modes between two
371 already existing ones.
372 - commands: `Object`. The keys are command names and the values are [command
373 object]s.
374 - onEnter(data, ...args): `Function`. Called when the mode is entered.
375 - onLeave(data): `Function`. Called when the mode is left.
376 - onInput(data, match): `Function`. Called when a key is pressed.
377
378 #### onEnter, onLeave and onInput
379
380 These methods are called with an object (called `data` above) with the following
381 properties:
382
383 - vim: The current [vim object].
384 - storage: An object unique to the current [vim object] and to the current mode.
385 Allows to share things between commands of the same mode by getting and
386 setting keys on it.
387
388 ##### onEnter
389
390 This method is called with an object as mentioned above, and after that there
391 may be any number of arguments (`args` in `vim.enterMode(modeName, ...args)`)
392 that the mode is free to do whatever it wants with.
393
394 Whatever is returned from `onEnter` will be returned from
395 `vim.enterMode(modeName, ...args)`.
396
397 ##### onInput
398
399 The object passed to this method (see above) also has the following properties:
400
401 - uiEvent: `Event` or `false`. The keydown event object if the event occured in
402 the browser UI, `false` otherwise (if the event occured in web page content).
403 - count: `Number`. The count for the command. `undefined` if no count. (This is
404 simply a copy of `match.count`. `match` is defined below.)
405
406 The above object should be passed to commands when running them. The mode is
407 free to do whatever it wants with the return value (if any) of the commands it
408 runs.
409
410 It also receives a [match object] as the second argument.
411
412 `onInput` should return `true` if the current keypress should not be passed on
413 to the browser and web pages, and `false` otherwise.
414
415 ### Category object
416
417 A category is an object with the follwing properties:
418
419 - name(): `Function`. Returns a human readable name of the category used in the
420 help dialog and VimFx’s settings page in the Add-ons Manager. Config file
421 users adding custom categories could simply return a string; extension authors
422 are encouraged to look up the name from a locale file.
423 - order: `Number`. The first of the default categories is the “uncategorized”
424 category. It has the order `100` and then they increase by `100` per category.
425 This allows to put new categories between two already existing ones.
426
427 ### Command object
428
429 A command is an object with the following properties:
430
431 - pref: `String`. The pref used to store the shortcuts for the command.
432 - run(args): `Function`. Called when the command is activated.
433 - description(): `Function`. Returns a description of the command (as a string),
434 shown in the help dialog and VimFx’s settings page in the Add-ons Manager.
435 - category: `String`. The category to add the command to. The value has to be
436 one of the keys of [`vimfx.get('categories')`][categories].
437 - order: `Number`. The first of the default commands has the order `100` and
438 then they increase by `100` per command. This allows to put new commands
439 between two already existing ones.
440
441 ### Match object
442
443 A `match` object has the following properties:
444
445 - type: `String`. It has one of the following values:
446
447 - `'full'`: The current keypress, together with previous keypresses, fully
448 matches a command shortcut.
449 - `'partial'`: The current keypress, together with previous keypresses,
450 partially matches a command shortcut.
451 - `'count'`: The current keypress is not part of a command shortcut, but is a
452 digit and contributes to the count of a future matched command.
453 - `'none'`: The current keypress is not part of a command shortcut and does
454 not contribute to a count.
455
456 - focus: `String` or `null`. The type of currently focused _element_ plus
457 current pressed _key_ combo. You might not want to run commands and suppress
458 the event if this value is anything other than null. It has one of the
459 following values, depending on what kind of _element_ is focused and which
460 _key_ was pressed:
461
462 - `'editable'`: element: some kind of text input, a `<select>` element or a
463 `contenteditable` element. key: any pressed key.
464 - `'activatable'`: element: an “activatable” element (link or button).
465 key: see the [`activatable_element_keys`] option.
466 - `'adjustable'`: element: an “adjustable” element (form control or video
467 player). key: see the [`adjustable_element_keys`] option.
468 - `'other'`: element: some other kind of element that can receive keystrokes,
469 for example an element in fullscreen mode. key: any pressed key.
470
471 If none of the above criteria is met, the value is `null`, which means that
472 the currently focused element does not appear to respond to keystrokes in any
473 special way.
474
475 - command: `null` unless `type` is `'full'`. Then it is the matched command (a
476 [command object]).
477
478 The matched command should usually be run at this point. It is suitable to
479 pass on the object passed to [onInput] to the command. Some modes might choose
480 to add extra properties to the object first. (That is favored over passing
481 several arguments, since it makes it easier for the command to in turn pass
482 the same data it got on to another command, if needed.)
483
484 Usually the return value of the command isn’t used, but that’s up to the mode.
485
486 - count: `Number`. The count for the command. `undefined` if no count.
487
488 - specialKeys: `Object`. The keys may be any of the following:
489
490 - `<force>`
491 - `<late>`
492
493 If a key exists, its value is always `true`. The keys that exist indicate the
494 [special keys] for the sequence used for the matched command (if any).
495
496 - keyStr: `String`. The current keypress represented as a string.
497
498 - unmodifiedKey: `String`. `keyStr` without modifiers.
499
500 - toplevel: `Boolean`. Whether or not the match was a toplevel match in the
501 shortcut key tree. This is `true` unless the match is part of the tail of a
502 multi-key shortcut.
503
504 ### Vim object
505
506 There is one `vim` object per tab.
507
508 A `vim` object has the following properties:
509
510 - window: [`Window`]. The current Firefox window object. Most commands
511 interacting with Firefox’s UI use this.
512
513 - browser: [`Browser`]. The `browser` that this vim object handles.
514
515 - options: `Object`. Provides access to all of VimFx’s options. It is an
516 [options object].
517
518 - mode: `String`. The current mode name.
519
520 - enterMode(modeName, ...args): `Function`. Enter mode `modeName`, passing
521 `...args` to the mode. It is up to every mode to do whatever it wants to with
522 `...args`. If `modeName` was already the current mode, nothing is done and
523 `undefined` is returned. Otherwise it us up to the mode to return whatever it
524 wants to.
525
526 - isUIEvent(event): `Function`. Returns `true` if `event` occurred in the
527 browser UI, and `false` otherwise (if it occurred in web page content).
528
529 - notify(message): `Function`. Display a notification with the text `message`.
530
531 - hideNotification(): `Function`. Hide the current notification (if any).
532
533 - markPageInteraction(): `Function`. Marks that the user has interacted with the
534 page. After that [autofocus prevention] is not done anymore. Commands
535 interacting with web page content might want to do this.
536
537 **Warning:** There are also properties starting with an underscore on `vim`
538 objects. They are private, and not supposed to be used outside of VimFx’s own
539 source code. They may change at any time.
540
541 ### Options object
542
543 An `options` object provides access to all of VimFx’s options. It is an object
544 whose keys are VimFx pref names.
545
546 Note that the values are not just simply `vimfx.get(pref)` for the `pref` in
547 question; they are _parsed_ (`parse(vimfx.get(pref))`):
548
549 - Space-separated prefs are parsed into arrays of strings.
550
551 - `black_list` and `{prev,next}_patterns` are parsed into arrays of regular
552 expressions.
553
554 (See [parse-prefs.coffee] for all details.)
555
556 Any [option overrides] are automatically taken into account when getting an
557 option value.
558
559 The [special options] are also available on this object.
560
561
562 ### Location object
563
564 A location object is very similar to [`window.location`] in web pages.
565 Technically, it is a [`URL`] instance. You can experient with the current
566 location object by opening the [web console] and entering `location`.
567
568
569 ## Frame script API
570
571 In frame scripts, the API consists of assigning global variables prefixed with
572 `VimFx`. VimFx then uses these when needed.
573
574 ```js
575 this.VimFxSomething = ...
576 ```
577
578 ### `VimFxHintMatcher(...)`
579
580 **Note:** This should only be used by config file users, not by extension
581 authors who wish to extend VimFx.
582
583 If available, it is used to let you customize which elements do and don’t get
584 hints. It might help to read about [the `f` commands] first.
585
586 ```js
587 this.VimFxHintMatcher = (id, element, {type, semantic}) => {
588 // Inspect `element` and change `type` and `semantic` if needed.
589 return {type, semantic}
590 }
591 ```
592
593 The arguments passed to this function are:
594
595 - id: `String`. A string identifying which command is used:
596
597 - `'normal'`: `f` or `af`.
598 - `'tab'`: `F` or `gf`.
599 - `'copy'`: `yf`.
600 - `'focus'`: `zf`.
601
602 - element: `Element`. One out of all elements currently inside the viewport.
603
604 - info: `Object`. It has the following properties:
605
606 - type: `String` or `null`. If a string, it means that `element` should get a
607 hint. If `null`, it won’t. See the available strings below. When a marker
608 is matched, `type` decides what happens to `element`.
609 - semantic: `Boolean`. Indicates whether or not the element is “semantic.”
610 Semantic elements get better hints.
611
612 This object contains information on how VimFx has matched `element`. You have
613 the opportunity to change this.
614
615 The available type strings depend on `id`:
616
617 - normal:
618
619 - link: A “proper” link (not used as a button with the help of JavaScript),
620 with an `href` attribute.
621 - text: An element that can you can type in, such as text inputs.
622 - clickable: Some clickable element not falling into another category.
623 - clickable-special: Like “clickable,” but uses a different technique to
624 simulate a click on the element. If “clickable” doesn’t work, try this one.
625 - scrollable: A scrollable element.
626
627 - tab:
628
629 - link: Like “link” when `id` is “normal” (see above).
630
631 - copy:
632
633 - link: Like “link” when `id` is “normal” (see above).
634 - text: Like “text” when `id` is “normal” (see above), except
635 contenteditable elements.
636 - contenteditable: Elements with “contenteditable” turned on.
637
638 - focus:
639
640 - focusable: Any focusable element not falling into another category.
641 - scrollable: Like “scrollable” when `id` is “normal” (see above).
642
643 The function must return an object with just like the `info` parameter (with
644 `type` and `semantic`).
645
646
647 ## Stability
648
649 The public API is currently **experimental** and therefore **unstable.** Things
650 might break with new VimFx versions. However, no breaking changes are planned,
651 and will be avoided if feasible.
652
653 As soon as VimFx 1.0.0 (which does not seem to be too far away) is released
654 backwards compatibility will be a priority and won’t be broken until VimFx
655 2.0.0.
656
657 [option overrides]: #vimfxaddoptionoverridesrules
658 [categories]: #vimfxgetcategories
659 [`vimfx.modes`]: #vimfxmodes
660 [onInput]: #oninput
661 [mode object]: #mode-object
662 [category object]: #category-object
663 [command object]: #command-object
664 [match object]: #match-object
665 [vim object]: #vim-object
666 [options object]: #options-object
667 [location object]: #location-object
668
669 [blacklisted]: options.md#blacklist
670 [special options]: options.md#special-options
671 [config file]: config-file.md
672 [bootstrap.js]: config-file.md#bootstrapjs
673 [autofocus prevention]: options.md#prevent-autofocus
674 [`activatable_element_keys`]: options.md#activatable_element_keys
675 [`adjustable_element_keys`]: options.md#adjustable_element_keys
676 [`notifications_enabled`]: options.md#notifications_enabled
677
678 [button]: button.md
679 [the `f` commands]: commands.md#the-f-commands-1
680 [special keys]: shortcuts.md#special-keys
681 [styling]: styling.md
682
683 [defaults.coffee]: ../extension/lib/defaults.coffee
684 [parse-prefs.coffee]: ../extension/lib/parse-prefs.coffee
685 [modes.coffee]: ../extension/lib/modes.coffee
686 [commands.coffee]: ../extension/lib/commands.coffee
687 [vim.coffee]: ../extension/lib/vim.coffee
688
689 [`Window`]: https://developer.mozilla.org/en-US/docs/Web/API/Window
690 [`Browser`]: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/browser
691 [`window.location`]: https://developer.mozilla.org/en-US/docs/Web/API/Location
692 [`URL`]: https://developer.mozilla.org/en-US/docs/Web/API/URL
693 [TabSelect]: https://developer.mozilla.org/en-US/docs/Web/Events/TabSelect
694 [web console]: https://developer.mozilla.org/en-US/docs/Tools/Web_Console
695 [about:config]: http://kb.mozillazine.org/About:config
Imprint / Impressum