sublime中编写Markdown文件自动添加行尾空格换行
sublime中编写Markdown文件自动添加行尾空格换行
作用
我们在写Markdown的时候,换行并不会生效,会自动连接起来,除非在后面添加两个空格,或者是两个换行。
所以,我想在保存文件的时候,自动在后面添加两个空格。当然,这个只需要在文章段落,以及列表中生效,其他的,比如标题或者代码块就不需要。
代码
import sublime
import sublime_plugin
import re
class MarkdownAutolineListener(sublime_plugin.EventListener):
def on_pre_save(self, view):
if view and view.syntax().name == 'Markdown':
view.run_command("markdown_autoline")
class MarkdownAutolineCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = sublime.Region(0, self.view.size())
content = self.view.substr(region)
line_regions = self.view.lines(region)
region_num = len(line_regions)
sel_rows = self.get_sel_rows()
sep = self.get_sep()
lines = content.split(sep)
new_content = ''
row = 0
for line in lines:
if row != 0:
new_content += sep
new_content += line
# skip: 1. lines already added 2 spaces; 2. last empty line; 3. lines with cursors; 4. empty/space lines
if not(line.endswith(' ')) and row < region_num and row not in sel_rows and not re.match(r'^[ \t]*$', line):
scope_name = self.view.scope_name(line_regions[row].begin())
if re.match(r'.*(paragraph.markdown|markup.list)', scope_name):
if line.endswith(' '): # add 1 space
new_content += ' '
else: # add 2 spaces
new_content += ' '
row += 1
# change once, easy to undo, if not changed don't replace
if content != new_content:
self.view.replace(edit, region, new_content)
def get_sep(self):
endings = self.view.line_endings()
if endings == 'unix':
sep = '\n'
elif endings == 'windows':
sep = '\n\r'
else:
sep = '\n'
return sep
def get_sel_rows(self):
sels = self.view.sel()
rows = []
for s in sels:
rows.append(self.view.rowcol(s.begin())[0])
return rows