python.vim 16KB

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