]> git.gir.st - VimFx.git/blob - extension/packages/vim.coffee
Minor cleanup
[VimFx.git] / extension / packages / vim.coffee
1 MODE_NORMAL = {}
2
3 class Vim
4 constructor: ({ @window, @commands, @modes, @esc }) ->
5 @mode = MODE_NORMAL
6 @keys = []
7
8 @storage =
9 commands: {}
10 modes: {}
11
12 for { name } in @commands
13 @storage.commands[name] = {}
14
15 for name of @modes
16 @storage.modes[name] = {}
17
18 enterMode: (mode, args) ->
19 # Note: `args` is an array of arguments to be passed to the mode's `onEnter` method. We cannot
20 # use `args...`, since that destroys the `this` context for the mode's `onEnter` method.
21 @mode = mode
22 @modes[mode].onEnter?(this, @storage.modes[mode], args)
23
24 enterNormalMode: ->
25 return if @mode == MODE_NORMAL
26 @modes[@mode].onEnterNormalMode?(this, @storage.modes[@mode])
27 @mode = MODE_NORMAL
28 @keys.length = 0
29
30 onInput: (keyStr, event) ->
31 @keys.push(keyStr)
32
33 if @mode == MODE_NORMAL
34 { match, exact, command } = @searchForCommand(@commands)
35
36 if match
37 if exact then command.func(this, @storage.commands[command.name], event)
38 return true
39 else
40 return false
41
42 else
43 if keyStr == @esc
44 @enterNormalMode()
45 return true
46 else
47 return @modes[@mode].onInput?(this, @storage.modes[@mode], keyStr, event)
48
49 # Intentionally taking `commands` as a parameter (instead of simply using `@commands`), so that
50 # the method can be reused by custom modes.
51 searchForCommand: (commands) ->
52 for index in [0...@keys.length] by 1
53 str = @keys[index..].join(',')
54 for command in commands
55 for key in command.keys()
56 if key.startsWith(str) and command.enabled()
57 @keys = @keys[index..]
58 return {match: true, exact: (key == str), command}
59
60 @keys.length = 0
61 return {match: false}
62
63 Vim.MODE_NORMAL = MODE_NORMAL
64
65 # What is minimally required for a command
66 class Vim.Command
67 constructor: (@name) ->
68 keys: -> return ['key1', 'key2', 'keyN']
69 enabled: -> return true
70 func: (vim, storage, event) ->
71
72 exports.Vim = Vim
Imprint / Impressum