Browse Source

Improve builtin-func and highlight type annotations in func args

 * Builtin-functions are highlighted only when used as global functions.
 * Annotations in type-only variable definitions and assignment statements are not supported yet due to potential conflicts with dictionary expressions.
 * Uses a custom syntax highlight def "Optional" (in my setup, it applies italic style.)
 * Taken from purpleP/python-syntax commits and customized.
Joongi Kim 7 years ago
parent
commit
43f3542282
1 changed files with 89 additions and 50 deletions
  1. 89
    50
      syntax/python.vim

+ 89
- 50
syntax/python.vim View File

163
 " we provide a dummy group here to avoid crashing pyrex.vim.
163
 " we provide a dummy group here to avoid crashing pyrex.vim.
164
 syn keyword pythonInclude       import
164
 syn keyword pythonInclude       import
165
 syn keyword pythonImport        import
165
 syn keyword pythonImport        import
166
+syn match pythonIdentifier "\v[a-zA-Z_][a-zA-Z0-9_]*" nextgroup=FunctionParameters
166
 syn keyword pythonException     try except finally
167
 syn keyword pythonException     try except finally
167
 syn keyword pythonOperator      and in is not or
168
 syn keyword pythonOperator      and in is not or
168
 
169
 
170
+" TODO: contain pythonTypeAnno in assignments and non-assigning variable type defs
171
+syn match pythonTypeAnno ":\s*[a-zA-Z0-9_\[\],\s]\+" display contained contains=pythonType
172
+syn keyword pythonType Any AnyStr Callable ClassVar Tuple Union Optional Type TypeVar contained
173
+syn keyword pythonType AbstractSet MutableSet Mapping MutableMapping Sequence MutableSequence ByteString Deque List contained
174
+syn keyword pythonType Set FrozenSet MappingView KeysView ItemsView ValuesView Awaitable Coroutine AsyncIterable contained
175
+syn keyword pythonType AsyncIterator ContextManager Dict DefaultDict Generator AsyncGenerator Text NamedTuple contained
176
+syn keyword pythonType Iterable Iterator Reversible SupportsInt SupportsFloat SupportsAbs SupportsRound Container contained
177
+syn keyword pythonType Hashable Sized Collection contained
178
+
169
 syn match pythonStatement   "\<yield\>" display
179
 syn match pythonStatement   "\<yield\>" display
170
 syn match pythonImport      "\<from\>" display
180
 syn match pythonImport      "\<from\>" display
171
 
181
 
179
   syn keyword pythonStatement   as nonlocal
189
   syn keyword pythonStatement   as nonlocal
180
   syn match   pythonStatement   "\<yield\s\+from\>" display
190
   syn match   pythonStatement   "\<yield\s\+from\>" display
181
   syn keyword pythonBuiltinObj  None True False
191
   syn keyword pythonBuiltinObj  None True False
182
-  syn match   pythonFunction    "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained
192
+  syn match   pythonFunction    "[a-zA-Z_][a-zA-Z0-9_]*" nextgroup=FunctionParameters display contained
183
   syn keyword pythonStatement   await async
193
   syn keyword pythonStatement   await async
184
   syn match   pythonStatement   "\<async\s\+def\>" nextgroup=pythonFunction skipwhite
194
   syn match   pythonStatement   "\<async\s\+def\>" nextgroup=pythonFunction skipwhite
185
   syn match   pythonStatement   "\<async\s\+with\>" display
195
   syn match   pythonStatement   "\<async\s\+with\>" display
186
   syn match   pythonStatement   "\<async\s\+for\>" display
196
   syn match   pythonStatement   "\<async\s\+for\>" display
187
 endif
197
 endif
188
 
198
 
199
+syn region FunctionParameters start='(' end=')' display contains=
200
+            \ FunctionParameters,
201
+            \ pythonRepeat,
202
+            \ pythonConditional,
203
+            \ pythonComment,
204
+            \ pythonOperator,
205
+            \ pythonNumber,
206
+            \ pythonNumberError,
207
+            \ pythonFloat,
208
+            \ pythonHexNumber,
209
+            \ pythonStatement,
210
+            \ pythonOctNumber,
211
+            \ pythonString,
212
+            \ pythonRawString,
213
+            \ pythonUniString,
214
+            \ pythonExClass,
215
+            \ pythonUniRawString,
216
+            \ pythonNumber,
217
+            \ pythonRawString,
218
+            \ pythonBytes,
219
+            \ pythonBuiltinObj,
220
+            \ pythonNone,
221
+            \ pythonBuiltinFunc,
222
+            \ pythonTypeAnno,
223
+            \ pythonBoolean nextgroup=pythonRaiseFromStatement display contained
224
+
189
 syn cluster pythonExpression contains=pythonStatement,pythonRepeat,pythonConditional,pythonOperator,pythonNumber,pythonHexNumber,pythonOctNumber,pythonBinNumber,pythonFloat,pythonString,pythonBytes,pythonBoolean,pythonBuiltinObj,pythonBuiltinFunc
225
 syn cluster pythonExpression contains=pythonStatement,pythonRepeat,pythonConditional,pythonOperator,pythonNumber,pythonHexNumber,pythonOctNumber,pythonBinNumber,pythonFloat,pythonString,pythonBytes,pythonBoolean,pythonBuiltinObj,pythonBuiltinFunc
190
 
226
 
191
 "
227
 "
425
 
461
 
426
 if s:Enabled("g:python_highlight_builtin_funcs")
462
 if s:Enabled("g:python_highlight_builtin_funcs")
427
   if s:Python2Syntax()
463
   if s:Python2Syntax()
428
-    syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(apply|basestring|buffer|callable|coerce)>'
429
-    syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(execfile|file|help|intern|long|raw_input)>'
430
-    syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(reduce|reload|unichr|unicode|xrange)>'
464
+    syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(apply|basestring|buffer|callable|coerce)>\ze\(' nextgroup=FunctionParameters
465
+    syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(execfile|file|help|intern|long|raw_input)>\ze\(' nextgroup=FunctionParameters
466
+    syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(reduce|reload|unichr|unicode|xrange)>\ze\(' nextgroup=FunctionParameters
431
     if s:Enabled("g:python_print_as_function")
467
     if s:Enabled("g:python_print_as_function")
432
-      syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(print)>'
468
+      syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(print)>\ze\(' nextgroup=FunctionParameters
433
     endif
469
     endif
434
   else
470
   else
435
-    syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(ascii|exec|memoryview|print)>'
471
+    syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(ascii|exec|memoryview|print)\ze\(>' nextgroup=FunctionParameters
436
   endif
472
   endif
437
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(__import__|abs|all|any)>'
438
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(bin|bool|bytearray|bytes)>'
439
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(chr|classmethod|cmp|compile|complex)>'
440
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(delattr|dict|dir|divmod|enumerate|eval)>'
441
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(filter|float|format|frozenset|getattr)>'
442
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(globals|hasattr|hash|hex|id)>'
443
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(input|int|isinstance)>'
444
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(issubclass|iter|len|list|locals|map|max)>'
445
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(min|next|object|oct|open|ord)>'
446
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(pow|property|range)>'
447
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(repr|reversed|round|set|setattr)>'
448
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(slice|sorted|staticmethod|str|sum|super|tuple)>'
449
-  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(type|vars|zip)>'
473
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(__import__|abs|all|any)>\ze\(' nextgroup=FunctionParameters
474
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(bin|bool|bytearray|bytes)>\ze\(' nextgroup=FunctionParameters
475
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(chr|classmethod|cmp|compile|complex)>\ze\(' nextgroup=FunctionParameters
476
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(delattr|dict|dir|divmod|enumerate|eval)>\ze\(' nextgroup=FunctionParameters
477
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(filter|float|format|frozenset|getattr)>\ze\(' nextgroup=FunctionParameters
478
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(globals|hasattr|hash|hex|id)>\ze\(' nextgroup=FunctionParameters
479
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(input|int|isinstance)>\ze\(' nextgroup=FunctionParameters
480
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(issubclass|iter|len|list|locals|map|max)>\ze\(' nextgroup=FunctionParameters
481
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(min|next|object|oct|open|ord)>\ze\(' nextgroup=FunctionParameters
482
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(pow|property|range)>\ze\(' nextgroup=FunctionParameters
483
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(repr|reversed|round|set|setattr)>\ze\(' nextgroup=FunctionParameters
484
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(slice|sorted|staticmethod|str|sum|super|tuple)>\ze\(' nextgroup=FunctionParameters
485
+  syn match pythonBuiltinFunc	'\v(\.)@<!\zs<(type|vars|zip)>\ze\(' nextgroup=FunctionParameters
450
 endif
486
 endif
451
 
487
 
452
 "
488
 "
455
 
491
 
456
 if s:Enabled("g:python_highlight_exceptions")
492
 if s:Enabled("g:python_highlight_exceptions")
457
   if s:Python2Syntax()
493
   if s:Python2Syntax()
458
-    syn keyword pythonExClass	StandardError
494
+    syn keyword pythonExClass	StandardError nextgroup=FunctionParameters
459
   else
495
   else
460
-    syn keyword pythonExClass	BlockingIOError ChildProcessError
461
-    syn keyword pythonExClass	ConnectionError BrokenPipeError
462
-    syn keyword pythonExClass	ConnectionAbortedError ConnectionRefusedError
463
-    syn keyword pythonExClass	ConnectionResetError FileExistsError
464
-    syn keyword pythonExClass	FileNotFoundError InterruptedError
465
-    syn keyword pythonExClass	IsADirectoryError NotADirectoryError
466
-    syn keyword pythonExClass	PermissionError ProcessLookupError TimeoutError
467
-
468
-    syn keyword pythonExClass	ResourceWarning
496
+    syn keyword pythonExClass	BlockingIOError ChildProcessError nextgroup=FunctionParameters
497
+    syn keyword pythonExClass	ConnectionError BrokenPipeError nextgroup=FunctionParameters
498
+    syn keyword pythonExClass	ConnectionAbortedError ConnectionRefusedError nextgroup=FunctionParameters
499
+    syn keyword pythonExClass	ConnectionResetError FileExistsError nextgroup=FunctionParameters
500
+    syn keyword pythonExClass	FileNotFoundError InterruptedError nextgroup=FunctionParameters
501
+    syn keyword pythonExClass	IsADirectoryError NotADirectoryError nextgroup=FunctionParameters
502
+    syn keyword pythonExClass	PermissionError ProcessLookupError TimeoutError nextgroup=FunctionParameters
503
+
504
+    syn keyword pythonExClass	ResourceWarning nextgroup=FunctionParameters
469
   endif
505
   endif
470
-  syn keyword pythonExClass	BaseException
471
-  syn keyword pythonExClass	Exception ArithmeticError
472
-  syn keyword pythonExClass	LookupError EnvironmentError
473
-
474
-  syn keyword pythonExClass	AssertionError AttributeError BufferError EOFError
475
-  syn keyword pythonExClass	FloatingPointError GeneratorExit IOError
476
-  syn keyword pythonExClass	ImportError IndexError KeyError
477
-  syn keyword pythonExClass	KeyboardInterrupt MemoryError NameError
478
-  syn keyword pythonExClass	NotImplementedError OSError OverflowError
479
-  syn keyword pythonExClass	ReferenceError RuntimeError StopIteration
480
-  syn keyword pythonExClass	SyntaxError IndentationError TabError
481
-  syn keyword pythonExClass	SystemError SystemExit TypeError
482
-  syn keyword pythonExClass	UnboundLocalError UnicodeError
483
-  syn keyword pythonExClass	UnicodeEncodeError UnicodeDecodeError
484
-  syn keyword pythonExClass	UnicodeTranslateError ValueError VMSError
485
-  syn keyword pythonExClass	WindowsError ZeroDivisionError
486
-
487
-  syn keyword pythonExClass	Warning UserWarning BytesWarning DeprecationWarning
488
-  syn keyword pythonExClass	PendingDepricationWarning SyntaxWarning
489
-  syn keyword pythonExClass	RuntimeWarning FutureWarning
490
-  syn keyword pythonExClass	ImportWarning UnicodeWarning
506
+  syn keyword pythonExClass	BaseException nextgroup=FunctionParameters
507
+  syn keyword pythonExClass	Exception ArithmeticError nextgroup=FunctionParameters
508
+  syn keyword pythonExClass	LookupError EnvironmentError nextgroup=FunctionParameters
509
+
510
+  syn keyword pythonExClass	AssertionError AttributeError BufferError EOFError nextgroup=FunctionParameters
511
+  syn keyword pythonExClass	FloatingPointError GeneratorExit IOError nextgroup=FunctionParameters
512
+  syn keyword pythonExClass	ImportError IndexError KeyError nextgroup=FunctionParameters
513
+  syn keyword pythonExClass	KeyboardInterrupt MemoryError NameError nextgroup=FunctionParameters
514
+  syn keyword pythonExClass	NotImplementedError OSError OverflowError nextgroup=FunctionParameters
515
+  syn keyword pythonExClass	ReferenceError RuntimeError StopIteration nextgroup=FunctionParameters
516
+  syn keyword pythonExClass	SyntaxError IndentationError TabError nextgroup=FunctionParameters
517
+  syn keyword pythonExClass	SystemError SystemExit TypeError nextgroup=FunctionParameters
518
+  syn keyword pythonExClass	UnboundLocalError UnicodeError nextgroup=FunctionParameters
519
+  syn keyword pythonExClass	UnicodeEncodeError UnicodeDecodeError nextgroup=FunctionParameters
520
+  syn keyword pythonExClass	UnicodeTranslateError ValueError VMSError nextgroup=FunctionParameters
521
+  syn keyword pythonExClass	WindowsError ZeroDivisionError nextgroup=FunctionParameters
522
+
523
+  syn keyword pythonExClass	Warning UserWarning BytesWarning DeprecationWarning nextgroup=FunctionParameters
524
+  syn keyword pythonExClass	PendingDepricationWarning SyntaxWarning nextgroup=FunctionParameters
525
+  syn keyword pythonExClass	RuntimeWarning FutureWarning nextgroup=FunctionParameters
526
+  syn keyword pythonExClass	ImportWarning UnicodeWarning nextgroup=FunctionParameters
491
 endif
527
 endif
492
 
528
 
493
 if s:Enabled("g:python_slow_sync")
529
 if s:Enabled("g:python_slow_sync")
577
 
613
 
578
   HiLink pythonExClass          Structure
614
   HiLink pythonExClass          Structure
579
 
615
 
616
+  HiLink pythonTypeAnno         Optional
617
+  HiLink pythonType             Special
618
+
580
   delcommand HiLink
619
   delcommand HiLink
581
 endif
620
 endif
582
 
621