A docstring

C change img/inc/fig snippet into id
U update em/st with CJK detection
This commit is contained in:
Meng Zhuo 2013-06-26 09:48:50 +08:00
parent 8e1e176998
commit 9ab873b6ea

View File

@ -4,6 +4,7 @@
# General Stuff # # General Stuff #
########################################################################### ###########################################################################
global !p global !p
import vim
from os import path as ospath from os import path as ospath
from string import Template from string import Template
import re import re
@ -29,17 +30,32 @@ DIRECTIVES = ['topic','sidebar','math','epigraph',
'raw'] 'raw']
NONE_CONTENT_DIRECTIVES = ['rubric', 'contents', 'header', NONE_CONTENT_DIRECTIVES = ['rubric', 'contents', 'header',
'footer', 'date', 'include', 'title' 'footer', 'date', 'include', 'title']
]
INCLUDABLE_DIRECTIVES_INDEX = {'img':'image', INCLUDABLE_DIRECTIVES = ['image', 'figure', 'include']
'fig':'figure', # CJK chars
'inc':'include'} # http://stackoverflow.com/questions/2718196/find-all-chinese-text-in-a-string-using-python-and-regex
CJK_RE = re.compile(u'[⺀-⺙⺛-⻳⼀-⿕々〇〡-〩〸-〺〻㐀-䶵一-鿃豈-鶴侮-頻並-龎]', re.UNICODE)
def has_cjk(char):
"""
Detect char contains CJK character
:param char: characters needs to be detect
"""
try:
CJK_RE.finditer(char).next()
except StopIteration:
return False
else:
return True
def real_filename(filename): def real_filename(filename):
# peal extension name off if possible """peal extension name off if possible
# i.e. "foo.bar.png will return "foo.bar" # i.e. "foo.bar.png will return "foo.bar"
names=filename.split('.') """
return ".".join(names[:-1]) if len(names) > 1 else filename return ospath.splitext(filename)[0]
def check_file_exist(rst_path, relative_path): def check_file_exist(rst_path, relative_path):
""" """
@ -53,8 +69,6 @@ def check_file_exist(rst_path, relative_path):
if ospath.isfile(abs_path): if ospath.isfile(abs_path):
return abs_path return abs_path
#TODO: File preview
#TODO: File list complete
def rst_char_len(char): def rst_char_len(char):
""" """
@ -91,23 +105,40 @@ def look_up_directives(regex, fpath):
:return: list, empty list if nothing match :return: list, empty list if nothing match
""" """
try:
with open(fpath) as source: with open(fpath) as source:
match = re.findall(regex, source.read()) match = re.findall(regex, source.read())
except IOError:
match = []
return match return match
def get_popular_code_type(path): def get_popular_code_type():
# find most popular code type in the given rst """
types = look_up_directives(r'[:|\.\.\s]code::?\s(\w+)', path) find most popular code type in the given rst
:param path: file to detect
:return: string, most popular code type in file
"""
buf = "".join(vim.current.buffer)
types = re.findall(r'[:|\.\.\s]code::?\s(\w+)', buf)
try: try:
popular_type = Counter(types).most_common()[0][0] popular_type = Counter(types).most_common()[0][0]
except IndexError: except IndexError:
popular_type = "lua" # Don't break default popular_type = "lua" # Don't break default
return popular_type return popular_type
def complete(t, opts): def complete(t, opts):
"""
get options that start with t
:param t: query string
:param opts: list that needs to be completed
:return: a string that start with t
"""
msg = "({0})" msg = "({0})"
if t: if t:
opts = [ m[len(t):] for m in opts if m.startswith(t) ] opts = [ m[len(t):] for m in opts if m.startswith(t) ]
@ -165,22 +196,26 @@ $0
endsnippet endsnippet
snippet em "Emphasize string" i snippet em "Emphasize string" i
*${1:${VISUAL:Em}}* $0 `!p
endsnippet # dirty but works with CJK charactor detection
if has_cjk(vim.current.line):
# the CJK characters doesn't had space to sperate them, like "我强调" snip.rv ="\ "`*${1:${VISUAL:Em}}*`!p
# should be "我\ *强调*\ " if has_cjk(vim.current.line):
# Therefor we need special snippet snip.rv ="\ "
snippet ec "Emphasize string (CJK)" w else:
\ *${1:${VISUAL:Em}}*\ $0 snip.rv = " "
`$0
endsnippet endsnippet
snippet st "Strong string" i snippet st "Strong string" i
**${1:${VISUAL:Strong}}** $0 `!p
endsnippet if has_cjk(vim.current.line):
snip.rv ="\ "`**${1:${VISUAL:Strong}}**`!p
snippet sc "Strong string (CJK)" w if has_cjk(vim.current.line):
\ **${1:${VISUAL:Strong}}**\ $0 snip.rv ="\ "
else:
snip.rv = " "
`$0
endsnippet endsnippet
snippet "li(st)? (?P<num>\d+)" "List" br snippet "li(st)? (?P<num>\d+)" "List" br
@ -201,7 +236,7 @@ endsnippet
# More Specialized Stuff. # # More Specialized Stuff. #
########################################################################### ###########################################################################
snippet cb "Code Block" b snippet cb "Code Block" b
.. code-block:: ${1:`!p snip.rv = get_popular_code_type(path)`} .. code-block:: ${1:`!p snip.rv = get_popular_code_type()`}
${2:code} ${2:code}
@ -210,29 +245,28 @@ endsnippet
# match snippets : # match snippets :
# img, inc, fig # img, inc, fig
snippet "(?P<shortcut>^img|inc|fig)" "Includable Block" !br snippet id "Includable Directives" b
`!p `!p
#TODO: Import img.template in rst relative path? real_name=real_filename(ospath.basename(t[2]))
real_name=real_filename(ospath.basename(t[1])) di=t[1][:2]
di=INCLUDABLE_DIRECTIVES_INDEX.get(match.groupdict()['shortcut'], 'include')
link="" link=""
content="" content=""
if di in ['image']: if di == 'im':
link = "|{0}|".format(real_name) link = "|{0}|".format(real_name)
if di == 'figure': if di == 'fi':
content=""" content="""
:alt: {0} :alt: {0}
{0}""".format(real_name) {0}""".format(real_name)
`
snip.rv = ".. {link}{di}:: ".format(di=di,link=link) ..`!p snip.rv = " %s" % link if link else ""` $1`!p snip.rv=complete(t[1], INCLUDABLE_DIRECTIVES)`:: ${2:file}`!p if content:
`${1:file}`!p if content:
snip.rv +=" "+content` snip.rv +=" "+content`
`!p `!p
# Tip of whether file is exist in comment type # Tip of whether file is exist in comment type
if not check_file_exist(path, t[1]): if not check_file_exist(path, t[2]):
snip.rv='.. FILE {0} does not exist'.format(t[1]) snip.rv='.. FILE {0} does not exist'.format(t[2])
else: else:
snip.rv="" snip.rv=""
`$0 `$0
@ -259,7 +293,7 @@ $0
endsnippet endsnippet
#it will be trigger at start of line or after a word #it will be trigger at start of line or after a word
snippet ro "Text Roles" b snippet ro "Text Roles" w
\ :$1`!p snip.rv=complete(t[1], \ :$1`!p snip.rv=complete(t[1],
TEXT_ROLES+look_up_directives(TEXT_ROLES_REGEX, TEXT_ROLES+look_up_directives(TEXT_ROLES_REGEX,
path))`:\`$2\`\ path))`:\`$2\`\