1 {CompositeDisposable} = require 'atom'
3 Base = require './base'
4 Selector = require './selector'
6 module.exports = class Change
7 constructor: (config) ->
8 @command = config.changeSurroundCommand
9 @context = "atom-text-editor.vim-mode.normal-mode"
10 @disposables = new CompositeDisposable
12 @curPairsWithTarget = []
13 @registerPairs config.pairs
15 getName: (key, targetKey) -> "change-#{key}-to-#{targetKey}"
17 registerPairs: (pairs) ->
18 pairs = (x for x in pairs when x.length > 0 and x.length %2 == 0)
22 if "#{pair}#{target}" not in @curPairs
23 @registerPair pair, target
24 @curPairs.push("#{pair}#{target}")
26 registerPair: (pair, target) ->
27 [left, right] = @splitPair(pair)
28 [target_left, target_right] = @splitPair(target)
30 for key in [left, right]
31 for targetKey in [target_left, target_right]
32 if "#{key}#{targetKey}" not in @curPairsWithTarget
33 name = "vim-surround:#{@getName(key, targetKey)}"
36 @disposables.add atom.commands.add @context, name, @getRunner pair, target
39 fullCommand = "#{@command} #{key} #{targetKey}"
40 keymapArg[fullCommand] = name
43 contextArg[@context] = keymapArg
45 # Capture the disposable heretom test!
47 @disposables.add atom.keymaps.add name, contextArg
48 @curPairsWithTarget.push("#{key}#{targetKey}")
51 return [pair[..(pair.length/2)-1], pair[pair.length/2..]]
53 getRunner: (from, to) -> ->
54 [left, right] = [from[0], from[1]]
55 [target_left, target_right] = [to[0], to[1]]
56 editor = atom.workspace.getActiveTextEditor()
57 selector = new Selector(editor, left, right)
60 cursorPos = editor.getCursorBufferPosition()
62 selector.inside().select()
63 editor.selections.forEach (selection) ->
64 text = selection.getText()
66 # restore cursore and select text with surrounding keys
67 editor.setCursorBufferPosition(cursorPos)
68 selector.outside().select()
70 editor.selections.forEach (selection) ->
71 selection.insertText "#{target_left}#{text}#{target_right}"
74 editor.setCursorBufferPosition(cursorPos)