sublimetext3 - 在 Sublime Text 中保存时自动运行命令
问题描述
eslint
当我在 Sublime Text 中保存文件.js
或文件时,是否可以自动运行?.jsx
我现在正在使用ESLint sublime 包,但每次使用Cmd + Option + e
.
谢谢!
解决方案
是的,这可以通过一个简单的事件驱动插件来完成,就像我在下面写的那样。
该插件已经过测试,但没有使用eslint
命令测试,因为我不想安装该软件包。显然,任何命令都可以运行而不是eslint
在插件的run_command("eslint")
行中。如果所需的命令采用 args,则可以像这样指定它们:run_command("command", {"arg_1": val, "arg_2": val})
.
该on_post_save_async(self, view)
方法(在我下面的插件中)将在view
保存后调用,即活动缓冲区 - 请注意,这包括自动保存。on_post_save_async()
在单独的线程中运行并且不会阻塞应用程序。您可以更改插件以使用类似的方法,具体取决于您是要eslint
在文件保存之前还是之后调用,以及该方法是应该阻塞应用程序还是在其自己的非阻塞线程中运行。以下是 4 个备选方案:
on_pre_save(self, view)
:在保存视图之前调用。它阻塞应用程序,直到方法返回。on_pre_save_async(self, view)
:在保存视图之前调用。在单独的线程中运行,并且不会阻塞应用程序。on_post_save(self, view)
: 保存视图后调用。它阻塞应用程序,直到方法返回。on_post_save_async(self, view)
: 保存视图后调用。在单独的线程中运行,并且不会阻塞应用程序。[目前在下面的插件中使用。]- Sublime Text
EventListener
文档位于此处- 也有加载方法。
将插件保存在 Sublime Text 包层次结构中的某个位置,并带有.py
扩展名。例如~/.config/sublime-text-3/Packages/User/AutoRunESLintOnSave.py
,它应该立即工作。
import sublime, sublime_plugin
class AutoRunESLintOnSave(sublime_plugin.EventListener):
""" A class to listen for events triggered by ST. """
def on_post_save_async(self, view):
"""
This is called after a view has been saved. It runs in a separate thread
and does not block the application.
"""
file_path = view.file_name()
if not file_path:
return
NOT_FOUND = -1
pos_dot = file_path.rfind(".")
if pos_dot == NOT_FOUND:
return
file_extension = file_path[pos_dot:]
if file_extension.lower() in [".js", ".jsx"]:
view.window().run_command("eslint")
# Slight variations are needed for an ApplicationCommand,
# a WindowCommand, or a TextCommand.
#
# view.run_command("text_command")
# view.window().run_command("window_command")
# sublime.run_command("application_command")
#
# Need args? Use this:
#
# view.run_command("command", {"arg_1": val, "arg_2": val})
您可以使用缓冲区的语法,而不是使用文件扩展名来触发运行eslint
命令,代码更加简洁。
def on_post_save_async(self, view):
""" Syntax version. """
current_syntax = view.settings().get("syntax")
if ("JavaScript.sublime-syntax" in current_syntax
or "JSX.sublime-syntax" in current_syntax):
view.window().run_command("eslint")
# You could, of course, use an exact match:
#
# current_syntax = view.settings().get("syntax")
# if current_syntax == "Packages/JavaScript/JavaScript.sublime-syntax":
# view.window().run_command("eslint")
#
# Run `view.settings().get("syntax")` in the console for the active syntax path.
推荐阅读
- object-detection - ArUco 标记的方向是否与获取对象的姿势相关
- excel - 使用带有 OR 条件的 Sumproduct 计数不返回所需的结果
- node.js - 无法获取简单的字符串
- google-sheets - 如何使用条件格式根据该行中的特定日期突出显示 googlesheets 中的一整行数据
- data-binding - 使用数据绑定时,扩展 BaseObservable 的 ViewModel 的 setter 方法如何工作?
- python - 在 Sequential 或 Functional API 模型中预测分类目标变量时,有没有办法获取类标签?
- c++ - 代码有一个 if else 条件,但代码没有检查我认为的条件
- python - Keras:'TypeError: 无法转换类型的对象
当我建立一个自定义层时发生了 to Tensor' - vue.js - 获取 vue3 composition api shadowroot 的参考
- html - 在平板电脑和 ipad 上自动调整图像大小