├── indent ├── typescriptreact.vim └── typescript.vim ├── syntax ├── typescriptreact.vim └── typescript.vim ├── compiler ├── typescriptreact.vim └── typescript.vim ├── ftplugin ├── typescriptreact.vim └── typescript.vim ├── vimshot01.png ├── ftdetect └── typescript.vim └── README.md /indent/typescriptreact.vim: -------------------------------------------------------------------------------- 1 | runtime! indent/typescript.vim 2 | -------------------------------------------------------------------------------- /syntax/typescriptreact.vim: -------------------------------------------------------------------------------- 1 | runtime! syntax/typescript.vim 2 | -------------------------------------------------------------------------------- /compiler/typescriptreact.vim: -------------------------------------------------------------------------------- 1 | runtime! compiler/typescript.vim 2 | -------------------------------------------------------------------------------- /ftplugin/typescriptreact.vim: -------------------------------------------------------------------------------- 1 | runtime! ftplugin/typescript.vim 2 | -------------------------------------------------------------------------------- /vimshot01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leafgarland/typescript-vim/HEAD/vimshot01.png -------------------------------------------------------------------------------- /ftdetect/typescript.vim: -------------------------------------------------------------------------------- 1 | " use `set filetype` to override default filetype=xml for *.ts files 2 | autocmd BufNewFile,BufRead *.ts set filetype=typescript 3 | " use `setfiletype` to not override any other plugins like ianks/vim-tsx 4 | autocmd BufNewFile,BufRead *.tsx setfiletype typescript 5 | -------------------------------------------------------------------------------- /ftplugin/typescript.vim: -------------------------------------------------------------------------------- 1 | if exists("b:did_ftplugin") 2 | finish 3 | endif 4 | let b:did_ftplugin = 1 5 | 6 | let s:cpo_save = &cpo 7 | set cpo-=C 8 | 9 | compiler typescript 10 | setlocal commentstring=//\ %s 11 | 12 | " Set 'formatoptions' to break comment lines but not other lines, 13 | " " and insert the comment leader when hitting or using "o". 14 | setlocal formatoptions-=t formatoptions+=croql 15 | 16 | setlocal suffixesadd+=.ts,.tsx 17 | 18 | let b:undo_ftplugin = "setl cms< fo< sua<" 19 | 20 | let &cpo = s:cpo_save 21 | unlet s:cpo_save 22 | -------------------------------------------------------------------------------- /compiler/typescript.vim: -------------------------------------------------------------------------------- 1 | if exists("current_compiler") 2 | finish 3 | endif 4 | let current_compiler = "typescript" 5 | 6 | if !exists("g:typescript_compiler_binary") 7 | let g:typescript_compiler_binary = "tsc" 8 | endif 9 | 10 | if !exists("g:typescript_compiler_options") 11 | let g:typescript_compiler_options = "" 12 | endif 13 | 14 | if exists(":CompilerSet") != 2 15 | command! -nargs=* CompilerSet setlocal 16 | endif 17 | 18 | let s:cpo_save = &cpo 19 | set cpo-=C 20 | 21 | execute 'CompilerSet makeprg=' 22 | \ . escape(g:typescript_compiler_binary, ' ') 23 | \ . '\ ' 24 | \ . escape(g:typescript_compiler_options, ' ') 25 | \ . '\ $*\ %' 26 | 27 | CompilerSet errorformat=%+A\ %#%f\ %#(%l\\\,%c):\ %m,%C%m 28 | 29 | let &cpo = s:cpo_save 30 | unlet s:cpo_save 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | An old Typescript Syntax for Vim 2 | ========================= 3 | 4 | --- 5 | 6 | NOTE: This Typescript syntax was created before Typescript's 1.0 release, more than a decade ago. I hope it 7 | has been helpful but there are now other options available. Vim has included 8 | [Typescript syntax](https://github.com/vim/vim/blob/master/runtime/syntax/typescript.vim) for some years, 9 | which receives more frequent updates at its own [repository](https://github.com/HerringtonDarkholme/yats.vim). 10 | Neovim can also use a [treesitter grammar](https://github.com/tree-sitter/tree-sitter-typescript) for highlighting. 11 | 12 | --- 13 | 14 | Syntax file and other settings for [TypeScript](http://typescriptlang.org). The 15 | syntax file was originally from this 2012 [blog 16 | post](https://docs.microsoft.com/en-us/archive/blogs/interoperability/sublime-text-vi-emacs-typescript-enabled). 17 | 18 | Checkout [Tsuquyomi](https://github.com/Quramy/tsuquyomi) for omni-completion 19 | and other features for TypeScript editing. 20 | 21 | Install 22 | ------- 23 | 24 | From Vim 8 onward, the plugin can be installed as simply as (Unix/Mac): 25 | ``` 26 | git clone https://github.com/leafgarland/typescript-vim.git ~/.vim/pack/typescript/start/typescript-vim 27 | ``` 28 | 29 | On Windows/Powershell, use the following: 30 | ``` 31 | git clone https://github.com/leafgarland/typescript-vim.git $home/vimfiles/pack/typescript/start/typescript-vim 32 | ``` 33 | 34 | For older versions of Vim, the simplest way to install is via a Vim add-in manager such as 35 | [Plug](https://github.com/junegunn/vim-plug), 36 | [Vundle](https://github.com/gmarik/vundle) or 37 | [Pathogen](https://github.com/tpope/vim-pathogen/). 38 | 39 | _See the [Installation Wiki](https://github.com/leafgarland/typescript-vim/wiki/Installation)_ 40 | 41 | ### Pathogen 42 | 43 | ``` 44 | git clone https://github.com/leafgarland/typescript-vim.git ~/.vim/bundle/typescript-vim 45 | ``` 46 | 47 | If you want to install manually then you need to copy the files from this 48 | repository into your vim path, see the vim docs for [:help 49 | runtimepath](http://vimdoc.sourceforge.net/htmldoc/options.html#'runtimepath') 50 | for more information. This might be as simple as copying the files and 51 | directories to `~/.vim/` but it depends on your Vim install and operating 52 | system. 53 | 54 | Usage 55 | ----- 56 | 57 | Once the files are installed the syntax highlighting and other settings will be 58 | automatically enabled anytime you edit a `.ts` file. 59 | 60 | Indenting 61 | --------- 62 | 63 | This plugin includes a custom indenter (based on [pangloss/vim-javascript's 64 | indenter](https://github.com/pangloss/vim-javascript/blob/master/indent/javascript.vim)), 65 | it works pretty well but there are cases where it fails. If these bother you or 66 | want to use other indent settings you can disable it by setting a flag in your 67 | `.vimrc`: 68 | 69 | ```vim 70 | let g:typescript_indent_disable = 1 71 | ``` 72 | 73 | If you want the indenter to automatically indent chained method calls as you type. 74 | 75 | ```typescript 76 | something 77 | .foo() 78 | .bar(); 79 | ``` 80 | 81 | Then add something like `setlocal indentkeys+=0.` to your `.vimrc`, see `:help 82 | 'indentkeys'` in vim for more information. 83 | 84 | If you use the `=` operator to re-indent code it will always indent 85 | chained method calls - this can be disabled by changing the regex the 86 | indent script uses to identify indented lines. In this case removing '.' 87 | from the regex means that it wont indent lines starting with '.'. Note, 88 | this is not ideal as the regex may change making your setting out of date. 89 | 90 | ```vim 91 | let g:typescript_opfirst='\%([<>=,?^%|*/&]\|\([-:+]\)\1\@!\|!=\|in\%(stanceof\)\=\>\)' 92 | ``` 93 | 94 | Compiler settings 95 | ----------------- 96 | 97 | This plugin contains compiler settings to set `makeprg` and `errorformat`. 98 | The compiler settings enable you to call the `tsc` compiler directly from Vim 99 | and display any errors or warnings in Vim's QuickFix window. 100 | 101 | To run the compiler, enter `:make`, this will run `tsc` against the last saved 102 | version of your currently edited file. 103 | 104 | The default for `makeprg` is `tsc $* %`. You can enter other compiler options into your `:make` 105 | command line and they will be inserted in place of `$*`. 106 | 107 | There are options to change the compiler name and to insert default options. 108 | 109 | ```vim 110 | let g:typescript_compiler_binary = 'tsc' 111 | let g:typescript_compiler_options = '' 112 | ``` 113 | 114 | These options will be passed to the binary as command arguments. For example, 115 | if `g:typescript_compiler_binary = 'tsc'` and `g:typescript_compiler_options = '--lib es6'`, 116 | `l:makeprg` will be: `tsc --lib es6 $* %`. 117 | 118 | You can completely override this plugin's compiler settings with something like 119 | this in your `.vimrc`, where you can set makeprg to whatever you want. 120 | 121 | ```vim 122 | autocmd FileType typescript :set makeprg=tsc 123 | ``` 124 | 125 | Note, this plugin's compiler settings are not used by Syntastic which has its own 126 | way of changing the options. See https://github.com/scrooloose/syntastic#faqargs. 127 | 128 | You can use something like this in your `.vimrc` to make the QuickFix 129 | window automatically appear if `:make` has any errors. 130 | 131 | ```vim 132 | autocmd QuickFixCmdPost [^l]* nested cwindow 133 | autocmd QuickFixCmdPost l* nested lwindow 134 | ``` 135 | 136 | Syntax highlighting 137 | ------------------- 138 | 139 | Syntax highlighting for TypeScript can be customized by following variables. 140 | 141 | - `g:typescript_ignore_typescriptdoc`: When this variable is defined, doccomments will not be 142 | highlighted. 143 | - `g:typescript_ignore_browserwords`: When this variable is set to `1`, browser API names such as 144 | `window` or `document` will not be highlighted. (default to `0`) 145 | 146 | ![Obligatory screenshot](https://raw.github.com/leafgarland/typescript-vim/master/vimshot01.png) 147 | -------------------------------------------------------------------------------- /indent/typescript.vim: -------------------------------------------------------------------------------- 1 | " Vim indent file 2 | " Language: Typescript 3 | " Acknowledgement: Almost direct copy from https://github.com/pangloss/vim-javascript 4 | 5 | " Only load this indent file when no other was loaded. 6 | if exists('b:did_indent') || get(g:, 'typescript_indent_disable', 0) 7 | finish 8 | endif 9 | let b:did_indent = 1 10 | 11 | " Now, set up our indentation expression and keys that trigger it. 12 | setlocal indentexpr=GetTypescriptIndent() 13 | setlocal autoindent nolisp nosmartindent 14 | setlocal indentkeys+=0],0) 15 | 16 | let b:undo_indent = 'setlocal indentexpr< smartindent< autoindent< indentkeys<' 17 | 18 | " Only define the function once. 19 | if exists('*GetTypescriptIndent') 20 | finish 21 | endif 22 | 23 | let s:cpo_save = &cpo 24 | set cpo&vim 25 | 26 | " Get shiftwidth value 27 | if exists('*shiftwidth') 28 | function s:sw() 29 | return shiftwidth() 30 | endfunction 31 | else 32 | function s:sw() 33 | return &sw 34 | endfunction 35 | endif 36 | 37 | " searchpair() wrapper 38 | if has('reltime') 39 | function s:GetPair(start,end,flags,skip,time,...) 40 | return searchpair('\m'.a:start,'','\m'.a:end,a:flags,a:skip,max([prevnonblank(v:lnum) - 2000,0] + a:000),a:time) 41 | endfunction 42 | else 43 | function s:GetPair(start,end,flags,skip,...) 44 | return searchpair('\m'.a:start,'','\m'.a:end,a:flags,a:skip,max([prevnonblank(v:lnum) - 1000,get(a:000,1)])) 45 | endfunction 46 | endif 47 | 48 | " Regex of syntax group names that are or delimit string or are comments. 49 | let s:syng_strcom = 'string\|comment\|regex\|special\|doc\|template\%(braces\)\@!' 50 | let s:syng_str = 'string\|template\|special' 51 | let s:syng_com = 'comment\|doc' 52 | " Expression used to check whether we should skip a match with searchpair(). 53 | let s:skip_expr = "synIDattr(synID(line('.'),col('.'),0),'name') =~? '".s:syng_strcom."'" 54 | 55 | function s:skip_func() 56 | if !s:free || search('\m`\|\${\|\*\/','nW',s:looksyn) 57 | let s:free = !eval(s:skip_expr) 58 | let s:looksyn = line('.') 59 | return !s:free 60 | endif 61 | let s:looksyn = line('.') 62 | return getline('.') =~ '\%<'.col('.').'c\/.\{-}\/\|\%>'.col('.').'c[''"]\|\\$' && 63 | \ eval(s:skip_expr) 64 | endfunction 65 | 66 | function s:alternatePair(stop) 67 | let pos = getpos('.')[1:2] 68 | while search('\m[][(){}]','bW',a:stop) 69 | if !s:skip_func() 70 | let idx = stridx('])}',s:looking_at()) 71 | if idx + 1 72 | if s:GetPair(['\[','(','{'][idx], '])}'[idx],'bW','s:skip_func()',2000,a:stop) <= 0 73 | break 74 | endif 75 | else 76 | return 77 | endif 78 | endif 79 | endwhile 80 | call call('cursor',pos) 81 | endfunction 82 | 83 | function s:save_pos(f,...) 84 | let l:pos = getpos('.')[1:2] 85 | let ret = call(a:f,a:000) 86 | call call('cursor',l:pos) 87 | return ret 88 | endfunction 89 | 90 | function s:syn_at(l,c) 91 | return synIDattr(synID(a:l,a:c,0),'name') 92 | endfunction 93 | 94 | function s:looking_at() 95 | return getline('.')[col('.')-1] 96 | endfunction 97 | 98 | function s:token() 99 | return s:looking_at() =~ '\k' ? expand('') : s:looking_at() 100 | endfunction 101 | 102 | function s:previous_token() 103 | let l:n = line('.') 104 | if (s:looking_at() !~ '\k' || search('\m\<','cbW')) && search('\m\S','bW') 105 | if (getline('.')[col('.')-2:col('.')-1] == '*/' || line('.') != l:n && 106 | \ getline('.') =~ '\%<'.col('.').'c\/\/') && s:syn_at(line('.'),col('.')) =~? s:syng_com 107 | while search('\m\/\ze[/*]','cbW') 108 | if !search('\m\S','bW') 109 | break 110 | elseif s:syn_at(line('.'),col('.')) !~? s:syng_com 111 | return s:token() 112 | endif 113 | endwhile 114 | else 115 | return s:token() 116 | endif 117 | endif 118 | return '' 119 | endfunction 120 | 121 | function s:others(p) 122 | return "((line2byte(line('.')) + col('.')) <= ".(line2byte(a:p[0]) + a:p[1]).") || ".s:skip_expr 123 | endfunction 124 | 125 | function s:tern_skip(p) 126 | return s:GetPair('{','}','nbW',s:others(a:p),200,a:p[0]) > 0 127 | endfunction 128 | 129 | function s:tern_col(p) 130 | return s:GetPair('?',':\@ 0 132 | endfunction 133 | 134 | function s:label_col() 135 | let pos = getpos('.')[1:2] 136 | let [s:looksyn,s:free] = pos 137 | call s:alternatePair(0) 138 | if s:save_pos('s:IsBlock') 139 | let poss = getpos('.')[1:2] 140 | return call('cursor',pos) || !s:tern_col(poss) 141 | elseif s:looking_at() == ':' 142 | return !s:tern_col([0,0]) 143 | endif 144 | endfunction 145 | 146 | " configurable regexes that define continuation lines, not including (, {, or [. 147 | let s:opfirst = '^' . get(g:,'typescript_opfirst', 148 | \ '\%([<>=,?^%|*/&]\|\([-.:+]\)\1\@!\|!=\|in\%(stanceof\)\=\>\)') 149 | let s:continuation = get(g:,'typescript_continuation', 150 | \ '\%([-+<>=,.~!?/*^%|&:]\|\<\%(typeof\|delete\|void\|in\|instanceof\)\)') . '$' 151 | 152 | function s:continues(ln,con) 153 | return !cursor(a:ln, match(' '.a:con,s:continuation)) && 154 | \ eval( (['s:syn_at(line("."),col(".")) !~? "regex"'] + 155 | \ repeat(['getline(".")[col(".")-2] != tr(s:looking_at(),">","=")'],3) + 156 | \ repeat(['s:previous_token() != "."'],5) + [1])[ 157 | \ index(split('/ > - + typeof in instanceof void delete'),s:token())]) 158 | endfunction 159 | 160 | " get the line of code stripped of comments and move cursor to the last 161 | " non-comment char. 162 | function s:Trim(ln) 163 | call cursor(a:ln+1,1) 164 | call s:previous_token() 165 | return strpart(getline('.'),0,col('.')) 166 | endfunction 167 | 168 | " Find line above 'lnum' that isn't empty or in a comment 169 | function s:PrevCodeLine(lnum) 170 | let l:n = prevnonblank(a:lnum) 171 | while l:n 172 | if getline(l:n) =~ '^\s*\/[/*]' 173 | if (stridx(getline(l:n),'`') > 0 || getline(l:n-1)[-1:] == '\') && 174 | \ s:syn_at(l:n,1) =~? s:syng_str 175 | return l:n 176 | endif 177 | let l:n = prevnonblank(l:n-1) 178 | elseif getline(l:n) =~ '\([/*]\)\1\@![/*]' && s:syn_at(l:n,1) =~? s:syng_com 179 | let l:n = s:save_pos('eval', 180 | \ 'cursor('.l:n.',1) + search(''\m\/\*'',"bW")') 181 | else 182 | return l:n 183 | endif 184 | endwhile 185 | endfunction 186 | 187 | " Check if line 'lnum' has a balanced amount of parentheses. 188 | function s:Balanced(lnum) 189 | let l:open = 0 190 | let l:line = getline(a:lnum) 191 | let pos = match(l:line, '[][(){}]', 0) 192 | while pos != -1 193 | if s:syn_at(a:lnum,pos + 1) !~? s:syng_strcom 194 | let l:open += match(' ' . l:line[pos],'[[({]') 195 | if l:open < 0 196 | return 197 | endif 198 | endif 199 | let pos = match(l:line, '[][(){}]', pos + 1) 200 | endwhile 201 | return !l:open 202 | endfunction 203 | 204 | function s:OneScope(lnum) 205 | let pline = s:Trim(a:lnum) 206 | let kw = 'else do' 207 | if pline[-1:] == ')' && s:GetPair('(', ')', 'bW', s:skip_expr, 100) > 0 208 | call s:previous_token() 209 | let kw = 'for if let while with' 210 | if index(split('await each'),s:token()) + 1 211 | call s:previous_token() 212 | let kw = 'for' 213 | endif 214 | endif 215 | return pline[-2:] == '=>' || index(split(kw),s:token()) + 1 && 216 | \ s:save_pos('s:previous_token') != '.' 217 | endfunction 218 | 219 | " returns braceless levels started by 'i' and above lines * &sw. 'num' is the 220 | " lineNr which encloses the entire context, 'cont' if whether line 'i' + 1 is 221 | " a continued expression, which could have started in a braceless context 222 | function s:iscontOne(i,num,cont) 223 | let [l:i, l:num, bL] = [a:i, a:num + !a:num, 0] 224 | let pind = a:num ? indent(l:num) + s:W : 0 225 | let ind = indent(l:i) + (a:cont ? 0 : s:W) 226 | while l:i >= l:num && (ind > pind || l:i == l:num) 227 | if indent(l:i) < ind && s:OneScope(l:i) 228 | let bL += s:W 229 | let l:i = line('.') 230 | elseif !a:cont || bL || ind < indent(a:i) 231 | break 232 | endif 233 | let ind = min([ind, indent(l:i)]) 234 | let l:i = s:PrevCodeLine(l:i - 1) 235 | endwhile 236 | return bL 237 | endfunction 238 | 239 | " https://github.com/sweet-js/sweet.js/wiki/design#give-lookbehind-to-the-reader 240 | function s:IsBlock() 241 | if s:looking_at() == '{' 242 | let l:n = line('.') 243 | let char = s:previous_token() 244 | if match(s:stack,'xml\|jsx') + 1 && s:syn_at(line('.'),col('.')-1) =~? 'xml\|jsx' 245 | return char != '{' 246 | elseif char =~ '\k' 247 | return index(split('return const let import export yield default delete var await void typeof throw case new in instanceof') 248 | \ ,char) < (line('.') != l:n) || s:previous_token() == '.' 249 | elseif char == '>' 250 | return getline('.')[col('.')-2] == '=' || s:syn_at(line('.'),col('.')) =~? '^jsflow' 251 | elseif char == ':' 252 | return getline('.')[col('.')-2] != ':' && s:label_col() 253 | elseif char == '/' 254 | return s:syn_at(line('.'),col('.')) =~? 'regex' 255 | endif 256 | return char !~ '[=~!<*,?^%|&([]' && 257 | \ (char !~ '[-+]' || l:n != line('.') && getline('.')[col('.')-2] == char) 258 | endif 259 | endfunction 260 | 261 | function GetTypescriptIndent() 262 | let b:js_cache = get(b:,'js_cache',[0,0,0]) 263 | " Get the current line. 264 | call cursor(v:lnum,1) 265 | let l:line = getline('.') 266 | " use synstack as it validates syn state and works in an empty line 267 | let s:stack = synstack(v:lnum,1) 268 | let syns = synIDattr(get(s:stack,-1),'name') 269 | 270 | " start with strings,comments,etc. 271 | if syns =~? s:syng_com 272 | if l:line =~ '^\s*\*' 273 | return cindent(v:lnum) 274 | elseif l:line !~ '^\s*\/[/*]' 275 | return -1 276 | endif 277 | elseif syns =~? s:syng_str && l:line !~ '^[''"]' 278 | if b:js_cache[0] == v:lnum - 1 && s:Balanced(v:lnum-1) 279 | let b:js_cache[0] = v:lnum 280 | endif 281 | return -1 282 | endif 283 | let l:lnum = s:PrevCodeLine(v:lnum - 1) 284 | if !l:lnum 285 | return 286 | endif 287 | 288 | let l:line = substitute(l:line,'^\s*','','') 289 | if l:line[:1] == '/*' 290 | let l:line = substitute(l:line,'^\%(\/\*.\{-}\*\/\s*\)*','','') 291 | endif 292 | if l:line =~ '^\/[/*]' 293 | let l:line = '' 294 | endif 295 | 296 | " the containing paren, bracket, curly, or closing '>'. 297 | " Many hacks for performance 298 | let idx = index([']',')','}','>'],l:line[0]) 299 | if b:js_cache[0] >= l:lnum && b:js_cache[0] < v:lnum && 300 | \ (b:js_cache[0] > l:lnum || s:Balanced(l:lnum)) 301 | call call('cursor',b:js_cache[1:]) 302 | else 303 | let [s:looksyn, s:free, top] = [v:lnum - 1, 1, (!indent(l:lnum) && 304 | \ s:syn_at(l:lnum,1) !~? s:syng_str) * l:lnum] 305 | if idx + 1 306 | call s:GetPair(['\[','(','{'][idx],'])}'[idx],'bW','s:skip_func()',2000,top) 307 | elseif getline(v:lnum) !~ '^\S' && syns =~? 'block' 308 | call s:GetPair('{','}','bW','s:skip_func()',2000,top) 309 | else 310 | call s:alternatePair(top) 311 | endif 312 | endif 313 | 314 | let b:js_cache = [v:lnum] + (line('.') == v:lnum ? [0,0] : getpos('.')[1:2]) 315 | let num = b:js_cache[1] 316 | 317 | let [s:W, isOp, bL, switch_offset] = [s:sw(),0,0,0] 318 | if !num || s:IsBlock() 319 | let ilnum = line('.') 320 | let pline = s:save_pos('s:Trim',l:lnum) 321 | if num && s:looking_at() == ')' && s:GetPair('(', ')', 'bW', s:skip_expr, 100) > 0 322 | let num = ilnum == num ? line('.') : num 323 | if idx < 0 && s:previous_token() ==# 'switch' && s:previous_token() != '.' 324 | if &cino !~ ':' 325 | let switch_offset = s:W 326 | else 327 | let cinc = matchlist(&cino,'.*:\zs\(-\)\=\(\d*\)\(\.\d\+\)\=\(s\)\=\C') 328 | let switch_offset = max([cinc[0] is '' ? 0 : (cinc[1].1) * 329 | \ ((strlen(cinc[2].cinc[3]) ? str2nr(cinc[2].str2nr(cinc[3][1])) : 10) * 330 | \ (cinc[4] is '' ? 1 : s:W)) / 10, -indent(num)]) 331 | endif 332 | if pline[-1:] != '.' && l:line =~# '^\%(default\|case\)\>' 333 | return indent(num) + switch_offset 334 | endif 335 | endif 336 | endif 337 | if idx < 0 && pline !~ '[{;]$' 338 | if pline =~# ':\@" 28 | hi link shebang Comment 29 | 30 | "" typescript comments"{{{ 31 | syn keyword typescriptCommentTodo TODO FIXME XXX TBD contained 32 | syn match typescriptLineComment "\/\/.*" contains=@Spell,typescriptCommentTodo,typescriptRef 33 | syn match typescriptRefComment /\/\/\/<\(reference\|amd-\(dependency\|module\)\)\s\+.*\/>$/ contains=typescriptRefD,typescriptRefS 34 | syn region typescriptRefD start=+"+ skip=+\\\\\|\\"+ end=+"\|$+ 35 | syn region typescriptRefS start=+'+ skip=+\\\\\|\\'+ end=+'\|$+ 36 | 37 | syn match typescriptCommentSkip "^[ \t]*\*\($\|[ \t]\+\)" 38 | syn region typescriptComment start="/\*" end="\*/" contains=@Spell,typescriptCommentTodo extend 39 | "}}} 40 | "" JSDoc support start"{{{ 41 | if !exists("typescript_ignore_typescriptdoc") 42 | syntax case ignore 43 | 44 | " syntax coloring for JSDoc comments (HTML) 45 | "unlet b:current_syntax 46 | 47 | syntax region typescriptDocComment start="/\*\*\s*$" end="\*/" contains=typescriptDocTags,typescriptCommentTodo,typescriptCvsTag,@typescriptHtml,@Spell fold extend 48 | syntax match typescriptDocTags contained "@\(param\|argument\|requires\|exception\|throws\|type\|class\|extends\|see\|link\|member\|module\|method\|title\|namespace\|optional\|default\|base\|file\|returns\=\)\>" nextgroup=typescriptDocParam,typescriptDocSeeTag skipwhite 49 | syntax match typescriptDocTags contained "@\(beta\|deprecated\|description\|fileoverview\|author\|license\|version\|constructor\|private\|protected\|final\|ignore\|addon\|exec\)\>" 50 | syntax match typescriptDocParam contained "\%(#\|\w\|\.\|:\|\/\)\+" 51 | syntax region typescriptDocSeeTag contained matchgroup=typescriptDocSeeTag start="{" end="}" contains=typescriptDocTags 52 | 53 | syntax case match 54 | endif "" JSDoc end 55 | "}}} 56 | syntax case match 57 | 58 | "" Syntax in the typescript code"{{{ 59 | syn match typescriptSpecial "\\\d\d\d\|\\x\x\{2\}\|\\u\x\{4\}" contained containedin=typescriptStringD,typescriptStringS,typescriptStringB display 60 | syn region typescriptStringD start=+"+ skip=+\\\\\|\\"+ end=+"\|$+ contains=typescriptSpecial,@htmlPreproc extend 61 | syn region typescriptStringS start=+'+ skip=+\\\\\|\\'+ end=+'\|$+ contains=typescriptSpecial,@htmlPreproc extend 62 | syn region typescriptStringB start=+`+ skip=+\\\\\|\\`+ end=+`+ contains=typescriptInterpolation,typescriptSpecial,@htmlPreproc extend 63 | 64 | syn region typescriptInterpolation matchgroup=typescriptInterpolationDelimiter 65 | \ start=/${/ end=/}/ contained 66 | \ contains=@typescriptExpression 67 | 68 | syn match typescriptNumber "-\=\<\d[0-9_]*L\=\>" display 69 | syn match typescriptNumber "-\=\<0[xX][0-9a-fA-F][0-9a-fA-F_]*\>" display 70 | syn match typescriptNumber "-\=\<0[bB][01][01_]*\>" display 71 | syn match typescriptNumber "-\=\<0[oO]\o[0-7_]*\>" display 72 | syn region typescriptRegexpString start=+/[^/*]+me=e-1 skip=+\\\\\|\\/+ end=+/[gimsuy]\{0,2\}\s*$+ end=+/[gimsuy]\{0,2\}\s*[;.,)\]}]+me=e-1 contains=@htmlPreproc oneline 73 | " syntax match typescriptSpecial "\\\d\d\d\|\\x\x\{2\}\|\\u\x\{4\}\|\\." 74 | " syntax region typescriptStringD start=+"+ skip=+\\\\\|\\$"+ end=+"+ contains=typescriptSpecial,@htmlPreproc 75 | " syntax region typescriptStringS start=+'+ skip=+\\\\\|\\$'+ end=+'+ contains=typescriptSpecial,@htmlPreproc 76 | " syntax region typescriptRegexpString start=+/\(\*\|/\)\@!+ skip=+\\\\\|\\/+ end=+/[gimsuy]\{,3}+ contains=typescriptSpecial,@htmlPreproc oneline 77 | " syntax match typescriptNumber /\<-\=\d\+L\=\>\|\<0[xX]\x\+\>/ 78 | syntax match typescriptFloat /\<-\=\%(\d[0-9_]*\.\d[0-9_]*\|\d[0-9_]*\.\|\.\d[0-9]*\)\%([eE][+-]\=\d[0-9_]*\)\=\>/ 79 | " syntax match typescriptLabel /\(?\s*\)\@/ 82 | "}}} 83 | "" typescript Prototype"{{{ 84 | syntax keyword typescriptPrototype contained prototype 85 | "}}} 86 | " DOM, Browser and Ajax Support {{{ 87 | """""""""""""""""""""""" 88 | if get(g:, 'typescript_ignore_browserwords', 0) 89 | syntax keyword typescriptBrowserObjects window navigator screen history location 90 | 91 | syntax keyword typescriptDOMObjects document event HTMLElement Anchor Area Base Body Button Form Frame Frameset Image Link Meta Option Select Style Table TableCell TableRow Textarea 92 | syntax keyword typescriptDOMMethods contained createTextNode createElement insertBefore replaceChild removeChild appendChild hasChildNodes cloneNode normalize isSupported hasAttributes getAttribute setAttribute removeAttribute getAttributeNode setAttributeNode removeAttributeNode getElementsByTagName hasAttribute getElementById adoptNode close compareDocumentPosition createAttribute createCDATASection createComment createDocumentFragment createElementNS createEvent createExpression createNSResolver createProcessingInstruction createRange createTreeWalker elementFromPoint evaluate getBoxObjectFor getElementsByClassName getSelection getUserData hasFocus importNode 93 | syntax keyword typescriptDOMProperties contained nodeName nodeValue nodeType parentNode childNodes firstChild lastChild previousSibling nextSibling attributes ownerDocument namespaceURI prefix localName tagName 94 | 95 | syntax keyword typescriptAjaxObjects XMLHttpRequest 96 | syntax keyword typescriptAjaxProperties contained readyState responseText responseXML statusText 97 | syntax keyword typescriptAjaxMethods contained onreadystatechange abort getAllResponseHeaders getResponseHeader open send setRequestHeader 98 | 99 | syntax keyword typescriptPropietaryObjects ActiveXObject 100 | syntax keyword typescriptPropietaryMethods contained attachEvent detachEvent cancelBubble returnValue 101 | 102 | syntax keyword typescriptHtmlElemProperties contained className clientHeight clientLeft clientTop clientWidth dir href id innerHTML lang length offsetHeight offsetLeft offsetParent offsetTop offsetWidth scrollHeight scrollLeft scrollTop scrollWidth style tabIndex target title 103 | 104 | syntax keyword typescriptEventListenerKeywords contained blur click focus mouseover mouseout load item 105 | 106 | syntax keyword typescriptEventListenerMethods contained scrollIntoView addEventListener dispatchEvent removeEventListener preventDefault stopPropagation 107 | endif 108 | " }}} 109 | "" Programm Keywords"{{{ 110 | syntax keyword typescriptSource import export from as 111 | syntax keyword typescriptIdentifier arguments this void 112 | syntax keyword typescriptStorageClass let var const using 113 | syntax keyword typescriptOperator delete new instanceof typeof 114 | syntax keyword typescriptBoolean true false 115 | syntax keyword typescriptNull null undefined 116 | syntax keyword typescriptMessage alert confirm prompt 117 | syntax keyword typescriptGlobal self top parent 118 | syntax keyword typescriptDeprecated escape unescape all applets alinkColor bgColor fgColor linkColor vlinkColor xmlEncoding 119 | "}}} 120 | "" Statement Keywords"{{{ 121 | syntax keyword typescriptConditional if else switch 122 | syntax keyword typescriptRepeat do while for in of 123 | syntax keyword typescriptBranch break continue yield await 124 | syntax keyword typescriptLabel case default async readonly 125 | syntax keyword typescriptStatement return with 126 | 127 | syntax keyword typescriptGlobalObjects Array Boolean Date Function Infinity JSON Math Number NaN Object Packages RegExp String Symbol netscape ArrayBuffer BigInt64Array BigUint64Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray Buffer Collator DataView DateTimeFormat Intl Iterator Map Set WeakMap WeakSet NumberFormat ParallelArray Promise Proxy Reflect Uint8ClampedArray WebAssembly console document fetch window 128 | syntax keyword typescriptGlobalNodeObjects module exports global process __dirname __filename 129 | 130 | syntax keyword typescriptExceptions try catch throw finally Error EvalError RangeError ReferenceError SyntaxError TypeError URIError 131 | 132 | syntax keyword typescriptReserved constructor declare as interface module abstract enum int short export interface static byte extends long super char final native synchronized class float package throws goto private transient debugger implements protected volatile double import public type namespace from get set keyof satisfies 133 | "}}} 134 | "" typescript/DOM/HTML/CSS specified things"{{{ 135 | 136 | " typescript Objects"{{{ 137 | syn match typescriptFunction "(super\s*|constructor\s*)" contained nextgroup=typescriptVars 138 | syn region typescriptVars start="(" end=")" contained contains=typescriptParameters transparent keepend 139 | syn match typescriptParameters "([a-zA-Z0-9_?.$][\w?.$]*)\s*:\s*([a-zA-Z0-9_?.$][\w?.$]*)" contained skipwhite 140 | "}}} 141 | " DOM2 Objects"{{{ 142 | syntax keyword typescriptType DOMImplementation DocumentFragment Node NodeList NamedNodeMap CharacterData Attr Element Text Comment CDATASection DocumentType Notation Entity EntityReference ProcessingInstruction void any string boolean number symbol never object unknown 143 | syntax keyword typescriptExceptions DOMException 144 | "}}} 145 | " DOM2 CONSTANT"{{{ 146 | syntax keyword typescriptDomErrNo INDEX_SIZE_ERR DOMSTRING_SIZE_ERR HIERARCHY_REQUEST_ERR WRONG_DOCUMENT_ERR INVALID_CHARACTER_ERR NO_DATA_ALLOWED_ERR NO_MODIFICATION_ALLOWED_ERR NOT_FOUND_ERR NOT_SUPPORTED_ERR INUSE_ATTRIBUTE_ERR INVALID_STATE_ERR SYNTAX_ERR INVALID_MODIFICATION_ERR NAMESPACE_ERR INVALID_ACCESS_ERR 147 | syntax keyword typescriptDomNodeConsts ELEMENT_NODE ATTRIBUTE_NODE TEXT_NODE CDATA_SECTION_NODE ENTITY_REFERENCE_NODE ENTITY_NODE PROCESSING_INSTRUCTION_NODE COMMENT_NODE DOCUMENT_NODE DOCUMENT_TYPE_NODE DOCUMENT_FRAGMENT_NODE NOTATION_NODE 148 | "}}} 149 | " HTML events and internal variables"{{{ 150 | syntax case ignore 151 | syntax keyword typescriptHtmlEvents onblur onclick oncontextmenu ondblclick onfocus onkeydown onkeypress onkeyup onmousedown onmousemove onmouseout onmouseover onmouseup onresize onload onsubmit 152 | syntax case match 153 | "}}} 154 | 155 | " Follow stuff should be highligh within a special context 156 | " While it can't be handled with context depended with Regex based highlight 157 | " So, turn it off by default 158 | if exists("typescript_enable_domhtmlcss") 159 | 160 | " DOM2 things"{{{ 161 | syntax match typescriptDomElemAttrs contained /\%(nodeName\|nodeValue\|nodeType\|parentNode\|childNodes\|firstChild\|lastChild\|previousSibling\|nextSibling\|attributes\|ownerDocument\|namespaceURI\|prefix\|localName\|tagName\)\>/ 162 | syntax match typescriptDomElemFuncs contained /\%(insertBefore\|replaceChild\|removeChild\|appendChild\|hasChildNodes\|cloneNode\|normalize\|isSupported\|hasAttributes\|getAttribute\|setAttribute\|removeAttribute\|getAttributeNode\|setAttributeNode\|removeAttributeNode\|getElementsByTagName\|getAttributeNS\|setAttributeNS\|removeAttributeNS\|getAttributeNodeNS\|setAttributeNodeNS\|getElementsByTagNameNS\|hasAttribute\|hasAttributeNS\)\>/ nextgroup=typescriptParen skipwhite 163 | "}}} 164 | " HTML things"{{{ 165 | syntax match typescriptHtmlElemAttrs contained /\%(className\|clientHeight\|clientLeft\|clientTop\|clientWidth\|dir\|id\|innerHTML\|lang\|length\|offsetHeight\|offsetLeft\|offsetParent\|offsetTop\|offsetWidth\|scrollHeight\|scrollLeft\|scrollTop\|scrollWidth\|style\|tabIndex\|title\)\>/ 166 | syntax match typescriptHtmlElemFuncs contained /\%(blur\|click\|focus\|scrollIntoView\|addEventListener\|dispatchEvent\|removeEventListener\|item\)\>/ nextgroup=typescriptParen skipwhite 167 | "}}} 168 | " CSS Styles in typescript"{{{ 169 | syntax keyword typescriptCssStyles contained color font fontFamily fontSize fontSizeAdjust fontStretch fontStyle fontVariant fontWeight letterSpacing lineBreak lineHeight quotes rubyAlign rubyOverhang rubyPosition 170 | syntax keyword typescriptCssStyles contained textAlign textAlignLast textAutospace textDecoration textIndent textJustify textJustifyTrim textKashidaSpace textOverflowW6 textShadow textTransform textUnderlinePosition 171 | syntax keyword typescriptCssStyles contained unicodeBidi whiteSpace wordBreak wordSpacing wordWrap writingMode 172 | syntax keyword typescriptCssStyles contained bottom height left position right top width zIndex 173 | syntax keyword typescriptCssStyles contained border borderBottom borderLeft borderRight borderTop borderBottomColor borderLeftColor borderTopColor borderBottomStyle borderLeftStyle borderRightStyle borderTopStyle borderBottomWidth borderLeftWidth borderRightWidth borderTopWidth borderColor borderStyle borderWidth borderCollapse borderSpacing captionSide emptyCells tableLayout 174 | syntax keyword typescriptCssStyles contained margin marginBottom marginLeft marginRight marginTop outline outlineColor outlineStyle outlineWidth padding paddingBottom paddingLeft paddingRight paddingTop 175 | syntax keyword typescriptCssStyles contained listStyle listStyleImage listStylePosition listStyleType 176 | syntax keyword typescriptCssStyles contained background backgroundAttachment backgroundColor backgroundImage backgroundPosition backgroundPositionX backgroundPositionY backgroundRepeat 177 | syntax keyword typescriptCssStyles contained clear clip clipBottom clipLeft clipRight clipTop content counterIncrement counterReset cssFloat cursor direction display filter layoutGrid layoutGridChar layoutGridLine layoutGridMode layoutGridType 178 | syntax keyword typescriptCssStyles contained marks maxHeight maxWidth minHeight minWidth opacity MozOpacity overflow overflowX overflowY verticalAlign visibility zoom cssText 179 | syntax keyword typescriptCssStyles contained scrollbar3dLightColor scrollbarArrowColor scrollbarBaseColor scrollbarDarkShadowColor scrollbarFaceColor scrollbarHighlightColor scrollbarShadowColor scrollbarTrackColor 180 | "}}} 181 | endif "DOM/HTML/CSS 182 | 183 | " Highlight ways"{{{ 184 | syntax match typescriptDotNotation "\." nextgroup=typescriptPrototype,typescriptDomElemAttrs,typescriptDomElemFuncs,typescriptDOMMethods,typescriptDOMProperties,typescriptHtmlElemAttrs,typescriptHtmlElemFuncs,typescriptHtmlElemProperties,typescriptAjaxProperties,typescriptAjaxMethods,typescriptPropietaryMethods,typescriptEventListenerMethods skipwhite skipnl 185 | syntax match typescriptDotNotation "\.style\." nextgroup=typescriptCssStyles 186 | "}}} 187 | 188 | "" end DOM/HTML/CSS specified things""}}} 189 | 190 | 191 | "" Code blocks 192 | syntax cluster typescriptAll contains=typescriptComment,typescriptLineComment,typescriptDocComment,typescriptStringD,typescriptStringS,typescriptStringB,typescriptRegexpString,typescriptNumber,typescriptFloat,typescriptDecorators,typescriptLabel,typescriptSource,typescriptType,typescriptOperator,typescriptBoolean,typescriptNull,typescriptFuncKeyword,typescriptConditional,typescriptGlobal,typescriptRepeat,typescriptBranch,typescriptStatement,typescriptGlobalObjects,typescriptMessage,typescriptIdentifier,typescriptStorageClass,typescriptExceptions,typescriptReserved,typescriptDeprecated,typescriptDomErrNo,typescriptDomNodeConsts,typescriptHtmlEvents,typescriptDotNotation,typescriptBrowserObjects,typescriptDOMObjects,typescriptAjaxObjects,typescriptPropietaryObjects,typescriptDOMMethods,typescriptHtmlElemProperties,typescriptDOMProperties,typescriptEventListenerKeywords,typescriptEventListenerMethods,typescriptAjaxProperties,typescriptAjaxMethods,typescriptFuncArg,typescriptGlobalNodeObjects 193 | 194 | if main_syntax == "typescript" 195 | syntax sync clear 196 | syntax sync ccomment typescriptComment minlines=200 197 | " syntax sync match typescriptHighlight grouphere typescriptBlock /{/ 198 | endif 199 | 200 | syntax keyword typescriptFuncKeyword function 201 | "syntax region typescriptFuncDef start="function" end="\(.*\)" contains=typescriptFuncKeyword,typescriptFuncArg keepend 202 | "syntax match typescriptFuncArg "\(([^()]*)\)" contains=typescriptParens,typescriptFuncComma contained 203 | "syntax match typescriptFuncComma /,/ contained 204 | " syntax region typescriptFuncBlock contained matchgroup=typescriptFuncBlock start="{" end="}" contains=@typescriptAll,typescriptParensErrA,typescriptParensErrB,typescriptParen,typescriptBracket,typescriptBlock fold 205 | 206 | syn match typescriptBraces "[{}\[\]]" 207 | syn match typescriptParens "[()]" 208 | syn match typescriptEndColons "[;,]" 209 | syn match typescriptLogicSymbols "\(&&\)\|\(||\)\|\(??\)\|\(!\)" 210 | syn match typescriptOpSymbols "=\{1,3}\|!==\|!=\|<\|>\|>=\|<=\|++\|+=\|--\|-=" 211 | 212 | " typescriptFold Function {{{ 213 | 214 | " function! typescriptFold() 215 | 216 | " skip curly braces inside RegEx's and comments 217 | syn region foldBraces start=/{/ skip=/\(\/\/.*\)\|\(\/.*\/\)/ end=/}/ transparent fold keepend extend 218 | 219 | " setl foldtext=FoldText() 220 | " endfunction 221 | 222 | " au FileType typescript call typescriptFold() 223 | 224 | " }}} 225 | 226 | " Define the default highlighting. 227 | if version < 508 228 | command -nargs=+ HiLink hi link 229 | else 230 | command -nargs=+ HiLink hi def link 231 | endif 232 | 233 | "typescript highlighting 234 | HiLink typescriptParameters Operator 235 | HiLink typescriptSuperBlock Operator 236 | 237 | HiLink typescriptEndColons Exception 238 | HiLink typescriptOpSymbols Operator 239 | HiLink typescriptLogicSymbols Boolean 240 | HiLink typescriptBraces Function 241 | HiLink typescriptParens Operator 242 | HiLink typescriptComment Comment 243 | HiLink typescriptLineComment Comment 244 | HiLink typescriptRefComment Include 245 | HiLink typescriptRefS String 246 | HiLink typescriptRefD String 247 | HiLink typescriptDocComment Comment 248 | HiLink typescriptCommentTodo Todo 249 | HiLink typescriptCvsTag Function 250 | HiLink typescriptDocTags Special 251 | HiLink typescriptDocSeeTag Function 252 | HiLink typescriptDocParam Function 253 | HiLink typescriptStringS String 254 | HiLink typescriptStringD String 255 | HiLink typescriptStringB String 256 | HiLink typescriptInterpolationDelimiter Delimiter 257 | HiLink typescriptRegexpString String 258 | HiLink typescriptGlobal Constant 259 | HiLink typescriptCharacter Character 260 | HiLink typescriptPrototype Type 261 | HiLink typescriptConditional Conditional 262 | HiLink typescriptBranch Conditional 263 | HiLink typescriptIdentifier Identifier 264 | HiLink typescriptStorageClass StorageClass 265 | HiLink typescriptRepeat Repeat 266 | HiLink typescriptStatement Statement 267 | HiLink typescriptFuncKeyword Keyword 268 | HiLink typescriptMessage Keyword 269 | HiLink typescriptDeprecated Exception 270 | HiLink typescriptError Error 271 | HiLink typescriptParensError Error 272 | HiLink typescriptParensErrA Error 273 | HiLink typescriptParensErrB Error 274 | HiLink typescriptParensErrC Error 275 | HiLink typescriptReserved Keyword 276 | HiLink typescriptOperator Operator 277 | HiLink typescriptType Type 278 | HiLink typescriptNull Type 279 | HiLink typescriptNumber Number 280 | HiLink typescriptFloat Number 281 | HiLink typescriptDecorators Special 282 | HiLink typescriptBoolean Boolean 283 | HiLink typescriptLabel Label 284 | HiLink typescriptSpecial Special 285 | HiLink typescriptSource Special 286 | HiLink typescriptGlobalObjects Special 287 | HiLink typescriptGlobalNodeObjects Special 288 | HiLink typescriptExceptions Special 289 | 290 | HiLink typescriptDomErrNo Constant 291 | HiLink typescriptDomNodeConsts Constant 292 | HiLink typescriptDomElemAttrs Label 293 | HiLink typescriptDomElemFuncs PreProc 294 | 295 | HiLink typescriptHtmlElemAttrs Label 296 | HiLink typescriptHtmlElemFuncs PreProc 297 | 298 | HiLink typescriptCssStyles Label 299 | 300 | " Ajax Highlighting 301 | HiLink typescriptBrowserObjects Constant 302 | 303 | HiLink typescriptDOMObjects Constant 304 | HiLink typescriptDOMMethods Function 305 | HiLink typescriptDOMProperties Special 306 | 307 | HiLink typescriptAjaxObjects Constant 308 | HiLink typescriptAjaxMethods Function 309 | HiLink typescriptAjaxProperties Special 310 | 311 | HiLink typescriptFuncDef Title 312 | HiLink typescriptFuncArg Special 313 | HiLink typescriptFuncComma Operator 314 | 315 | HiLink typescriptHtmlEvents Special 316 | HiLink typescriptHtmlElemProperties Special 317 | 318 | HiLink typescriptEventListenerKeywords Keyword 319 | 320 | HiLink typescriptNumber Number 321 | HiLink typescriptPropietaryObjects Constant 322 | 323 | delcommand HiLink 324 | 325 | " Define the htmltypescript for HTML syntax html.vim 326 | "syntax clear htmltypescript 327 | "syntax clear typescriptExpression 328 | syntax cluster htmltypescript contains=@typescriptAll,typescriptBracket,typescriptParen,typescriptBlock,typescriptParenError 329 | syntax cluster typescriptExpression contains=@typescriptAll,typescriptBracket,typescriptParen,typescriptBlock,typescriptParenError,@htmlPreproc 330 | 331 | let b:current_syntax = "typescript" 332 | if main_syntax == 'typescript' 333 | unlet main_syntax 334 | endif 335 | 336 | " vim: ts=4 337 | --------------------------------------------------------------------------------