kakoune

Fork of kakoune, an acceptable text editor
git clone git://git.laack.co/kakoune.git
Log | Files | Refs

python.kak (11136B)


      1 # http://python.org
      2 # ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
      3 
      4 # Detection
      5 # ‾‾‾‾‾‾‾‾‾
      6 
      7 hook global BufCreate .*[.](py) %{
      8     set-option buffer filetype python
      9 }
     10 
     11 # Initialization
     12 # ‾‾‾‾‾‾‾‾‾‾‾‾‾‾
     13 
     14 hook global WinSetOption filetype=python %{
     15     require-module python
     16 
     17     set-option window static_words %opt{python_static_words}
     18 
     19     hook window InsertChar \n -group python-insert python-insert-on-new-line
     20     hook window InsertChar \n -group python-indent python-indent-on-new-line
     21     # cleanup trailing whitespaces on current line insert end
     22     hook window ModeChange pop:insert:.* -group python-trim-indent %{ try %{ execute-keys -draft <semicolon> x s ^\h+$ <ret> d } }
     23     hook -once -always window WinSetOption filetype=.* %{ remove-hooks window python-.+ }
     24 }
     25 
     26 hook -group python-highlight global WinSetOption filetype=python %{
     27     add-highlighter window/python ref python
     28     hook -once -always window WinSetOption filetype=.* %{ remove-highlighter window/python }
     29 }
     30 
     31 provide-module python %§
     32 
     33 # Highlighters & Completion
     34 # ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
     35 
     36 add-highlighter shared/python regions
     37 add-highlighter shared/python/code default-region group
     38 add-highlighter shared/python/docstring     region -match-capture ^\h*("""|''') (?<!\\)(?:\\\\)*("""|''') regions
     39 
     40 add-highlighter shared/python/documentation region '##'  '$'              fill documentation
     41 add-highlighter shared/python/comment       region '#'   '$'              fill comment
     42 
     43 # String interpolation
     44 add-highlighter shared/python/f_triple_string region -match-capture [fF]("""|''') (?<!\\)(?:\\\\)*("""|''') group
     45 add-highlighter shared/python/f_triple_string/ fill string
     46 add-highlighter shared/python/f_triple_string/ regex \{.*?\} 0:value
     47 
     48 add-highlighter shared/python/f_double_string region '[fF]"'   (?<!\\)(\\\\)*" group
     49 add-highlighter shared/python/f_double_string/ fill string
     50 add-highlighter shared/python/f_double_string/ regex \{.*?\} 0:value
     51 
     52 add-highlighter shared/python/f_single_string region "[fF]'"   (?<!\\)(\\\\)*' group
     53 add-highlighter shared/python/f_single_string/ fill string
     54 add-highlighter shared/python/f_single_string/ regex \{.*?\} 0:value
     55 
     56 
     57 # Regular string
     58 add-highlighter shared/python/triple_string region -match-capture ("""|''') (?<!\\)(?:\\\\)*("""|''') fill string
     59 add-highlighter shared/python/double_string region '"'   (?<!\\)(\\\\)*" fill string
     60 add-highlighter shared/python/single_string region "'"   (?<!\\)(\\\\)*' fill string
     61 
     62 # Integer formats
     63 add-highlighter shared/python/code/ regex '(?i)\b0b[01]+l?\b' 0:value
     64 add-highlighter shared/python/code/ regex '(?i)\b0x[\da-f]+l?\b' 0:value
     65 add-highlighter shared/python/code/ regex '(?i)\b0o?[0-7]+l?\b' 0:value
     66 add-highlighter shared/python/code/ regex '(?i)\b([1-9]\d*|0)l?\b' 0:value
     67 # Float formats
     68 add-highlighter shared/python/code/ regex '\b\d+[eE][+-]?\d+\b' 0:value
     69 add-highlighter shared/python/code/ regex '(\b\d+)?\.\d+\b' 0:value
     70 add-highlighter shared/python/code/ regex '\b\d+\.' 0:value
     71 # Imaginary formats
     72 add-highlighter shared/python/code/ regex '\b\d+\+\d+[jJ]\b' 0:value
     73 
     74 add-highlighter shared/python/docstring/ default-region fill documentation
     75 add-highlighter shared/python/docstring/ region '(>>>|\.\.\.) \K'    (?=''')|(?=""") ref python
     76 
     77 evaluate-commands %sh{
     78     # Grammar
     79     values="True False None self inf"
     80     meta="import from"
     81 
     82     # attributes and methods list based on https://docs.python.org/3/reference/datamodel.html
     83     attributes="__annotations__ __closure__ __code__ __defaults__ __dict__ __doc__
     84                 __globals__ __kwdefaults__ __module__ __name__ __qualname__"
     85     methods="__abs__ __add__ __aenter__ __aexit__ __aiter__ __and__ __anext__
     86              __await__ __bool__ __bytes__ __call__ __complex__ __contains__
     87              __del__ __delattr__ __delete__ __delitem__ __dir__ __divmod__
     88              __enter__ __eq__ __exit__ __float__ __floordiv__ __format__
     89              __ge__ __get__ __getattr__ __getattribute__ __getitem__
     90              __gt__ __hash__ __iadd__ __iand__ __ifloordiv__ __ilshift__
     91              __imatmul__ __imod__ __imul__ __index__ __init__
     92              __init_subclass__ __int__ __invert__ __ior__ __ipow__
     93              __irshift__ __isub__ __iter__ __itruediv__ __ixor__ __le__
     94              __len__ __length_hint__ __lshift__ __lt__ __matmul__
     95              __missing__ __mod__ __mul__ __ne__ __neg__ __new__ __or__
     96              __pos__ __pow__ __radd__ __rand__ __rdivmod__ __repr__
     97              __reversed__ __rfloordiv__ __rlshift__ __rmatmul__ __rmod__
     98              __rmul__ __ror__ __round__ __rpow__ __rrshift__ __rshift__
     99              __rsub__ __rtruediv__ __rxor__ __set__ __setattr__
    100              __setitem__ __set_name__ __slots__ __str__ __sub__
    101              __truediv__ __xor__"
    102 
    103     # built-in exceptions https://docs.python.org/3/library/exceptions.html
    104     exceptions="ArithmeticError AssertionError AttributeError BaseException BlockingIOError
    105                 BrokenPipeError BufferError BytesWarning ChildProcessError
    106                 ConnectionAbortedError ConnectionError ConnectionRefusedError
    107                 ConnectionResetError DeprecationWarning EOFError Exception
    108                 FileExistsError FileNotFoundError FloatingPointError FutureWarning
    109                 GeneratorExit ImportError ImportWarning IndentationError
    110                 IndexError InterruptedError IsADirectoryError KeyboardInterrupt
    111                 KeyError LookupError MemoryError ModuleNotFoundError NameError
    112                 NotADirectoryError NotImplementedError OSError OverflowError
    113                 PendingDeprecationWarning PermissionError ProcessLookupError
    114                 RecursionError ReferenceError ResourceWarning RuntimeError
    115                 RuntimeWarning StopAsyncIteration StopIteration SyntaxError
    116                 SyntaxWarning SystemError SystemExit TabError TimeoutError TypeError
    117                 UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError
    118                 UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning
    119                 ZeroDivisionError"
    120 
    121     # Keyword list is collected using `keyword.kwlist` from `keyword`
    122     keywords="and as assert async await break class continue def del elif else except exec
    123               finally for global if in is lambda nonlocal not or pass print
    124               raise return try while with yield"
    125 
    126     # Collected from `keyword.softkwlist`
    127     soft_keywords="_ case match"
    128 
    129     types="bool buffer bytearray bytes complex dict file float frozenset int
    130            list long memoryview object set str tuple unicode xrange"
    131 
    132     functions="abs all any ascii bin breakpoint callable chr classmethod compile complex
    133                delattr dict dir divmod enumerate eval exec filter
    134                format frozenset getattr globals hasattr hash help
    135                hex id __import__ input isinstance issubclass iter
    136                len locals map max memoryview min next oct open ord
    137                pow print property range repr reversed round
    138                setattr slice sorted staticmethod sum super type vars zip"
    139 
    140     join() { sep=$2; eval set -- $1; IFS="$sep"; echo "$*"; }
    141 
    142     # Add the language's grammar to the static completion list
    143     printf %s\\n "declare-option str-list python_static_words $(join "${values} ${meta} ${attributes} ${methods} ${exceptions} ${keywords} ${types} ${functions}" ' ')"
    144 
    145     # Highlight keywords
    146     printf %s "
    147         add-highlighter shared/python/code/ regex '\b($(join "${values}" '|'))\b' 0:value
    148         add-highlighter shared/python/code/ regex '\b($(join "${meta}" '|'))\b' 0:meta
    149         add-highlighter shared/python/code/ regex '\b($(join "${attributes}" '|'))\b' 0:attribute
    150         add-highlighter shared/python/code/ regex '\bdef\s+($(join "${methods}" '|'))\b' 1:function
    151         add-highlighter shared/python/code/ regex '\b($(join "${exceptions}" '|'))\b' 0:function
    152         add-highlighter shared/python/code/ regex '\b($(join "${keywords} ${soft_keywords}" '|'))\b' 0:keyword
    153         add-highlighter shared/python/code/ regex '\b($(join "${functions}" '|'))\b\(' 1:builtin
    154         add-highlighter shared/python/code/ regex '\b($(join "${types}" '|'))\b' 0:type
    155         add-highlighter shared/python/code/ regex '^\h*(@[\w_.]+))' 1:attribute
    156     "
    157 }
    158 
    159 add-highlighter shared/python/code/ regex (?<=[\w\s\d\)\]'"_])(<=|<<|>>|>=|<>?|>|!=|==|\||\^|&|\+|-|\*\*?|//?|%|~) 0:operator
    160 add-highlighter shared/python/code/ regex (?<=[\w\s\d'"_])((?<![=<>!]):?=(?![=])|[+*-]=) 0:builtin
    161 add-highlighter shared/python/code/ regex ^\h*(?:from|import)\h+(\S+) 1:module
    162 
    163 # Commands
    164 # ‾‾‾‾‾‾‾‾
    165 
    166 define-command -hidden python-insert-on-new-line %{ evaluate-commands -itersel -draft %{
    167     execute-keys <semicolon>
    168     try %{
    169         evaluate-commands -draft -save-regs '/"' %{
    170             # Ensure previous line is a comment
    171             execute-keys -draft kxs^\h*#+\h*<ret>
    172 
    173             # now handle the coment continuation logic
    174             try %{
    175                 # try and match a regular block comment, copying the prefix
    176                 execute-keys -draft -save-regs '' k x 1s^(\h*#+\h*)\S.*$ <ret> y
    177                 execute-keys -draft P
    178             } catch %{
    179                 try %{
    180                     # try and match a regular block comment followed by a single
    181                     # empty comment line
    182                     execute-keys -draft -save-regs '' kKx 1s^(\h*#+\h*)\S+\n\h*#+\h*$ <ret> y
    183                     execute-keys -draft P
    184                 } catch %{
    185                     try %{
    186                         # try and match a pair of empty comment lines, and delete
    187                         # them if we match
    188                         execute-keys -draft kKx <a-k> ^\h*#+\h*\n\h*#+\h*$ <ret> <a-d>
    189                     } catch %{
    190                         # finally, we need a special case for a new line inserted
    191                         # into a file that consists of a single empty comment - in
    192                         # that case we can't expect to copy the trailing whitespace,
    193                         # so we add our own
    194                         execute-keys -draft -save-regs '' k x1s^(\h*#+)\h*$<ret> y
    195                         execute-keys -draft P
    196                         execute-keys -draft i<space>
    197                     }
    198                 }
    199             }
    200         }
    201 
    202         # trim trailing whitespace on the previous line
    203         try %{ execute-keys -draft k x s\h+$<ret> d }
    204     }
    205 } }
    206 
    207 define-command -hidden python-indent-on-new-line %<
    208     evaluate-commands -draft -itersel %<
    209         # preserve previous line indent
    210         try %{ execute-keys -draft <semicolon> K <a-&> }
    211         # cleanup trailing whitespaces from previous line
    212         try %{ execute-keys -draft k x s \h+$ <ret> d }
    213         # indent after line ending with :
    214         try %{ execute-keys -draft , k x <a-k> :$ <ret> <a-K> ^\h*# <ret> j <a-gt> }
    215         # deindent closing brace/bracket when after cursor (for arrays and dictionaries)
    216         try %< execute-keys -draft x <a-k> ^\h*[}\]] <ret> gh / [}\]] <ret> m <a-S> 1<a-&> >
    217     >
    218 >
    219 
    220 §