Sublime Text 3 - 确保 _only_ 文件末尾有一个尾随换行符

Sublime Text 3 - ensure _only_ one trailing newline at end of file

我正在使用 Sublime Text 3 并希望确保我在保存时 在文件末尾得到一个新行。目前,我的 whitespace 有 90% 的时间完美运行,使用:

"ensure_newline_at_eof_on_save": true

"trim_trailing_white_space_on_save": true

... 但是,文件每隔一段时间就会在文件末尾保存 两个 新行。

当保存前最后一个换行符上有白色 space 时会出现这种情况,配置设置添加换行符,然后 删除白色space。在配置中更改这些设置的顺序无法解决此问题。

我没能找到其他原因,所以这很可能是唯一的原因,但理想情况下我想检查保存时是否有不止一个换行符。

除非文件末尾正好有一个新行,否则我工作的环境无法通过测试,所以这有点麻烦。我的问题是是否有一个插件/方法可以更严格地保存,确保只有一个尾随新行。

编辑:

我已经扩展了我在下面发布的插件,现在可以使用 Package Control.

安装
  • Single Trailing Newline 是一个 Sublime Text 包,它确保文件末尾只有一个尾随换行符。它的工作原理是删除文件末尾的所有空格和换行符(如果有的话),然后插入一个换行符。

  • 每次保存文件时插件可以自动设置为运行。这在默认情况下是禁用的,但通过更改设置,它可以对所有文件或仅对特定语法的文件启用。

  • 提供命令选项板条目以更改程序包的设置; adding/removing 将触发插件的语法,并允许或阻止插件使用 运行 所有语法。

原答案:

这是一个可以做到这一点的插件。

将以下代码保存在扩展名为 .py 的文件中,例如EnsureExactlyOneTrailingNewLineAtEndOfFileOnSave.py 并将文件复制到您的包目录中。当您保存文件时,它会去除文件末尾的所有尾随换行符和空格,然后添加一个尾随换行符。

#
# A Sublime Text plugin to ensure that exactly one trailing
# newline is at the end of all files when files are saved.
#
# License: MIT License
#

import sublime, sublime_plugin

class OneTrailingNewLineAtEndOfFileOnSaveListener(sublime_plugin.EventListener):

    def on_pre_save(self, view):
        # A sublime_plugin.TextCommand class is needed for an edit object.
        view.run_command("one_trailing_new_line_at_end_of_file")
        return None

class OneTrailingNewLineAtEndOfFileCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        # Ignore empty files.
        if self.view.size() == 0:
            return

        # Work backwards from the end of the file looking for the last
        # significant char (one that is neither whitespace nor a newline).

        pos = self.view.size() - 1
        whitespace = ("\n", "\t", " ")

        while pos >= 0 and self.view.substr(pos) in whitespace:
            pos -= 1

        # Delete from the last significant char to the end of
        # the file and then add a single trailing newline.

        del_region = sublime.Region(pos + 1, self.view.size())
        self.view.erase(edit, del_region)
        self.view.insert(edit, self.view.size(), "\n")