Add extension to keep or add a single trailing newline

This commit is contained in:
Kevin Sawicki
2012-12-17 18:30:31 -08:00
parent 07a5672e20
commit 8afe4dbaef
5 changed files with 69 additions and 0 deletions

View File

@@ -807,3 +807,11 @@ describe 'Buffer', ->
buffer.delete([[0, 0], [0, 1]], '')
advanceClock(delay)
expect(contentsModifiedHandler).toHaveBeenCalledWith(differsFromDisk:false)
describe ".append(text)", ->
it "adds text to the end of the buffer", ->
buffer.setText("")
buffer.append("a")
expect(buffer.getText()).toBe "a"
buffer.append("b\nc");
expect(buffer.getText()).toBe "ab\nc"

View File

@@ -189,6 +189,9 @@ class Buffer
@change(new Range(startPoint, endPoint), '')
append: (text) ->
@insert(@getEofPosition(), text)
insert: (point, text) ->
@change(new Range(point, point), text)

View File

@@ -0,0 +1 @@
module.exports = require 'single-trailing-newline/src/single-trailing-newline'

View File

@@ -0,0 +1,39 @@
SingleTrailingNewline = require 'single-trailing-newline'
RootView = require 'root-view'
fs = require 'fs'
describe "SingleTrailingNewline", ->
[rootView, editor, path] = []
beforeEach ->
path = "/tmp/atom-whitespace.txt"
fs.write(path, "")
rootView = new RootView(path)
SingleTrailingNewline.activate(rootView)
rootView.focus()
editor = rootView.getActiveEditor()
afterEach ->
fs.remove(path) if fs.exists(path)
rootView.remove()
it "adds a trailing newline when there is no trailing newline", ->
editor.insertText "foo"
editor.save()
expect(editor.getText()).toBe "foo\n"
it "removes extra trailing newlines and only keeps one", ->
editor.insertText "foo\n\n\n\n"
editor.save()
expect(editor.getText()).toBe "foo\n"
it "leaves a buffer with a single trailing newline untouched", ->
editor.insertText "foo\nbar\n"
editor.save()
expect(editor.getText()).toBe "foo\nbar\n"
it "leaves an empty buffer untouched", ->
editor.insertText ""
editor.save()
expect(editor.getText()).toBe ""

View File

@@ -0,0 +1,18 @@
module.exports =
name: "Add a single trailing newline"
activate: (rootView) ->
for buffer in rootView.project.getBuffers()
@addSingleTrailingNewlineBeforeSave(buffer)
rootView.project.on 'new-buffer', (buffer) =>
@addSingleTrailingNewlineBeforeSave(buffer)
addSingleTrailingNewlineBeforeSave: (buffer) ->
buffer.on 'before-save', ->
if buffer.getLastLine() is ''
row = buffer.getLastRow()
while row and buffer.lineForRow(--row) is ''
buffer.deleteRow(row)
else
buffer.append('\n')