vim9script if executable('black') &l:formatprg = "black -q - 2>/dev/null" elseif executable('yapf') &l:formatprg = "yapf" endif setlocal foldignore= b:undo_ftplugin ..= ' | setl foldignore< formatprg< | silent! autocmd! PythonAutoImport' # Convince python that 'def' is a macro like C's #define setlocal define=^\\s*def setl dictionary=$HOME/.vim/data/python.dict setl makeprg=python3\ % # NOTE: tidy-imports misses some imports. Put them in ~/.pyflyby # nnoremap vh :term ++close pydoc3 # nnoremap vb :!open https://docs.python.org/3/search.html\?q= # nnoremap vf :% !black -q - # You can use :w !cmd to write the current buffer to the stdin of an external # command. A related command is :%!cmd which does the same thing and then # replaces the current buffer with the output of the command. (:h :range!) nnoremap vi ::% !tidy-imports --replace-star-imports -r -p --quiet --black # Works, but intrusive # augroup PythonAutoImport | autocmd! # autocmd bufwritepre * { # if &ft == 'python' && 'tidy-imports'->executable() # :% !tidy-imports --replace-star-imports -r -p --quiet --black # endif # } # augroup END # nnoremap vt $":new \| exec 'nn q :bd!\' \| 0read !leetcode test {bufname()->fnamemodify(':t')->matchstr('^\d\+')}" # nnoremap vx $":new \| exec 'nn q :bd!\' \| 0read !leetcode exec {bufname()->fnamemodify(':t')->matchstr('^\d\+')}" nnoremap vp :new \| exec 'nn q :bd!' \| r !python3 # nnoremap p :Ipython g:pyindent_open_paren = 'shiftwidth()' # https://github.com/vim/vim/blob/v8.2.0/runtime/indent/python.vim # Abbreviations def GetSurroundingFn(): string var fpat = '\vdef\s+\zs\k+' var lnum = search(fpat, 'nb') if lnum > 0 var fname = getline(lnum)->matchstr(fpat) .. '()' var cpat = '\vclass\s+\zs\k+' lnum = search(cpat, 'nb') if lnum > 0 return getline(lnum)->matchstr(cpat) .. '().' .. fname endif return fname endif return '' enddef iabbr def abbr#NotCtx('def') ? 'def' : 'def ):-f)i=abbr#Eatchar()' iabbr def_ def ():"""."""-f(i=abbr#Eatchar() iabbr def__ def ():o'''>>> print()'''4k_f(i=abbr#Eatchar() iabbr try_ try: \pass \except Exception as err: \print(f"Unexpected {err=}, {type(err)=}") \raiseelse: \pass5kcw=abbr#Eatchar() iabbr main__2 \ if __name__ == "__main__": \import doctest \doctest.testmod()=abbr#Eatchar() iabbr main__ \ if __name__ == "__main__": \main()=abbr#Eatchar() iabbr python3# #!/usr/bin/env python3=abbr#Eatchar() iabbr '''_ ''' \>>> print(=GetSurroundingFn()) \'''ggOfrom sys import stderrGoo \:normal imain__2 \?>>> print:nohlg_hi=abbr#Eatchar() iabbr """ """."""3h=abbr#Eatchar() iabbr case_ match myval: \case 10: \pass \case _:3k_fm;i=abbr#Eatchar() iabbr match_case_ match myval: \case 10: \pass \case _:3k_fm;i=abbr#Eatchar() iabbr enum_ Color = Enum('Color', ['RED', 'GRN'])_fC=abbr#Eatchar() iabbr pre print(, file=stderr)F,i=abbr#Eatchar() iabbr pr print()i=abbr#Eatchar() iabbr tuple_ Point = namedtuple('Point', 'x y')_=abbr#Eatchar() iabbr tuple__ Point = namedtuple('Point', ('x', 'y'), defaults=(None,) * 2)_=abbr#Eatchar() iabbr namedtuple_ Point = namedtuple('Point', 'x y')_=abbr#Eatchar() iabbr namedtuple__ Point = namedtuple('Point', ('x', 'y'), defaults=(None,) * 2)_=abbr#Eatchar() # # collections iabbr defaultdict_ defaultdict(int)=abbr#Eatchar() iabbr defaultdict__ defaultdict(set)=abbr#Eatchar() iabbr defaultdict___ defaultdict(lambda: '[default value]')=abbr#Eatchar() iabbr dict_default_ defaultdict(int)=abbr#Eatchar() iabbr dict_default__ defaultdict(set)=abbr#Eatchar() iabbr dict_default___ defaultdict(lambda: '[default value]')=abbr#Eatchar() # iabbr cache_ @functools.cache=abbr#Eatchar() iabbr __init__ def __init__(self):hi=abbr#Eatchar() iabbr __add__ def __add__(self, other):=abbr#Eatchar() iabbr __sub__ def __sub__(self, other):=abbr#Eatchar() iabbr __mul__ def __mul__(self, other):=abbr#Eatchar() iabbr __truediv__ def __truediv__(self, other):=abbr#Eatchar() iabbr __floordiv__ def __floordiv__(self, other):=abbr#Eatchar() # commands # Reuse terminal running ipython or start a new one def Ipython() var listedbufs = getbufinfo({buflisted: 1}) var ipbufidx = listedbufs->indexof((_, v) => v.name =~? 'ipython') if ipbufidx != -1 var ipbufnr = listedbufs[ipbufidx].bufnr if bufwinnr(ipbufnr) == -1 # ipython opthons can be placed in a config file exec $'sbuffer {listedbufs[ipbufidx].bufnr}' endif else :term ++close ++kill=term ipython3 --no-confirm-exit --colors=Linux endif enddef command Ipython Ipython() # popup menu if exists('g:loaded_scope') import autoload 'scope/popup.vim' def Things() var things = [] for nr in range(1, line('$')) var line = getline(nr) if line =~ '\(^\|\s\)\(def\|class\) \k\+(' || line =~ 'if __name__ == "__main__":' things->add({text: $"{line} ({nr})", linenr: nr}) endif endfor popup.FilterMenu.new("Py Things", things, (res, key) => { exe $":{res.linenr}" normal! zz }, (winid, _) => { win_execute(winid, $"syn match FilterMenuLineNr '(\\d\\+)$'") hi def link FilterMenuLineNr Comment }) enddef elseif exists('g:loaded_vimsuggest') # import autoload 'vimsuggest/addons/addons.vim' # command! -nargs=* -complete=customlist,Complete VSArtifacts addons.DoArtifactsAction() # nnoremap / :VSArtifacts # def Complete(A: string, L: string, C: number): list # var patterns = [ # '\(^\|\s\)\(def\|class\) \k\+(', # 'if __name__ == "__main__":' # ] # return addons.ArtifactsComplete(A, L, C, patterns) # enddef # :defcompile # Otherwise compile errors within Complete() show up only upon pressing nnoremap / :VSGlobal \v(^\|\s)(def\|class).{-} else def Definitions(): list var items = [] for nr in range(1, line('$')) var name = getline(nr)->matchstr('\(^\|\s\)\(def\|class\)\s\+\zs\k\+\ze(') if name != null_string items->add({text: name, lnum: nr}) endif endfor return items enddef command -buffer -nargs=* -complete=customlist,Completor PyGoTo DoCommand() nnoremap / :PyGoTo def DoCommand(arg: string = null_string) var items = (arg == null_string) ? Definitions() : Definitions()->matchfuzzy(arg, {matchseq: 1, key: 'text'}) if !items->empty() exe $":{items[0].lnum}" normal! zz endif enddef def Completor(arg: string, cmdline: string, cursorpos: number): list var items = (arg == null_string) ? Definitions() : Definitions()->matchfuzzy(arg, {matchseq: 1, key: 'text'}) return items->mapnew((_, v) => v.text) enddef endif if exists(":LspDocumentSymbol") == 2 # nnoremap / LspDocumentSymbol nnoremap z Things() elseif exists('g:loaded_scope') nnoremap / Things() endif