Adds snippets for python and tex

master
Jonathan Hodgson 4 years ago
parent 3b3e0b2d16
commit 5291e0587f
  1. 246
      UltiSnips/python.snippets
  2. 336
      UltiSnips/tex.snippets

@ -0,0 +1,246 @@
##########
# COMMON #
##########
# The smart def and smart class snippets use a global option called
# "g:ultisnips_python_style" which, if set to "doxygen" will use doxygen
# style comments in docstrings.
global !p
NORMAL = 0x1
DOXYGEN = 0x2
SPHINX = 0x3
GOOGLE = 0x4
NUMPY = 0x5
JEDI = 0x6
SINGLE_QUOTES = "'"
DOUBLE_QUOTES = '"'
class Arg(object):
def __init__(self, arg):
self.arg = arg
name_and_type = arg.split('=')[0].split(':')
self.name = name_and_type[0].strip()
self.type = name_and_type[1].strip() if len(name_and_type) == 2 else None
def __str__(self):
return self.name
def __unicode__(self):
return self.name
def is_kwarg(self):
return '=' in self.arg
def is_vararg(self):
return '*' in self.name
def get_args(arglist):
args = [Arg(arg) for arg in arglist.split(',') if arg]
args = [arg for arg in args if arg.name != 'self']
return args
def get_quoting_style(snip):
style = snip.opt("g:ultisnips_python_quoting_style", "double")
if style == 'single':
return SINGLE_QUOTES
return DOUBLE_QUOTES
def triple_quotes(snip):
style = snip.opt("g:ultisnips_python_triple_quoting_style")
if not style:
return get_quoting_style(snip) * 3
return (SINGLE_QUOTES if style == 'single' else DOUBLE_QUOTES) * 3
def triple_quotes_handle_trailing(snip, quoting_style):
"""
Generate triple quoted strings and handle any trailing quote char,
which might be there from some autoclose/autopair plugin,
i.e. when expanding ``"|"``.
"""
if not snip.c:
# Do this only once, otherwise the following error would happen:
# RuntimeError: The snippets content did not converge: …
_, col = vim.current.window.cursor
line = vim.current.line
# Handle already existing quote chars after the trigger.
_ret = quoting_style * 3
while True:
try:
nextc = line[col]
except IndexError:
break
if nextc == quoting_style and len(_ret):
_ret = _ret[1:]
col = col+1
else:
break
snip.rv = _ret
else:
snip.rv = snip.c
def get_style(snip):
style = snip.opt("g:ultisnips_python_style", "normal")
if style == "doxygen": return DOXYGEN
elif style == "sphinx": return SPHINX
elif style == "google": return GOOGLE
elif style == "numpy": return NUMPY
elif style == "jedi": return JEDI
else: return NORMAL
def format_arg(arg, style):
if style == DOXYGEN:
return "@param %s TODO" % arg
elif style == SPHINX:
return ":param %s: TODO" % arg
elif style == NORMAL:
return ":%s: TODO" % arg
elif style == GOOGLE:
return "%s (TODO): TODO" % arg
elif style == JEDI:
return ":type %s: TODO" % arg
elif style == NUMPY:
return "%s : TODO" % arg
def format_return(style):
if style == DOXYGEN:
return "@return: TODO"
elif style in (NORMAL, SPHINX, JEDI):
return ":returns: TODO"
elif style == GOOGLE:
return "Returns: TODO"
def write_docstring_args(args, snip):
if not args:
snip.rv += ' {0}'.format(triple_quotes(snip))
return
snip.rv += '\n' + snip.mkline('', indent='')
style = get_style(snip)
if style == GOOGLE:
write_google_docstring_args(args, snip)
elif style == NUMPY:
write_numpy_docstring_args(args, snip)
else:
for arg in args:
snip += format_arg(arg, style)
def write_google_docstring_args(args, snip):
kwargs = [arg for arg in args if arg.is_kwarg()]
args = [arg for arg in args if not arg.is_kwarg()]
if args:
snip += "Args:"
snip.shift()
for arg in args:
snip += format_arg(arg, GOOGLE)
snip.unshift()
snip.rv += '\n' + snip.mkline('', indent='')
if kwargs:
snip += "Kwargs:"
snip.shift()
for kwarg in kwargs:
snip += format_arg(kwarg, GOOGLE)
snip.unshift()
snip.rv += '\n' + snip.mkline('', indent='')
def write_numpy_docstring_args(args, snip):
if args:
snip += "Parameters"
snip += "----------"
kwargs = [arg for arg in args if arg.is_kwarg()]
args = [arg for arg in args if not arg.is_kwarg()]
if args:
for arg in args:
snip += format_arg(arg, NUMPY)
if kwargs:
for kwarg in kwargs:
snip += format_arg(kwarg, NUMPY) + ', optional'
snip.rv += '\n' + snip.mkline('', indent='')
def write_init_body(args, parents, snip):
parents = [p.strip() for p in parents.split(",")]
parents = [p for p in parents if p != 'object']
for p in parents:
snip += p + ".__init__(self)"
if parents:
snip.rv += '\n' + snip.mkline('', indent='')
for arg in filter(lambda arg: not arg.is_vararg(), args):
snip += "self._%s = %s" % (arg, arg)
def write_slots_args(args, snip):
quote = get_quoting_style(snip)
arg_format = quote + '_%s' + quote
args = [arg_format % arg for arg in args]
snip += '__slots__ = (%s,)' % ', '.join(args)
def write_function_docstring(t, snip):
"""
Writes a function docstring with the current style.
:param t: The values of the placeholders
:param snip: UltiSnips.TextObjects.SnippetUtil object instance
"""
snip.rv = ""
snip >> 1
args = get_args(t[2])
if args:
write_docstring_args(args, snip)
style = get_style(snip)
if style == NUMPY:
snip += 'Returns'
snip += '-------'
snip += 'TODO'
else:
snip += format_return(style)
snip.rv += '\n' + snip.mkline('', indent='')
snip += triple_quotes(snip)
def get_dir_and_file_name(snip):
return os.getcwd().split(os.sep)[-1] + '.' + snip.basename
endglobal
snippet ! "entry function with docstrings and if __name__" b
def ${1:main}(`!p
if snip.indent:
snip.rv = 'self' + (", " if len(t[2]) else "")`${2:arg1}):
`!p snip.rv = triple_quotes(snip)`${4:Main entry function.}`!p
write_function_docstring(t, snip) `
${5:${VISUAL:pass}}
if __name__ == `!p snip.rv = get_quoting_style(snip)`__main__`!p snip.rv = get_quoting_style(snip)`:
$1()
endsnippet
snippet ifarg " with docstrings" b
if len(sys.argv) > $1 and sys.argv[$1] == "${2:something}":
$0
endsnippet

@ -0,0 +1,336 @@
global !p
texMathZones = ['texMathZone' + x for x in ['A', 'AS', 'B', 'BS', 'C', 'CS', 'D', 'DS', 'E', 'ES', 'F', 'FS', 'G', 'GS', 'H', 'HS', 'I', 'IS', 'J', 'JS', 'K', 'KS', 'L', 'LS', 'DS', 'V', 'W', 'X', 'Y', 'Z', 'AmsA', 'AmsB', 'AmsC', 'AmsD', 'AmsE', 'AmsF', 'AmsG', 'AmsAS', 'AmsBS', 'AmsCS', 'AmsDS', 'AmsES', 'AmsFS', 'AmsGS' ]]
texIgnoreMathZones = ['texMathText']
texMathZoneIds = vim.eval('map('+str(texMathZones)+", 'hlID(v:val)')")
texIgnoreMathZoneIds = vim.eval('map('+str(texIgnoreMathZones)+", 'hlID(v:val)')")
ignore = texIgnoreMathZoneIds[0]
def math():
synstackids = vim.eval("synstack(line('.'), col('.') - (col('.')>=2 ? 1 : 0))")
try:
first = next(i for i in reversed(synstackids) if i in texIgnoreMathZoneIds or i in texMathZoneIds)
return first != ignore
except StopIteration:
return False
def create_table(snip):
rows = snip.buffer[snip.line].split('x')[0]
cols = snip.buffer[snip.line].split('x')[1]
int_val = lambda string: int(''.join(s for s in string if s.isdigit()))
rows = int_val(rows)
cols = int_val(cols)
offset = cols + 1
old_spacing = snip.buffer[snip.line][:snip.buffer[snip.line].rfind('\t') + 1]
snip.buffer[snip.line] = ''
final_str = old_spacing + "\\begin{tabular}{|" + "|".join(['$' + str(i + 1) for i in range(cols)]) + "|}\n"
for i in range(rows):
final_str += old_spacing + '\t'
final_str += " & ".join(['$' + str(i * cols + j + offset) for j in range(cols)])
final_str += " \\\\\\\n"
final_str += old_spacing + "\\end{tabular}\n$0"
snip.expand_anon(final_str)
def add_row(snip):
row_len = int(''.join(s for s in snip.buffer[snip.line] if s.isdigit()))
old_spacing = snip.buffer[snip.line][:snip.buffer[snip.line].rfind('\t') + 1]
snip.buffer[snip.line] = ''
final_str = old_spacing
final_str += " & ".join(['$' + str(j + 1) for j in range(row_len)])
final_str += " \\\\\\"
snip.expand_anon(final_str)
endglobal
snippet article "article template" b
\documentclass[12pt]{article}
\usepackage{geometry} % Required for adjusting page dimensions
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{longtable}
\usepackage{booktabs}
\usepackage[UKenglish]{babel}
\geometry{
paper=a4paper, % Change to letterpaper for US letter
top=3cm, % Top margin
bottom=1.5cm, % Bottom margin
left=4.5cm, % Left margin
right=4.5cm, % Right margin
%showframe, % Uncomment to show how the type block is set on the page
}
\title{$1}
\author{Jonathan Hodgson}
\date{\today}
\begin{document}
\maketitle
\section{$2}
$0
\end{document}
endsnippet
snippet standalone "standalone template" b
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
$0
\end{tikzpicture}
\end{document}
endsnippet
snippet "b(egin)?" "begin{} / end{}" br
\begin{${1:something}}
${0:${VISUAL}}
\end{$1}
endsnippet
snippet frame "frame environment" b
\begin{frame}
\frametitle{${1:title}}
${0:${VISUAL}}
\note{%
}
\end{frame}
endsnippet
snippet abs "abstract environment" b
\begin{abstract}
$0
\end{abstract}
endsnippet
snippet tab "tabular / array environment" b
\begin{${1:t}${1/(t)$|(a)$|(.*)/(?1:abular)(?2:rray)/}}{${2:c}}
$0${2/(?<=.)(c|l|r)|./(?1: & )/g}
\end{$1${1/(t)$|(a)$|(.*)/(?1:abular)(?2:rray)/}}
endsnippet
pre_expand "create_table(snip)"
snippet "gentbl(\d+)x(\d+)" "Generate table of *width* by *height*" r
endsnippet
pre_expand "add_row(snip)"
snippet "tr(\d+)" "Add table row of dimension ..." r
endsnippet
snippet table "Table environment" b
\begin{table}[${1:htpb}]
\centering
\caption{${2:caption}}
\label{tab:${3:label}}
\begin{${4:t}${4/(t)$|(a)$|(.*)/(?1:abular)(?2:rray)/}}{${5:c}}
$0${5/(?<=.)(c|l|r)|./(?1: & )/g}
\end{$4${4/(t)$|(a)$|(.*)/(?1:abular)(?2:rray)/}}
\end{table}
endsnippet
snippet fig "Figure environment" b
\begin{figure}[${2:htpb}]
\centering
\includegraphics[width=${3:0.8}\linewidth]{${4:name.ext}}
\caption{${4/(\w+)\.\w+/\u$1/}$0}%
\label{fig:${4/(\w+)\.\w+/$1/}}
\end{figure}
endsnippet
snippet enum "Enumerate" b
\begin{enumerate}
\item $0
\end{enumerate}
endsnippet
snippet item "Itemize" b
\begin{itemize}
\item $0
\end{itemize}
endsnippet
snippet desc "Description" b
\begin{description}
\item[$1] $0
\end{description}
endsnippet
snippet it "Individual item" b
\item $0
endsnippet
snippet part "Part" b
\part{${1:part name}}%
\label{prt:${2:${1/(\w+)|\W+/(?1:\L$0\E:_)/ga}}}
$0
endsnippet
snippet cha "Chapter" b
\chapter{${1:chapter name}}%
\label{cha:${2:${1/\\\w+\{(.*?)\}|\\(.)|(\w+)|([^\w\\]+)/(?4:_:\L$1$2$3\E)/ga}}}
$0
endsnippet
snippet sec "Section"
\section{${1:${VISUAL:section name}}}%
\label{sec:${2:${1/\\\w+\{(.*?)\}|\\(.)|(\w+)|([^\w\\]+)/(?4:_:\L$1$2$3\E)/ga}}}
$0
endsnippet
snippet sec* "Section"
\section*{${1:${VISUAL:section name}}}%
\label{sec:${2:${1/\\\w+\{(.*?)\}|\\(.)|(\w+)|([^\w\\]+)/(?4:_:\L$1$2$3\E)/ga}}}
${0}
endsnippet
snippet sub "Subsection"
\subsection{${1:${VISUAL:subsection name}}}%
\label{sub:${2:${1/\\\w+\{(.*?)\}|\\(.)|(\w+)|([^\w\\]+)/(?4:_:\L$1$2$3\E)/ga}}}
$0
endsnippet
snippet sub* "Subsection"
\subsection*{${1:${VISUAL:subsection name}}}%
\label{sub:${2:${1/\\\w+\{(.*?)\}|\\(.)|(\w+)|([^\w\\]+)/(?4:_:\L$1$2$3\E)/ga}}}
${0}
endsnippet
snippet ssub "Subsubsection"
\subsubsection{${1:${VISUAL:subsubsection name}}}%
\label{ssub:${2:${1/\\\w+\{(.*?)\}|\\(.)|(\w+)|([^\w\\]+)/(?4:_:\L$1$2$3\E)/ga}}}
$0
endsnippet
snippet ssub* "Subsubsection"
\subsubsection*{${1:${VISUAL:subsubsection name}}}%
\label{ssub:${2:${1/\\\w+\{(.*?)\}|\\(.)|(\w+)|([^\w\\]+)/(?4:_:\L$1$2$3\E)/ga}}}
${0}
endsnippet
snippet par "Paragraph"
\paragraph{${1:${VISUAL:paragraph name}}}%
\label{par:${2:${1/\\\w+\{(.*?)\}|\\(.)|(\w+)|([^\w\\]+)/(?4:_:\L$1$2$3\E)/ga}}}
$0
endsnippet
snippet subp "Subparagraph"
\subparagraph{${1:${VISUAL:subparagraph name}}}%
\label{par:${2:${1/\\\w+\{(.*?)\}|\\(.)|(\w+)|([^\w\\]+)/(?4:_:\L$1$2$3\E)/ga}}}
$0
endsnippet
snippet ac "Acroynm normal" b
\ac{${1:acronym}}
$0
endsnippet
snippet acl "Acroynm expanded" b
\acl{${1:acronym}}
$0
endsnippet
snippet ni "Non-indented paragraph" b
\noindent
$0
endsnippet
snippet pac "Package" b
\usepackage`!p snip.rv='[' if t[1] else ""`${1:options}`!p snip.rv = ']' if t[1] else ""`{${2:package}}$0
endsnippet
snippet lp "Long parenthesis"
\left(${1:${VISUAL:contents}}\right)$0
endsnippet
snippet "mint(ed)?( (\S+))?" "Minted code typeset" br
\begin{minted}{${1:language}}
${2:${VISUAL:code}}
\end{minted}
$0
endsnippet
context "math()"
snippet '([A-Za-z])(\d)' "auto subscript" wrA
`!p snip.rv = match.group(1)`_`!p snip.rv = match.group(2)`
endsnippet
context "math()"
snippet '([A-Za-z])_(\d\d)' "auto subscript2" wrA
`!p snip.rv = match.group(1)`_{`!p snip.rv = match.group(2)`}
endsnippet
context "math()"
snippet // "Fraction" iA
\\frac{$1}{$2}$0
endsnippet
snippet / "Fraction" i
\\frac{${VISUAL}}{$1}$0
endsnippet
context "math()"
snippet '((\d+)|(\d*)(\\)?([A-Za-z]+)((\^|_)(\{\d+\}|\d))*)/' "symbol frac" wrA
\\frac{`!p snip.rv = match.group(1)`}{$1}$0
endsnippet
context "math()"
snippet sq "\sqrt{}" iA
\sqrt{${1:${VISUAL}}} $0
endsnippet
snippet '^.*\)/' "() Fraction" wrA
`!p
stripped = match.string[:-1]
depth = 0
i = len(stripped) - 1
while True:
if stripped[i] == ')': depth += 1
if stripped[i] == '(': depth -= 1
if depth == 0: break;
i -= 1
snip.rv = stripped[0:i] + "\\frac{" + stripped[i+1:-1] + "}"
`{$1}$0
endsnippet
# vim:ft=snippets:
Loading…
Cancel
Save