forked from sijk/sublime-licence-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Licence Snippets.py
80 lines (61 loc) · 2.73 KB
/
Licence Snippets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import os
import os.path
import re
from collections import Callable
from datetime import date
from getpass import getuser
from sublime_plugin import TextCommand
# This must be computed on import because of the way ST2 load plugins (__file__
# ends up being relative to plugin's directory and cwd may change later).
SNIPPETS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
'snippets'))
# Mapping of additional snippet variable names to their values. If the value is
# callable, it is called on snippet insertion to compute actual value.
SNIPPET_VARS = {
'YEAR': date.today().year, # TM_YEAR doesn't seem to be supported.
'USER': getuser() # TM_FULLNAME doesn't seem to be supported.
}
def inc_placeholder(match):
''' Return matched text with number captured by group "num" increased. '''
s = match.string
a, b = match.span()
i, j = match.span('num')
return s[a:i] + str(int(s[i:j]) + 1) + s[j:b]
def load_snippet(file_name):
# Load the file assuming UTF-8.
with open(os.path.join(SNIPPETS_DIR, file_name), 'rU') as f:
text = f.read().decode('utf-8')
# Wrap everything in one big tabstop and renumber old tabstops. This is
# done for technical reasons to support automatic commenting/warpping
# inserted text.
text = re.sub(r'(?:\\\\)*\$(\{)?(?P<num>\d+)(?(1)[:/}]|)', inc_placeholder,
text)
text = u'${{1:{0}}}'.format(text)
return text
class InsertLicenceCommand(TextCommand):
def run(self, edit, name):
view = self.view
settings = view.settings()
comment_style = settings.get('licence_comment_style', 'line')
if comment_style not in ('none', 'line', 'block'):
raise ValueError('Invalid value for licence_comment_style setting')
wrap_lines = settings.get('licence_wrap_lines', False)
if wrap_lines not in (True, False):
raise ValueError('Invalid value for licence_wrap_lines setting')
args = {'contents': load_snippet(name)}
for key, value in SNIPPET_VARS.iteritems():
if isinstance(value, Callable):
value = value()
args[key] = unicode(value) # Allow non-text values.
view.run_command('insert_snippet', args)
# Since load_snippet wraps everything in one big tabstop, the whole
# inserted text is now selected.
if comment_style != 'none':
view.run_command('toggle_comment',
{'block': comment_style == 'block'})
if wrap_lines:
view.run_command('wrap_lines')
# Proceed to original first tabstop.
view.run_command('next_field')
def is_enabled(self):
return len(self.view.sel()) == 1