From 6324a60d72d232ec231a6a5bd5c2c4516861339e Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 23 Jan 2013 16:21:43 -0800 Subject: [PATCH] Wrap selection in brackets Enclose the selection in brackets when an opening bracket is typed and the selection is non-empty Closes #41 --- spec/app/language-mode-spec.coffee | 11 +++++++++++ src/app/language-mode.coffee | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/spec/app/language-mode-spec.coffee b/spec/app/language-mode-spec.coffee index ff606e011..68184adf4 100644 --- a/spec/app/language-mode-spec.coffee +++ b/spec/app/language-mode-spec.coffee @@ -145,6 +145,17 @@ describe "LanguageMode", -> expect(buffer.lineForRow(0)).toBe '"ok"' expect(editSession.getCursorBufferPosition()).toEqual [0, 4] + describe "when there is text selected", -> + it "wraps the selection with brackets", -> + editSession.insertText 'text' + editSession.moveCursorToBottom() + editSession.selectToTop() + editSession.selectAll() + editSession.insertText '(' + expect('(text)').toBe buffer.getText() + expect(editSession.getSelectedBufferRange()).toEqual [[0, 1], [0, 5]] + expect(editSession.getSelection().isReversed()).toBeTruthy() + describe "when inserting a quote", -> describe "when a word character is before the cursor", -> it "does not automatically insert closing quote", -> diff --git a/src/app/language-mode.coffee b/src/app/language-mode.coffee index 4afbee747..1649fe373 100644 --- a/src/app/language-mode.coffee +++ b/src/app/language-mode.coffee @@ -26,6 +26,10 @@ class LanguageMode previousCharacter = @editSession.getTextInBufferRange([cursorBufferPosition.add([0, -1]), cursorBufferPosition]) nextCharacter = @editSession.getTextInBufferRange([cursorBufferPosition, cursorBufferPosition.add([0,1])]) + if @isOpeningBracket(text) and not @editSession.getSelection().isEmpty() + @wrapSelectionInBrackets(text) + return false + hasWordAfterCursor = /\w/.test(nextCharacter) hasWordBeforeCursor = /\w/.test(previousCharacter) @@ -61,6 +65,18 @@ class LanguageMode @editSession.delete() false + wrapSelectionInBrackets: (bracket) -> + pair = @pairedCharacters[bracket] + @editSession.mutateSelectedText (selection) => + return if selection.isEmpty() + + range = selection.getBufferRange() + options = reverse: selection.isReversed() + wrappedText = "#{bracket}#{selection.getText()}#{pair}" + selection.insertText(wrappedText) + newRange = [range.start.add([0, 1]), range.end.add([0, 1])] + selection.setBufferRange(newRange, options) + reloadGrammar: -> path = @buffer.getPath() pathContents = @buffer.cachedDiskContents