aboutsummaryrefslogtreecommitdiff
path: root/atom/packages/vim-surround/lib/command/base.coffee
blob: b40e644356b8f20d1990d94051f94367b8c1c806 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
{CompositeDisposable} = require 'atom'

module.exports = class Base

  constructor: (config) ->
    @disposables = new CompositeDisposable

    @curPairs = []
    @registerPairs config.pairs

  registerPairs: (pairs) ->
    pairs = (x for x in pairs when x.length > 0 and x.length %2 == 0)

    for pair in pairs
      if pair not in @curPairs
        @registerPair pair
        @curPairs.push(pair)

  registerPair: (pair) ->
    [left, right] = @splitPair(pair)

    if left != right
      @createPairBindings left, "#{left} ", " #{right}"
    @createPairBindings right, left, right

  createPairBindings: (key, left, right) ->
    name = "vim-surround:#{@getName key}"

    # First, we add a command to the system to actually perform the surround.
    # We attach the disposable to our object's list.
    @disposables.add atom.commands.add @context, name, @getRunner left, right

    # Next, we build up keybindings for our command. First, we build a
    # space-delineated version of our key that's passed in. This breaks up
    # double keys like `{%` into the seperate keystroke form: `{ %`
    keys = ""
    for i in [0..key.length-1]
      if i == 0
        keys = key[i]
      else
        keys = "#{keys} #{key[i]}"

    # Making a one-command keymap data structure here. Basically:
    # "atom-text-editor.vim-mode.visual-mode":
    #   "s (":
    #     "vim-surround:surround-("

    keymapArg = {}
    fullCommand = "#{@command} #{keys}"
    keymapArg[fullCommand] = name

    contextArg = {}
    contextArg[@context] = keymapArg

    # Capture the disposable heretom test!
    @disposables.add atom.keymaps.add name, contextArg

  splitPair: (pair) ->
    return [pair[..(pair.length/2)-1], pair[pair.length/2..]]