kakoune

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

raku.kak (21053B)


      1 # https://www.raku.org/
      2 # ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
      3 # Adapted from source:
      4 #    <https://github.com/hankache/raku.nanorc>
      5 #    <https://github.com/mawww/kakoune/pull/5515>
      6 #
      7 
      8 # Detection
      9 # ‾‾‾‾‾‾‾‾‾
     10 
     11 hook global BufCreate .*\.raku(mod|doc|test)?$ %{
     12     set-option buffer filetype raku
     13 }
     14 
     15 # Initialization
     16 # ‾‾‾‾‾‾‾‾‾‾‾‾‾‾
     17 
     18 hook global WinSetOption filetype=raku %{
     19     require-module raku
     20 
     21     set-option window static_words %opt{raku_static_words}
     22 
     23     # cleanup trailing whitespaces when exiting insert mode
     24     hook window ModeChange pop:insert:.* -group raku-trim-indent %{ try %{ execute-keys -draft xs^\h+$<ret>d } }
     25     hook window InsertChar \n -group raku-insert raku-insert-on-new-line
     26     hook window InsertChar \n -group raku-indent raku-indent-on-new-line
     27     hook window InsertChar \{ -group raku-indent raku-indent-on-opening-curly-brace
     28     hook window InsertChar \} -group raku-indent raku-indent-on-closing-curly-brace
     29 
     30     hook -once -always window WinSetOption filetype=.* %{ remove-hooks window raku-.+ }
     31 }
     32 
     33 hook -group raku-highlight global WinSetOption filetype=raku %{
     34     add-highlighter window/raku ref raku
     35     hook -once -always window WinSetOption filetype=.* %{ remove-highlighter window/raku }
     36 }
     37 
     38 provide-module raku %§
     39 
     40 # Highlighters
     41 # ‾‾‾‾‾‾‾‾‾‾‾‾
     42 
     43 add-highlighter shared/raku regions
     44 add-highlighter shared/raku/code default-region group
     45 add-highlighter shared/raku/dquote region %{(?<!')"} %{(?<!\\)(\\\\)*"} group
     46 add-highlighter shared/raku/squote region %{'} %{(?<!\\)'} group
     47 
     48 # Comments - single line
     49 add-highlighter shared/raku/comment_line region %{#(?![|=])} %{$} fill comment
     50 # Comments - single/multiline
     51 add-highlighter shared/raku/comment-paren region -recurse \( %{\Q#`(} \) fill comment
     52 add-highlighter shared/raku/comment-brace region -recurse \{ %/\Q#`{/ \} fill comment
     53 add-highlighter shared/raku/comment-bracket region -recurse \[ %{\Q#`[} \] fill comment
     54 add-highlighter shared/raku/comment-angle region -recurse < %{\Q#`<} > fill comment
     55 
     56 # Rakudoc Declarator block/single line
     57 add-highlighter shared/raku/pod_block region -match-capture %{^=begin\h+[A-Za-z0-9'\-]+} %{^=end\h+[A-Za-z0-9'\-]+$} fill documentation
     58 add-highlighter shared/raku/pod_line  region %{#(?=[|=])} %{$} fill documentation
     59 
     60 # Heredocs
     61 add-highlighter shared/raku/heredoc-slash region -match-capture %{\b(?:q|qq|Q|qw|qx):to\h*/([\w'-]+)/} %{^\h*([\w'-]+)$} fill string
     62 add-highlighter shared/raku/heredoc-angle region -match-capture %{\b(?:q|qq|Q|qw|qx):to\h*<([\w'-]+)>} %{^\h*([\w'-]+)$} fill string
     63 
     64 # Double quoted strings
     65 add-highlighter shared/raku/dquote/ fill string
     66 add-highlighter shared/raku/dquote/ regex \{.*?\} 0:function
     67 
     68 # Single quoted strings
     69 add-highlighter shared/raku/squote/ fill string
     70 
     71 # Discolour loading a modules FQN
     72 add-highlighter shared/raku/code/ regex %{^(import|need|unit|use)\h+(lib|module)?(?S)(.+);} 0:default+fa
     73 
     74 # Variables
     75 add-highlighter shared/raku/code/ regex %{[$@%&](\.|!|\^)?([A-Za-z]|_)} 0:variable
     76 add-highlighter shared/raku/code/ regex %{[$@%&](\.|!|\^)?([A-Za-z]|_)([A-Za-z0-9]|-|_)*([A-Za-z0-9]|_)} 0:variable
     77 add-highlighter shared/raku/code/ regex %{[$@%&](\?|\*)([A-Z])([A-Z]|-)*([A-Z])} 0:variable
     78 
     79 # Angle brackets
     80 add-highlighter shared/raku/code/ regex %{<([A-Za-z0-9]|-| |\.|_|/)*>} 0:default
     81 add-highlighter shared/raku/code/ regex %{\$<([A-Za-z0-9]|-|_)*>} 0:default
     82 add-highlighter shared/raku/code/ regex %{(<|>)} 0:default
     83 
     84 # Versions
     85 add-highlighter shared/raku/code/ regex %{\b(v([0-9]|\*)(\.([A-Za-z0-9]|\*))*)\b} 0:default
     86 
     87 # Sym
     88 add-highlighter shared/raku/code/ regex %{:sym} 0:attribute
     89 
     90 # Regex
     91 add-highlighter shared/raku/code/ regex %{(?S)(m|rx|tr|TR|s|S)?/.*/} 0:attribute
     92 
     93 # Regex Match
     94 add-highlighter shared/raku/code/ regex %{\$/} 0:builtin
     95 
     96 # Numbers
     97 add-highlighter shared/raku/code/ regex %{\b([0-9]+)\b} 0:value
     98 add-highlighter shared/raku/code/ regex %{\b([0-9]*(\.|_)[0-9]+)\b} 0:value
     99 add-highlighter shared/raku/code/ regex %{\b([0-9]+(e)[0-9]+)\b} 0:value
    100 add-highlighter shared/raku/code/ regex %{\b([0-9]*(\+)*([0-9]|NaN\\|Inf\\)+i)\b} 0:value
    101 
    102 # Nativecall types
    103 add-highlighter shared/raku/code/ regex %{\b(int8|int16|int32|int64|uint8|uint16|uint32|uint64|long|longlong|num32|num64|size_t|bool|CArray|Pointer)\b} 0:type
    104 
    105 # Traits
    106 add-highlighter shared/raku/code/ regex %{\b(rw|required|native|repr|export|symbol)\b} 0:keyword
    107 
    108 # Booleans
    109 add-highlighter shared/raku/code/ regex %{\b(True|False)\b} 0:builtin
    110 
    111 # Ops
    112 add-highlighter shared/raku/code/ regex %{\b(eq|ne|gt|lt|le|ge|div|gcd|lcm|leg|cmp|ff)\b} 0:operator
    113 add-highlighter shared/raku/code/ regex %{\b(=|=>|==|!=|<|>|<=|>=|\+|\*|-|/|~|\*\*|%|%%|<=>|~~|\+\+|--|\?|!|\.\.|\.\.\^|\^\.\.|\^\.\.\^|\^|\.\.\.|\||\.)\b} 0:operator
    114 add-highlighter shared/raku/code/ regex %{\b(»|∈|∉|∋|∌|∩|∪|≼|≽|⊂|⊃|⊄|⊅|⊆|⊇|⊈|⊉|⊍|⊎|⊖|∅|∘|⚛)\b} 0:operator
    115 
    116 add-highlighter shared/raku/code/ regex %{\b(infix:<[+-]>)\b} 0:function
    117 
    118 # Grammar
    119 evaluate-commands %sh{
    120     # Exceptions
    121     exceptions="X::AdHoc X::Anon::Augment X::Anon::Multi X::Assignment::RO X::Attribute::NoPackage
    122                 X::Attribute::Package X::Attribute::Undeclared X::Augment::NoSuchType X::Bind
    123                 X::Bind::NativeType X::Bind::Slice X::Caller::NotDynamic X::Channel::ReceiveOnClosed
    124                 X::Channel::SendOnClosed X::Comp X::Composition::NotComposable X::Constructor::Positional
    125                 X::ControlFlow X::ControlFlow::Return X::DateTime::TimezoneClash X::Declaration::Scope
    126                 X::Declaration::Scope::Multi X::Does::TypeObject X::Eval::NoSuchLang X::Export::NameClash
    127                 X::Inheritance::NotComposed X::Inheritance::Unsupported X::IO X::IO::Chdir X::IO::Chmod
    128                 X::IO::Copy X::IO::Cwd X::IO::Dir X::IO::DoesNotExist X::IO::Link X::IO::Mkdir X::IO::Move
    129                 X::IO::Rename X::IO::Rmdir X::IO::Symlink X::IO::Unlink X::Method::InvalidQualifier
    130                 X::Method::NotFound X::Method::Private::Permission X::Method::Private::Unqualified
    131                 X::Mixin::NotComposable X::NoDispatcher X::Numeric::Real X::NYI X::Obsolete X::OS
    132                 X::OutOfRange X::Package::Stubbed X::Parameter::Default X::Parameter::MultipleTypeConstraints
    133                 X::Parameter::Placeholder X::Parameter::Twigil X::Parameter::WrongOrder X::Phaser::Multiple
    134                 X::Phaser::PrePost X::Placeholder::Block X::Placeholder::Mainline X::Pod X::Proc::Async
    135                 X::Proc::Async::AlreadyStarted X::Proc::Async::CharsOrBytes X::Proc::Async::MustBeStarted
    136                 X::Proc::Async::OpenForWriting X::Proc::Async::TapBeforeSpawn X::Proc::Unsuccessful
    137                 X::Promise::CauseOnlyValidOnBroken X::Promise::Vowed X::Redeclaration X::Role::Initialization
    138                 X::Seq::Consumed X::Sequence::Deduction X::Signature::NameClash X::Signature::Placeholder
    139                 X::Str::Numeric X::StubCode X::Syntax X::Syntax::Augment::WithoutMonkeyTyping
    140                 X::Syntax::Comment::Embedded X::Syntax::Confused X::Syntax::InfixInTermPosition
    141                 X::Syntax::Malformed X::Syntax::Missing X::Syntax::NegatedPair X::Syntax::NoSelf
    142                 X::Syntax::Number::RadixOutOfRange X::Syntax::P5 X::Syntax::Regex::Adverb
    143                 X::Syntax::Regex::SolitaryQuantifier X::Syntax::Reserved X::Syntax::Self::WithoutObject
    144                 X::Syntax::Signature::InvocantMarker X::Syntax::Term::MissingInitializer X::Syntax::UnlessElse
    145                 X::Syntax::Variable::Match X::Syntax::Variable::Numeric X::Syntax::Variable::Twigil
    146                 X::Temporal X::Temporal::InvalidFormat X::TypeCheck X::TypeCheck::Assignment X::TypeCheck::Binding
    147                 X::TypeCheck::Return X::TypeCheck::Splice X::Undeclared"
    148 
    149     # Keywords
    150     keywords="my our class role grammar is does sub method submethod try CATCH default when if
    151               elsif else unless with orwith without for given proceed succeed loop while until
    152               repeat module use need import require unit constant enum multi return has token
    153               rule make made proto state augment but anon supersede let subset gather returns
    154               return-rw"
    155 
    156     # Methods
    157     methods="ACCEPTS ASSIGN-KEY ASSIGN-POS AT-KEY AT-POS Array BIND-KEY BIND-POS Bag BagHash Bool
    158              Bridge CALL-ME CREATE Capture Channel Complex DELETE-KEY DELETE-POS DESTROY DISTROnames
    159              Date DateTime EVAL EXISTS-KEY EXISTS-POS Hash IO IO::Notification.watch-path Instant
    160              Int KERNELnames List Map Mix MixHash NFC NFD NFKC NFKD Num Numeric Promise Rat Real
    161              SPEC Set SetHash Slip Str Supply VMnames WHERE WHEREFORE WHICH WHY abs abs2rel absolute
    162              accept accessed acquire act action actions add add_attribute add_enum_value add_fallback
    163              add_method add_parent add_private_method add_role add_trustee adverb after all allocate
    164              allof allowed alternative-names annotations antipair antipairs any anyof app_lifetime
    165              append arch archname args arity assuming ast at attributes auth backtrace base base-repeating
    166              basename batch bind-stderr bind-stdin bind-stdout bind-udp bits bless block bool-only
    167              bounds break broken build-date bytes cache calling-package can cancel candidates cando
    168              canonpath caps caption capture catdir categorize categorize-list catfile catpath cause
    169              ceiling changed channel chdir child child-name child-typename chmod chomp chunks classify
    170              classify-list cleanup clone close close-stdin closed code codes collate column comb
    171              combinations command comment compiler compose compose_type composer condition config
    172              configure_destroy configure_type_checking conj connect constraints construct contains
    173              contents copy count count-only cpu-cores cpu-usage create_type cue curdir curupdir d
    174              day day-of-month day-of-week day-of-year daycount days-in-month declaration decode
    175              decoder deepmap default defined delayed denominator desc destroyers devnull did-you-mean
    176              dir-sep dirname do does done duckmap dynamic e eager earlier elems emit enclosing encode
    177              encoder encoding end ends-with enum_from_value enum_value_list enum_values enums eof
    178              exception excludes-max excludes-min exitcode exp expected extension f fail feature file
    179              filename find_method find_method_qualified finish first flat flatmap floor flush fmt
    180              format formatter freeze from from-list from-loop from-posix full get get_value getc
    181              gist got grab grabpairs grep handle handled handles hardware has_accessor hash head
    182              headers hh-mm-ss hidden hides hour how hyper id illegal im in in-timezone indent indices
    183              infinite infix install_method_cache instead int-bounds interval invalid-str invert
    184              invocant is-absolute is-hidden is-initial-thread is-int is-lazy is-leap-year is-relative
    185              is-routine is-setting is-win isNaN is_trusted is_type isa item iterator join keep kept
    186              key keyof keys kill kv kxxv l lang last later lazy leading level line lines link list
    187              listen live local lock lookup lsb made make map match max maxpairs merge message method
    188              method_table methods migrate min minmax minpairs minute misplaced mode modified month
    189              move msb multi multiness my name named named_names narrow native-descriptor new
    190              new-from-daycount new-from-pairs new_type next next-handle nl-in nl-out nodemap none
    191              norm not note now nude numerator of offset offset-in-hours offset-in-minutes old
    192              on-close on-switch one open opened operation optional ords orig os-error osname
    193              out-buffer package package-kind package-name packages pair pairs pairup parameter params
    194              parent parent-name parents parse parsefile parts path path-sep payload peer-host peer-port
    195              perl permutations phaser pick pickpairs pid placeholder plus polar poll polymod pop pos
    196              positional posix postfix postmatch precomp-ext precomp-target pred prefix prematch prepend
    197              print print-nl print-to printf private private_method_table proc produce promise protect
    198              pull-one push push-all push-at-least push-exactly push-until-lazy put qualifier-type
    199              quit r race radix rand range raw re read readchars readonly ready reallocate reals reason
    200              rebless receive recv redispatcher redo reduce rel2abs relative release rename repeated
    201              replacement reserved resolve restore result resume rethrow reverse right role roles_to_compose
    202              rolish roll rootdir roots rotor round routine-type run rwx s say schedule-on scheduler
    203              scope sec second seek self send set-instruments set_hidden set_name set_package set_rw
    204              set_value setup_finalization shape share shell shift sibling sigil sign signal signals
    205              signature sink sink-all skip skip-at-least skip-at-least-pull-one skip-one slurp slurp-rest
    206              slurpy so socket-host socket-port sort source source-package spawn splice split splitdir
    207              splitpath spurt sqrt squish stable start started starts-with status stderr stdout sub_signature
    208              subbuf subbuf-rw subname subparse subst subst-mutate substr-eq substr-rw succ sum symlink
    209              t tail take tap target target-name tell then throttle throw timezone tmpdir to to-posix
    210              today toggle total trailing trans tree trim trim-leading trim-trailing truncate truncated-to
    211              trusts try_acquire trying twigil type type_captures typename udp uncaught_handler unimatch
    212              uniname uninames uniprop uniprops unique unival univals unlink unlock unpack unpolar unshift
    213              unwrap updir utc value values variable verbose-config version volume vow w wait watch watch-path
    214              week week-number week-year weekday-of-month what when whole-second words workaround wrap write
    215              write-to x yada year yield yyyy-mm-dd z zip zip-latest WHAT WHO HOW DEFINITE VAR mro BUILD"
    216 
    217     # Phasers
    218     phasers="BEGIN CHECK INIT END CLOSE ENTER LEAVE KEEP UNDO PRE POST FIRST NEXT LAST CATCH CONTROL QUIT DOC"
    219 
    220     # Pragmas
    221     pragmas="MONKEY-SEE-NO-EVAL MONKEY-TYPING MONKEY-GUTS MONKEY experimental fatal lib newline nqp"
    222 
    223     # Subs
    224     subroutines="Bool EVALFILE MAIN T USAGE abs acos acosec acosech acosh acotan acotanh asec asech asin
    225                  asinh atan atan2 atanh atomic-assign atomic-dec-fetch atomic-fetch atomic-fetch-add
    226                  atomic-fetch-dec atomic-fetch-inc atomic-fetch-sub atomic-inc-fetch await bag callframe
    227                  callsame callwith cas categorize ceiling cglobal chars chdir chmod chomp chop chr chrs
    228                  cis classify codes comb combinations cos cosec cosech cosh cotan cotanh cross defined
    229                  die dir elems end exit exp explicitly-manage expmod fc first flat flip floor full-barrier
    230                  gist grep index indir is-prime item join keys kv lastcall lc lines
    231                  log log10 map mix mkdir nativecast nativesizeof nextcallee nextsame nextwith open ord
    232                  ords pack pairs parse-base parse-names periods permutations pick pop print produce prompt
    233                  push put rand reduce repeated report reverse rindex rmdir roll roots rotate round roundrobin
    234                  run samecase samemark samewith say sech set shell shift signal sin sinh sleep sleep-timer
    235                  sleep-until slip slurp snap snapper sort splice split sprintf spurt sqrt squish srand
    236                  subbuf-rw substr sum take take-rw tan tanh tc tclc trim trim-leading trim-trailing truncate
    237                  uc uniparse unique unival unshift val values warn wordcase words zip"
    238 
    239     # Test Module
    240     tests="plan done-testing bail-out todo skip skip-rest diag subtest pass flunk ok nok cmp-ok
    241            is-deeply isnt is-approx like unlike use-ok isa-ok does-ok can-ok dies-ok lives-ok
    242            eval-dies-ok eval-lives-ok throws-like fails-like"
    243 
    244     # Types
    245     types="Any Array Associative AST atomicint Attribute Backtrace Backtrace::Frame Bag Baggy BagHash
    246            Blob Block Bool Buf Callable CallFrame Cancellation Capture Channel Code compiler Complex
    247            ComplexStr Cool CurrentThreadScheduler Cursor Date Dateish DateTime Distro Duration Encoding
    248            Exception Failure FatRat Grammar Hash HyperWhatever Instant Int IntStr IO IO::ArgFiles
    249            IO::CatHandle IO::Handle IO::Notification IO::Path IO::Path::Cygwin IO::Path::QNX IO::Path::Unix
    250            IO::Path::Win32 IO::Pipe IO::Socket IO::Socket::Async IO::Socket::INET IO::Spec IO::Spec::Cygwin
    251            IO::Spec::QNX IO::Spec::Unix IO::Spec::Win32 IO::Special Iterable Iterator Junction Kernel
    252            Label List Lock Lock::Async Macro Map Match Metamodel::AttributeContainer Metamodel::C3MRO
    253            Metamodel::ClassHOW Metamodel::EnumHOW Metamodel::Finalization Metamodel::MethodContainer
    254            Metamodel::MROBasedMethodDispatch Metamodel::MultipleInheritance Metamodel::Naming
    255            Metamodel::Primitives Metamodel::PrivateMethodContainer Metamodel::RoleContainer
    256            Metamodel::Trusting Method Mix MixHash Mixy Mu NFC NFD NFKC NFKD Nil Num Numeric NumStr
    257            ObjAt Order Pair Parameter Perl Pod::Block Pod::Block::Code Pod::Block::Comment
    258            Pod::Block::Declarator Pod::Block::Named Pod::Block::Para Pod::Block::Table Pod::Heading
    259            Pod::Item Positional PositionalBindFailover Proc Proc::Async Promise Proxy PseudoStash
    260            QuantHash Range Rat Rational RatStr Real Regex Routine Scalar Scheduler Semaphore Seq Set
    261            SetHash Setty Signature Slip Stash Str StrDistance Stringy Sub Submethod Supplier
    262            Supplier::Preserving Supply Systemic Tap Telemetry Telemetry::Instrument::Thread
    263            Telemetry::Instrument::Usage Telemetry::Period Telemetry::Sampler Thread ThreadPoolScheduler
    264            UInt Uni utf8 Variable Version VM Whatever WhateverCode WrapHandle int uint num str"
    265 
    266     join() { sep=$2; eval set -- $1; IFS="$sep"; echo "$*"; }
    267 
    268     # Add the language's grammar to the static completion list
    269     printf %s\\n "declare-option str-list raku_static_words $(join "${exceptions} ${keywords} ${methods} ${phasers} ${pragmas} ${subroutines} ${tests} ${types}" ' ')"
    270 
    271     # Highlight keywords
    272     printf %s "
    273         add-highlighter shared/raku/code/ regex \b($(join "${exceptions}" '|'))\b 0:default
    274         add-highlighter shared/raku/code/ regex \b($(join "${keywords}" '|'))\b 0:keyword
    275         add-highlighter shared/raku/code/ regex \b($(join "${methods}" '|'))\b 0:function
    276         add-highlighter shared/raku/code/ regex \b($(join "${phasers}" '|'))\b 0:function
    277         add-highlighter shared/raku/code/ regex \b($(join "${pragmas}" '|'))\b 0:function
    278         add-highlighter shared/raku/code/ regex \b($(join "${subroutines}" '|'))\b 0:function
    279         add-highlighter shared/raku/code/ regex \b($(join "${tests}" '|'))\b 0:default+u
    280         add-highlighter shared/raku/code/ regex \b($(join "${types}" '|'))\b 0:type
    281     "
    282 }
    283 
    284 # Commands
    285 # ‾‾‾‾‾‾‾‾
    286 
    287 define-command -hidden raku-insert-on-new-line %~
    288     evaluate-commands -draft -itersel %=
    289         # copy # comments prefix and following white spaces
    290         try %{ execute-keys -draft <semicolon><c-s>kx s ^\h*\K#\h* <ret> y<c-o>P<esc> }
    291     =
    292 ~
    293 
    294 define-command -hidden raku-indent-on-new-line %~
    295     evaluate-commands -draft -itersel %=
    296         # preserve previous line indent
    297         try %{ execute-keys -draft <semicolon>K<a-&> }
    298         # indent after lines ending with { or (
    299         try %[ execute-keys -draft kx <a-k> [{(]\h*$ <ret> j<a-gt> ]
    300         # cleanup trailing white spaces on the previous line
    301         try %{ execute-keys -draft kx s \h+$ <ret>d }
    302         # align to opening paren of previous line
    303         try %{ execute-keys -draft [( <a-k> \A\([^\n]+\n[^\n]*\n?\z <ret> s \A\(\h*.|.\z <ret> '<a-;>' & }
    304         # indent after a switch's case/default statements
    305         try %[ execute-keys -draft kx <a-k> ^\h*(case|default).*:$ <ret> j<a-gt> ]
    306         # indent after if|else|while|for
    307         try %[ execute-keys -draft <semicolon><a-F>)MB <a-k> \A(if|else|while|for)\h*\(.*\)\h*\n\h*\n?\z <ret> s \A|.\z <ret> 1<a-&>1<a-,><a-gt> ]
    308         # deindent closing brace(s) when after cursor
    309         try %[ execute-keys -draft x <a-k> ^\h*[})] <ret> gh / [})] <ret> m <a-S> 1<a-&> ]
    310     =
    311 ~
    312 
    313 define-command -hidden raku-indent-on-opening-curly-brace %[
    314     # align indent with opening paren when { is entered on a new line after the closing paren
    315     try %[ execute-keys -draft -itersel h<a-F>)M <a-k> \A\(.*\)\h*\n\h*\{) <ret> s \A|.\z <ret> 1<a-&> ]
    316 ]
    317 
    318 define-command -hidden raku-indent-on-closing-curly-brace %[
    319     # align to opening curly brace when alone on a line
    320     try %[ execute-keys -itersel -draft <a-h><a-k>^\h+\}$<ret>hms\A|.\z<ret>1<a-&> ]
    321 ]
    322 
    323 §