From 4de910566e4d64c58348dd11edf09b2f6522166d Mon Sep 17 00:00:00 2001 From: Lee Dohm Date: Wed, 18 Nov 2015 18:57:32 -0800 Subject: [PATCH] :racehorse: Make all replacements outside the editor Applies to #16 --- lib/tabs-to-spaces.coffee | 41 ++++++++++++++++++++++++--------------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/lib/tabs-to-spaces.coffee b/lib/tabs-to-spaces.coffee index fb69da0..b413d60 100644 --- a/lib/tabs-to-spaces.coffee +++ b/lib/tabs-to-spaces.coffee @@ -1,10 +1,10 @@ # Public: Handles the interface between Atom and the Tabs to Spaces package. class TabsToSpaces # Private: Regular expression for matching a chunk of whitespace on a line. - allWhitespace: /[ \t]+/g + allWhitespace: /[ \t]+/gm # Private: Regular expression for matching leading whitespace on a line. - leadingWhitespace: /^[ \t]+/g + leadingWhitespace: /^[ \t]+/gm # Public: Converts all leading spaces to tabs in the current buffer. # @@ -56,19 +56,25 @@ class TabsToSpaces # # * `editor` {TextEditor} in which to perform the replacement. replaceAllWhitespaceWithSpaces: (editor) -> - editor.transact => - editor.scan @allWhitespace, ({match, replace}) => - count = @countSpaces(match[0]) - replace("#{@multiplyText(' ', count)}") + originalText = editor.getText() + newText = originalText.replace @allWhitespace, (match) => + count = @countSpaces(match) + @multiplyText(' ', count) + + if newText isnt originalText + editor.setText(newText) # Private: Replaces leading whitespace with the appropriate number of spaces. # # * `editor` {TextEditor} in which to perform the replacement. replaceWhitespaceWithSpaces: (editor) -> - editor.transact => - editor.scan @leadingWhitespace, ({match, replace}) => - count = @countSpaces(match[0]) - replace("#{@multiplyText(' ', count)}") + originalText = editor.getText() + newText = originalText.replace @leadingWhitespace, (match) => + count = @countSpaces(match) + @multiplyText(' ', count) + + if newText isnt originalText + editor.setText(newText) # Private: Replaces leading whitespace with the appropriate number of tabs and spaces. # @@ -78,11 +84,14 @@ class TabsToSpaces # # * `editor` {TextEditor} in which to perform the replacement. replaceWhitespaceWithTabs: (editor) -> - editor.transact => - editor.scan @leadingWhitespace, ({match, replace}) => - count = @countSpaces(match[0]) - tabs = count // @editor.getTabLength() - spaces = count %% @editor.getTabLength() - replace("#{@multiplyText('\t', tabs)}#{@multiplyText(' ', spaces)}") + originalText = editor.getText() + newText = originalText.replace @leadingWhitespace, (match) => + count = @countSpaces(match) + tabs = count // editor.getTabLength() + spaces = count %% editor.getTabLength() + "#{@multiplyText('\t', tabs)}#{@multiplyText(' ', spaces)}" + + if newText isnt originalText + editor.setText(newText) module.exports = new TabsToSpaces