-
Notifications
You must be signed in to change notification settings - Fork 853
Expand file tree
/
Copy pathpython.py
More file actions
289 lines (251 loc) · 7.71 KB
/
python.py
File metadata and controls
289 lines (251 loc) · 7.71 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import re
from contextlib import suppress
from talon import Context, Module, actions, settings
from ...core.described_functions import create_described_insert_between
from ..tags.generic_types import (
SimpleLanguageSpecificTypeConnector,
format_type_parameter_arguments,
)
from ..tags.operators import Operators
mod = Module()
ctx = Context()
ctx.matches = r"""
code.language: python
"""
"""a set of fields used in python docstrings that will follow the
reStructuredText format"""
docstring_fields = {
"class": ":class:",
"function": ":func:",
"parameter": ":param:",
"raise": ":raise:",
"returns": ":return:",
"type": ":type:",
"return type": ":rtype:",
# these are sphinx-specific
"see also": ".. seealso:: ",
"notes": ".. notes:: ",
"warning": ".. warning:: ",
"todo": ".. todo:: ",
}
mod.list("python_docstring_fields", desc="python docstring fields")
ctx.lists["user.python_docstring_fields"] = docstring_fields
exception_list = [
"BaseException",
"SystemExit",
"KeyboardInterrupt",
"GeneratorExit",
"Exception",
"StopIteration",
"StopAsyncIteration",
"ArithmeticError",
"FloatingPointError",
"OverflowError",
"ZeroDivisionError",
"AssertionError",
"AttributeError",
"BufferError",
"EOFError",
"ImportError",
"ModuleNotFoundError",
"LookupError",
"IndexError",
"KeyError",
"MemoryError",
"NameError",
"UnboundLocalError",
"OSError",
"BlockingIOError",
"ChildProcessError",
"ConnectionError",
"BrokenPipeError",
"ConnectionAbortedError",
"ConnectionRefusedError",
"ConnectionResetError",
"FileExistsError",
"FileNotFoundError",
"InterruptedError",
"IsADirectoryError",
"NotADirectoryError",
"PermissionError",
"ProcessLookupError",
"TimeoutError",
"ReferenceError",
"RuntimeError",
"NotImplementedError",
"RecursionError",
"SyntaxError",
"IndentationError",
"TabError",
"SystemError",
"TypeError",
"ValueError",
"UnicodeError",
"UnicodeDecodeError",
"UnicodeEncodeError",
"UnicodeTranslateError",
"Warning",
"DeprecationWarning",
"PendingDeprecationWarning",
"RuntimeWarning",
"SyntaxWarning",
"UserWarning",
"FutureWarning",
"ImportWarning",
"UnicodeWarning",
"BytesWarning",
"ResourceWarning",
]
mod.list("python_exception", desc="python exceptions")
ctx.lists["user.python_exception"] = {
" ".join(re.findall("[A-Z][^A-Z]*", exception)).lower(): exception
for exception in exception_list
}
# This is not part of the long term stable API
# After we implement generics support for several languages,
# we plan on abstracting out from the specific implementations into a general grammar
mod.list(
"python_generic_type", desc="A python type that takes type parameter arguments"
)
# this should be moved to a talon-list file after this becomes stable
ctx.lists["user.python_generic_type"] = {
"callable": "Callable",
"dictionary": "dict",
"iterable": "Iterable",
"list": "list",
"optional": "Optional",
"set": "set",
"tuple": "tuple",
"union": "Union",
}
@ctx.capture(
"user.generic_type_parameter_argument", rule="<user.code_type> | [type] <user.text>"
)
def generic_type_parameter_argument(m) -> str:
"""A Python type parameter for a generic data structure"""
with suppress(AttributeError):
return m.code_type
return actions.user.formatted_text(m.text, "PUBLIC_CAMEL_CASE")
@ctx.capture(
"user.generic_data_structure",
rule="{user.python_generic_type} | [type] <user.text>",
)
def generic_data_structure(m) -> str:
"""A Python generic data structure that takes type parameter arguments"""
with suppress(AttributeError):
return m.python_generic_type
return actions.user.formatted_text(m.text, "PUBLIC_CAMEL_CASE")
@ctx.capture(
"user.generic_type_connector", rule="<user.common_generic_type_connector>|or"
)
def generic_type_connector(m) -> SimpleLanguageSpecificTypeConnector:
"""A Python specific type connector for union types"""
with suppress(AttributeError):
return m.common_generic_type_connector
return SimpleLanguageSpecificTypeConnector(" | ")
@ctx.capture(
"user.generic_type_parameter_arguments",
rule="<user.generic_type_parameter_argument> [<user.generic_type_additional_type_parameters>]",
)
def generic_type_parameter_arguments(m) -> str:
return format_type_parameter_arguments(m, ", ", "[", "]")
@mod.capture(
rule="<user.generic_data_structure> of <user.generic_type_parameter_arguments>"
)
def python_generic_type(m) -> str:
"""A generic type with specific type parameters"""
parameters = m.generic_type_parameter_arguments
return f"{m.generic_data_structure}[{parameters}]"
# End of unstable section
operators = Operators(
# code_operators_array
SUBSCRIPT=create_described_insert_between("[", "]"),
# code_operators_assignment
ASSIGNMENT=" = ",
ASSIGNMENT_SUBTRACTION=" -= ",
ASSIGNMENT_ADDITION=" += ",
ASSIGNMENT_MULTIPLICATION=" *= ",
ASSIGNMENT_DIVISION=" /= ",
ASSIGNMENT_MODULO=" %= ",
ASSIGNMENT_INCREMENT=" += 1",
ASSIGNMENT_BITWISE_AND=" &= ",
ASSIGNMENT_BITWISE_OR=" |= ",
ASSIGNMENT_BITWISE_EXCLUSIVE_OR=" ^= ",
ASSIGNMENT_BITWISE_LEFT_SHIFT=" <<= ",
ASSIGNMENT_BITWISE_RIGHT_SHIFT=" >>= ",
# code_operators_bitwise
BITWISE_NOT="~",
BITWISE_AND=" & ",
BITWISE_OR=" | ",
BITWISE_EXCLUSIVE_OR=" ^ ",
BITWISE_LEFT_SHIFT=" << ",
BITWISE_RIGHT_SHIFT=" >> ",
# code_operators_lambda
LAMBDA=create_described_insert_between("lambda ", ": "),
# code_operators_math
MATH_SUBTRACT=" - ",
MATH_ADD=" + ",
MATH_MULTIPLY=" * ",
MATH_DIVIDE=" / ",
MATH_INTEGER_DIVIDE=" // ",
MATH_MODULO=" % ",
MATH_EXPONENT=" ** ",
MATH_EQUAL=" == ",
MATH_NOT_EQUAL=" != ",
MATH_GREATER_THAN=" > ",
MATH_GREATER_THAN_OR_EQUAL=" >= ",
MATH_LESS_THAN=" < ",
MATH_LESS_THAN_OR_EQUAL=" <= ",
MATH_AND=" and ",
MATH_OR=" or ",
MATH_NOT=" not ",
MATH_IN=" in ",
MATH_NOT_IN=" not in ",
)
@ctx.action_class("user")
class UserActions:
def code_get_operators() -> Operators:
return operators
def code_self():
actions.insert("self")
def code_operator_object_accessor():
actions.insert(".")
def code_insert_null():
actions.insert("None")
def code_insert_is_null():
actions.insert(" is None")
def code_insert_is_not_null():
actions.insert(" is not None")
def code_insert_true():
actions.insert("True")
def code_insert_false():
actions.insert("False")
def code_insert_function(text: str, selection: str):
text += f"({selection or ''})"
actions.user.paste(text)
actions.edit.left()
def code_default_function(text: str):
actions.user.code_public_function(text)
def code_private_function(text: str):
"""Inserts private function declaration"""
result = "def _{}():".format(
actions.user.formatted_text(
text, settings.get("user.code_private_function_formatter")
)
)
actions.user.paste(result)
actions.edit.left()
actions.edit.left()
def code_public_function(text: str):
result = "def {}():".format(
actions.user.formatted_text(
text, settings.get("user.code_public_function_formatter")
)
)
actions.user.paste(result)
actions.edit.left()
actions.edit.left()
def code_insert_type_annotation(type: str):
actions.insert(f": {type}")
def code_insert_return_type(type: str):
actions.insert(f" -> {type}")