python.vim 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. " Vim syntax file
  2. " Language: Python
  3. " Maintainer: Neil Schemenauer <nas@python.ca>
  4. " Last Change: 2014 Jul 16
  5. " Credits: Zvezdan Petkovic <zpetkovic@acm.org>
  6. " Neil Schemenauer <nas@python.ca>
  7. " Dmitry Vasiliev
  8. "
  9. " This version is a major rewrite by Zvezdan Petkovic.
  10. "
  11. " - introduced highlighting of doctests
  12. " - updated keywords, built-ins, and exceptions
  13. " - corrected regular expressions for
  14. "
  15. " * functions
  16. " * decorators
  17. " * strings
  18. " * escapes
  19. " * numbers
  20. " * space error
  21. "
  22. " - corrected synchronization
  23. " - more highlighting is ON by default, except
  24. " - space error highlighting is OFF by default
  25. "
  26. " Optional highlighting can be controlled using these variables.
  27. "
  28. " let python_no_builtin_highlight = 1
  29. " let python_no_doctest_code_highlight = 1
  30. " let python_no_doctest_highlight = 1
  31. " let python_no_exception_highlight = 1
  32. " let python_no_number_highlight = 1
  33. " let python_space_error_highlight = 1
  34. "
  35. " All the options above can be switched on together.
  36. "
  37. " let python_highlight_all = 1
  38. "
  39. " For version 5.x: Clear all syntax items.
  40. " For version 6.x: Quit when a syntax file was already loaded.
  41. if version < 600
  42. syntax clear
  43. elseif exists("b:current_syntax")
  44. finish
  45. endif
  46. " We need nocompatible mode in order to continue lines with backslashes.
  47. " Original setting will be restored.
  48. let s:cpo_save = &cpo
  49. set cpo&vim
  50. " Keep Python keywords in alphabetical order inside groups for easy
  51. " comparison with the table in the 'Python Language Reference'
  52. " http://docs.python.org/reference/lexical_analysis.html#keywords.
  53. " Groups are in the order presented in NAMING CONVENTIONS in syntax.txt.
  54. " Exceptions come last at the end of each group (class and def below).
  55. "
  56. " Keywords 'with' and 'as' are new in Python 2.6
  57. " (use 'from __future__ import with_statement' in Python 2.5).
  58. "
  59. " Some compromises had to be made to support both Python 3.0 and 2.6.
  60. " We include Python 3.0 features, but when a definition is duplicated,
  61. " the last definition takes precedence.
  62. "
  63. " - 'False', 'None', and 'True' are keywords in Python 3.0 but they are
  64. " built-ins in 2.6 and will be highlighted as built-ins below.
  65. " - 'exec' is a built-in in Python 3.0 and will be highlighted as
  66. " built-in below.
  67. " - 'nonlocal' is a keyword in Python 3.0 and will be highlighted.
  68. " - 'print' is a built-in in Python 3.0 and will be highlighted as
  69. " built-in below (use 'from __future__ import print_function' in 2.6)
  70. "
  71. syn keyword pythonStatement False, None, True
  72. syn keyword pythonStatement as assert break continue del exec global
  73. syn keyword pythonStatement lambda nonlocal pass print return with yield
  74. syn keyword pythonStatement class def nextgroup=pythonFunction skipwhite
  75. syn keyword pythonConditional elif else if
  76. syn keyword pythonRepeat for while
  77. syn keyword pythonOperator and in is not or
  78. syn keyword pythonException except finally raise try
  79. syn keyword pythonInclude from import
  80. " Decorators (new in Python 2.4)
  81. syn match pythonDecorator "@" display nextgroup=pythonFunction skipwhite
  82. " The zero-length non-grouping match before the function name is
  83. " extremely important in pythonFunction. Without it, everything is
  84. " interpreted as a function inside the contained environment of
  85. " doctests.
  86. " A dot must be allowed because of @MyClass.myfunc decorators.
  87. syn match pythonFunction
  88. \ "\%(\%(def\s\|class\s\|@\)\s*\)\@<=\h\%(\w\|\.\)*" contained
  89. " Add spelling to comments with some exceptions
  90. syn match pythonComment "#.*$" contains=pythonTodo,@Spell
  91. " Skip for PyLint's in-line comment rules
  92. syn match pythonComment "# pylint:.*$" display contains=@NoSpell
  93. " Skip noqa inline comments
  94. syn match pythonComment "# noqa.*$" display contains=@NoSpell
  95. syn keyword pythonTodo FIXME NOTE NOTES TODO XXX contained
  96. " Triple-quoted strings can contain doctests.
  97. syn region pythonString
  98. \ start=+[uU]\=\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
  99. \ contains=pythonEscape,@Spell
  100. syn region pythonString
  101. \ start=+[uU]\=\z('''\|"""\)+ end="\z1" keepend
  102. \ contains=pythonEscape,pythonSpaceError,pythonDoctest,@Spell
  103. syn region pythonRawString
  104. \ start=+[uU]\=[rR]\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
  105. \ contains=@Spell
  106. syn region pythonRawString
  107. \ start=+[uU]\=[rR]\z('''\|"""\)+ end="\z1" keepend
  108. \ contains=pythonSpaceError,pythonDoctest,@Spell
  109. syn match pythonEscape +\\[abfnrtv'"\\]+ contained
  110. syn match pythonEscape "\\\o\{1,3}" contained
  111. syn match pythonEscape "\\x\x\{2}" contained
  112. syn match pythonEscape "\%(\\u\x\{4}\|\\U\x\{8}\)" contained
  113. " Python allows case-insensitive Unicode IDs: http://www.unicode.org/charts/
  114. syn match pythonEscape "\\N{.\{-}}" contained
  115. syn match pythonEscape "\\$"
  116. if exists("python_highlight_all")
  117. if exists("python_no_builtin_highlight")
  118. unlet python_no_builtin_highlight
  119. endif
  120. if exists("python_no_doctest_code_highlight")
  121. unlet python_no_doctest_code_highlight
  122. endif
  123. if exists("python_no_doctest_highlight")
  124. unlet python_no_doctest_highlight
  125. endif
  126. if exists("python_no_exception_highlight")
  127. unlet python_no_exception_highlight
  128. endif
  129. if exists("python_no_number_highlight")
  130. unlet python_no_number_highlight
  131. endif
  132. let python_space_error_highlight = 1
  133. endif
  134. " It is very important to understand all details before changing the
  135. " regular expressions below or their order.
  136. " The word boundaries are *not* the floating-point number boundaries
  137. " because of a possible leading or trailing decimal point.
  138. " The expressions below ensure that all valid number literals are
  139. " highlighted, and invalid number literals are not. For example,
  140. "
  141. " - a decimal point in '4.' at the end of a line is highlighted,
  142. " - a second dot in 1.0.0 is not highlighted,
  143. " - 08 is not highlighted,
  144. " - 08e0 or 08j are highlighted,
  145. "
  146. " and so on, as specified in the 'Python Language Reference'.
  147. " http://docs.python.org/reference/lexical_analysis.html#numeric-literals
  148. if !exists("python_no_number_highlight")
  149. " numbers (including longs and complex)
  150. syn match pythonNumber "\<0[oO]\=\o\+[Ll]\=\>"
  151. syn match pythonNumber "\<0[xX]\x\+[Ll]\=\>"
  152. syn match pythonNumber "\<0[bB][01]\+[Ll]\=\>"
  153. syn match pythonNumber "\<\%([1-9]\d*\|0\)[Ll]\=\>"
  154. syn match pythonNumber "\<\d\+[jJ]\>"
  155. syn match pythonNumber "\<\d\+[eE][+-]\=\d\+[jJ]\=\>"
  156. syn match pythonNumber
  157. \ "\<\d\+\.\%([eE][+-]\=\d\+\)\=[jJ]\=\%(\W\|$\)\@="
  158. syn match pythonNumber
  159. \ "\%(^\|\W\)\@<=\d*\.\d\+\%([eE][+-]\=\d\+\)\=[jJ]\=\>"
  160. endif
  161. " Group the built-ins in the order in the 'Python Library Reference' for
  162. " easier comparison.
  163. " http://docs.python.org/library/constants.html
  164. " http://docs.python.org/library/functions.html
  165. " http://docs.python.org/library/functions.html#non-essential-built-in-functions
  166. " Python built-in functions are in alphabetical order.
  167. if !exists("python_no_builtin_highlight")
  168. " built-in constants
  169. " 'False', 'True', and 'None' are also reserved words in Python 3.0
  170. syn keyword pythonBuiltin False True None
  171. syn keyword pythonBuiltin NotImplemented Ellipsis __debug__
  172. " built-in functions
  173. syn keyword pythonBuiltin abs all any bin bool chr classmethod
  174. syn keyword pythonBuiltin compile complex delattr dict dir divmod
  175. syn keyword pythonBuiltin enumerate eval filter float format
  176. syn keyword pythonBuiltin frozenset getattr globals hasattr hash
  177. syn keyword pythonBuiltin help hex id input int isinstance
  178. syn keyword pythonBuiltin issubclass iter len list locals map max
  179. syn keyword pythonBuiltin min next object oct open ord pow print
  180. syn keyword pythonBuiltin property range repr reversed round set
  181. syn keyword pythonBuiltin setattr slice sorted staticmethod str
  182. syn keyword pythonBuiltin sum super tuple type vars zip __import__
  183. " Python 2.6 only
  184. syn keyword pythonBuiltin basestring callable cmp execfile file
  185. syn keyword pythonBuiltin long raw_input reduce reload unichr
  186. syn keyword pythonBuiltin unicode xrange
  187. " Python 3.0 only
  188. syn keyword pythonBuiltin ascii bytearray bytes exec memoryview
  189. " non-essential built-in functions; Python 2.6 only
  190. syn keyword pythonBuiltin apply buffer coerce intern
  191. endif
  192. " From the 'Python Library Reference' class hierarchy at the bottom.
  193. " http://docs.python.org/library/exceptions.html
  194. if !exists("python_no_exception_highlight")
  195. " builtin base exceptions (only used as base classes for other exceptions)
  196. syn keyword pythonExceptions BaseException Exception
  197. syn keyword pythonExceptions ArithmeticError EnvironmentError
  198. syn keyword pythonExceptions LookupError
  199. " builtin base exception removed in Python 3.0
  200. syn keyword pythonExceptions StandardError
  201. " builtin exceptions (actually raised)
  202. syn keyword pythonExceptions AssertionError AttributeError BufferError
  203. syn keyword pythonExceptions EOFError FloatingPointError GeneratorExit
  204. syn keyword pythonExceptions IOError ImportError IndentationError
  205. syn keyword pythonExceptions IndexError KeyError KeyboardInterrupt
  206. syn keyword pythonExceptions MemoryError NameError NotImplementedError
  207. syn keyword pythonExceptions OSError OverflowError ReferenceError
  208. syn keyword pythonExceptions RuntimeError StopIteration SyntaxError
  209. syn keyword pythonExceptions SystemError SystemExit TabError TypeError
  210. syn keyword pythonExceptions UnboundLocalError UnicodeError
  211. syn keyword pythonExceptions UnicodeDecodeError UnicodeEncodeError
  212. syn keyword pythonExceptions UnicodeTranslateError ValueError VMSError
  213. syn keyword pythonExceptions WindowsError ZeroDivisionError
  214. " builtin warnings
  215. syn keyword pythonExceptions BytesWarning DeprecationWarning FutureWarning
  216. syn keyword pythonExceptions ImportWarning PendingDeprecationWarning
  217. syn keyword pythonExceptions RuntimeWarning SyntaxWarning UnicodeWarning
  218. syn keyword pythonExceptions UserWarning Warning
  219. endif
  220. if exists("python_space_error_highlight")
  221. " trailing whitespace
  222. syn match pythonSpaceError display excludenl "\s\+$"
  223. " mixed tabs and spaces
  224. syn match pythonSpaceError display " \+\t"
  225. syn match pythonSpaceError display "\t\+ "
  226. endif
  227. " Do not spell doctests inside strings.
  228. " Notice that the end of a string, either ''', or """, will end the contained
  229. " doctest too. Thus, we do *not* need to have it as an end pattern.
  230. if !exists("python_no_doctest_highlight")
  231. if !exists("python_no_doctest_code_highlight")
  232. syn region pythonDoctest
  233. \ start="^\s*>>>\s" end="^\s*$"
  234. \ contained contains=ALLBUT,pythonDoctest,@Spell
  235. syn region pythonDoctestValue
  236. \ start=+^\s*\%(>>>\s\|\.\.\.\s\|"""\|'''\)\@!\S\++ end="$"
  237. \ contained
  238. else
  239. syn region pythonDoctest
  240. \ start="^\s*>>>" end="^\s*$"
  241. \ contained contains=@NoSpell
  242. endif
  243. endif
  244. " Sync at the beginning of class, function, or method definition.
  245. syn sync match pythonSync grouphere NONE "^\s*\%(def\|class\)\s\+\h\w*\s*("
  246. if version >= 508 || !exists("did_python_syn_inits")
  247. if version <= 508
  248. let did_python_syn_inits = 1
  249. command -nargs=+ HiLink hi link <args>
  250. else
  251. command -nargs=+ HiLink hi def link <args>
  252. endif
  253. " The default highlight links. Can be overridden later.
  254. HiLink pythonStatement Statement
  255. HiLink pythonConditional Conditional
  256. HiLink pythonRepeat Repeat
  257. HiLink pythonOperator Operator
  258. HiLink pythonException Exception
  259. HiLink pythonInclude Include
  260. HiLink pythonDecorator Define
  261. HiLink pythonFunction Function
  262. HiLink pythonComment Comment
  263. HiLink pythonTodo Todo
  264. HiLink pythonString String
  265. HiLink pythonRawString String
  266. HiLink pythonEscape Special
  267. if !exists("python_no_number_highlight")
  268. HiLink pythonNumber Number
  269. endif
  270. if !exists("python_no_builtin_highlight")
  271. HiLink pythonBuiltin Function
  272. endif
  273. if !exists("python_no_exception_highlight")
  274. HiLink pythonExceptions Structure
  275. endif
  276. if exists("python_space_error_highlight")
  277. HiLink pythonSpaceError Error
  278. endif
  279. if !exists("python_no_doctest_highlight")
  280. HiLink pythonDoctest Special
  281. HiLink pythonDoctestValue Define
  282. endif
  283. delcommand HiLink
  284. endif
  285. let b:current_syntax = "python"
  286. let &cpo = s:cpo_save
  287. unlet s:cpo_save
  288. " vim:set sw=2 sts=2 ts=8 noet: