【问题标题】:Sublime Text 3 - ensure _only_ one trailing newline at end of fileSublime Text 3 - 确保文件末尾_only_一个尾随换行符
【发布时间】:2016-10-14 03:56:13
【问题描述】:

我正在使用 Sublime Text 3,并希望确保在保存时在文件末尾添加一个新行。目前,90% 的时间我的空白都可以完美地工作,使用:

"ensure_newline_at_eof_on_save": true

"trim_trailing_white_space_on_save": true

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

这似乎发生在保存前最后一个换行符上有空格时,配置设置添加一个换行符,然后删除空格。在配置中更改这些设置的顺序并不能解决此问题。

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

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

【问题讨论】:

  • 在什么情况下“每隔一段时间”保存的文件是两个换行符?除非我们能重现问题,否则我们无法帮助您。
  • 谢谢@MattDMo - 好点,我已经更新了这个问题。这是我能看到的唯一导致问题的场合。感谢您的建议。

标签: newline sublimetext3 sublimetext eof sublime-text-plugin


【解决方案1】:

编辑:

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

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

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

  • 提供命令面板条目来更改包的设置;添加/删除将触发插件的语法,并允许或阻止插件以所有语法运行。

原答案:

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

将以下代码保存在具有.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")

【讨论】:

  • 效果很好!非常感谢你把这些放在一起@mattst,如果可以的话,再加一百万:)
  • @SRack 没问题,这是我一段时间以来一直想要的东西。请参阅我编辑的答案,扩展插件可以设置为仅使用特定语法并且还具有其他功能。
  • @SRack 该插件已进一步扩展(请参阅我的帖子已再次编辑),现在可以在 Package Control 上使用。我建议你卸载手动安装,然后使用 Package Control 安装,这样你会自动获得更新。
  • 谢谢你!在自己的设置中找到首选项很奇怪,我最初的想法是这被添加到了常规设置页面,所以不得不将 sn-p 添加到自定义用户设置中让我失望了!但就像一个魅力!刚刚添加{"enable_for_all_syntaxes": true}
猜你喜欢
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-06
  • 2013-04-28
  • 2012-01-27
  • 1970-01-01
相关资源
最近更新 更多