]> git.gir.st - VimFx.git/blob - extension/packages/vim.coffee
Fix a likely future bug
[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 @lastKeyStr = null
8 @suppress = false
9
10 @storage =
11 commands: {}
12 modes: {}
13
14 for { name } in @commands
15 @storage.commands[name] = {}
16
17 for name of @modes
18 @storage.modes[name] = {}
19
20 enterMode: (mode, args) ->
21 # Note: `args` is an array of arguments to be passed to the mode's `enter` method. We cannot use
22 # `args...`, since that destroys the `this` context for the mode's `enter` method.
23 @mode = mode
24 @modes[mode].enter(this, @storage.modes[mode], args)
25
26 enterNormalMode: ->
27 for name, mode of @modes
28 mode.onEnterNormalMode?(this, @storage.modes[name])
29 @mode = MODE_NORMAL
30
31 handleKeyDown: (event, keyStr) ->
32 @suppress = true
33 if @mode == MODE_NORMAL or keyStr == @esc
34 @keys.push(keyStr)
35 @lastKeyStr = keyStr
36 if command = @findCommand(@keys)
37 command.func(this, @storage.commands[command.name])
38 return command.name != @esc
39 else if @maybeCommand(@keys)
40 return true
41 else
42 @keys.length = 0
43 else if not (event.ctrlKey or event.metaKey)
44 @modes[@mode].handleKeyDown(this, @storage.modes[@mode], event, keyStr)
45
46 @suppress = false
47 @keys.length = 0
48 return false
49
50 handleKeyPress: (event) ->
51 return @lastKeyStr != @esc and @suppress
52
53 handleKeyUp: (event) ->
54 suppress = @suppress
55 @suppress = false
56 return @lastKeyStr != @esc and suppress
57
58 findCommand: (keys) ->
59 for i in [0...keys.length]
60 str = keys[i..].join(',')
61 for command in @commands
62 for key in command.keys()
63 if key == str and command.enabled()
64 return command
65
66 maybeCommand: (keys) ->
67 for i in [0...keys.length]
68 str = keys[i..].join(',')
69 for command in @commands
70 for key in command.keys()
71 if key.indexOf(str) == 0 and command.enabled()
72 return true
73
74 # What is minimally required for a command
75 class Vim.Command
76 constructor: (@keyValues, @name) ->
77 keys: -> return @keyValues
78 enabled: -> return true
79
80 exports.Vim = Vim
Imprint / Impressum