[英]Custom AutoFormat in Sublime Text
有沒有辦法使用正則表達式進行格式化,但在當前文檔上綁定一些替換所有表達式以進行格式化? 我經常使用滿是正則表達式的手來清理我的 SQL 腳本,而且我不想每次都手動完成。 有沒有辦法讓所有這些熱鍵同時運行?
這無關緊要,但這里是我使用的 SQL Regex 腳本,其中 -- 是注釋,第二行是替換變量。 如果您願意,您可以將其用作參考或將其用於您自己的腳本。
-- Add a space between = or + or * or / phrases
([@\w\d'")\]])([+=*\/]|<>|<=|>=|>|<)(['"@\w\d(-\[])
$1 $2 $3
-- Remove unnessisary space at the end of a line
([-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/\d\w])\h+$
$1
-- Add space between minus sign. Doesn't work after a letter because it could be mistaken with a hyphan.
([\d)\]])([-])([\w\d(\[])
$1 $2 $3
-- Add a space after a , that comes after a letter, ), ', or "
([)\w\d'")])([,])([\w\d'"(@])
$1$2 $3
-- Fix dates in comments that are messed up from adding spacing to /
\* *(Created on: )?(\d{1,2}) *\/ *(\d{1,2}) *\/ *(\d)
* $1$2/$3/$4
正如 Keith Hall 指出的, packagecontrol.io/packages/RegReplace可以很好地完成這項工作。
但是,僅供參考,如果您想直接創建這樣的自定義命令,它將如下所示:
下拉Preferences > Browse Packages
...,然后進入 User 文件夾。
創建一個名為sql_cleanup.py
的文件並粘貼以下內容:
from sublime_plugin import TextCommand
import re
# Sublime automatically recognizes this class name as being the "sql_fixup" command
class SqlFixupCommand(TextCommand):
def run(self, edit):
self._edit = edit
self._process_text()
def _get_file_content(self):
return self.view.substr(sublime.Region(0, self.view.size()))
def _update_file(self, doc):
self.view.replace(self._edit, sublime.Region(0, self.view.size()), doc)
def _process_text(self):
txt = self._get_file_content()
# Add a space between = or + or * or / phrases
txt = re.sub(r"([@\w\d'\")\]])([+=*\/]|<>|<=|>=|>|<)(['\"@\w\d(-\[])", r"\1 \2 \3", txt)
# Remove unnecessary space at the end of a line
txt = re.sub(r"([-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/\d\w])\h+$", r"\1", txt)
# Add space between minus sign. Doesn't work after a letter because it could be mistaken with a hyphen.
txt = re.sub(r"([\d)\]])([-])([\w\d(\[])", r"\1 \2 \3", txt)
# Add a space after a , that comes after a letter, ), ', or "
txt = re.sub(r"([)\w\d'\")])([,])([\w\d'\"(@])", r"\1\2 \3", txt)
# Fix dates in comments that are messed up from adding spacing to /
txt = re.sub(r"\* *(Created on: )?(\d{1,2}) *\/ *(\d{1,2}) *\/ *(\d)", r"* \1\2/\3/\4", txt)
self._update_file(txt)
sql_cleanup.sublime-commands
的文件並粘貼以下內容:[
{ "caption": "SQL: Fix Up Code","command": "sql_fixup" },
]
Main.sublime-menu
的文件,其中包含以下內容:(如果已經有一個名為 SQL 的子菜單,那么這會將其添加到任何已經存在的菜單中)那里。)[
{
"id": "tools",
"children": [
{
"caption": "SQL",
"id": "sql-tools",
"mnemonic": "S",
"children": [
{
"caption": "Fix Up Code",
"command": "sql_fixup" },
]
}
]
},
]
Default (Windows).sublime-keymap
(或您所在的任何平台)的文件,其內容類似於以下內容:(此示例將其綁定到按住 CTRL 鍵並鍵入 UQ .)[
{ "keys": ["ctrl+u", "ctrl+q"], "command": "sql_fixup" },
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.