Add global substitution

This commit is contained in:
Corey Johnson & Nathan Sobo
2012-03-21 16:16:14 -07:00
parent e51f340da1
commit 65a0d099bc
3 changed files with 28 additions and 11 deletions

View File

@@ -11,8 +11,19 @@ describe "CommandInterpreter", ->
interpreter = new CommandInterpreter()
describe "substitution", ->
it "performs the substitution within the current dot", ->
it "does nothing if there are no matches", ->
editor.selection.setBufferRange([[6, 0], [6, 44]])
interpreter.eval(editor, 's/not-in-text/foo/')
expect(buffer.lineForRow(6)).toBe ' current < pivot ? left.push(current) : right.push(current);'
it "performs a single substitution within the current dot", ->
editor.selection.setBufferRange([[6, 0], [6, 44]])
interpreter.eval(editor, 's/current/foo/')
expect(buffer.lineForRow(6)).toBe ' foo < pivot ? left.push(current) : right.push(current);'
describe "when suffixed with a g", ->
it "performs a multiple substitutions within the current dot", ->
editor.selection.setBufferRange([[6, 0], [6, 44]])
interpreter.eval(editor, 's/current/foo/g')
expect(buffer.lineForRow(6)).toBe ' foo < pivot ? left.push(foo) : right.push(current);'

View File

@@ -1,19 +1,23 @@
module.exports =
class Substitution
constructor: (@findText, @replaceText) ->
@findRegex = new RegExp(@findText)
global: false
constructor: (@findText, @replaceText, @options) ->
@findRegex = new RegExp(@findText, "g")
@global = 'g' in @options
perform: (editor) ->
{ buffer } = editor
selectedText = editor.getSelectedText()
selectionStartIndex = buffer.characterIndexForPosition(editor.getSelection().getBufferRange().start)
match = @findRegex.exec(selectedText)
matchStartIndex = selectionStartIndex + match.index
matchEndIndex = matchStartIndex + match[0].length
while match = @findRegex.exec(selectedText)
matchStartIndex = selectionStartIndex + match.index
matchEndIndex = matchStartIndex + match[0].length
startPosition = buffer.positionForCharacterIndex(matchStartIndex)
endPosition = buffer.positionForCharacterIndex(matchEndIndex)
startPosition = buffer.positionForCharacterIndex(matchStartIndex)
endPosition = buffer.positionForCharacterIndex(matchEndIndex)
buffer.change([startPosition, endPosition], @replaceText)
buffer.change([startPosition, endPosition], @replaceText)
break unless @global
selectedText = editor.getSelectedText()

View File

@@ -3,6 +3,8 @@
}
substitution
= "s" _ "/" find:([^/]*) "/" replace:([^/]*) "/" { return new Substitution(find.join(''), replace.join('')) }
= "s" _ "/" find:([^/]*) "/" replace:([^/]*) "/" _ options:[g]* {
return new Substitution(find.join(''), replace.join(''), options)
}
_ = " "*