Skip to content

Commit

Permalink
🐎 Make all replacements outside the editor
Browse files Browse the repository at this point in the history
Applies to #16
  • Loading branch information
lee-dohm committed Nov 19, 2015
1 parent 2e5c582 commit 4de9105
Showing 1 changed file with 25 additions and 16 deletions.
41 changes: 25 additions & 16 deletions lib/tabs-to-spaces.coffee
Original file line number Diff line number Diff line change
@@ -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.
#
Expand Down Expand Up @@ -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.
#
Expand All @@ -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

0 comments on commit 4de9105

Please sign in to comment.