]> git.gir.st - VimFx.git/blob - extension/lib/vimfx.coffee
Allow any mode to enter the "autoInsertMode" of Normal mode
[VimFx.git] / extension / lib / vimfx.coffee
1 ###
2 # Copyright Simon Lydell 2015.
3 #
4 # This file is part of VimFx.
5 #
6 # VimFx is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # VimFx is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
18 ###
19
20 notation = require('vim-like-key-notation')
21 prefs = require('./prefs')
22 utils = require('./utils')
23 Vim = require('./vim')
24
25 DIGIT = /^\d$/
26 FORCE_KEY = '<force>'
27
28 class VimFx extends utils.EventEmitter
29 constructor: (@modes, @options) ->
30 super()
31 @vimBucket = new utils.Bucket(((window) => new Vim(window, this)), this)
32 @createKeyTrees()
33 @reset()
34 @on('modechange', ({mode}) => @reset(mode))
35 @currentVim = null
36 @on('bucket.get', (vim) =>
37 return if @currentVim == vim
38 @currentVim = vim
39 @emit('currentVimChange', vim)
40 )
41 @customCommandCounter = 0
42
43 reset: (mode = null) ->
44 @currentKeyTree = if mode then @keyTrees[mode] else {}
45 @lastInputTime = 0
46 @count = ''
47
48 getCurrentLocation: -> @currentVim?.window.location
49
50 createKeyTrees: ->
51 {@keyTrees, @forceCommands, @errors} = createKeyTrees(@modes)
52
53 stringifyKeyEvent: (event) ->
54 return notation.stringify(event, {
55 ignoreKeyboardLayout: @options.ignore_keyboard_layout
56 translations: @options.translations
57 })
58
59 consumeKeyEvent: (event, vim) ->
60 { mode } = vim
61 return unless keyStr = @stringifyKeyEvent(event)
62
63 now = Date.now()
64 @reset(mode) if now - @lastInputTime >= @options.timeout
65 @lastInputTime = now
66
67 toplevel = (@currentKeyTree == @keyTrees[mode])
68
69 if toplevel and @options.keyValidator
70 unless @options.keyValidator(keyStr, mode)
71 @reset(mode)
72 return
73
74 type = 'none'
75 command = null
76
77 switch
78 when keyStr of @currentKeyTree
79 next = @currentKeyTree[keyStr]
80 if next instanceof Leaf
81 type = 'full'
82 command = next.command
83 else
84 @currentKeyTree = next
85 type = 'partial'
86
87 when toplevel and DIGIT.test(keyStr) and
88 not (keyStr == '0' and @count == '')
89 @count += keyStr
90 type = 'count'
91
92 else
93 @reset(mode)
94
95 count = if @count == '' then undefined else Number(@count)
96 force = if command then (command.pref of @forceCommands) else false
97 focus = @getFocusType(vim, event, keyStr)
98 @reset(mode) if type == 'full'
99 return {type, focus, command, count, force, keyStr }
100
101 getFocusType: (vim, event, keyStr) ->
102 target = event.originalTarget
103 document = target.ownerDocument
104
105 { activatable_element_keys, adjustable_element_keys } = @options
106 return switch
107 when utils.isTextInputElement(target) or
108 utils.isContentEditable(target)
109 'editable'
110 when (utils.isActivatable(target) and
111 keyStr in activatable_element_keys)
112 'activatable'
113 when (utils.isAdjustable(target) and
114 keyStr in adjustable_element_keys)
115 'adjustable'
116 when vim.rootWindow.TabView.isVisible() or
117 document.fullscreenElement or document.mozFullScreenElement
118 'other'
119 else
120 null
121
122 getGroupedCommands: (options = {}) ->
123 modes = {}
124 for modeName, mode of @modes
125 if options.enabledOnly
126 usedSequences = getUsedSequences(@keyTrees[modeName])
127 for commandName, command of mode.commands
128 enabledSequences = null
129 if options.enabledOnly
130 enabledSequences = utils.removeDuplicates(
131 command._sequences.filter((sequence) ->
132 return (usedSequences[sequence] == command.pref)
133 )
134 )
135 continue if enabledSequences.length == 0
136 categories = modes[modeName] ?= {}
137 category = categories[command.category] ?= []
138 category.push({command, enabledSequences, order: command.order})
139
140 modesSorted = []
141 for modeName, categories of modes
142 categoriesSorted = []
143 for categoryName, commands of categories
144 category = @options.categories[categoryName]
145 categoriesSorted.push({
146 name: category.name()
147 _name: categoryName
148 order: category.order
149 commands: commands.sort(byOrder)
150 })
151 mode = @modes[modeName]
152 modesSorted.push({
153 name: mode.name()
154 _name: modeName
155 order: mode.order
156 categories: categoriesSorted.sort(byOrder)
157 })
158 return modesSorted.sort(byOrder)
159
160 byOrder = (a, b) -> a.order - b.order
161
162 class Leaf
163 constructor: (@command, @originalSequence) ->
164
165 createKeyTrees = (modes) ->
166 keyTrees = {}
167 errors = {}
168 forceCommands = {}
169
170 pushError = (error, command) ->
171 (errors[command.pref] ?= []).push(error)
172
173 pushOverrideErrors = (command, tree) ->
174 for { command: overriddenCommand, originalSequence } in getLeaves(tree)
175 error =
176 id: 'overridden_by'
177 subject: command.description()
178 context: originalSequence
179 pushError(error, overriddenCommand)
180 return
181
182 pushForceKeyError = (command, originalSequence) ->
183 error =
184 id: 'illegal_force_key'
185 subject: FORCE_KEY
186 context: originalSequence
187 pushError(error, command)
188
189 for modeName, { commands } of modes
190 keyTrees[modeName] = {}
191 for commandName, command of commands
192 { shortcuts, errors: parseErrors } = parseShortcutPref(command.pref)
193 pushError(error, command) for error in parseErrors
194 command._sequences = []
195
196 for shortcut in shortcuts
197 [ prefixKeys..., lastKey ] = shortcut.normalized
198 tree = keyTrees[modeName]
199 command._sequences.push(shortcut.original)
200
201 for prefixKey, index in prefixKeys
202 if prefixKey == FORCE_KEY
203 if index == 0
204 forceCommands[command.pref] = true
205 else
206 pushForceKeyError(command, shortcut.original)
207 continue
208
209 if prefixKey of tree
210 next = tree[prefixKey]
211 if next instanceof Leaf
212 pushOverrideErrors(command, next)
213 tree = tree[prefixKey] = {}
214 else
215 tree = next
216 else
217 tree = tree[prefixKey] = {}
218
219 if lastKey == FORCE_KEY
220 pushForceKeyError(command, shortcut.original)
221 continue
222 if lastKey of tree
223 pushOverrideErrors(command, tree[lastKey])
224 tree[lastKey] = new Leaf(command, shortcut.original)
225
226 return {keyTrees, forceCommands, errors}
227
228 parseShortcutPref = (pref) ->
229 shortcuts = []
230 errors = []
231
232 # The shorcut prefs are read from root in order to support other extensions to
233 # extend VimFx with custom commands.
234 prefValue = prefs.root.get(pref).trim()
235
236 unless prefValue == ''
237 for sequence in prefValue.split(/\s+/)
238 shortcut = []
239 errored = false
240 for key in notation.parseSequence(sequence)
241 try
242 shortcut.push(notation.normalize(key))
243 catch error
244 throw error unless error.id?
245 errors.push(error)
246 errored = true
247 break
248 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
249
250 return {shortcuts, errors}
251
252 getLeaves = (node) ->
253 if node instanceof Leaf
254 return [node]
255 leaves = []
256 for key, value of node
257 leaves.push(getLeaves(value)...)
258 return leaves
259
260 getUsedSequences = (tree) ->
261 usedSequences = {}
262 for leaf in getLeaves(tree)
263 usedSequences[leaf.originalSequence] = leaf.command.pref
264 return usedSequences
265
266 module.exports = VimFx
Imprint / Impressum