/vim/after/ftplugin/python_snippets.vim
Vim Script | 202 lines | 145 code | 21 blank | 36 comment | 20 complexity | 3a56a5e767dd7f11785039a68a9fd526 MD5 | raw file
1if !exists('loaded_snippet') || &cp
2 finish
3endif
4
5" Given a string containing a list of arguments (e.g. "one, two = 'test'"),
6" this function cleans it up by removing useless whitespace and commas.
7function! PyCleanupArgs(text)
8 if a:text == 'args'
9 return ''
10 endif
11 let text = substitute(a:text, '\(\w\)\s\(\w\)', '\1,\2', 'g')
12 return join(split(text, '\s*,\s*'), ', ')
13endfunction
14
15" Given a string containing a list of arguments (e.g. "one = 'test', *args,
16" **kwargs"), this function returns a string containing only the variable
17" names, separated by spaces, e.g. "one two".
18function! PyGetVarnamesFromArgs(text)
19 let text = substitute(a:text, 'self,*\s*', '', '')
20 let text = substitute(text, '\*\*\?\k\+', '', 'g')
21 let text = substitute(text, '=.\{-},', '', 'g')
22 let text = substitute(text, '=.\{-}$', '', 'g')
23 let text = substitute(text, '\s*,\s*', ' ', 'g')
24 if text == ' '
25 return ''
26 endif
27 return text
28endfunction
29
30" Returns the current indent as a string.
31function! PyGetIndentString()
32 if &expandtab
33 let tabs = indent('.') / &shiftwidth
34 let tabstr = repeat(' ', &shiftwidth)
35 else
36 let tabs = indent('.') / &tabstop
37 let tabstr = '\t'
38 endif
39 return repeat(tabstr, tabs)
40endfunction
41
42" Given a string containing a list of arguments (e.g. "one = 'test', *args,
43" **kwargs"), this function returns them formatted correctly for the
44" docstring.
45function! PyGetDocstringFromArgs(text)
46 let text = PyGetVarnamesFromArgs(a:text)
47 if a:text == 'args' || text == ''
48 return ''
49 endif
50 let indent = PyGetIndentString()
51 let st = g:snip_start_tag
52 let et = g:snip_end_tag
53 let docvars = map(split(text), 'v:val." -- ".st.et')
54 return '\n'.indent.join(docvars, '\n'.indent).'\n'.indent
55endfunction
56
57" Given a string containing a list of arguments (e.g. "one = 'test', *args,
58" **kwargs"), this function returns them formatted as a variable assignment in
59" the form "self._ONE = ONE", as used in class constructors.
60function! PyGetVariableInitializationFromVars(text)
61 let text = PyGetVarnamesFromArgs(a:text)
62 if a:text == 'args' || text == ''
63 return ''
64 endif
65 let indent = PyGetIndentString()
66 let st = g:snip_start_tag
67 let et = g:snip_end_tag
68 let assert_vars = map(split(text), '"assert ".v:val." ".st.et')
69 let assign_vars = map(split(text), '"self._".v:val." = ".v:val')
70 let assertions = join(assert_vars, '\n'.indent)
71 let assignments = join(assign_vars, '\n'.indent)
72 return assertions.'\n'.indent.assignments.'\n'.indent
73endfunction
74
75" Given a string containing a list of arguments (e.g. "one = 'test', *args,
76" **kwargs"), this function returns them with the default arguments removed.
77function! PyStripDefaultValue(text)
78 return substitute(a:text, '=.*', '', 'g')
79endfunction
80
81" Returns the number of occurences of needle in haystack.
82function! Count(haystack, needle)
83 let counter = 0
84 let index = match(a:haystack, a:needle)
85 while index > -1
86 let counter = counter + 1
87 let index = match(a:haystack, a:needle, index+1)
88 endwhile
89 return counter
90endfunction
91
92" Returns replacement if the given subject matches the given match.
93" Returns the subject otherwise.
94function! PyReplace(subject, match, replacement)
95 if a:subject == a:match
96 return a:replacement
97 endif
98 return a:subject
99endfunction
100
101" Returns the % operator with a tuple containing n elements appended, where n
102" is the given number.
103function! PyHashArgList(count)
104 if a:count == 0
105 return ''
106 endif
107 let st = g:snip_start_tag
108 let et = g:snip_end_tag
109 return ' % ('.st.et.repeat(', '.st.et, a:count - 1).')'
110endfunction
111
112let st = g:snip_start_tag
113let et = g:snip_end_tag
114let cd = g:snip_elem_delim
115
116" Note to users: The following method of defininf snippets is to allow for
117" changes to the default tags.
118" Feel free to define your own as so:
119" Snippet mysnip This is the expansion text.<{}>
120" There is no need to use exec if you are happy to hardcode your own start and
121" end tags
122
123" Properties, setters and getters.
124exec "Snippet prop ".st."attribute".et." = property(get_".st."attribute".et.", set_".st."attribute".et.st.et.")<CR>".st.et
125exec "Snippet get def get_".st."name".et."(self):<CR>return self._".st."name".et."<CR>".st.et
126exec "Snippet set def set_".st."name".et."(self, ".st."value".et."):
127\<CR>self._".st."name".et." = ".st."value:PyStripDefaultValue(@z)".et."
128\<CR>".st.et
129
130" Functions and methods.
131exec "Snippet def def ".st."fname".et."(".st."args:PyCleanupArgs(@z)".et."):
132\<CR>\"\"\"
133\<CR>".st.et."
134\<CR>".st."args:PyGetDocstringFromArgs(@z)".et."\"\"\"
135\<CR>".st."pass".et."
136\<CR>".st.et
137exec "Snippet cm ".st."class".et." = classmethod(".st."class".et.")<CR>".st.et
138
139" Class definition.
140exec "Snippet cl class ".st."ClassName".et."(".st."object".et."):
141\<CR>\"\"\"
142\<CR>This class represents ".st.et."
143\<CR>\"\"\"
144\<CR>
145\<CR>def __init__(self, ".st."args:PyCleanupArgs(@z)".et."):
146\<CR>\"\"\"
147\<CR>Constructor.
148\<CR>".st."args:PyGetDocstringFromArgs(@z)".et."\"\"\"
149\<CR>".st."args:PyGetVariableInitializationFromVars(@z)".et.st.et
150
151" Keywords
152exec "Snippet for for ".st."variable".et." in ".st."ensemble".et.":<CR>".st."pass".et."<CR>".st.et
153exec "Snippet pf print '".st."s".et."'".st."s:PyHashArgList(Count(@z, '%[^%]'))".et."<CR>".st.et
154exec "Snippet im import ".st."module".et."<CR>".st.et
155exec "Snippet from from ".st."module".et." import ".st.'name:PyReplace(@z, "name", "*")'.et."<CR>".st.et
156exec "Snippet % '".st."s".et."'".st."s:PyHashArgList(Count(@z, '%[^%]'))".et.st.et
157exec "Snippet ass assert ".st."expression".et.st.et
158" From Kib2
159exec "Snippet bc \"\"\"<CR>".st.et."<CR>\"\"\"<CR>".st.et
160
161" Try, except, finally.
162exec "Snippet trye try:
163\<CR>".st.et."
164\<CR>except Exception, e:
165\<CR>".st.et."
166\<CR>".st.et
167
168exec "Snippet tryf try:
169\<CR>".st.et."
170\<CR>finally:
171\<CR>".st.et."
172\<CR>".st.et
173
174exec "Snippet tryef try:
175\<CR>".st.et."
176\<CR>except Exception, e:
177\<CR>".st.et."
178\<CR>finally:
179\<CR>".st.et."
180\<CR>".st.et
181
182" Other multi statement templates
183" From Panos
184exec "Snippet ifn if __name__ == '".st."main".et."':<CR>".st.et
185exec "Snippet ifmain if __name__ == '__main__':<CR>".st.et
186
187" Shebang
188exec "Snippet sb #!/usr/bin/env python<CR># -*- coding: ".st."encoding".et." -*-<CR>".st.et
189exec "Snippet sbu #!/usr/bin/env python<CR># -*- coding: UTF-8 -*-<CR>".st.et
190" From Kib2
191exec "Snippet sbl1 #!/usr/bin/env python<CR># -*- coding: Latin-1 -*-<CR>".st.et
192
193" Unit tests.
194exec "Snippet unittest if __name__ == '__main__':
195\<CR>import unittest
196\<CR>
197\<CR>class ".st."ClassName".et."Test(unittest.TestCase):
198\<CR>def setUp(self):
199\<CR>".st."pass".et."
200\<CR>
201\<CR>def runTest(self):
202\<CR>".st.et