Skip to content

Instantly share code, notes, and snippets.

@idvorkin
Created July 15, 2023 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idvorkin/180e8fbec825b0eeb18895d22441e6a3 to your computer and use it in GitHub Desktop.
Save idvorkin/180e8fbec825b0eeb18895d22441e6a3 to your computer and use it in GitHub Desktop.
" Common things in all of my vimrc's
" File in git: ~/gits/settings/default_vimrc
set nocompatible
set nohls
set ignorecase
set noincsearch
set guioptions-=T
set guioptions-=m
" Remove right hand scroll bars
set guioptions-=R
set guioptions-=r
set sw=4
set ts=4
set expandtab
set cindent
set laststatus=2
runtime macros/matchit.vim
syntax on
:ca lcdb lcd %:p:h
set tags=tags;/
" OMG - How to support italics in vim in TMUX
" https://rsapkf.netlify.com/blog/enabling-italics-vim-tmux
function! FixMojiBake()
" See charector under cursor -
" ga
" Search for non unicode charecters
" /[^\x00-\x7F]
" Replace hypens
:%s/\%x97/-/g
:%s/\%x96/-/g
" Replace smart quotes
:%s/\%x93/"/g
:%s/\%x94/"/g
" Remove TMs and oes
:%s/\%x99//g
:%s/\%x9c//g
:%s/\%x9d//g
"
" Replace apostrophe
:%s/\%x92/'/g
" Replace apostrophe in bear
:%s/\%xe2\%x80/'/g
endfunction
function! FirstPersonToThirdPerson()
" Trim the whitespace off the ends
:%s;\s\+$;;
" Add a period to the end if it's not there.
:g!/\.$/s;$;.;
" do a bunch of replaces.
:%s;^I;You;
:%s;\. ^I;You;g
:%s; I ; you ;g
:%s; am ; are ;g
:%s; me\([ \.,$]\); you\1;g
:%s; me\([ \.,$]\); you\1;g
:%s; mine\([ \.,$]\); yours\1;g
:%s;^Me ;You ;g
:%s; myself\([ \.,$]\); yourself\1;g
:%s; my ; your ;g
:%s;^My ;Your ;g
:%s;^\.$;
endfunction
function! SetupPlugins()
" Vundle setup
" Instructions @ https://github.com/VundleVim/Vundle.vim/blob/master/README.md
" git clone https://github.com/VundleVim/Vundle.vim %USERPROFILE%/vimfiles/bundle/vundle
" MAC - $ git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
filetype off
set rtp+=~/vimfiles/bundle/Vundle
set rtp+=~/.vim/bundle/Vundle.vim
if filereadable(expand("~/homebrew/opt/fzf/plugin/fzf.vim"))
so ~/homebrew/opt/fzf/plugin/fzf.vim
endif
if filereadable(expand("~/../linuxbrew/.linuxbrew/opt/fzf/plugin/fzf.vim"))
so ~/../linuxbrew/.linuxbrew/opt/fzf/plugin/fzf.vim
endif
if filereadable(expand("/opt/homebrew/opt/fzf/plugin/fzf.vim"))
so /opt/homebrew/opt/fzf/plugin/fzf.vim
endif
call vundle#begin()
Plugin 'miyakogi/conoline.vim'
" Highlight current line
" ConoLineEnable (Highlight current line)
Plugin 'frazrepo/vim-rainbow' " # :RainbowToggle
Plugin 'fcpg/vim-osc52'
Bundle 'VundleVim/Vundle.vim'
Bundle 'jparise/vim-graphql'
Bundle 'webdevel/tabulous'
Bundle 'r0mai/vim-djinni'
Bundle 'mattn/webapi-vim'
Bundle 'majutsushi/tagbar'
Bundle 'luochen1990/rainbow'
Bundle 'tyru/open-browser.vim'
" q - quit tagbar
" p - jump to tag
" P - tag to preview
" C-P, C-N next high level tag
Bundle 'tpope/vim-fugitive'
" Bundle for Mercurial
Bundle 'ludovicchabant/vim-lawrencium'
Bundle 'aserebryakov/vim-todo-lists'
" Open todo file.
let g:VimTodoListsMoveItems = 0
let g:VimTodoListsDatesEnabled = 1
let g:VimTodoListsDatesFormat = "%a %b %d, %Y"
"
" Writing tools
Bundle 'Ron89/thesaurus_query.vim'
"
:noremap <Leader>tr :ThesaurusQueryReplaceCurrentWord<CR>
Bundle 'junegunn/limelight.vim'
Bundle 'reedes/vim-pencil'
Bundle 'junegunn/goyo.vim'
Bundle 'inkarkat/vim-ingo-library'
Bundle 'inkarkat/vim-spellcheck'
Bundle 'panozzaj/vim-autocorrect'
Bundle 'HerringtonDarkholme/yats.vim'
" :IndentGuidesEnable
" :IndentGuidesDisable
" :IndentGuidesToggle
Bundle 'nathanaelkane/vim-indent-guides'
Plugin 'ekalinin/Dockerfile.vim'
Bundle 'mhinz/vim-startify'
Bundle 'tbastos/vim-lua'
" Cool does wrapping
" help surround
" Wrap current line
" ys -> you surround, motion, element
" yss* <- Wrap 'Surround' line '*'
" ds" -> delete surround
" cs" -> change surround
Bundle 'tpope/vim-surround'
Bundle 'bling/vim-airline'
Bundle 'chrisbra/csv.vim'
Bundle 'altercation/vim-colors-solarized'
Bundle 'vim-scripts/ZoomWin'
" Markdown stuff
" *******************************
Bundle 'godlygeek/tabular'
Bundle 'mzlogin/vim-markdown-toc'
" Still too early and slow
" Bundle 'SidOfc/mkdx'
" :GenTocGFM
" :UpdateToc
Bundle 'plasticboy/vim-markdown'
" :TOC - Generate a toc sidebar
" :VSize - Resize to 20
" ]] Next Header
" [[ Prev Header
Bundle 'parkr/vim-jekyll'
Bundle 'christoomey/vim-quicklink'
Bundle 'elzr/vim-json'
Bundle 'PProvost/vim-ps1'
Bundle 'othree/javascript-libraries-syntax.vim'
Bundle "pangloss/vim-javascript"
Bundle "scrooloose/nerdtree"
Bundle "rking/ag.vim"
Bundle "OrangeT/vim-csharp.git"
" OmniSharp doesn't seem to wrok on WSL, let it go.
" Bundle "OmniSharp/omnisharp-vim"
Bundle "lukaszkorecki/workflowish"
Bundle "keith/swift.vim"
" http://vimcolors.com/?page=11
Bundle 'flazz/vim-colorschemes'
Bundle 'dhruvasagar/vim-table-mode'
Bundle 'atelierbram/vim-colors_atelier-schemes'
" Comment \cc
" Uncomment \cu
Bundle 'scrooloose/nerdcommenter'
" I use this instead of FZF or Ctrl-P
"Bundle 'Shougo/denite.nvim'
"Bundle 'Shougo/neomru.vim'
Bundle 'roxma/nvim-yarp'
Bundle 'roxma/vim-hug-neovim-rpc'
" Trying to use fzf cz it looks awesome.
Plugin 'junegunn/fzf.vim'
" PymodeLintAuto
Plugin 'python-mode/python-mode'
let g:pymode_python = 'python3'
let g:pymode_lint_checkers = ['pyflakes' ]
let g:pymode_options_colorcolumn = 0
let g:pymode_warnings = 1
let g:pymode_options_max_line_length = 1000
let g:pymode_lint_options_pep8 =
\ {'max_line_length': g:pymode_options_max_line_length}
let g:pymode_lint_options_pylint =
\ {'max-line-length': g:pymode_options_max_line_length}
let g:pymode_lint_ignore = ["E501", "W0611",]
" Plugin 'plytophogy/vim-virtualenv'
" black needs virtual env, which can't find
" Plugin 'ambv/black'
" Write on Save
" autocmd BufWritePost *.py execute ':Black'
Plugin 'kchmck/vim-coffee-script'
Plugin 'aklt/plantuml-syntax'
Plugin 'scrooloose/vim-slumlord'
Plugin 'mhinz/vim-signify' " Not sure why but gitgutter doesn't display the signs correctly, disable that and use signify for line highlight
" \hp -> Preview hunk
" \hu -> Undo Hunk
:nmap <leader>hu :SignifyHunkUndo<cr>
:nmap <leader>hp :SignifyHunkDiff<cr>
" ]c -> Next hunk
" ]c -> Prev hunk
" \hp -> Preview hunk
" \hu -> Undo Hunk
" Plugin 'airblade/vim-gitgutter'
let g:gitgutter_signs=0
" ]c -> Next hunk
" ]c -> Prev hunk
" \hp -> Preview hunk
" \hu -> Undo Hunk
" :GitGutterFold
" :GitGutterEnable
" let g:gitgutter_set_sign_backgrounds=1
" :highlight! link SignColumn LineNr
" :highlight SignColumn guibg='blue' ctermbg='blue'
" :highlight SignColumn ctermbg='DarkRed'
" let g:gitgutter_preview_win_floating=1
" Replace syntastic with ale
" Bundle 'scrooloose/syntastic'
" disable Ale for now as it's mucking my table of contents.
" Plugin 'w0rp/ale'
Plugin 'prettier/vim-prettier'
" Ale for prose requires
" write-good
" prose-lint
" vale
Plugin 'lgalke/vim-compiler-vale'
Plugin 'danro/rename.vim'
" Plugin 'easymotion/vim-easymotion'
" All of your Plugins must be added before the following line
Plugin 'PolyCement/vim-tweego'
" coc and friends, too complex so far
" Plugin 'neoclide/coc.nvim', {'branch': 'release'}
" \r - rename
" \n - usages
" \d definition - maybe remap to C-]
" K - help
Plugin 'davidhalter/jedi-vim'
Plugin 'github/copilot.vim'
call vundle#end() " required
endfunc
call SetupPlugins()
" Setup Fzf
func FzFConfig()
:cab ls :Buffers<CR>
:nmap g* :exec ":Lines '" expand('<cword>')<CR>
" Ahh, FZF, how complex you are:
" using fd as the source for fzf
command! -bang -complete=dir -nargs=* FF
\ call fzf#run(fzf#wrap('ff', {'source': 'fd --follow . ~/blog', 'dir':<q-args>,'sink':'e'}, <bang>0))
:cab ff FF<CR>
" Some FZF help
" typing = fuzzy match
" 'actual match
" $end
" ^start
" | or :w
"
:nnoremap <C-P> :History<cr>
:nnoremap <C-O> :FF<cr>
:nnoremap <C-I> :BTags<cr>
endfunc
call FzFConfig()
func SetupAutoFixEnglish()
" Can fix with Sed
" sed -i -e 's/ teh / the /g' *
" grab these from .aspell.en.prepl
:iab teh the
:iab hte the
:iab taht that
:iab ot to
:iab hte the
:iab zach Zach
:iab alot a lot
:iab amelia Amelia
:iab tori Tori
:iab ammon Ammon
:iab adn and
:iab nad and
:iab cna can
:iab dont don't
:iab fi if
:iab fo of
:iab iwll will
:iab wiht with
:iab htgorugh through
:iab htis this
:iab htourhg through
endfunc
call SetupAutoFixEnglish()
filetype plugin indent on " required
" Set font-size default to be a decent size.
if ( has("win32") || has("win64") || has("win16") )
if !exists("g:loaded")
" TBD: Setting the guifont causes the window to move, so only set the
" guifont if it hasn't been set before.
let defaultFont="Consolas:h14"
let g:loaded=1
exec "set guifont=".defaultFont
endif
endif
"
"WOFL Helpers
" HELP @ https://github.com/lukaszkorecki/workflowish"
func! OneNoteToWafl()
" Tabs to spaces
" Dots to *'s
%s/\%u2022/*/g
%s/\%u25cb/*/g
%s/\%u00b7/*/g
endfunc
func! WriteOn()
:Goyo!
:Goyo
:PencilSoft
:Limelight
" :ALEDisable " Remove spelling and grammer
endfunc
command! IGWriteOn :call WriteOn()
command! IGWriteOff :call WriteOff()
func! WriteOff()
:Goyo!
:PencilOff
:Limelight!
" :ALEEnable "Remove spelling and grammer
endfunc
" TBD Checkbox processing
" add these only to markdown/html; checkboxopen, checkboxdone
" Perhaps be clever and alternate between open and done like in OneNote via C-1
" Using digraphs - so cool
" C-K 9744 // Checkmark complete
" C-K 9745 // Checkmark open
" https://www.fileformat.info/info/unicode/char/2611/index.htm
" :dig td 9744
" :dig tc 9745
:iab mdt ☐
:iab mdtd ☐
:iab mdc ☑
:iab mdtodo ☐
:iab mddone ☑
:cab mdcbt g/^#/s;# \*\*\(.*\)\*\*;# \1;
" Note can't use _ in ab, so using 'e' for expand
:iab esummarize {%include summarize-page.html src="/TK" %}
:iab eyoutube {%include youtube.html src="TK" %}
:cab rfiles :r !exa ~/rare_git/blob/ig66
:iab epics {%include bi_table.html is="<cr><cr>" %}
" Family journal, ig66
func! Ig66Files(week)
:match Comment /^#.*/
" setup macros
:map <buffer> ffj :s!\(.*\)!{\%include bi_table.html is="\1" \%}!<cr>
:map <buffer> ffp :exe ':!viu '.expand('<cword>')<cr>
" erase buffer
:g/^/d
:exe expand(':lcd ~/rare_git/blob/ig66/'.a:week)
:exe expand(':r !exa ~/rare_git/blob/ig66/'.a:week)
" Put on trailing ; so joins(gj) work
" Add a trailing semicolon
:%s!$!;!
:%g/montage/d
" write help
:0
:normal O# Useful shortcuts - preview filefj
:normal o# ffp - preview filefj
:normal o# ffJ - wrap with bi_tablefj
:normal o# gJ - Join lines together before wrapping with ffJ fj
:normal ofj
endfunc
func! MarkDownWordToLink()
" cool yiw takes the word, and jumps you to the beginning of it.
normal yiwi[ea](http://www.pa.com)
endfunc
func! MarkDownClearBoldTitles()
":cab mdcbt g/^#/s;# \*\*\(.*\)\*\*;# \1;"
endfunc
func! MarkDownWordToGoogleLucky()
" cool yiw takes the word, and jumps you to the beginning of it.
normal yiwi[ea](http://www.google.com/search?btnI&q=)hp
endfunc
func! JsToSingleLineClipBoard()
" Creating a bookmarklet requires all JS to be on a single line.
" Make it a single line and put it on global clipboard to paste into JS
" console.
" NOTE: when creating bookmarklets, you'll need to terminate all lines
" with a ';' and only use inline comments, and end with void();
" NOTE: when making it the bookmark, you need to start with javascript:
" Join all to one line.
exec ":%j"
" Copy to Clipboard
normal "*yy
" Undo
normal u
`
endfunc
" Assume no longer need these - put back if you do.
let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
set termguicolors
if has ("gui-running")
:colo Tomorrow-Night-Blue
else
:colo darkblue
endif
" Remove trailing whitespace:
autocmd BufWritePre * :%s/\s\+$//e
" Markdown
" ToC - Sidebar to navigate.
" ][ - sibling prev
" [] - sibling next
let g:vim_markdown_follow_anchor = 1 " ge will jump to anchor (TBD: Map to C-]
let g:vim_markdown_toc_autofit = 1 " Great for not wasting extra space
" let g:vim_markdown_frontmatter = 1
set conceallevel=2
let g:vim_markdown_new_list_item_indent = 1
let g:vim_markdown_auto_insert_bullets = 1
let g:vim_markdown_folding_level = 4
let g:vmt_list_item_char='-'
" Always enable softpencil
autocmd BufEnter *md :exe ":compiler vale"
autocmd BufEnter *md :exe ":SoftPencil"
autocmd BufEnter *md :exe ":call AutoCorrect()"
" autocmd BufEnter *md :exe ":Limelight"
" autocmd BufLeave *md :exe ":Limelight!"
" let g:vim_markdown_folding_disabled = 1
" Break lines on word boudnaries only
set linebreak
" Jekyll - posts for use with JPost
" JVPost - create jekyll post in new vertical split
let g:jekyll_post_extension = '.md'
let g:jekyll_post_template = [
\ '---',
\ 'layout: post',
\ 'title: "JEKYLL_TITLE"',
\ 'date: "JEKYLL_DATE"',
\ 'tags:',
\ ' - ',
\ '---',
\ ]
let g:jekyll_post_dirs = ['_posts', '../_posts','_drafts','../_drafts']
function! EscapeKey()
" Do mappings for funny keyboard
:inoremap ` <esc>
:inoremap C-<esc> `
:cnoremap ` <esc>
:cnoremap C-<esc> `
endfunction
function! FJEscape()
" Do mappings for funny keyboard
:inoremap fj <esc>
:cnoremap fj <esc>
:noremap ;; :
endfunction
" :iunmap fj
" :cunmap fj
call FJEscape()
function! FixEscapeKey()
:call EscapeKey()
endfunction
let g:ale_fixers = {
\ 'javascript': ['prettier'],
\ 'css': ['prettier'],
\ 'markdown': ['prettier'],
\}
" let g:ale_fix_on_save = 1
" Scripting reference
" https://devhints.io/vimscript
" :py3file ~/settings/vim_python.py
command! IgDaily :n! `~/settings/vim_python.py makedailypage`
command! Ig3 :resize 10<cr>
function! OpenConvoFile()
let bufexists = 0
let bufnum = 0
" Check if a buffer with the filename ending in '.convo' exists.
for buf in range(1, bufnr('$'))
if bufexists(buf) && matchstr(bufname(buf), '.*\.convo$') != ''
let bufexists = 1
let bufnum = buf
break
endif
endfor
" If the '.convo' buffer exists but not in any window, open it in a new window
if bufexists && bufwinnr(bufnum) == -1
execute 'sbuffer' bufnum
" If the '.convo' buffer exists and in a window, switch to that window.
elseif bufexists
execute bufwinnr(bufnum) . 'wincmd w'
" If the '.convo' buffer doesn't exist, create a new one.
else
execute 'new `~/settings/vim_python.py make-convo` '
endif
endfunction
function! MakeGist()
" Write the current buffer to a temporary file
" Use the gh command to create a gist and copy the url to clipboard
silent! execute '!gh gist create % --public | pbc -selection clipboard'
" Delete the temporary file
silent! execute '!rm /tmp/tmpfile'
endfunction
command! IgMakeGist :call MakeGist()
command! IgConvo :call OpenConvoFile()
command! IgWeekly :n! `~/settings/vim_python.py makeweeklyreport`
command! IgYesterweek :n! `~/settings/vim_python.py makeweeklyreport --weekoffset -1`
command! IgYesterday :n! `~/settings/vim_python.py makedailypage --daysoffset -1`
cab Ddt !python3 ~/gits/nlp/dump_grateful.py todo --markdown
cab Ddg !python3 ~/gits/nlp/dump_grateful.py grateful
cab Dda !python3 ~/gits/nlp/dump_grateful.py awesome
command! Sodot :so ~/.vimrc
command! Soed :n ~/settings/default_vimrc
command! VSize :vert resize 30
command! IgTodo :r !python3 ~/gits/nlp/dump_grateful.py todo --markdown 2
command! IgMdToc :r ~/settings/vim/snip_toc.md
command! IgGptBook :r ~/settings/vim/snip_preamble_toc.md
command! IgFixBook :%s;### \(.*\);**\1**
command! Ig2 :lcd ~/gits/igor2/<bar>:GFiles
command! IgBlog :lcd ~/blog/<bar>:GFiles
command! IgRandomBlog :n `~/settings/vim_python.py randomblogpost`
cab P3 :!python3 % <cr>
cab Pb :!black % <cr>
" Common work flow: Switch to current directory, git write, commit and push.
cab DdC :lcd %:p:h<CR>:Gwrite<CR>:!git diff --staged %:p <CR> :!read -k <CR>:!git commit %:p -m "Save %"<CR>:!git push<CR>
cab DdG :lcd %:p:h<CR>:Gwrite<CR>:!git diff --staged %:p <CR> :!read -k <CR>:!git commit %:p <CR>:!git push<CR>
" I never use ToHTML and it makes it harder to use Toc
" This is loaded in the html plugin, which I'm disabling.
" search for the below string to find it.
let g:loaded_2html_plugin = 'vim8.1_v1'
" leaving the below in for an example of one time load only
if !exists ("g:execute_on_first_load_only")
" Can only delete it once
let g:execute_on_first_load_only = "1"
":delc TOhtml
endif
"Auto spell check in aspell.
:cab aspell :w!<CR>:!aspell check %<CR>:e! %<CR>
" I always want the local cd.
:cab Gcd :Glcd
" Add alias to regenerate tags for this repo.
" Using FD honors the .gitignore
:cab GTag :Glcd<CR>:!ctags `fd md$`
:cab lg :!lazygit
" Copied from https://gist.github.com/jackkinsella/aa7374a6832cca8a09eadc3434a33c24`
" Automatically reload file when underlying files change (e.g. git)
set autoread
"By default, swap out all instances in a line during substitutions
set gdefault
function SetupTagbar()
" Update markdown tagbar need to install mdctags
" https://github.com/wsdjeg/mdctags.rs#installation
let g:tagbar_left = 1
let g:tagbar_sort = 0
let g:tagbar_foldlevel = 99
let g:tagbar_autoshowtag = 1
let g:tagbar_compact = 1
command! TagbarV let g:tagbar_vertical=1|:TagbarOpen
command! TagbarH let g:tagbar_vertical=0|:TagbarOpen
let g:tagbar_type_markdown = {
\ 'ctagsbin' : 'mdctags',
\ 'ctagsargs' : '',
\ 'kinds' : [
\ 'a:h1:0:0',
\ 'b:h2:0:0',
\ 'c:h3:0:0',
\ 'd:h4:0:0',
\ 'e:h5:0:0',
\ 'f:h6:0:0',
\ ],
\ 'sro' : '::',
\ 'kind2scope' : {
\ 'a' : 'h1',
\ 'b' : 'h2',
\ 'c' : 'h3',
\ 'd' : 'h4',
\ 'e' : 'h5',
\ 'f' : 'h6',
\ },
\ 'scope2kind' : {
\ 'h1' : 'a',
\ 'h2' : 'b',
\ 'h3' : 'c',
\ 'h4' : 'd',
\ 'h5' : 'e',
\ 'h6' : 'f',
\}
\}
endfunc
call SetupTagbar()
function MdBoldToTitle()
" Strip bold and make it an L4
" Copy into a macroc
" 0xx$hhxxxI#### 
" Copy into the search string
" Search string for a full line bold
" /^*\*\(.*\)\*\*$ "
endfunction
" Useful for iPlug stuff
function! SetupIPlug()
iplug add 'https://github.com/junegunn/goyo.vim'
iplug add 'https://github.com/reedes/vim-pencil'
iplug add 'https://github.com/inkarkat/vim-spellcheck'
iplug add 'https://github.com/tpope/vim-surround'
iplug add 'https://github.com/parkr/vim-jekyll'
iplug add "https://github.com/scrooloose/nerdtree"
iplug add 'https://github.com/scrooloose/nerdcommenter'
iplug update
endfunc
func SetupFBSpecific()
"""""""""""""
" FB Specific -- Careful to leak nothing useful.
"""""""""""""
let g:bgdot= "~/fbsource/fbcode/shellconfigs/rc/vim/biggrep.vim"
if filereadable (expand(g:bgdot))
echo "At Facebook"
:so ~/fbsource/fbcode/shellconfigs/rc/vim/biggrep.vim
endif
endfunc
call SetupFBSpecific()
if exists('##TextYankPost')
augroup BlinkClipboardIntegration
autocmd!
" For some reason '*' doesn't show up in the clipboard names, so using
" 'cy, instead '*y as used expect
autocmd TextYankPost * if v:event.regname == 'c' | call SendViaOSC52(join(v:event["regcontents"],"\n")) | endif
augroup END
endif
" MDX is currently unused as it's not ready, lets watch as it develops
" Favorite feature is opening tags in Fzf Window
let g:mkdx#settings = { 'highlight': { 'enable': 1 },
\ 'enter': { 'shift': 1 },
\ 'links': { 'external': { 'enable': 1 } },
\ 'toc': { 'text': 'Table of Contents', 'update_on_write': 1 },
\ 'fold': { 'enable': 1 } }
let g:polyglot_disabled = ['markdown'] " for vim-polyglot users, it loads Plasticboy's markdown
" plugin which unfortunately interferes
" with mkdx list indentation
fun! s:MkdxGoToHeader(header)
" given a line: ' 84: # Header'
" this will match the number 84 and move the cursor to the start of that line
call cursor(str2nr(get(matchlist(a:header, ' *\([0-9]\+\)'), 1, '')), 1)
endfun
fun! s:MkdxFormatHeader(key, val)
let text = get(a:val, 'text', '')
let lnum = get(a:val, 'lnum', '')
" if the text is empty or no lnum is present, return the empty string
if (empty(text) || empty(lnum)) | return text | endif
" We can't jump to it if we don't know the line number so that must be present in the outpt line.
" We also add extra padding up to 4 digits, so I hope your markdown files don't grow beyond 99.9k lines ;)
return repeat(' ', 4 - strlen(lnum)) . lnum . ': ' . text
endfun
fun! s:MkdxFzfQuickfixHeaders()
" passing 0 to mkdx#QuickfixHeaders causes it to return the list instead of opening the quickfix list
" this allows you to create a 'source' for fzf.
" first we map each item (formatted for quickfix use) using the function MkdxFormatHeader()
" then, we strip out any remaining empty headers.
let headers = filter(map(mkdx#QuickfixHeaders(0), function('<SID>MkdxFormatHeader')), 'v:val != ""')
" run the fzf function with the formatted data and as a 'sink' (action to execute on selected entry)
" supply the MkdxGoToHeader() function which will parse the line, extract the line number and move the cursor to it.
call fzf#run(fzf#wrap(
\ {'source': headers, 'sink': function('<SID>MkdxGoToHeader') }
\ ))
endfun
" finally, map it -- in this case, I mapped it to overwrite the default action for toggling quickfix (<PREFIX>I)
" :nnoremap <silent> <C-U> :call <SID>MkdxFzfQuickfixHeaders()<Cr>
:nnoremap <silent> <C-Y> :TagbarOpen fj<cr>
" Setup surround for b (old) and i(talics) for markdown.
" echo char2nr('b') -> 105
"
" Cheat Sheat
" - yssX - soround the current line with italics(i) or bold(b) or something
" else.
"
" - Once in visual mode, S will do the surround folowed by the b so like
" select text in visual mode, then Sb will make it bold.
autocmd FileType markdown let b:surround_105 = "*\r*" " i = 105
autocmd FileType markdown let b:surround_98 = "**\r**" " b = 98
" Disable bells
set belloff=all
let g:rainbow_active = 1 "set to 0 if you want to enable it later via :RainbowToggle
" When doing a visual selection the last line is lost when you do 'A'ppend
" So you need to capture the last line (TODO See if can pass that to gpt sink
" options)
let gpt_last_line=0
" The default sink escapes the output, this way we can skip that.
" We can also unescapet the gpt output too.
function GptSinkAppend(completion)
" gpt3.py wrap encodes newlines as ;;
let gpt_decoded = substitute(a:completion,';','\n',"g")
let insert_command = 'normal A'.gpt_decoded
execute ":".string(g:gpt_last_line)
execute insert_command
endfunction
function GptSinkReplace(completion)
" gpt3.py wrap encodes newlines as ;;
let gpt_decoded = substitute(a:completion,';','\n',"g")
" write output to register j
call setreg("j",gpt_decoded)
" erase current selected text
" This puts cursor on last line.
execute ":".string(g:gpt_first_line).",".string(g:gpt_last_line)."d"
" Write register before current line - which is now the last line.
execute ":put! j"
endfunction
" range after the function enables access to a:firstline, a:lastline
function! GptCompleteSimple(gpt_command='stdin',gpt_params='',sink='GptSinkAppend') range
let lines = getline(a:firstline, a:lastline)
let g:gpt_last_line = a:lastline
let g:gpt_first_line = a:firstline
let tempname_in = "~/tmp/gpt3.in.ipc"
let tempname_out = "~/tmp/gpt3.out.ipc"
call writefile(lines, expand(tempname_in))
" let gpt_cmd = 'cat '.tempname_in.' | python3.10 ~/gpt3.py stdin -no-stream --responses=4 > ' . tempname_out
let gpt_cmd = 'cat '.tempname_in.' | python3.10 ~/gpt3.py stdin --u4 | tee ' . tempname_out
echom gpt_cmd
execute "!".gpt_cmd
execute ":".string(g:gpt_last_line)
execute "-1r ".tempname_out
endfunction
" range after the function enables access to a:firstline, a:lastline
function! GptComplete(gpt_command='stdin',gpt_params='',sink='GptSinkAppend') range
let lines = getline(a:firstline, a:lastline)
let g:gpt_last_line = a:lastline
let g:gpt_first_line = a:firstline
let tempname_in = "~/tmp/gpt3.in.ipc"
let tempname_out = "~/tmp/gpt3.out.ipc"
call writefile(lines, expand(tempname_in))
if a:sink == "GptSinkReplace"
let gpt_cmd = 'cat '.tempname_in.' | python3.10 ~/gpt3.py '. a:gpt_command . ' > ' . tempname_out
echom gpt_cmd
execute a:firstline. ",". a:lastline ."w !".gpt_cmd
let delta_cmd = "!delta ".tempname_in. " ". tempname_out
echom delta_cmd
execute delta_cmd
" Run pause command
execute "!read -s -k '?GPT changes'"
" Erase the selected text, putting the cursor on last line.
execute ":".string(g:gpt_first_line).",".string(g:gpt_last_line)."d"
" Read file placing it before the last line
execute "-1r ".tempname_out
return
endif
let gpt_source = 'cat '.tempname_in.'| python3 ~/gpt3.py '. a:gpt_command . ' --responses=5 --to-fzf '.a:gpt_params
" -to_fzf is ';' separated, we can look at it in the preview window expanded
let preview = "echo {} | sed 's/;/\\n/g'"
let wrapped = fzf#wrap({'source': gpt_source, 'sink':function(a:sink),
\ 'options':['--preview', preview, '--preview-window', 'down:wrap']})
call fzf#run(wrapped)
endfunction
" Turn a line of ; into gratefulness line.
" Turn a line to grateful to avoid lots of escapes. Format
" <grateful for>;< god for>;<other>;<other for>;<igor for>
" Discovered Bands;Easy to use weights everywhere; Amazon ; Selling everything ; Using the bands
cab grl :s/\"*\s*\(.*\)\s*;\s*\(.*\);\s*\(.*\)\s*;\s*\(.*\)\s*;\s*\(.*\)/1. \1 **God** \2 **\3** \4 **Igor** \5<CR>
function! SetupGPT()
" Get commit mssage, then erase blank line from the start
: cab ecommit call MakeCommitMesage()<CR>
: cab ecc call GptComplete()<CR>
: cab ecs call GptComplete("study")<CR>
: cab ec5 call GptComplete("eli5")<CR>
: cab ecdr call GptComplete("tldr")<CR>
: cab ecj call GptComplete("joke")<CR>
: cab ecpoem call GptComplete("poem")<CR>
: cab ecsum call GptComplete("summary")<CR>
: cab ecfix call GptComplete("fix", "", "GptSinkReplace")<CR>
:cab egpt !~/gpt3.py
" Select section
cab ess :?\#?+1,/\#/-1
" Select selection and fix
cab esf :?\#?+1,/\#/-1 call GptComplete("fix", "", "GptSinkReplace")<CR>
" Select selection and joke
cab esj :?\#?+1,/\#/-1 call GptComplete("joke")
" <expr> say repplace the rhs with evaluation of rhs
" inoremap <expr> <c-x><c-f> fzf#vim#complete("echo ".getline("."))
" inoremap <expr> <c-x><c-g> CompleteGpt()
" nnoremap <expr> <c-x><c-g> CompleteGpt()
endfunction
call SetupGPT()
func! GptCompleteToBottom()
" hack fj is the escape key - a nice hack sicne <esc> doesn't work with
" normal command
:normal Go fj
:% call GptCompleteSimple()
endfunc
func! SetupForConvo()
" :match Comment /^\s*>.*/
set syntax=markdown
" Turn off hitting enter indents - which BTW, is annoying
:setlocal nocin
" In insert mode, add cariage return to hint AI that it's its turn ..
:imap <buffer> ffj <cr><cr><esc>:% call GptCompleteSimple()<cr>
:map <buffer> ffj :call GptCompleteToBottom()<cr>
" Erase the current GPT answer
:map <buffer> ffd :?---?,/---/d<cr>
" Keep the current answer
:map <buffer> ffk :?--- \*\*0?,?---?d<cr>:/---/,/--- \*\*9/d<cr>
:set ft=markdown
endfunc
autocmd BufEnter *convo.md call SetupForConvo()
autocmd BufEnter *COMMIT_EDITMSG :map ffj :call MakeCommitMesage()<cr>
" Refactor to share with convo maps
autocmd BufEnter *COMMIT_EDITMSG :map <buffer> ffd :?---?,/---/d<cr>
autocmd BufEnter *COMMIT_EDITMSG :map <buffer> ffk :?--- \*\*0?,?---?d<cr>:/---/,/--- \*\*9/d<cr>
function! MakeCommitMesage()
let tempfile=tempname()
let gpt_from_git_diff = '!git diff --staged -U10 | ~/gpt3.py commit-message --debug --responses=4'
execute gpt_from_git_diff . ' > ' . shellescape(tempfile)
try
silent execute 'read' tempfile
finally
call delete(tempfile)
endtry
endfunction
cab pbp :r !pbpaste
cab pbc :w !pbcopy
cab pbr :r !pbpaste
cab pbw :w !pbcopy
command! PromptEulogy :r !shuf -n 3 ~/gits/igor2/eulogy_prompts.md
if (has('mac'))
:cab ghlink :exe "!gh browse " . expand('%') . ':' . line(".") . "" <cr>
else
:cab ghlink :exe "!gh browse -n " . expand('%') . ':' . line(".") . "\| pbcopy" <cr>
endif
function! SetupOpenBrowser()
let g:netrw_nogx = 1 " disable netrw's gx mapping.
nmap gx <Plug>(openbrowser-smart-search)
vmap gx <Plug>(openbrowser-smart-search)
"if (has('unix'))
"let g:netrw_browsex_viewer= "pbcopy"
"let g:netrw_suppress_gx_mes=0
"let g:openbrowser_browser_commands=[
"\ {"name": "zsh",
"\ "args": ["zsh", "-c", '"pbcopy {uri}"'],
"\ }
"\]
"endif
" https://www.google4.com
endfunc
call SetupOpenBrowser()
" Reload when saving vimrc, which is the whole point of changin dotfile
augroup reload_vimrc | au!
au BufWritePost *default_vimrc source ~/.vimrc
augroup END
let g:copilot_filetypes = {
\ 'markdown': v:true,
\ }
" viminfo controls max old files, which is where History is found
" Setting value is super arcane, first param is count files setting to 1000
" Annoyingly, only set on vim exit (so cross session files not findable)
set viminfo='1000,<50,s10,h
" ConoLineEnable
" vim:foldmethod=indent:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment