diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..6a462a3 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{sh,py,vim}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..aa7cd17 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,40 @@ +name: check + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install validation tools + run: sudo apt-get update && sudo apt-get install -y shellcheck tmux vim-nox + + - name: Check shell scripts + run: | + bash -n install.sh uninstall.sh bash_tools.sh bash_tools/*.sh + shellcheck install.sh uninstall.sh bash_tools.sh bash_tools/*.sh + + - name: Check Python + run: python3 -m compileall -q win-install.py + + - name: Check Vim startup + run: vim -Nu "$PWD/.vimrc" -n -es -c 'doautocmd VimEnter' -c 'qa!' + + - name: Check tmux configuration + run: | + tmux -L dotfiles-check -f "$PWD/.tmux.conf" new-session -d + tmux -L dotfiles-check kill-server + + - name: Reject empty tracked files + shell: bash + run: | + while IFS= read -r -d '' file; do + [[ -s "$file" ]] || { echo "Empty tracked file: $file"; exit 1; } + done < <(git ls-files -z) diff --git a/.gitignore b/.gitignore index 4b50cca..b51535b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .DS_Store *.pyc +__pycache__/ *._* .vim/ node_modules/ diff --git a/.gitt b/.gitt deleted file mode 100644 index e69de29..0000000 diff --git a/.tmux.conf b/.tmux.conf index 2812ad4..db30a53 100644 --- a/.tmux.conf +++ b/.tmux.conf @@ -1,67 +1,43 @@ set-option -sg escape-time 10 -set -g default-terminal "screen-256color" -# set -g default-terminal "xterm-256color" -set-option -g history-limit 1000000 - -set -g focus-events on # requirement for vim's vim-tmux-clipboard plugin - -# turn off status line +set -g default-terminal 'tmux-256color' +set -as terminal-features ',xterm-256color:RGB' +set -g history-limit 100000 +set -g mouse on +set -g focus-events on set -g status off - -set-option -sa terminal-overrides ',xterm-256color:RGB' setw -g mode-keys vi -bind-key -T copy-mode-vi 'v' send -X begin-selection -bind-key -T copy-mode-vi 'y' send-keys -X copy-pipe-and-cancel 'xclip -in -selection clipboard' -# vim-like pane resizing -bind-key -r C-k resize-pane -U -bind-key -r C-j resize-pane -D +bind-key -T copy-mode-vi v send -X begin-selection +bind-key -T copy-mode-vi y send -X copy-pipe-and-cancel \ + 'if command -v wl-copy >/dev/null 2>&1; then wl-copy; elif command -v xclip >/dev/null 2>&1; then xclip -in -selection clipboard; elif command -v pbcopy >/dev/null 2>&1; then pbcopy; elif command -v clip.exe >/dev/null 2>&1; then clip.exe; else cat >/dev/null; fi' + +# Prefix + Ctrl-H/J/K/L resizes panes. bind-key -r C-h resize-pane -L +bind-key -r C-j resize-pane -D +bind-key -r C-k resize-pane -U bind-key -r C-l resize-pane -R -# vim-like pane switching -# bind-key -n C-k select-pane -U -# bind-key -n C-j select-pane -D -# bind-key -n C-h select-pane -L -# bind-key -n C-l select-pane -R - -# and now unbind keys -unbind Up -unbind Down -unbind Left -unbind Right - -unbind C-Up -unbind C-Down -unbind C-Left -unbind C-Right - -# Smart pane switching with awareness of Vim splits. -# See: https://github.com/christoomey/vim-tmux-navigator +# Ctrl-H/J/K/L moves seamlessly between tmux panes and Vim splits. is_vim="ps -o state= -o comm= -t '#{pane_tty}' \ - | grep -iqE '^[^TXZ ]+ +(\\S+\\/)?g?(view|l?n?vim?x?)(diff)?$'" -bind-key -n 'C-h' if-shell "$is_vim" 'send-keys C-h' 'select-pane -L' -bind-key -n 'C-j' if-shell "$is_vim" 'send-keys C-j' 'select-pane -D' -bind-key -n 'C-k' if-shell "$is_vim" 'send-keys C-k' 'select-pane -U' -bind-key -n 'C-l' if-shell "$is_vim" 'send-keys C-l' 'select-pane -R' -tmux_version='$(tmux -V | sed -En "s/^tmux ([0-9]+(.[0-9]+)?).*/\1/p")' -if-shell -b '[ "$(echo "$tmux_version < 3.0" | bc)" = 1 ]' \ - "bind-key -n 'C-\\' if-shell \"$is_vim\" 'send-keys C-\\' 'select-pane -l'" -if-shell -b '[ "$(echo "$tmux_version >= 3.0" | bc)" = 1 ]' \ - "bind-key -n 'C-\\' if-shell \"$is_vim\" 'send-keys C-\\\\' 'select-pane -l'" + | grep -iqE '^[^TXZ ]+ +(\\S+\\/)?g?\\.?(view|l?n?vim?x?)(diff)?(-wrapped)?$'" +bind-key -n C-h if-shell "$is_vim" 'send-keys C-h' 'select-pane -L' +bind-key -n C-j if-shell "$is_vim" 'send-keys C-j' 'select-pane -D' +bind-key -n C-k if-shell "$is_vim" 'send-keys C-k' 'select-pane -U' +bind-key -n C-l if-shell "$is_vim" 'send-keys C-l' 'select-pane -R' +bind-key -n 'C-\' if-shell "$is_vim" 'send-keys C-\' 'select-pane -l' -bind-key -T copy-mode-vi 'C-h' select-pane -L -bind-key -T copy-mode-vi 'C-j' select-pane -D -bind-key -T copy-mode-vi 'C-k' select-pane -U -bind-key -T copy-mode-vi 'C-l' select-pane -R +bind-key -T copy-mode-vi C-h select-pane -L +bind-key -T copy-mode-vi C-j select-pane -D +bind-key -T copy-mode-vi C-k select-pane -U +bind-key -T copy-mode-vi C-l select-pane -R bind-key -T copy-mode-vi 'C-\' select-pane -l set -g @plugin 'tmux-plugins/tpm' set -g @plugin 'tmux-plugins/tmux-sensible' - set -g @plugin 'roosta/tmux-fuzzback' set -g @fuzzback-popup-size '90%' set -g @fuzzback-popup 1 set -g @fuzzback-fzf-colors 'gutter:-1,bg+:-1' -run '~/.tmux/plugins/tpm/tpm' +if-shell 'test -x "$HOME/.tmux/plugins/tpm/tpm"' \ + 'run-shell "$HOME/.tmux/plugins/tpm/tpm"' diff --git a/.vimrc b/.vimrc index e76ab59..f2b818d 100644 --- a/.vimrc +++ b/.vimrc @@ -1,269 +1,253 @@ - " dotfile location - let g:dotfiledir = expand(fnamemodify(resolve(expand(':p')), ':h').'/') - " vim runtime folder - let g:vim_dir = expand('~/.vim/') +" Vim 9 configuration shared across Linux, WSL, Windows, and macOS. +if v:version < 900 + echoerr 'This configuration requires Vim 9 or newer.' + finish +endif - " detect vim type(vim or nvim) - let g:vim_v = 0 - if has('nvim') - let g:vim_type = 'nvim' - else - let g:vim_type = 'vim' - let g:vim_v = v:version - endif +let g:dotfiledir = fnamemodify(resolve(expand(':p')), ':h') . '/' +let g:dotvimdir = g:dotfiledir . 'config/vim' +let g:vim_dir = has('win32') || has('win64') ? expand('~/vimfiles') : expand('~/.vim') +execute 'set runtimepath^=' . fnameescape(g:dotvimdir) - " detect operating system (Windows/Linux/Darwin) - let g:isWSL = 0 - if has("win64") || has("win32") || has("win16") - let g:os = "Windows" - set updatetime=50 - if executable('pwsh') - " prefer to use powershell 7 - set shell=pwsh - else - set shell=powershell - endif - else - let g:os = substitute(system('uname'), '\n', '', '') - if system('uname -r') =~ "icrosoft" - let g:isWSL = 1 - endif - endif +let g:os = has('win32') || has('win64') ? 'Windows' + \ : has('macunix') ? 'Darwin' + \ : substitute(system('uname'), '\n', '', '') +if g:os ==# 'Windows' + if executable('pwsh') + set shell=pwsh + elseif executable('powershell') + set shell=powershell + endif +endif - set runtimepath^=~/.vim runtimepath+=~/.vim/after - let &packpath=&runtimepath +let mapleader = ',' +let maplocalleader = '_' - " The default leader is '\', but many people prefer ',' as it's in a standard - let mapleader = ',' - let maplocalleader = '_' +filetype plugin indent on +syntax enable +set encoding=utf-8 +set belloff=all +set mouse=a +set hidden +set history=1000 +set updatetime=300 +set shortmess+=filmnrxoOtTF +set backspace=indent,eol,start +set number +set cursorline +set cursorlineopt=number +set noshowmode +set showmatch +set incsearch +set hlsearch +set ignorecase +set smartcase +set wildmenu +set wildmode=list:longest,full +set scrolloff=5 +set sidescrolloff=5 +set splitright +set splitbelow +set display=lastline +set expandtab +set shiftwidth=4 +set tabstop=4 +set softtabstop=4 +set autoindent +set nojoinspaces +set nospell +set list +set listchars=tab:•\ ,trail:•,extends:»,precedes:« +let &fillchars = 'eob: ,vert:│,stl: ,stlnc: ' +set foldmethod=syntax +set foldlevelstart=99 +set undofile +set undolevels=1000 +set undoreload=10000 +set viewoptions=folds +if has('termguicolors') + set termguicolors +endif -" General { +for s:dir in ['backup', 'swap', 'undo', 'view'] + let s:path = g:vim_dir . '/' . s:dir + if !isdirectory(s:path) + silent! call mkdir(s:path, 'p') + endif +endfor +execute 'set backupdir=' . fnameescape(g:vim_dir . '/backup//') +execute 'set directory=' . fnameescape(g:vim_dir . '/swap//') +execute 'set undodir=' . fnameescape(g:vim_dir . '/undo//') +execute 'set viewdir=' . fnameescape(g:vim_dir . '/view//') - filetype plugin indent on " Automatically detect file types. - syntax on " Syntax highlighting - set belloff=all " Turn off the annoying bell - set mouse=a " Automatically enable mouse usage - set mousehide " Hide the mouse cursor while typing - set shortmess+=F " Don't show the file name when open new file - " scriptencoding utf-8 +if has('clipboard') + if g:os ==# 'Darwin' || g:os ==# 'Windows' + set clipboard=unnamed + else + set clipboard=unnamedplus + endif +endif - set shortmess+=filmnrxoOtT " Abbrev. of messages (avoids 'hit enter') - " set viewoptions=folds,options,cursor,unix,slash " Better Unix / Windows compatibility - " set virtualedit=onemore " Allow for cursor beyond last character - set history=1000 " Store a ton of history (default is 20) - set hidden " Allow buffer switching without saving - set iskeyword-=. " '.' is an end of word designator - set iskeyword-=# " '#' is an end of word designator - set iskeyword+=- +augroup DotfilesCore + autocmd! + autocmd FileType javascript,typescript,lua setlocal tabstop=2 shiftwidth=2 softtabstop=2 + autocmd FileType haskell,ruby,yaml setlocal tabstop=2 shiftwidth=2 softtabstop=2 + autocmd FileType c,cpp,vim,java,python,lua setlocal colorcolumn=80 + autocmd FileType help setlocal colorcolumn= + autocmd FileType * setlocal formatoptions-=o + autocmd BufNewFile,BufRead *.html.twig setfiletype html.twig + autocmd BufNewFile,BufRead *.ts setfiletype typescript + autocmd BufReadPost * if line("'\"") > 1 && line("'\"") <= line('$') | execute 'normal! g`"' | endif + autocmd BufWinLeave ?* if &buftype ==# '' && !empty(expand('%:p')) | silent! mkview | endif + autocmd BufWinEnter ?* if &buftype ==# '' && !empty(expand('%:p')) | silent! loadview | endif +augroup END - augroup FileFormat - autocmd! - autocmd FileType javascript,typescript,lua setlocal tabstop=2 shiftwidth=2 softtabstop=2 - " autocmd FileType c,cpp,python,java setlocal tabstop=4 shiftwidth=4 softtabstop=4 - autocmd BufNewFile,BufRead *.html.twig set filetype=html.twig - autocmd FileType haskell,puppet,ruby,yml setlocal expandtab shiftwidth=2 softtabstop=2 - " Instead of reverting the cursor to the last position in the buffer, we - " set it to the first line when editing a git commit message - autocmd FileType gitcommit au! BufEnter COMMIT_EDITMSG call setpos('.', [0, 1, 1, 0]) - augroup END +nnoremap j gj +nnoremap k gk +nnoremap Y y$ +xnoremap < >gv +nnoremap h :nohlsearch +nnoremap ws :%s/\s\+$//e +nnoremap s :%s/\<\>/ +nnoremap q :bprevious +nnoremap e :bnext +nnoremap % :vsplit +nnoremap " :split +nnoremap q: +nnoremap Q +command! WQ wq +command! Wq wq +command! W write +command! Q quit - " Setting up the directories { - " set backup " Backups are nice ... - if has('persistent_undo') - set undofile " So is persistent undo ... - set undolevels=1000 " Maximum number of changes that can be undone - set undoreload=10000 " Maximum number lines to save for undo on a buffer reload - endif - " } +" Plugin installation is explicit: run install.sh or :PlugInstall/:PlugUpdate. +let s:plug_vim = g:vim_dir . '/autoload/plug.vim' +if filereadable(s:plug_vim) + execute 'source ' . fnameescape(s:plug_vim) + call plug#begin(g:vim_dir . '/plugged') + Plug 'vim-fuzzbox/fuzzbox.vim' + Plug 'preservim/nerdtree', { 'on': ['NERDTreeToggle', 'NERDTreeFind'] } + Plug 'ryanoasis/vim-devicons' -" } + Plug 'tpope/vim-repeat' + Plug 'tpope/vim-surround' + Plug 'tpope/vim-commentary' -" Vim UI { -" - set noshowmode - set cursorline " Highlight current line - set cursorlineopt=number " only highlight line number - set cmdheight=1 " get rid of the extra useless line at the bottom(if not working, probably a plugin is changing the value) + Plug 'tpope/vim-fugitive' + Plug 'airblade/vim-gitgutter' - set backspace=indent,eol,start " Backspace for dummies - set fillchars=eob:\ ,vert:│,stl:\ ,stlnc:\ , " it can remove '~' at the end of buffer, and window split line - set number " Line numbers on - set showmatch " Show matching brackets/parenthesis - set incsearch " Find as you type search - set hlsearch " Highlight search terms - set winminheight=0 " Windows can be 0 line high - set ignorecase " Case insensitive search - set smartcase " Case sensitive when uc present - set wildmenu " Show list instead of just completing - set wildmode=list:longest,full " Command completion, list matches, then longest common part, then all. - set whichwrap=b,s,h,l,<,>,[,] " Backspace and cursor keys wrap too - set scrolljump=1 " Lines to scroll when cursor leaves screen - set scrolloff=5 " Minimum lines to keep above and below cursor - set sidescrolloff=5 " Minimum lines to keep at the left or right of the cursor - set display=lastline " don't replace whole long line with @@@ - augroup cc - au! - autocmd FileType c,cpp,vim,java,python,lua set colorcolumn=80 - autocmd FileType help set colorcolumn= - augroup END + Plug 'mhinz/vim-startify' + Plug 'Donaldttt/vim-bufferline' + Plug 'Donaldttt/vim-global-statusline', { 'branch': 'vim9' } + Plug 'christoomey/vim-tmux-navigator' -" } + Plug 'sainnhe/everforest' + Plug 'bluz71/vim-moonfly-colors', { 'as': 'moonfly' } + Plug 'NLKNguyen/papercolor-theme' + call plug#end() +else + echohl WarningMsg + echom 'vim-plug is not installed; run install.sh to install plugins.' + echohl None +endif -" Formatting { - set autoindent " Indent at the same level of the previous line - set expandtab " Tabs are spaces, not tabs - set shiftwidth=4 " Use indents of 4 spaces - set tabstop=4 " An indentation every four columns - set softtabstop=4 " Let backspace delete indent +" Fuzzbox replaces the former Fuzzyy plugin and keeps its familiar mappings. +let g:fuzzbox_dropdown = 1 +let g:fuzzbox_window_defaults = {'maxwidth': 0.8, 'maxheight': 0.8} +let g:fuzzbox_window_options = { + \ 'files': {'width': 0.8}, + \ 'buffers': {'preview': 1, 'width': 0.8, 'preview_ratio': 0.5}, + \ 'grep': {'preview': 1, 'width': 0.8, 'preview_ratio': 0.5}, + \ 'mru': {'preview': 1}} +nnoremap fl :FuzzyCmdHistory - set conceallevel=0 - set nojoinspaces " Prevents inserting two spaces after punctuation on a join (J) - set splitright " Puts new vsplit windows to the right of the current - set splitbelow " Puts new split windows to the bottom of the current - " set nolist " let vim not showing '$' or other sign - set list " Display unprintable characters f12 - switches +" NERDTree remains intentionally small; Fuzzbox handles most navigation. +let g:NERDShutUp = 1 +let g:NERDTreeMinimalMenu = 1 +let g:NERDTreeMinimalUI = 1 +let g:NERDTreeChDirMode = 0 +let g:NERDTreeQuitOnOpen = 1 +let g:NERDTreeMouseMode = 2 +let g:NERDTreeShowHidden = 1 +let g:NERDTreeMapOpenExpl = '' +let g:NERDTreeDirArrowCollapsible = '' +let g:NERDTreeDirArrowExpandable = '' - " stop inserting the current comment leader after hitting 'o' or 'O' in Normal mode - au FileType * setlocal formatoptions-=o +function! s:ToggleTree() abort + if exists('t:NERDTreeBufName') && bufwinnr(t:NERDTreeBufName) != -1 + NERDTreeClose + elseif &filetype ==# 'startify' || empty(expand('%:p')) + NERDTreeToggle + else + NERDTreeFind + endif +endfunction +nnoremap e :call ToggleTree() - set listchars=tab:•\ ,trail:•,extends:»,precedes:« " Unprintable chars mapping +let g:gitgutter_map_keys = 0 +nnoremap gt :GitGutterBufferToggle - set nospell " Spell checking off - set matchpairs+=<:> " Match, to be used with % +let g:tmux_navigator_no_mappings = 1 +nnoremap :TmuxNavigateLeft +nnoremap :TmuxNavigateDown +nnoremap :TmuxNavigateUp +nnoremap :TmuxNavigateRight -" } +let g:bufferline_echo = 0 +let g:bufferline_modified = '+' +let g:bufferline_active_buffer_left = '[' +let g:bufferline_active_buffer_right = ']' -" Key (re)Mappings { +let g:startify_change_to_dir = 0 +let g:startify_files_number = 8 +let g:startify_bookmarks = [g:dotfiledir . '.vimrc'] +let g:startify_lists = [ + \ {'header': [' RECENT'], 'type': 'files'}, + \ {'header': [' BOOKMARKS'], 'type': 'bookmarks'}] - " Wrapped lines goes down/up to next row, rather than next line in file. - noremap j gj - noremap k gk +function! s:StatuslineHighlights() abort + highlight default DotModeNormal cterm=reverse gui=reverse + highlight default link DotModeInsert DiffAdd + highlight default link DotModeVisual Visual + highlight default link DotModeCommand DiffChange +endfunction - " Yank from the cursor to the end of the line, to be consistent with C and D. - nnoremap Y y$ +function! s:StatuslineUpdate() abort + if !exists('g:StlSetPart') || !exists('g:StlRefresh') + return + endif + let l:modes = { + \ 'n': [' NORMAL ', 'DotModeNormal'], + \ 'i': [' INSERT ', 'DotModeInsert'], + \ 'v': [' VISUAL ', 'DotModeVisual'], + \ 'V': [' V-LINE ', 'DotModeVisual'], + \ nr2char(22): [' V-BLOCK ', 'DotModeVisual'], + \ 'c': [' COMMAND ', 'DotModeCommand']} + let l:current = get(l:modes, mode(), [' ' . &filetype . ' ', 'StatusLine']) + call g:StlSetPart(0, l:current[0], l:current[1], 'mode') + let l:name = empty(expand('%:t')) ? '[No Name]' : expand('%:t') + call g:StlSetPart(10, ' ' . l:name . (&modified ? ' [+]' : ''), '', 'filename') + try + call g:StlSetPart(30, ' ' . bufferline#get_echo_string(), '', 'buffers') + catch + endtry + call g:StlSetPart(max([0, &columns - 14]), printf(' %d:%d ', line('.'), virtcol('.')), '', 'position') + call g:StlRefresh() +endfunction - set foldmethod=syntax - augroup vimfold - autocmd! - if has('nvim') - " check tree-sitter config - else - autocmd FileType python set foldmethod=indent - autocmd FileType vim set foldmethod=syntax - endif - augroup END +augroup DotfilesUi + autocmd! + autocmd VimEnter * call theme#Init() | call StatuslineHighlights() | call StatuslineUpdate() + autocmd ModeChanged,BufEnter,BufDelete,BufWritePost * call StatuslineUpdate() + autocmd CursorHold * call StatuslineUpdate() + autocmd ColorScheme * call StatuslineHighlights() +augroup END - " so when a buffer open it wouldn't be fold by default - " set nofoldenable - set foldlevelstart=99 +nnoremap cbg :call theme#toggleBg() +nnoremap ctb :call theme#toggleTransparent() - " Visual shifting (does not exit Visual mode) - vnoremap < >gv - - " Allow using the repeat operator with a visual selection (!) - " http://stackoverflow.com/a/8064607/127816 - vnoremap . :normal . - - " For when you forget to sudo.. Really Write the file. - " cmap w!! w !sudo tee % >/dev/null - - " Adjust viewports to the same size - map = = - - " Map ff to display all lines with keyword under cursor - " and ask which one to jump to - nmap j [I:let nr = input("Which one: ")exe "normal " . nr ."[\t" - - " Easier horizontal scrolling - map zl zL - map zh zH - -" Functions { - - " Initialize directories for undo, swap, viewdir (see :h undodir, etc.) - " to ~/.vim/.vim* - function! InitializeDirectories() - let common_dir = g:vim_dir - let dir_list = { - \ 'backupdir' : '.vimbackup', - \ 'viewdir' : '.vimviews', - \ 'directory' : '.vimswap' } - - if has('persistent_undo') - let dir_list['undodir'] = '.vimundo' - endif - - for [settingname, dirname] in items(dir_list) - let directory = common_dir . dirname . '/' - if exists("*mkdir") - if !isdirectory(directory) - call mkdir(directory) - endif - endif - if !isdirectory(directory) - echo "Warning: Unable to create backup directory: " . directory - echo "Try: mkdir -p " . directory - else - let directory = substitute(directory, " ", "\\\\ ", "g") - exec "set " . settingname . "=" . directory - endif - endfor - endfunction - call InitializeDirectories() - -" Visual mode pressing * or # searches for the current selection -" Super useful! From an idea by Michael Naumann - vnoremap * :call VisualSelection('', '')/=@/ - vnoremap # :call VisualSelection('', '')?=@/ - -" Fix file type error for typescript - autocmd BufNewFile,BufRead *.ts set filetype=typescript - -" copy to system - if g:os == 'Darwin' || g:os == 'Windows' - set clipboard=unnamed - else - if g:isWSL && has('nvim') - " :h clipboard-wsl - set clipboard=unnamedplus - - " cache has to be enabled otherwise cause freeze - " obviously wsl without xclip won't work - let g:clipboard = { - \ 'name': 'WSLxclip', - \ 'copy': { - \ '+': 'xclip -quiet -i -selection clipboard', - \ '*': 'xclip -quiet -i -selection primary', - \ }, - \ 'paste': { - \ '+': 'xclip -o -selection clipboard', - \ '*': 'xclip -o -selection primary', - \ }, - \ 'cache_enabled': 1, - \ } - elseif g:isWSL - set clipboard=unnamedplus - else - set clipboard=unnamedplus - endif - endif - -" fix paste mess up when using tmux - if &term =~ "screen" - let &t_BE = "\e[?2004h" - let &t_BD = "\e[?2004l" - exec "set t_PS=\e[200~" - exec "set t_PE=\e[201~" - endif - -" disable netrw as i am using nerdtree and nvim-tree -let g:loaded_netrw = 1 -let g:loaded_netrwPlugin = 1 - -" Use bundles config { - if filereadable(g:dotfiledir."/main.vim") - execute('source '.g:dotfiledir.'/main.vim') - endif -" } +if has('gui_running') + set guifont=Hack\ Nerd\ Font:h13 +endif diff --git a/README.md b/README.md index fe4906e..4251d1d 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,77 @@ # Dotfiles -All kind of dot files -## Installation +Focused Vim 9, Bash, and tmux configuration for Linux, WSL, and macOS. The +Windows installer manages the same Vim configuration. -### Linux, \*nix, Mac OSX Installation +## Requirements -Simply copying and pasting the following line into a terminal. +- Git +- Vim 9 or newer +- `curl` for the Unix installer +- Optional: tmux, zoxide, ripgrep, and a Nerd Font + +## Install + +Clone the repository, then install all components: ```bash - curl https://raw.githubusercontent.com/Donaldttt/dotfiles/main/install.sh -L > dotfiles_install.sh && sh dotfiles_install.sh +git clone https://github.com/Donaldttt/dotfiles.git ~/.dotfiles +~/.dotfiles/install.sh ``` -or +Components can be installed independently and combined: ```bash - sh <(curl https://raw.githubusercontent.com/Donaldttt/dotfiles/main/install.sh -L) +~/.dotfiles/install.sh vim +~/.dotfiles/install.sh shell tmux ``` +The installer backs up conflicting files, creates managed links, and installs +Vim plugins and TPM. It never updates an existing repository automatically and +does not install zoxide; if zoxide is already available, the managed Bash block +initializes it. + +On Windows, clone the repository and run: + +```powershell +python .\win-install.py +``` + +## Vim + +The Vim setup includes Fuzzbox and NERDTree navigation, Fugitive and GitGutter, +Startify, a compact global statusline, and five color schemes. + +Useful mappings use `,` as the leader key: + +- `,ff`: files +- `,fg`: text search +- `,e`: NERDTree +- `,cbg`: light/dark mode +- `,ctb`: transparency +- `:FuzzyColors`: choose a color scheme + +Plugin maintenance is explicit: + +```vim +:PlugUpdate +:PlugClean +``` + +## Update and uninstall + +Update safely from a clean worktree: + +```bash +git -C ~/.dotfiles pull --ff-only +~/.dotfiles/install.sh +``` + +To remove managed links and the managed Bash block: + +```bash +~/.dotfiles/uninstall.sh +``` + +Uninstalling intentionally retains the repository, backups, Vim data/plugins, +and TPM so user data is never removed implicitly. diff --git a/bash_tools.sh b/bash_tools.sh index 7199ad4..cd14a7e 100644 --- a/bash_tools.sh +++ b/bash_tools.sh @@ -1,70 +1,38 @@ -# args: -# $1: -# The IP address you want to query geo info for. -# If no argument supplied, the host machine's ip will -# be used -# doc for api: https://ip-api.com/docs/api +# Bash-only interactive shell helpers. +[[ -n ${BASH_VERSION:-} ]] || return 0 -if [ -n "$ZSH_NAME" ]; then - SHELL_NAME=zsh - DOTFILE_DIR=${0:a:h}/ - # enable emacs key bindings - bindkey -e - source $DOTFILE_DIR/bash_tools/theme_zsh.sh -elif [ -n "$SHELL" ];then - SHELL_NAME=bash - DOTFILE_DIR=$(dirname ${BASH_SOURCE[0]})/ - source $DOTFILE_DIR/bash_tools/theme_bash.sh -fi - -## ENVIRONMENT +DOTFILE_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" export EDITOR='vim' -export PATH=$PATH:~/.local/bin +export VISUAL="$EDITOR" +case ":$PATH:" in + *":$HOME/.local/bin:"*) ;; + *) export PATH="$PATH:$HOME/.local/bin" ;; +esac -# For references: -# https://askubuntu.com/questions/466198/how-do-i-change-the-color-for-directories-with-ls-in-the-console +# shellcheck source=bash_tools/theme_bash.sh +source "$DOTFILE_DIR/bash_tools/theme_bash.sh" +# shellcheck source=bash_tools/ls_colors_theme.sh +source "$DOTFILE_DIR/bash_tools/ls_colors_theme.sh" -# We use vivid to generate configuration for LS_COLORS -# more info: https://github.com/sharkdp/vivid -source $DOTFILE_DIR/bash_tools/ls_colors_theme.sh -alias ls='ls --color=auto' +if ls --color=auto -d . >/dev/null 2>&1; then + alias ls='ls --color=auto' +elif [[ $OSTYPE == darwin* ]]; then + alias ls='ls -G' +fi -# get ipinfo of the machine -function ipinfo(){ - local api_str="http://ip-api.com/json/$1?fields=query,country,regionName,city,district,zip,isp,org,reverse,mobile,proxy,hosting" - if ! hash python; then - curl "$api_str" - else - curl -s "$api_str" | python -m json.tool - fi +# Search for a literal string. Usage: fct +fct() { + (($# == 2)) || { printf 'Usage: fct \n' >&2; return 2; } + if command -v rg >/dev/null 2>&1; then + rg -n --fixed-strings -- "$2" "$1" + else + grep -Rnw -- "$1" -e "$2" + fi } -# find file contain certain text string($2) in certain directory($1) -function fct(){ - grep -rnw $1 -e $2 +# Query dict.org. Usage: odict +odict() { + (($# == 1)) || { printf 'Usage: odict \n' >&2; return 2; } + curl --fail --silent --show-error "dict://dict.org/d:$1" } - -# online directory -function odict(){ - curl dict://dict.org/d:"${1}" -} - -# self host directory -function dict(){ - python $DOTFILE_DIR/bash_tools/dict.py $1 $2 -} - -# set_wallpaper() function -source $DOTFILE_DIR/bash_tools/wallpaper.sh - -# -# Command Configuration -# - -# -A: get rid of . and .. -# -t: Sort by time. Display the newest first -#alias ls=ls -At - -source $DOTFILE_DIR/bash_tools/fzf_file_seletor.sh - diff --git a/bash_tools/dict.py b/bash_tools/dict.py deleted file mode 100644 index f15ba56..0000000 --- a/bash_tools/dict.py +++ /dev/null @@ -1,92 +0,0 @@ -import json -import sys -import re - -from urllib.request import urlopen - -Usage = """ -Usage: python3 dict.sh [word] -""" - -HAS_RICH = 0 -try: - from rich.console import Console - from rich.panel import Panel - from rich.text import Text - from rich import print - HAS_RICH = 1 -except: - pass - -def basic_paring(data): - """ Display data in the most simple way - """ - word = data["word"] - defs = data["def"] - samples = data["sample_sentence"] - ponetic = data["phonetic"] - - print(word) - - if len(ponetic.items()) > 0: - for _, v in ponetic.items(): - print(v, end=" ") - print() - print() - - if len(defs) > 0: - for k in defs: - print(k, defs[k]) - print() - - for s in samples[:2]: - print("-", end=" ") - print(s['en']) - print() - -def rich_paring(data): - console = Console() - word = data["word"] - defs = data["def"] - ponetic = data["phonetic"] - samples = data["sample_sentence"] - - console.print(word, style="bold magenta") - print() - - if len(ponetic.items()) > 0: - for _, v in ponetic.items(): - #v = v.replace('[', '\[').replace(']', ']') - console.print(Text(v, style="yellow")) - print() - - if len(defs) > 0: - for k in defs: - console.print(Text(k, style="green")) - console.print(Text(defs[k], style="cyan")) - print() - - for s in samples[:2]: - ens = s['en'].replace('"', '\"') - ens = re.sub(r'\*\*([^ ]*?)\*\*', r'[/][red]\1[/][yellow4]', ens) - - text = Text.from_markup("[yellow4]" + ens + "[/]", justify="left") - panel = Panel(text) - - console.print(panel) - - -if __name__ == "__main__": - if len(sys.argv) != 2: - print(Usage) - exit(1) - - word = sys.argv[1] - url = "http://do.useless.pw/{}".format(word) - r = urlopen(url) - content = r.read() - json_content = json.loads(content) - if not HAS_RICH: - basic_paring(json_content) - else: - rich_paring(json_content) diff --git a/bash_tools/fzf_file_seletor.sh b/bash_tools/fzf_file_seletor.sh deleted file mode 100755 index 2959307..0000000 --- a/bash_tools/fzf_file_seletor.sh +++ /dev/null @@ -1,228 +0,0 @@ -#!/bin/bash - -# For any command require a file path, this function -# helps to select the correct file with key words -# Usage: -# Add the command to desired list - -# fzf match everything -fzf_command_list_all=(\ -) - -# fzf match files -fzf_command_list_file=(\ -set_wallpaper \ -) - -# fzf only match folders -fzf_command_list_dir=(\ -cd \ -) - -# in case above functions are broken -function no_fzf(){ - for c in "${fzf_command_list_all[@]}"; do - unalias $c - done - for c in "${fzf_command_list_file[@]}"; do - unalias $c - done - for c in "${fzf_command_list_dir[@]}"; do - unalias $c - done -} - -function dp(){ - local debug=0 - [ "$debug" = "1" ] && echo $1 -} - -# SHELL specific setting -if [ ! -z "$ZSH_NAME" ]; then - SHELL_NAME=zsh - dp "[bash_tools]: In ZSH shell" - # disable error output when - # wildcard found 0 match - setopt +o nomatch - - #setopt extended_glob - - # show hidden file when using wildcard - # use in fzf_selector - # only for zsh - setopt dotglob - setopt glob_dots -else - # temporary - SHELL_NAME=bash - dp "[bash_tools]: In non-ZSH shell" - # only for bash - shopt -s dotglob - - # allow reverse wildcard exp. !(b*) - # shopt -s extglob - - # allows filename patterns which match no - # files to expand to a null string, rather - # than themselves - shopt -s nullglob -fi - -ret='' - -# $1 keyword -# $2 -# 0: show all -# 1: only show directories -# 2: only show files -function fzf_selector() { - ret=$1 - if [ "$1" = "." ] || [ "$1" = ".." ] || \ - [[ "$1" == -* ]] || [[ "$1" == */* ]]; then - dp "fzf return directly" - return 1 - fi - - if [ $2 = 0 ]; then - all_items=(*) - elif [ $2 = 1 ]; then - dp "try to find dirs" - all_items=(*/) - elif [ $2 = 2 ]; then - dp "try to find files" - if [ "$SHELL_NAME" = "zsh" ]; then - eval "all_items=(*(^/))" - elif [ "$SHELL_NAME" = "bash" ]; then - # no easy way to list just regular files - # in bash??? - all=(*) - all_items=() - for item in "${all[@]}"; do - [ -f "$item" ] && all_items+=("$item") - done - fi - fi - - - dp "fzf-keyword: $1" - files=() - # match - # 1. try match file/dir equals to keyword completely - # 2. try match file/dir which keyword is substring of - # 3. try match file/dir equals to keyword completely after ignoring cases - # 4. try match file/dir which keyword is substring of after ignoring cases - - for item in "${all_items[@]}"; do - dp "item: $item" - # 1. - if [ "$item" = "$1" ] || [ "$item" = "$1/" ]; then - return 0 - fi - - # 2. - # this line ignore cases - # [[ $1 =~ [A-Z] ]] && \ - grep $1 <<< $item > /dev/null 2>&1 && \ - files+=("$item") - done - - dp "len contains upper cases ${#files[@]}" - - if [ "${#files[@]}" = "0" ]; then - for item in "${all_items[@]}"; do - # 3. - if ([ "$SHELL_NAME" = "bash" ] && ( [ "${item,,}" = "${1,,}" ] || [ "${item,,}" = "${1,,}/" ] )) || \ - ([ "$SHELL_NAME" = "zsh" ] && ( [ "${item:l}" = "${1:l}" ] || [ "${item:l}" = "${1:l}/" ] )) ; then - ret=$item - return 0 - fi - # 4. - grep -i $1 <<< $item > /dev/null 2>&1 && files+=("$item") - done - fi - - if [ "${#files[@]}" = "0" ]; then - # if grep find zero file - ret=$1 - elif [ "${#files[@]}" = "1" ]; then - ret=$files - else - select file in "${files[@]}"; do - ret=$file - break - done - fi -} - -# $1 command for fzf substuting(like ls) -# $2 original args pass to function -# $3 command require file type (file: 0 |directory: 1) -function fzf_command_execute() { - local args=($@) - local len=${#args[@]} - - dp "args: $args" - dp "lens: $len" - - # zsh shell's array starts with 1 rather than 0 - if [ ! -z "$ZSH_NAME" ]; then - dp "zsh" - flag="${args[2]}" - unset 'args[2]' - command_prefix="${args[1]}" - else - dp "not zsh" - flag="${args[1]}" - unset 'args[1]' - command_prefix="${args[0]}" - fi - - dp "flag: $flag" - - if [ "$len" = "2" ]; then - # flag will take 1 length - # so if len == 2 means no argument is given - ${args[@]} - return 0 - fi - # probably work for bash - #keyword="${args: -1}" - - keyword="" - slice_flag=1 - for arg in "${args[@]:2}"; do - dp "argg $arg" - if [ "$slice_flag" = "1" ]; then - if [ "$keyword" = "" ]; then - keyword="$arg" - else - keyword="$keyword $arg" - fi - elif [[ "$arg" == "-"* ]]; then - command_prefix="$command_prefix $arg" - else - slice_flag=1 - fi - done - dp "command_prefix: $command_prefix" - dp "keyword: $keyword" - - # Delete last argument - # Here we assume it is a file path - - fzf_selector "$keyword" $flag - dp "ret: $ret" - - $command_prefix "$ret" -} - -for c in "${fzf_command_list_all[@]}"; do - alias $c="fzf_command_execute $c 0" -done -for c in "${fzf_command_list_file[@]}"; do - alias $c="fzf_command_execute $c 2" -done -for c in "${fzf_command_list_dir[@]}"; do - alias $c="fzf_command_execute $c 1" -done - diff --git a/bash_tools/theme_bash.sh b/bash_tools/theme_bash.sh index 0d55366..1342997 100644 --- a/bash_tools/theme_bash.sh +++ b/bash_tools/theme_bash.sh @@ -1,23 +1,9 @@ +__dotfiles_git_prompt() { + local branch marks='' + branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || return + git diff --no-ext-diff --quiet --ignore-submodules -- 2>/dev/null || marks+=' *' + git diff --cached --no-ext-diff --quiet --ignore-submodules -- 2>/dev/null || marks+=' +' + printf '\[\e[38;5;166m\](%s\[\e[38;5;204m\]%s\[\e[38;5;166m\])\[\e[0m\]' "$branch" "$marks" +} -# display git status -export GIT_PS1_SHOWDIRTYSTATE=1 -if [[ $(type -t __git_ps1) != function ]]; then - __git_ps1(){ - - local branch=`git branch 2>/dev/null | grep '*' | sed 's/* \(.*\)/\1/'` - - if [ -n "$branch" ]; then - status=`git status 2>/dev/null` - local stage_info="not staged for commit" - local commit_info="Changes to be committed" - - local stage_sign='' - local commit_sign='' - [[ "$status" == *"$stage_info"* ]] && stage_sign=" *" - [[ "$status" == *"$commit_info"* ]] && commit_sign=" +" - echo "(${branch}${stage_sign}${commit_sign})" - fi - } -fi -export PS1=' \[\e[0;32m\]\w\[\e[01;31m\]$(__git_ps1 "(%s)")\[\e[00m\] ' -# » +PS1=' \[\e[38;5;106m\]\w\[\e[0m\]$(__dotfiles_git_prompt)\$ ' diff --git a/bash_tools/theme_zsh.sh b/bash_tools/theme_zsh.sh deleted file mode 100644 index b5e5196..0000000 --- a/bash_tools/theme_zsh.sh +++ /dev/null @@ -1,38 +0,0 @@ -# Autoload zsh add-zsh-hook and vcs_info functions (-U autoload w/o substition, -z use zsh style) -autoload -Uz add-zsh-hook vcs_info -autoload -U colors && colors -# Enable substitution in the prompt. -setopt prompt_subst -# Run vcs_info just before a prompt is displayed (precmd) -add-zsh-hook precmd vcs_info -# Enable checking for (un)staged changes, enabling use of %u and %c -zstyle ':vcs_info:*' check-for-changes true -# Set custom strings for an unstaged vcs repo changes (*) and staged changes (+) -zstyle ':vcs_info:*' unstagedstr ' *' -zstyle ':vcs_info:*' stagedstr ' +' -# Set the format of the Git information for vcs_info - -# 3-Digit codes for various colors: -# https://unix.stackexchange.com/a/124409/194343 - -vcs_info='%F{166}(%b%F{204}%u%c%f%F{166})%f' -zstyle ':vcs_info:git:*' formats $vcs_info - -zstyle ':vcs_info:git:*' actionformats '(%b|%a%u%c)' - -#export PS1='%F{green}%1~ %F{cyan}${vcs_info_msg_0_}%f ' - -local user="%B%(!.%F{red}.%F{green})%n%f " - -local user_symbol='%(!.#.$)' -local current_dir="%B%~%b" -local vcs_branch='${vcs_info_msg_0_}' - -#PROMPT="╭─${user}${current_dir}${vcs_branch} -#╰─%B${user_symbol}%b " - -#PROMPT="%F{magenta}› ${current_dir}${vcs_branch} " - -PROMPT=" %F{106}${current_dir}%f${vcs_branch}$ " - - diff --git a/bash_tools/wallpaper.sh b/bash_tools/wallpaper.sh deleted file mode 100644 index 198753b..0000000 --- a/bash_tools/wallpaper.sh +++ /dev/null @@ -1,35 +0,0 @@ - -# Linux specific functions -if [[ "$OSTYPE" == "linux-gnu"* ]]; then - -set_gnome_wp() { - gsettings set org.gnome.desktop.background picture-uri "file://$1" - gsettings set org.gnome.desktop.background picture-uri-dark "file://$1" -} - -function set_wallpaper(){ - local file=$1 - # convert to abs path - if [[ ! "$file" = /* ]]; then - file=$(pwd)/$1 - fi - set_gnome_wp $file -} - -fi - -# Mac OSX specific functions -if [[ "$OSTYPE" == "darwin"* ]]; then - -function set_wallpaper(){ - local file=$1 - # convert to abs path - if [[ ! "$file" = /* ]]; then - file=$(pwd)/$1 - fi - - apple_script_single_desk="tell application \"Finder\" to set desktop picture to POSIX file \"$file\"" - osascript -e "$apple_script_single_desk" -} - -fi diff --git a/config/coc/java/lombok-1.18.26.jar b/config/coc/java/lombok-1.18.26.jar deleted file mode 100644 index d7d7d69..0000000 Binary files a/config/coc/java/lombok-1.18.26.jar and /dev/null differ diff --git a/config/colortrans.py b/config/colortrans.py deleted file mode 100755 index 329c668..0000000 --- a/config/colortrans.py +++ /dev/null @@ -1,376 +0,0 @@ -#! /usr/bin/env python3 - -""" Convert values between RGB hex codes and xterm-256 color codes. - -Nice long listing of all 256 colors and their codes. Useful for -developing console color themes, or even script output schemes. - -Resources: -* http://en.wikipedia.org/wiki/8-bit_color -* http://en.wikipedia.org/wiki/ANSI_escape_code -* /usr/share/X11/rgb.txt - -I'm not sure where this script was inspired from. I think I must have -written it from scratch, though it's been several years now. -""" - -__author__ = 'Micah Elliott http://MicahElliott.com' -__version__ = '0.1' -__copyright__ = 'Copyright (C) 2011 Micah Elliott. All rights reserved.' -__license__ = 'WTFPL http://sam.zoy.org/wtfpl/' - -#--------------------------------------------------------------------- - -import sys, re - -CLUT = [ # color look-up table -# 8-bit, RGB hex - - # Primary 3-bit (8 colors). Unique representation! - ('00', '000000'), - ('01', '800000'), - ('02', '008000'), - ('03', '808000'), - ('04', '000080'), - ('05', '800080'), - ('06', '008080'), - ('07', 'c0c0c0'), - - # Equivalent "bright" versions of original 8 colors. - ('08', '808080'), - ('09', 'ff0000'), - ('10', '00ff00'), - ('11', 'ffff00'), - ('12', '0000ff'), - ('13', 'ff00ff'), - ('14', '00ffff'), - ('15', 'ffffff'), - - # Strictly ascending. - ('16', '000000'), - ('17', '00005f'), - ('18', '000087'), - ('19', '0000af'), - ('20', '0000d7'), - ('21', '0000ff'), - ('22', '005f00'), - ('23', '005f5f'), - ('24', '005f87'), - ('25', '005faf'), - ('26', '005fd7'), - ('27', '005fff'), - ('28', '008700'), - ('29', '00875f'), - ('30', '008787'), - ('31', '0087af'), - ('32', '0087d7'), - ('33', '0087ff'), - ('34', '00af00'), - ('35', '00af5f'), - ('36', '00af87'), - ('37', '00afaf'), - ('38', '00afd7'), - ('39', '00afff'), - ('40', '00d700'), - ('41', '00d75f'), - ('42', '00d787'), - ('43', '00d7af'), - ('44', '00d7d7'), - ('45', '00d7ff'), - ('46', '00ff00'), - ('47', '00ff5f'), - ('48', '00ff87'), - ('49', '00ffaf'), - ('50', '00ffd7'), - ('51', '00ffff'), - ('52', '5f0000'), - ('53', '5f005f'), - ('54', '5f0087'), - ('55', '5f00af'), - ('56', '5f00d7'), - ('57', '5f00ff'), - ('58', '5f5f00'), - ('59', '5f5f5f'), - ('60', '5f5f87'), - ('61', '5f5faf'), - ('62', '5f5fd7'), - ('63', '5f5fff'), - ('64', '5f8700'), - ('65', '5f875f'), - ('66', '5f8787'), - ('67', '5f87af'), - ('68', '5f87d7'), - ('69', '5f87ff'), - ('70', '5faf00'), - ('71', '5faf5f'), - ('72', '5faf87'), - ('73', '5fafaf'), - ('74', '5fafd7'), - ('75', '5fafff'), - ('76', '5fd700'), - ('77', '5fd75f'), - ('78', '5fd787'), - ('79', '5fd7af'), - ('80', '5fd7d7'), - ('81', '5fd7ff'), - ('82', '5fff00'), - ('83', '5fff5f'), - ('84', '5fff87'), - ('85', '5fffaf'), - ('86', '5fffd7'), - ('87', '5fffff'), - ('88', '870000'), - ('89', '87005f'), - ('90', '870087'), - ('91', '8700af'), - ('92', '8700d7'), - ('93', '8700ff'), - ('94', '875f00'), - ('95', '875f5f'), - ('96', '875f87'), - ('97', '875faf'), - ('98', '875fd7'), - ('99', '875fff'), - ('100', '878700'), - ('101', '87875f'), - ('102', '878787'), - ('103', '8787af'), - ('104', '8787d7'), - ('105', '8787ff'), - ('106', '87af00'), - ('107', '87af5f'), - ('108', '87af87'), - ('109', '87afaf'), - ('110', '87afd7'), - ('111', '87afff'), - ('112', '87d700'), - ('113', '87d75f'), - ('114', '87d787'), - ('115', '87d7af'), - ('116', '87d7d7'), - ('117', '87d7ff'), - ('118', '87ff00'), - ('119', '87ff5f'), - ('120', '87ff87'), - ('121', '87ffaf'), - ('122', '87ffd7'), - ('123', '87ffff'), - ('124', 'af0000'), - ('125', 'af005f'), - ('126', 'af0087'), - ('127', 'af00af'), - ('128', 'af00d7'), - ('129', 'af00ff'), - ('130', 'af5f00'), - ('131', 'af5f5f'), - ('132', 'af5f87'), - ('133', 'af5faf'), - ('134', 'af5fd7'), - ('135', 'af5fff'), - ('136', 'af8700'), - ('137', 'af875f'), - ('138', 'af8787'), - ('139', 'af87af'), - ('140', 'af87d7'), - ('141', 'af87ff'), - ('142', 'afaf00'), - ('143', 'afaf5f'), - ('144', 'afaf87'), - ('145', 'afafaf'), - ('146', 'afafd7'), - ('147', 'afafff'), - ('148', 'afd700'), - ('149', 'afd75f'), - ('150', 'afd787'), - ('151', 'afd7af'), - ('152', 'afd7d7'), - ('153', 'afd7ff'), - ('154', 'afff00'), - ('155', 'afff5f'), - ('156', 'afff87'), - ('157', 'afffaf'), - ('158', 'afffd7'), - ('159', 'afffff'), - ('160', 'd70000'), - ('161', 'd7005f'), - ('162', 'd70087'), - ('163', 'd700af'), - ('164', 'd700d7'), - ('165', 'd700ff'), - ('166', 'd75f00'), - ('167', 'd75f5f'), - ('168', 'd75f87'), - ('169', 'd75faf'), - ('170', 'd75fd7'), - ('171', 'd75fff'), - ('172', 'd78700'), - ('173', 'd7875f'), - ('174', 'd78787'), - ('175', 'd787af'), - ('176', 'd787d7'), - ('177', 'd787ff'), - ('178', 'd7af00'), - ('179', 'd7af5f'), - ('180', 'd7af87'), - ('181', 'd7afaf'), - ('182', 'd7afd7'), - ('183', 'd7afff'), - ('184', 'd7d700'), - ('185', 'd7d75f'), - ('186', 'd7d787'), - ('187', 'd7d7af'), - ('188', 'd7d7d7'), - ('189', 'd7d7ff'), - ('190', 'd7ff00'), - ('191', 'd7ff5f'), - ('192', 'd7ff87'), - ('193', 'd7ffaf'), - ('194', 'd7ffd7'), - ('195', 'd7ffff'), - ('196', 'ff0000'), - ('197', 'ff005f'), - ('198', 'ff0087'), - ('199', 'ff00af'), - ('200', 'ff00d7'), - ('201', 'ff00ff'), - ('202', 'ff5f00'), - ('203', 'ff5f5f'), - ('204', 'ff5f87'), - ('205', 'ff5faf'), - ('206', 'ff5fd7'), - ('207', 'ff5fff'), - ('208', 'ff8700'), - ('209', 'ff875f'), - ('210', 'ff8787'), - ('211', 'ff87af'), - ('212', 'ff87d7'), - ('213', 'ff87ff'), - ('214', 'ffaf00'), - ('215', 'ffaf5f'), - ('216', 'ffaf87'), - ('217', 'ffafaf'), - ('218', 'ffafd7'), - ('219', 'ffafff'), - ('220', 'ffd700'), - ('221', 'ffd75f'), - ('222', 'ffd787'), - ('223', 'ffd7af'), - ('224', 'ffd7d7'), - ('225', 'ffd7ff'), - ('226', 'ffff00'), - ('227', 'ffff5f'), - ('228', 'ffff87'), - ('229', 'ffffaf'), - ('230', 'ffffd7'), - ('231', 'ffffff'), - - # Gray-scale range. - ('232', '080808'), - ('233', '121212'), - ('234', '1c1c1c'), - ('235', '262626'), - ('236', '303030'), - ('237', '3a3a3a'), - ('238', '444444'), - ('239', '4e4e4e'), - ('240', '585858'), - ('241', '626262'), - ('242', '6c6c6c'), - ('243', '767676'), - ('244', '808080'), - ('245', '8a8a8a'), - ('246', '949494'), - ('247', '9e9e9e'), - ('248', 'a8a8a8'), - ('249', 'b2b2b2'), - ('250', 'bcbcbc'), - ('251', 'c6c6c6'), - ('252', 'd0d0d0'), - ('253', 'dadada'), - ('254', 'e4e4e4'), - ('255', 'eeeeee'), -] - -def _str2hex(hexstr): - return int(hexstr, 16) - -def _strip_hash(rgb): - # Strip leading `#` if exists. - if rgb.startswith('#'): - rgb = rgb.lstrip('#') - return rgb - -def _create_dicts(): - short2rgb_dict = dict(CLUT) - rgb2short_dict = {} - for k, v in short2rgb_dict.items(): - rgb2short_dict[v] = k - return rgb2short_dict, short2rgb_dict - -def short2rgb(short): - return SHORT2RGB_DICT[short] - -def print_all(): - """ Print all 256 xterm color codes. - """ - for short, rgb in CLUT: - sys.stdout.write('\033[48;5;%sm%s:%s' % (short, short, rgb)) - sys.stdout.write("\033[0m ") - sys.stdout.write('\033[38;5;%sm%s:%s' % (short, short, rgb)) - sys.stdout.write("\033[0m\n") - print("Printed all codes.") - print("You can translate a hex or 0-255 code by providing an argument.") - -def rgb2short(rgb): - """ Find the closest xterm-256 approximation to the given RGB value. - @param rgb: Hex code representing an RGB value, eg, 'abcdef' - @returns: String between 0 and 255, compatible with xterm. - >>> rgb2short('123456') - ('23', '005f5f') - >>> rgb2short('ffffff') - ('231', 'ffffff') - >>> rgb2short('0DADD6') # vimeo logo - ('38', '00afd7') - """ - rgb = _strip_hash(rgb) - incs = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff) - # Break 6-char RGB code into 3 integer vals. - parts = [ int(h, 16) for h in re.split(r'(..)(..)(..)', rgb)[1:4] ] - res = [] - for part in parts: - i = 0 - while i < len(incs)-1: - s, b = incs[i], incs[i+1] # smaller, bigger - if s <= part <= b: - s1 = abs(s - part) - b1 = abs(b - part) - if s1 < b1: closest = s - else: closest = b - res.append(closest) - break - i += 1 - #print '***', res - res = ''.join([ ('%02.x' % i) for i in res ]) - equiv = RGB2SHORT_DICT[ res ] - #print '***', res, equiv - return equiv, res - -RGB2SHORT_DICT, SHORT2RGB_DICT = _create_dicts() - -#--------------------------------------------------------------------- - -if __name__ == '__main__': - import doctest - doctest.testmod() - if len(sys.argv) == 1: - print_all() - raise SystemExit - arg = sys.argv[1] - if len(arg) < 4 and int(arg) < 256: - rgb = short2rgb(arg) - sys.stdout.write('xterm color \033[38;5;%sm%s\033[0m -> RGB exact \033[38;5;%sm%s\033[0m' % (arg, arg, arg, rgb)) - sys.stdout.write("\033[0m\n") - else: - short, rgb = rgb2short(arg) - sys.stdout.write('RGB %s -> xterm color approx \033[38;5;%sm%s (%s)' % (arg, short, short, rgb)) - sys.stdout.write("\033[0m\n") diff --git a/config/fish/config.fish b/config/fish/config.fish deleted file mode 100644 index 41e52e9..0000000 --- a/config/fish/config.fish +++ /dev/null @@ -1,7 +0,0 @@ -set __fish_git_prompt_show_informative_status 1 -function fish_prompt -d "Write out the prompt" - # This shows up as USER@HOST /home/user/ >, with the directory colored - # $USER and $hostname are set by fish, so you can just use them - # instead of using `whoami` and `hostname` - printf ' %s%s%s%s$ ' (set_color $fish_color_cwd) (prompt_pwd) (set_color normal) (fish_git_prompt) -end diff --git a/config/glazewm/config.yaml b/config/glazewm/config.yaml deleted file mode 100644 index bcb92c7..0000000 --- a/config/glazewm/config.yaml +++ /dev/null @@ -1,164 +0,0 @@ -gaps: - inner_gap: 5 - outer_gap: 5 - -bar: - height: 20 - position: "top" - opacity: 0.6 - # background: "#101010" - background: "#282c34" - # foreground: "white" - foreground: "#ffffff" - # font_family: "Segoe UI" - font_family: "Hack Nerd Mono" - font_size: "13" - padding: "1 6 1 6" - components_left: - - type: "workspaces" - opacity: 0.7 - components_right: - - type: "clock" - time_formatting: "hh:mm tt ddd MMM d" - -workspaces: - - name: 1 - - name: 2 - - name: 3 - - name: 4 - - name: 5 - - name: 6 - - name: 7 - - name: 8 - - name: 9 - -window_rules: - # Task Manager requires admin privileges to manage and should be ignored unless running - # the WM as admin. - - command: "ignore" - match_process_name: "Taskmgr" - match_process_name: "msrdc" - - # Launches system dialogs as floating by default (eg. File Explorer save/open dialog). - - command: "set floating" - match_class_name: "#32770" - - # Some applications (eg. Steam) have borders that extend past the normal border size. - - command: "resize borders 0px -7px -7px -7px" - match_process_name: "steam" - - - command: "set tiling" - match_process_name: "neovide" - -keybindings: - # Shift focus in a given direction. - - command: "focus left" - bindings: ["Alt+H", "Alt+Left"] - - command: "focus right" - bindings: ["Alt+L", "Alt+Right"] - - command: "focus up" - bindings: ["Alt+K", "Alt+Up"] - - command: "focus down" - bindings: ["Alt+J", "Alt+Down"] - - # Move focused window in a given direction. - - command: "move left" - bindings: ["Alt+Shift+H", "Alt+Shift+Left"] - - command: "move right" - bindings: ["Alt+Shift+L", "Alt+Shift+Right"] - - command: "move up" - bindings: ["Alt+Shift+K", "Alt+Shift+Up"] - - command: "move down" - bindings: ["Alt+Shift+J", "Alt+Shift+Down"] - - # Resize focused window by a percentage or pixel amount. - - command: "resize width -2%" - binding: "Alt+U" - - command: "resize width +2%" - binding: "Alt+P" - - command: "resize height +2%" - binding: "Alt+O" - - command: "resize height -2%" - binding: "Alt+I" - - # Change layout direction to be either horizontal or vertical. - - command: "layout horizontal" - binding: "Alt+Shift+V" - - command: "layout vertical" - binding: "Alt+V" - - # Change focus between floating / tiling windows. - - command: "toggle focus mode" - binding: "Alt+Space" - - # Change the focused window to be floating / tiling. - - command: "toggle floating" - binding: "Alt+Shift+Space" - - # Change the focused window to be maximized / unmaximized. - - command: "toggle maximized" - binding: "Alt+F" - - # Minimize focused window. - - command: "set minimized" - binding: "Alt+M" - - # Close focused window. - - command: "close" - binding: "Alt+Shift+Q" - - # Kill GlazeWM process safely. - - command: "exit wm" - binding: "Alt+Shift+E" - - # Re-evaluate configuration file. - - command: "reload config" - binding: "Alt+Shift+R" - - # Launch CMD terminal (alternatively `exec wt` or `exec %ProgramFiles%/Git/git-bash.exe` - # to start Windows Terminal and Git Bash respectively. - - command: "exec wt" - binding: "Alt+Enter" - - - command: "exec chrome" - binding: "Alt+F2" - - # Change focus to a workspace defined in `workspaces` config. - - command: "focus workspace 1" - binding: "Alt+1" - - command: "focus workspace 2" - binding: "Alt+2" - - command: "focus workspace 3" - binding: "Alt+3" - - command: "focus workspace 4" - binding: "Alt+4" - - command: "focus workspace 5" - binding: "Alt+5" - - command: "focus workspace 6" - binding: "Alt+6" - - command: "focus workspace 7" - binding: "Alt+7" - - command: "focus workspace 8" - binding: "Alt+8" - - command: "focus workspace 9" - binding: "Alt+9" - - # Move focused window to a workspace defined in `workspaces` config. - - commands: ["move to workspace 1", "focus workspace 1"] - binding: "Alt+Shift+1" - - commands: ["move to workspace 2", "focus workspace 2"] - binding: "Alt+Shift+2" - - commands: ["move to workspace 3", "focus workspace 3"] - binding: "Alt+Shift+3" - - commands: ["move to workspace 4", "focus workspace 4"] - binding: "Alt+Shift+4" - - commands: ["move to workspace 5", "focus workspace 5"] - binding: "Alt+Shift+5" - - commands: ["move to workspace 6", "focus workspace 6"] - binding: "Alt+Shift+6" - - commands: ["move to workspace 7", "focus workspace 7"] - binding: "Alt+Shift+7" - - commands: ["move to workspace 8", "focus workspace 8"] - binding: "Alt+Shift+8" - - commands: ["move to workspace 9", "focus workspace 9"] - bindings: ["Alt+Shift+9"] diff --git a/config/setuplib/README.md b/config/setuplib/README.md deleted file mode 100644 index 15b4615..0000000 --- a/config/setuplib/README.md +++ /dev/null @@ -1,4 +0,0 @@ - -# SETUPLIB - -a python library for writing cross-platform env setup script diff --git a/config/setuplib/setup.py b/config/setuplib/setup.py deleted file mode 100644 index e69de29..0000000 diff --git a/config/setuplib/setuplib/__init__.py b/config/setuplib/setuplib/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/config/setuplib/setuplib/utils.py b/config/setuplib/setuplib/utils.py deleted file mode 100644 index 0182738..0000000 --- a/config/setuplib/setuplib/utils.py +++ /dev/null @@ -1,26 +0,0 @@ -import sys -import os - -class setup(): - def __init__(self): - pass - - def _has_path(self, path): - """ - Check if path exists(is file or directory) - """ - return os.path.exists(path) - - def _is_file(self, path): - """ - Check if path is file - """ - return os.path.isfile(path) - - def _is_dir(self, path): - """ - Check if path is directory - """ - return os.path.isdir(path) - - diff --git a/config/user/git_config.sh b/config/user/git_config.sh deleted file mode 100755 index 747df33..0000000 --- a/config/user/git_config.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -git config --global user.name "Nachuan Tang" -git config --global user.email "tangnachuan1208@gmail.com" diff --git a/config/vim/.gitignore b/config/vim/.gitignore deleted file mode 100644 index 1854e41..0000000 --- a/config/vim/.gitignore +++ /dev/null @@ -1 +0,0 @@ -theme_config.vim diff --git a/config/vim/autoload/airline/themes/sunbather_dark.vim b/config/vim/autoload/airline/themes/sunbather_dark.vim deleted file mode 100644 index a7eb55e..0000000 --- a/config/vim/autoload/airline/themes/sunbather_dark.vim +++ /dev/null @@ -1,85 +0,0 @@ -" Base16 Classic Dark vim-airline-theme (https://github.com/dawikur/base16-vim-airline-themes) -" For vim-airline (https://github.com/vim-airline/vim-airline) -" By Jason Heeris (http://heeris.id.au) - -let s:scheme_slug = 'sunbather_dark' - -let g:airline#themes#{s:scheme_slug}#palette = {} - -" GUI color definitions -let s:gui00 = '#151515' -let s:gui01 = '#202020' -let s:gui02 = '#303030' -let s:gui03 = '#505050' -let s:gui04 = '#B0B0B0' -let s:gui05 = '#D0D0D0' -let s:gui06 = '#E0E0E0' -let s:gui07 = '#F5F5F5' -let s:gui08 = '#AC4142' -let s:gui09 = '#D28445' -let s:gui0A = '#F4BF75' -let s:gui0B = '#90A959' -let s:gui0C = '#75B5AA' -let s:gui0D = '#6A9FB5' -let s:gui0E = '#AA759F' -let s:gui0F = '#8F5536' - -" Terminal color definitions -let s:cterm00 = "00" -let s:cterm03 = "08" -let s:cterm05 = "07" -let s:cterm07 = "15" -let s:cterm08 = "01" -let s:cterm0A = "03" -let s:cterm0B = "02" -let s:cterm0C = "06" -let s:cterm0D = "04" -let s:cterm0E = "05" -if exists("base16colorspace") && base16colorspace == "256" - let s:cterm01 = "18" - let s:cterm02 = "19" - let s:cterm04 = "20" - let s:cterm06 = "21" - let s:cterm09 = "16" - let s:cterm0F = "17" -else - let s:cterm01 = "10" - let s:cterm02 = "11" - let s:cterm04 = "12" - let s:cterm06 = "13" - let s:cterm09 = "09" - let s:cterm0F = "14" -endif - -let g:airline#themes#{s:scheme_slug}#palette.normal = airline#themes#generate_color_map( - \ [ s:gui01, s:gui04, s:cterm01, s:cterm04 ], - \ [ s:gui04, s:gui02, s:cterm04, s:cterm02 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ]) -let g:airline#themes#{s:scheme_slug}#palette.normal_modified = { - \ 'airline_c' : [ s:gui07, s:gui01, s:cterm07, s:cterm01 ]} - -let g:airline#themes#{s:scheme_slug}#palette.insert = airline#themes#generate_color_map( - \ [ s:gui01, s:gui0B, s:cterm01, s:cterm0B ], - \ [ s:gui04, s:gui02, s:cterm04, s:cterm02 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ]) -let g:airline#themes#{s:scheme_slug}#palette.insert_modified = { - \ 'airline_c' : [ s:gui07, s:gui01, s:cterm07, s:cterm01 ]} - -let g:airline#themes#{s:scheme_slug}#palette.replace = airline#themes#generate_color_map( - \ [ s:gui01, s:gui0E, s:cterm01, s:cterm0E ], - \ [ s:gui04, s:gui02, s:cterm04, s:cterm02 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ]) -let g:airline#themes#{s:scheme_slug}#palette.replace_modified = { - \ 'airline_c' : [ s:gui07, s:gui01, s:cterm07, s:cterm01 ]} - -let g:airline#themes#{s:scheme_slug}#palette.visual = airline#themes#generate_color_map( - \ [ s:gui01, s:gui09, s:cterm01, s:cterm09 ], - \ [ s:gui04, s:gui02, s:cterm04, s:cterm02 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ]) -let g:airline#themes#{s:scheme_slug}#palette.visual_modified = { - \ 'airline_c' : [ s:gui07, s:gui01, s:cterm07, s:cterm01 ]} - -let g:airline#themes#{s:scheme_slug}#palette.inactive = airline#themes#generate_color_map( - \ [ s:gui01, s:gui01, s:cterm01, s:cterm01 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ], - \ [ s:gui05, s:gui01, s:cterm05, s:cterm01 ]) diff --git a/config/vim/autoload/airline/themes/sunbather_light.vim b/config/vim/autoload/airline/themes/sunbather_light.vim deleted file mode 100644 index 9a93401..0000000 --- a/config/vim/autoload/airline/themes/sunbather_light.vim +++ /dev/null @@ -1,85 +0,0 @@ -" Base16 Summerfruit Light vim-airline-theme (https://github.com/dawikur/base16-vim-airline-themes) -" For vim-airline (https://github.com/vim-airline/vim-airline) -" By Christopher Corley (http://christop.club/) - -let s:scheme_slug = 'sunbather_light' - -let g:airline#themes#{s:scheme_slug}#palette = {} - -" GUI color definitions -let s:gui00 = '#FFFFFF' -let s:gui01 = '#E0E0E0' -let s:gui02 = '#D0D0D0' -let s:gui03 = '#B0B0B0' -let s:gui04 = '#000000' -let s:gui05 = '#101010' -let s:gui06 = '#151515' -let s:gui07 = '#202020' -let s:gui08 = '#FF0086' -let s:gui09 = '#FD8900' -let s:gui0A = '#ABA800' -let s:gui0B = '#00C918' -let s:gui0C = '#1FAAAA' -let s:gui0D = '#3777E6' -let s:gui0E = '#AD00A1' -let s:gui0F = '#CC6633' - -" Terminal color definitions -let s:cterm00 = "00" -let s:cterm03 = "08" -let s:cterm05 = "07" -let s:cterm07 = "15" -let s:cterm08 = "01" -let s:cterm0A = "03" -let s:cterm0B = "02" -let s:cterm0C = "06" -let s:cterm0D = "04" -let s:cterm0E = "05" -if exists("base16colorspace") && base16colorspace == "256" - let s:cterm01 = "18" - let s:cterm02 = "19" - let s:cterm04 = "20" - let s:cterm06 = "21" - let s:cterm09 = "16" - let s:cterm0F = "17" -else - let s:cterm01 = "10" - let s:cterm02 = "11" - let s:cterm04 = "12" - let s:cterm06 = "13" - let s:cterm09 = "09" - let s:cterm0F = "14" -endif - -let g:airline#themes#{s:scheme_slug}#palette.normal = airline#themes#generate_color_map( - \ [ s:gui01, s:gui04, s:cterm01, s:cterm04 ], - \ [ s:gui04, s:gui02, s:cterm04, s:cterm02 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ]) -let g:airline#themes#{s:scheme_slug}#palette.normal_modified = { - \ 'airline_c' : [ s:gui07, s:gui01, s:cterm07, s:cterm01 ]} - -let g:airline#themes#{s:scheme_slug}#palette.insert = airline#themes#generate_color_map( - \ [ s:gui01, s:gui0B, s:cterm01, s:cterm0B ], - \ [ s:gui04, s:gui02, s:cterm04, s:cterm02 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ]) -let g:airline#themes#{s:scheme_slug}#palette.insert_modified = { - \ 'airline_c' : [ s:gui07, s:gui01, s:cterm07, s:cterm01 ]} - -let g:airline#themes#{s:scheme_slug}#palette.replace = airline#themes#generate_color_map( - \ [ s:gui01, s:gui0E, s:cterm01, s:cterm0E ], - \ [ s:gui04, s:gui02, s:cterm04, s:cterm02 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ]) -let g:airline#themes#{s:scheme_slug}#palette.replace_modified = { - \ 'airline_c' : [ s:gui07, s:gui01, s:cterm07, s:cterm01 ]} - -let g:airline#themes#{s:scheme_slug}#palette.visual = airline#themes#generate_color_map( - \ [ s:gui01, s:gui09, s:cterm01, s:cterm09 ], - \ [ s:gui04, s:gui02, s:cterm04, s:cterm02 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ]) -let g:airline#themes#{s:scheme_slug}#palette.visual_modified = { - \ 'airline_c' : [ s:gui07, s:gui01, s:cterm07, s:cterm01 ]} - -let g:airline#themes#{s:scheme_slug}#palette.inactive = airline#themes#generate_color_map( - \ [ s:gui01, s:gui01, s:cterm01, s:cterm01 ], - \ [ s:gui04, s:gui01, s:cterm04, s:cterm01 ], - \ [ s:gui05, s:gui01, s:cterm05, s:cterm01 ]) diff --git a/config/vim/autoload/clipboard.vim b/config/vim/autoload/clipboard.vim deleted file mode 100644 index 3d60173..0000000 --- a/config/vim/autoload/clipboard.vim +++ /dev/null @@ -1,27 +0,0 @@ -" vim build with clipboard support doesn't need this and it work -" better than neovim - -func s:helper() - call system('printf "%s" '.shellescape(join(v:event['regcontents'], "\n")).' | xclip -sel clip' ) -endfunc - -func! clipboard#get() -endfunc - -func! clipboard#enable() - augroup WSLClipboard - au! - au TextYankPost * call s:helper() - augroup END -endfunc - -func! clipboard#disable() - augroup WSLClipboard - au! - augroup END -endfunc - -func! clipboard#paste() - return system('xclip -o -sel clip' ) -endfunc - diff --git a/config/vim/autoload/config.vim b/config/vim/autoload/config.vim deleted file mode 100644 index 73b38ea..0000000 --- a/config/vim/autoload/config.vim +++ /dev/null @@ -1,45 +0,0 @@ -let s:path = get(g:, '_config_path', fnamemodify( - \ resolve(expand(':p')), ':h:h').'/_config.vim') -let s:config = {} - -function! config#saveConfig() - let p = utils#readvar(s:path) - if type(p) != type({}) - let p = {} - endif - let vim_type = has('nvim') ? 'nvim' : 'vim' - let config = has_key(p, vim_type) && type(p[vim_type]) == v:t_dict - \ ? p[vim_type] : {} - let config = utils#merge(config, s:config) - - " vim and nvim may have diferenrt available plugins - let p[vim_type] = config - call utils#savevar(p, s:path) -endfunction - -function! s:loadConfig() - let result = utils#readvar(s:path) - " if it is dictionary - let vim_type = has('nvim') ? 'nvim' : 'vim' - if type(result) == v:t_dict - if has_key(result, vim_type) - let config = result[vim_type] - if type(config) == v:t_dict - let s:config = config - return - endif - endif - endif -endfunction - -function! config#setConfig(dict) - let s:config = utils#merge(s:config, a:config) -endfunction - -function! config#init() - call config#loadConfig() - augroup config - autocmd! - autocmd VimLeave * call config#saveConfig() - augroup END -endfunction diff --git a/config/vim/autoload/options.vim b/config/vim/autoload/options.vim deleted file mode 100644 index d814601..0000000 --- a/config/vim/autoload/options.vim +++ /dev/null @@ -1,171 +0,0 @@ - -" this intent to create a list of options that can be toggled on/off - -let s:options = {} - -if !has('nvim') - import autoload 'fuzzyy/utils/selector.vim' -endif - -" opt is a dictionary with the following keys(* = required): -" togglefunc and enablefunc/disablefunc are mutually exclusive -" params: -" - name: name of the option -" - opt: a dictionary with following options(): -" - desc: description, -" - togglefunc: function reference, if exists, enablefunc and disablefunc -" will be ignored, -" - enablefunc: function reference, if this exists, disablefunc must exists -" as well and vice verse -" - disablefunc: function reference, -" - isEnabled: string, true or false or function reference. only needed when -" using enablefunc and disablefunc -function! options#add(name, opt) abort - if (!has_key(a:opt, 'togglefunc') - \ && (!has_key(a:opt, 'enablefunc') || !has_key(a:opt, 'disablefunc'))) - throw 'invalid option (togglefunc or enablefunc/disablefunc must be set))' - endif - - if !has_key(a:opt, 'isEnabled') && !has_key(a:opt, 'togglefunc') - throw 'specify initial state(isEnabled) or set togglefunc' - endif - - for key in ['togglefunc', 'enablefunc', 'disablefunc'] - if has_key(a:opt, key) && type(a:opt[key]) != v:t_func - throw key . ' must be a function reference' - endif - endfor - - if !has_key(a:opt, 'desc') - let a:opt['desc'] = '' - endif - - let s:options[a:name] = a:opt -endfunction - -" Register a simple vim option -" params: -" - name: name of the option -" - dictionary(optional): -" - desc: description of the option -function! options#addVimOption(name, ...) abort - let opt = {} - - func opt.togglefunc(key) - if eval('&' . a:key) - execute('set no' . a:key) - else - execute('set ' . a:key) - endif - endfunc - - if a:0 > 0 - let opt['desc'] = a:1 - endif - - call options#add(a:name, opt) -endfunction - -function! options#getAll() abort - let list = [] - for [key, val] in items(s:options) - let desc = val.desc != '' ? ' - ' . val.desc : '' - call add(list, [key, key . desc]) - endfor - return list -endfunction - -function! options#getAllRaw() abort - let list = [] - for [key, val] in items(s:options) - call add(list, [key, desc]) - endfor - return list -endfunction - -function! options#toggle(name) abort - if !has_key(s:options, a:name) - throw 'invalid option name: ' . a:name - endif - - let opt = s:options[a:name] - if has_key(opt, 'togglefunc') - call opt.togglefunc(a:name) - else - if type(opt.isEnabled) == v:t_func - let isEnabled = opt.isEnabled() - else - let isEnabled = opt.isEnabled - endif - if isEnabled - call opt.disablefunc() - else - call opt.enablefunc() - endif - if type(opt.isEnabled) != v:t_func - let s:options[a:name].isEnabled = opt.isEnabled ? v:false : v:true - endif - endif -endfunction - -function! options#preSet() - call options#addVimOption('number', 'show line number') - call options#addVimOption('relativenumber') - - let colorcolumnOpt = { - \ 'desc': 'show color column', - \ 'isEnabled': &colorcolumn != '' - \ } - function colorcolumnOpt.togglefunc(...) - if &colorcolumn == '' - let &colorcolumn = '80' - else - let &colorcolumn = '' - endif - endfunction - - call options#add('colorcolumn', colorcolumnOpt) - - let toggleBgOpt = { - \ 'desc': 'toggle dark/light theme', - \ } - function toggleBgOpt.togglefunc(...) - call theme#toggleBg() - endfunction - call options#add('dark/light', toggleBgOpt) -endfunction - -function! s:select(wid, result) - let result = a:result[0] - if result != v:null - let key = s:rmap[result] - call options#toggle(key) - endif -endfunction - -function! options#fzf_options() - let list = [] - let s:rmap = {} - for [key, val] in items(s:options) - let desc = val.desc != '' ? key . ' - ' . val.desc : key - call add(list, desc) - let s:rmap[desc] = key - endfor - let s:fzf_list = list - call selector.Start( list, - \ { - \ 'select_cb' : function('s:select'), - \ 'yoffset' : 0.3, - \ 'height' : 0.4, - \ 'title' : 'Options', - \ 'width' : 0.4 - \ }) -endfunc - -function! options#init() - call options#preSet() - if !has('nvim') - command! -nargs=0 Options call options#fzf_options() - nnoremap fo :Options - endif -endfunction diff --git a/config/vim/autoload/os.vim b/config/vim/autoload/os.vim deleted file mode 100644 index 06fcc89..0000000 --- a/config/vim/autoload/os.vim +++ /dev/null @@ -1,8 +0,0 @@ -func! os#getOS() - if has("win64") || has("win32") || has("win16") - return "Windows" - else - return substitute(system('uname'), '\n', '', '') - endif -endfunc - diff --git a/config/vim/autoload/theme.vim b/config/vim/autoload/theme.vim index e0df6d6..de36934 100644 --- a/config/vim/autoload/theme.vim +++ b/config/vim/autoload/theme.vim @@ -1,383 +1,120 @@ -let s:path = get(g:, 'theme_config_path', fnamemodify( - \ resolve(expand(':p')), ':h:h').'/theme_config.vim') +let s:path = get(g:, 'vim_dir', expand('~/.vim')) . '/theme.json' +let s:defaults = { + \ 'background': 'dark', + \ 'dark': {'theme': 'moonfly', 'transparent': v:false}, + \ 'light': {'theme': 'PaperColor', 'transparent': v:false}} +let s:config = deepcopy(s:defaults) +let s:applying = v:false +let s:transparent_groups = [ + \ 'Normal', 'NormalNC', 'EndOfBuffer', 'Folded', 'LineNr', 'SignColumn', + \ 'StatusLine', 'StatusLineNC', 'VertSplit', 'WinSeparator', 'NormalFloat'] -let s:themefixes = [] - -let s:bgType = has('termguicolors') ? 'guibg' : 'ctermbg' - -" sometimes even in termguicolors, when guibg is not set, the bg will fall -" back to use ctermbg, so we have to set them both to none -let s:bgNonType = !has('termguicolors') ? 'guibg=NONE' : 'ctermbg=NONE' -let s:transBlendOpt = has('nvim') ? ' blend=0' : '' - -let s:default_config = { - \ 'background': 'dark', - \ 'light': { - \ 'theme': 'sunbather_light', - \ 'default': 'sunbather_light', - \ 'transparent': v:false, - \ 'airline_theme': 'sunbather_light', - \ }, - \ 'dark': { - \ 'theme': 'base16-harmonic-dark', - \ 'default': 'base16-harmonic-dark', - \ 'transparent': v:false, - \ 'airline_theme': 'base16-harmonic-dark', - \ }, -\ } - -" When enable transparent background, these group will be set to transparent -let s:transgroups = [ - \ 'Normal', 'NormalNC', 'Comment', 'Constant', 'Special', 'Identifier', - \ 'Folded', 'Statusline', 'StatuslineNC', - \ 'Statement', 'PreProc', 'Type', 'Underlined', 'String', 'Function', - \ 'Conditional', 'Repeat', 'Operator', 'Structure', 'LineNr', 'NonText', - \ 'SignColumn', 'CursorLineNr', 'EndOfBuffer', 'VertSplit', - \ 'DiagnosticSignWarn', 'DiagnosticSignError', 'DiagnosticSignInfo',] - -" background group that will be set to normal's background color -let s:cleanbg = ['DiagnosticSignWarn', 'DiagnosticSignError', 'DiagnosticSignInfo', - \ 'VertSplit', 'LineNr', 'SignColumn', 'NormalFloat'] - -let s:config = get(g:, 'theme_config', s:default_config) - -function! theme#setConfig(bg, key, value) - let s:config[a:bg][a:key] = a:value -endfunction -" register extra transparent hi group -function! theme#getCleanBg() - return s:cleanbg -endfunction - -function! theme#getBgType() - return s:bgType -endfunction - -function! theme#getTransGroup() - return s:transgroups -endfunction - -" register extra transparent hi group -function theme#addCleanBg(group) - let li = type(a:group) == 1 ? [a:group] : a:group - for hi in li - if index(s:cleanbg, hi) == -1 - call add(s:cleanbg, hi) - endif - endfor -endfunction - -" register extra transparent hi group -function theme#addTransGroup(group) - let li = type(a:group) == 1 ? [a:group] : a:group - for hi in li - if index(s:transgroups, hi) == -1 - call add(s:transgroups, hi) - endif - endfor -endfunction - -function! theme#setColor(bg, ...) - let colors_name = a:0 > 0 ? a:1 : s:config[a:bg].theme - if !utils#hascolorscheme(colors_name) - let colors_name = 'default' - endif - noa let &bg = a:bg - call theme#setStlColor(a:bg) - let s:config.background = a:bg - let s:config[a:bg].theme = colors_name - noa execute("colorscheme " . colors_name) - if &background != a:bg - noa let &bg = a:bg - endif - " some theme will pick their own airline theme or airline will - " automatically pick theme based on colorscheme - if exists('g:airline_theme') && g:airline_theme != s:config[a:bg].airline_theme - call theme#setStlColor(a:bg, g:airline_theme) - endif -endfunction - -" Change bottom airline/lualine theme -function! theme#setStlColor(bg, ...) - if has('nvim-0.5') - " lualine will change theme automatically +function! s:Merge(defaults, override) abort + let l:result = deepcopy(a:defaults) + if type(a:override) != v:t_dict + return l:result + endif + for [l:key, l:value] in items(a:override) + if type(l:value) == v:t_dict && type(get(l:result, l:key)) == v:t_dict + let l:result[l:key] = s:Merge(l:result[l:key], l:value) else - if utils#hasplug('vim-airline') && exists(':AirlineTheme') - let theme = a:0 > 0 ? a:1 : s:config[a:bg].airline_theme - try - execute('AirlineTheme ' . theme) - catch - let theme = s:default_config[a:bg].airline_theme - execute('AirlineTheme ' . theme) - endtry - let s:config[a:bg].airline_theme = theme - endif + let l:result[l:key] = l:value endif + endfor + return l:result endfunction -function! theme#inTransparent() - return s:config[&background].transparent +function! s:Available(name) abort + return !empty(globpath(&runtimepath, 'colors/' . a:name . '.vim', 1, 1)) endfunction -" return 1 if link to other group -" return 2 if not exists -" return 0 if normal -function! s:hiType(group) - try - let hi = execute('hi '.a:group) - if hi =~# 'link' - return 2 - endif - catch - return 1 - endtry - return 0 +function! s:ApplyTransparency() abort + if !s:config[&background].transparent + return + endif + for l:group in s:transparent_groups + execute 'highlight ' . l:group . ' guibg=NONE ctermbg=NONE' + endfor endfunction -function s:applyTransparent() - let tail = ' ' . s:bgType . '=NONE term=NONE gui=NONE cterm=NONE ' - if has('nvim') - let tail .= s:transBlendOpt - else - let tail .= s:bgNonType - endif - for group in s:transgroups - if s:hiType(group) != 0 - continue - endif - " cterm and term sometimes are set to reverse so we need to clean them - " too - " for the last part, we can't clear all terms or it will fall back to - " default which is not transparent - execute('hi! '.group . tail) - endfor - call s:generalThemeFix() - " for group in s:cleanbg - " if s:hiType(group) != 0 - " continue - " endif - " execute('hi! '.group . tail) - " endfor +function! s:Load() abort + if !filereadable(s:path) + return deepcopy(s:defaults) + endif + try + let l:saved = json_decode(join(readfile(s:path), "\n")) + return s:Merge(s:defaults, l:saved) + catch + return deepcopy(s:defaults) + endtry endfunction -" some callback function to enable transparent background -" for specific colorscheme - -" or general callback for all colorscheme when specific colorscheme callback -" is not available -" g:dark_transparent_enable_cb -" g:light_transparent_enable_cb - -function! theme#enableTransparent() abort - let colorscheme_name = utils#colorschemename() - let bg = &background - if exists('g:'.bg.'_transparent_enable_cb') && g:dark_transparent_enable_cb != '' - let cb_name = get(g:, bg.'_transparent_enable_cb', '') - if cb_name != '' - execute('call '.cb_name.'()') - endif - elseif exists('g:Transparent_enable_func') - if type(g:Transparent_enable_func) != v:t_func - echoerr 'g:Transparent_enable_func is not a function' - endif - call g:Transparent_enable_func() - else - call s:applyTransparent() - augroup SetTransparent - autocmd! - autocmd ColorScheme * call s:applyTransparent() - augroup END - endif - let s:config[bg].transparent = v:true +function! theme#save() abort + try + call mkdir(fnamemodify(s:path, ':h'), 'p') + call writefile([json_encode(s:config)], s:path) + catch + " A read-only home directory should not prevent Vim from exiting cleanly. + endtry endfunction -function! theme#disableTransparent() abort - augroup SetTransparent - autocmd! - augroup END - let bg = &background - let s:config[bg].transparent = v:false - let colorscheme_name = utils#colorschemename() - if exists('g:'.bg.'_transparent_disable_cb') - let cb_name = get(g:, bg.'_transparent_disable_cb', '') - if cb_name != '' - execute('call '.cb_name.'()') - endif - elseif exists('g:Transparent_disable_func') - if type(g:Transparent_disable_func) != v:t_func - echoerr 'g:Transparent_disable_func is not a function' - endif - call g:Transparent_disable_func() - else - execute('colorscheme ' . s:config[bg].theme) - endif +function! theme#apply(name) abort + let l:background = &background + let l:name = s:Available(a:name) ? a:name + \ : (l:background ==# 'dark' ? 'sunbather_dark' : 'sunbather_light') + let s:applying = v:true + try + execute 'colorscheme ' . l:name + finally + let s:applying = v:false + endtry + let &background = l:background + let s:config.background = l:background + let s:config[l:background].theme = l:name + call s:ApplyTransparency() endfunction -" ToggleTransparent background -function! theme#toggleTransparent() - if s:config[&background].transparent - call theme#disableTransparent() - else - call theme#enableTransparent() - endif +function! theme#toggleBg() abort + let l:background = &background ==# 'dark' ? 'light' : 'dark' + let l:theme = s:config[l:background].theme + let s:applying = v:true + try + let &background = l:background + finally + let s:applying = v:false + endtry + let s:config.background = l:background + call theme#apply(l:theme) endfunction -" Allow to trigger background -function! theme#toggleBg() - " Inversion - let newbg = &background == "dark" ? 'light' : 'dark' - call theme#setColor(newbg) - if s:config[&background].transparent - call theme#enableTransparent() - elseif !s:config[&background].transparent - call theme#disableTransparent() - endif +function! theme#toggleTransparent() abort + let s:config[&background].transparent = !s:config[&background].transparent + if s:config[&background].transparent + call s:ApplyTransparency() + else + call theme#apply(s:config[&background].theme) + endif endfunction -function! theme#saveConfig() - let p = utils#readvar(s:path) - if type(p) != type({}) - let p = {} - endif - - let vim_type = has('nvim') ? 'nvim' : 'vim' - - let config = has_key(p, vim_type) && type(p[vim_type]) == 4 - \ ? p[vim_type] : {} - - let config = utils#merge(config, s:config) - - " vim and nvim may have diferenrt available plugins - let p[vim_type] = config - call utils#savevar(p, s:path) +function! theme#onColorScheme(name) abort + if s:applying + return + endif + if a:name !~# '^sunbather_' && index(['everforest', 'moonfly', 'PaperColor'], a:name) < 0 + return + endif + let s:config.background = &background + let s:config[&background].theme = a:name + call s:ApplyTransparency() endfunction -function! theme#loadConfig() - let result = utils#readvar(s:path) - " if it is dictionary - let vim_type = has('nvim') ? 'nvim' : 'vim' - if type(result) == 4 - if has_key(result, vim_type) - let config = result[vim_type] - if type(config) == 4 - return config - endif - endif - endif - return {} -endfunction - -function! theme#getHiTerms(group) - let output = execute('hi ' . a:group) - if stridx(output, 'links to') > 0 - let higroup = matchstr(output, 'links.to.\?\zs\S\+\ze') - return theme#getHiTerms(higroup) - endif - let list = split(output, '') - let dict = {} - - for item in list - if stridx(item, '=') > 0 - let splited = split(item, '=') - let dict[splited[0]] = splited[1] - endif - endfor - - for item in ['guibg', 'ctermbg', 'term', 'cterm', 'guifg', 'ctermfg'] - if ! has_key(dict, item) - let dict[item] = 'NONE' - endif - endfor - return dict -endfunction - -function! theme#getHiTerm(group, term) - " Store output of group to variable - let output = theme#getHiTerms(a:group) - return output[a:term] -endfunction - -function! s:regiesterThemeFix(Func) - call add(s:theme_fix, a:Func) -endfunction - -function! s:generalThemeFix() -" The following is for getting rid of the vim split bar and match its -" and number cols' color with backgroud - " if theme#inTransparent() - " return - " endif - if &bg != s:config.background - execute('set bg=' . s:config.background) - endif - - let normal = theme#getHiTerms('normal') - let hiTerms = ' ' - for term in ['guibg', 'ctermbg', 'term', 'cterm'] - let hiTerms .= term . '=' . normal[term] . ' ' - endfor - - for group in s:cleanbg - " if s:hiType(group) != 0 - " continue - " endif - " transBlendOpt is used to prevent hi from being clear - execute('hi! ' . group . hiTerms) - endfor - - " highlight cursorline number only - " this needs option set cursorlineopt=number - if s:hiType('CursorLineNr') == 0 - hi! CursorLineNr guibg=NONE ctermbg=NONE cterm=bold gui=bold - endif - - for Func in s:themefixes - call Func() - endfor -endfunction - -function! theme#Init() - if has('termguicolors') - set termguicolors - endif - - if has('nvim') - set fillchars+=stl:\ ,stlnc:\ , - endif - - let s:config = utils#merge(s:default_config, theme#loadConfig()) - - let bg = s:config.background - if utils#hascolorscheme(s:config[bg].theme) - call theme#setColor(bg) - else - call theme#setColor(bg, s:config[bg].default) - endif - - if s:config[bg].transparent - call theme#enableTransparent() - else - call theme#disableTransparent() - endif - call s:generalThemeFix() - - if exists('*options#add') - let toggle_transparent = { 'desc' : 'Toggle transparent background' } - func toggle_transparent.togglefunc(...) - call theme#toggleTransparent() - endfunc - call options#add('toggle_transparent', toggle_transparent) - endif - - augroup GeneralTheme - autocmd! - autocmd ColorScheme * call s:generalThemeFix() - autocmd ColorScheme * let s:config.background = &bg | call theme#setColor(&bg, expand('')) - autocmd VimLeave * call theme#saveConfig() - augroup END - -endfunction - -function! theme#getConfig() - return s:config +function! theme#Init() abort + let s:config = s:Load() + let &background = get(s:config, 'background', 'dark') + call theme#apply(s:config[&background].theme) + augroup DotfilesTheme + autocmd! + autocmd ColorScheme * call theme#onColorScheme(expand('')) + autocmd VimLeavePre * call theme#save() + augroup END endfunction diff --git a/config/vim/autoload/utils.vim b/config/vim/autoload/utils.vim deleted file mode 100644 index a4758e7..0000000 --- a/config/vim/autoload/utils.vim +++ /dev/null @@ -1,194 +0,0 @@ - -" return a python version available (from 3 to 2) -fun! utils#get_usable_py() - let py = '' - if executable('python3') - let py = 'python3' - elseif executable('python2') - let py = 'python2' - elseif executable('python') - let py = 'python' - endif - return py -endfun - -" Check if plugin exists -function! utils#hasplug(plug_name, ...) - let plug_dir_name = get(a:, 1, a:plug_name) " optional argument for the name of plug's folder - if has_key(g:plugs, a:plug_name) && isdirectory(g:plugin_dir . "/" . plug_dir_name) - if has_key(g:plugs[a:plug_name], 'for') || has_key(g:plugs[a:plug_name], 'on') - if (has_key(g:plugs[a:plug_name], 'for') && len(g:plugs[a:plug_name]['for']) == 0) || - \ (has_key(g:plugs[a:plug_name], 'on') && len(g:plugs[a:plug_name]['on']) == 0) - return v:false - endif - endif - return v:true - endif - return v:false -endfunction - -" This function is used to save a variable to a file -function! utils#savevar(var, file) - let serialized = string(a:var) - call writefile([serialized], a:file) -endfun - -" This function is used to retrieve a variable from a file -" only first line is count -function! utils#readvar(file) - if !filereadable(a:file) - return v:null - endif - let serialized = readfile(a:file) - if(len(serialized) == 0) - return v:null - endif - execute "let result = " . serialized[0] - return result -endfun - -" Merge two dictionaries, also recursively merging nested keys. -" Use extend() if you don't need to merge nested keys. -fun! utils#merge(defaults, override) - let l:new = copy(a:defaults) - for [l:k, l:v] in items(a:override) - let l:new[l:k] = (type(l:v) is v:t_dict && type(get(l:new, l:k)) is v:t_dict) - \ ? utils#merge(l:new[l:k], l:v) - \ : l:v - endfor - return l:new -endfun - -"Remove all trailing whitespace by pressing ws -fun! utils#trimwhitespace() - let l:save = winsaveview() - keeppatterns %s/\s*\r\=$//e - call winrestview(l:save) -endfun - -function! utils#hascolorscheme(name) - let scheme = a:name - let colors = globpath(&runtimepath, printf('colors/%s.vim', scheme), 1, 1) - if len(colors) > 0 | return 1 | endif - let colors += globpath(&packpath, printf('pack/*/start/*/colors/%s.vim', scheme), 1, 1) - if len(colors) > 0 | return 1 | endif - let colors += globpath(&packpath, printf('pack/*/opt/*/colors/%s.vim', scheme), 1, 1) - if len(colors) > 0 | return 1 | endif - if has('nvim') - let colors = globpath(&runtimepath, printf('colors/%s.lua', scheme), 1, 1) - if len(colors) > 0 | return 1 | endif - let colors += globpath(&packpath, printf('pack/*/start/*/colors/%s.lua', scheme), 1, 1) - if len(colors) > 0 | return 1 | endif - let colors += globpath(&packpath, printf('pack/*/opt/*/colors/%s.lua', scheme), 1, 1) - if len(colors) > 0 | return 1 | endif - endif - return 0 -endfunction - -" get current colorscheme name -" return default if not found -function! utils#colorschemename() - return execute('colo')[1:] - try - return g:colors_name - catch /^Vim:E121/ - return "default" - catch /.*/ - return "default" - endtry -endfunction - -" debug function print out highlight group of cursor position -function! utils#showHiGroup(...) - if !exists("*synstack") - return - endif - let l = a:0 == 2 ? a:1 : line('.') - let c = a:0 == 2 ? a:2 : col('.') - echo map(synstack(l, c), 'synIDattr(v:val, "name")') - - :echo "hi<" . synIDattr(synID(l,c,1),"name") . '> trans<' - \ . synIDattr(synID(l,c,0),"name") . "> lo<" - \ . synIDattr(synIDtrans(synID(l,c,1)),"name") . ">" - -endfunc - -" get highlight group information and return as dictionary -function! utils#getHi(group) - let output = execute('hi ' . a:group) - let list = split(output, '\s\+') - let dict = {} - for item in list - if match(item, '=') > 0 - let splited = split(item, '=') - let dict[splited[0]] = splited[1] - endif - endfor - return dict -endfunction - -function! utils#isTransparent() - let dict = utils#getHi('Normal') - let isGui = &termguicolors - if isGui - if !has_key(dict, 'guibg') - return 1 - endif - elseif !isGui - if !has_key(dict, 'ctermfg') - return 1 - endif - endif - return 0 -endfunction - -function! s:scratch() - split - noswapfile hide enew - setlocal buftype=nofile - setlocal bufhidden=hide - setlocal nobuflisted -endfunction - -" search highlight group with pattern -function! utils#searchHi(pattern) - execute("filter /" . a:pattern . "/ highlight") - " color not working - " let temp_reg = @" - " redir @" - " silent! execute("filter /" . a:pattern . "/ highlight") - " redir END - " let output = copy(@") - " let @" = temp_reg - " call s:scratch() - " put! =output -endfunc - -function! utils#swapword() - let word = expand("") - let l1 = g:swap_dict[0] - let l2 = g:swap_dict[1] - let inx = index(l1, word) - if inx != -1 - let newword = l2[inx] - else - let inx = index(l2, word) - if inx != -1 - let newword = l1[inx] - endif - endif - if inx != -1 - execute "normal ciw" . newword . "\" - endif -endfunction - -function! utils#files(...) - if a:0 > 0 - let path = a:1 - else - let path = getcwd() - endif - let files = glob(path . '/**', 1, 1, 1) - return files -endfunction - diff --git a/config/vim/bin/preview.py b/config/vim/bin/preview.py deleted file mode 100755 index d751efb..0000000 --- a/config/vim/bin/preview.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env python3 - -""" preview.py theme arg -""" - -import os -import sys - -class bcolors: - HEADER = '\033[95m' - OKBLUE = '\033[94m' - OKCYAN = '\033[96m' - OKGREEN = '\033[92m' - WARNING = '\033[93m' - RED = '\033[31m' - YELLOW = '\033[33m' - FAIL = '\033[91m' - ENDC = '\033[0m' - BOLD = '\033[1m' - UNDERLINE = '\033[4m' - -def is_tool(name): - """Check whether `name` is on PATH and marked as executable.""" - from shutil import which - return which(name) is not None - -def get_preview_tool(): - exec = None - if is_tool('bat'): - exec = 'bat' - elif is_tool('batcat'): - exec = 'batcat' - elif is_tool('cat'): - exec = 'cat' - return exec - -if __name__ == '__main__': - - theme = sys.argv[1] - if theme == 'light': - theme = 'ansi' - tcolor = '31' - color = bcolors.RED - else: - theme = '1337' - tcolor = '33' - color = bcolors.YELLOW - - filepath = ''.join(sys.argv[2:]) - args = filepath.split(":") - args += [None, None] - - file = args[0] - center = args[1] - # print(sys.argv[2:]) - # exit(0) - # if os.name == 'nt': - # file += args[1] - # center = args[2] - - if file == None or not os.path.isfile(file): - print("File not found {}".format(file)) - exit(0) - - if center is None: center = 0 - - batcmd = get_preview_tool() - cmdstr = None - - if file[0] == '-': - file = './' + file - if batcmd: - if batcmd == 'cat': - if center: - cmdstr = 'cat -n {} | perl -pe "s/^.*?\s{}\s.*?$/\e[1;{}m$&\e[0m/g"'.format(file, center, tcolor) - else: - cmdstr = 'cat -n {}'.format(file) - elif batcmd == 'bat': - cmdstr = 'bat --theme={} --style=numbers --color=always \ - --pager=never --highlight-line={} "{}"'.format(theme, center, file) - if cmdstr: - os.system(cmdstr) - else: - f = open(file, 'r') - Lines = f.readlines() - center = int(center) - linenr = 1 - - for line in Lines: - if linenr == center: - print("{}{:4d} {}{}".format(color, linenr, line, bcolors.ENDC), end='') - else: - print("{:4d} {}".format(linenr, line), end='') - linenr += 1 - f.close() - - - diff --git a/config/vim/configs/gui-config.vim b/config/vim/configs/gui-config.vim deleted file mode 100644 index 2fda1bc..0000000 --- a/config/vim/configs/gui-config.vim +++ /dev/null @@ -1,30 +0,0 @@ -if has('gui') || exists('g:neovide') - set guifont=Hack\ Nerd\ Font:h13 - - " neovide doesn't support copy from host, so we have to map it ourselves - - if exists('g:neovide') - - func! s:enabletp() - let g:neovide_transparency=0.9 - endfunc - func! s:disabletp() - let g:neovide_transparency=1.0 - endfunc - let g:Transparent_disable_func = function('s:disabletp') - let g:Transparent_enable_func = function('s:enabletp') - - let g:neovide_transparency=0.9 - " let g:neovide_transparency_point=0.8 - if g:os == 'Darwin' - nnoremap "+p - cnoremap + - inoremap + - else - nnoremap "+p - cnoremap + - inoremap + - endif - endif - -endif diff --git a/config/vim/lua/fzy_lua.lua b/config/vim/lua/fzy_lua.lua deleted file mode 100644 index 301c64c..0000000 --- a/config/vim/lua/fzy_lua.lua +++ /dev/null @@ -1,276 +0,0 @@ --- The lua implementation of the fzy string matching algorithm - -local SCORE_GAP_LEADING = -0.005 -local SCORE_GAP_TRAILING = -0.005 -local SCORE_GAP_INNER = -0.01 -local SCORE_MATCH_CONSECUTIVE = 1.0 -local SCORE_MATCH_SLASH = 0.9 -local SCORE_MATCH_WORD = 0.8 -local SCORE_MATCH_CAPITAL = 0.7 -local SCORE_MATCH_DOT = 0.6 -local SCORE_MAX = math.huge -local SCORE_MIN = -math.huge -local MATCH_MAX_LENGTH = 1024 - -local fzy = {} - --- Check if `needle` is a subsequence of the `haystack`. --- --- Usually called before `score` or `positions`. --- --- Args: --- needle (string) --- haystack (string) --- case_sensitive (bool, optional): defaults to false --- --- Returns: --- bool -function fzy.has_match(needle, haystack, case_sensitive) - if not case_sensitive then - needle = string.lower(needle) - haystack = string.lower(haystack) - end - - local j = 1 - for i = 1, string.len(needle) do - j = string.find(haystack, needle:sub(i, i), j, true) - if not j then - return false - else - j = j + 1 - end - end - - return true -end - -local function is_lower(c) - return c:match("%l") -end - -local function is_upper(c) - return c:match("%u") -end - -local function precompute_bonus(haystack) - local match_bonus = {} - - local last_char = "/" - for i = 1, string.len(haystack) do - local this_char = haystack:sub(i, i) - if last_char == "/" or last_char == "\\" then - match_bonus[i] = SCORE_MATCH_SLASH - elseif last_char == "-" or last_char == "_" or last_char == " " then - match_bonus[i] = SCORE_MATCH_WORD - elseif last_char == "." then - match_bonus[i] = SCORE_MATCH_DOT - elseif is_lower(last_char) and is_upper(this_char) then - match_bonus[i] = SCORE_MATCH_CAPITAL - else - match_bonus[i] = 0 - end - - last_char = this_char - end - - return match_bonus -end - -local function compute(needle, haystack, D, M, case_sensitive) - -- Note that the match bonuses must be computed before the arguments are - -- converted to lowercase, since there are bonuses for camelCase. - local match_bonus = precompute_bonus(haystack) - local n = string.len(needle) - local m = string.len(haystack) - - if not case_sensitive then - needle = string.lower(needle) - haystack = string.lower(haystack) - end - - -- Because lua only grants access to chars through substring extraction, - -- get all the characters from the haystack once now, to reuse below. - local haystack_chars = {} - for i = 1, m do - haystack_chars[i] = haystack:sub(i, i) - end - - for i = 1, n do - D[i] = {} - M[i] = {} - - local prev_score = SCORE_MIN - local gap_score = i == n and SCORE_GAP_TRAILING or SCORE_GAP_INNER - local needle_char = needle:sub(i, i) - - for j = 1, m do - if needle_char == haystack_chars[j] then - local score = SCORE_MIN - if i == 1 then - score = ((j - 1) * SCORE_GAP_LEADING) + match_bonus[j] - elseif j > 1 then - local a = M[i - 1][j - 1] + match_bonus[j] - local b = D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE - score = math.max(a, b) - end - D[i][j] = score - prev_score = math.max(score, prev_score + gap_score) - M[i][j] = prev_score - else - D[i][j] = SCORE_MIN - prev_score = prev_score + gap_score - M[i][j] = prev_score - end - end - end -end - --- Compute a matching score. --- --- Args: --- needle (string): must be a subequence of `haystack`, or the result is --- undefined. --- haystack (string) --- case_sensitive (bool, optional): defaults to false --- --- Returns: --- number: higher scores indicate better matches. See also `get_score_min` --- and `get_score_max`. -function fzy.score(needle, haystack, case_sensitive) - local n = string.len(needle) - local m = string.len(haystack) - - if n == 0 or m == 0 or m > MATCH_MAX_LENGTH or n > m then - return SCORE_MIN - elseif n == m then - return SCORE_MAX - else - local D = {} - local M = {} - compute(needle, haystack, D, M, case_sensitive) - return M[n][m] - end -end - --- Compute the locations where fzy matches a string. --- --- Determine where each character of the `needle` is matched to the `haystack` --- in the optimal match. --- --- Args: --- needle (string): must be a subequence of `haystack`, or the result is --- undefined. --- haystack (string) --- case_sensitive (bool, optional): defaults to false --- --- Returns: --- {int,...}: indices, where `indices[n]` is the location of the `n`th --- character of `needle` in `haystack`. --- number: the same matching score returned by `score` -function fzy.positions(needle, haystack, case_sensitive) - local n = string.len(needle) - local m = string.len(haystack) - - if n == 0 or m == 0 or m > MATCH_MAX_LENGTH or n > m then - return {}, SCORE_MIN - elseif n == m then - local consecutive = {} - for i = 1, n do - consecutive[i] = i - end - return consecutive, SCORE_MAX - end - - local D = {} - local M = {} - compute(needle, haystack, D, M, case_sensitive) - - local positions = {} - local match_required = false - local j = m - for i = n, 1, -1 do - while j >= 1 do - if D[i][j] ~= SCORE_MIN and (match_required or D[i][j] == M[i][j]) then - match_required = (i ~= 1) and (j ~= 1) and ( - M[i][j] == D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE) - positions[i] = j - j = j - 1 - break - else - j = j - 1 - end - end - end - - return positions, M[n][m] -end - --- Apply `has_match` and `positions` to an array of haystacks. --- --- Args: --- needle (string) --- haystack ({string, ...}) --- case_sensitive (bool, optional): defaults to false --- --- Returns: --- {{idx, positions, score}, ...}: an array with one entry per matching line --- in `haystacks`, each entry giving the index of the line in `haystacks` --- as well as the equivalent to the return value of `positions` for that --- line. -function fzy.filter(needle, haystacks, case_sensitive) - local result = {} - local idx = 1 - for line in haystacks() do - if fzy.has_match(needle, line, case_sensitive) then - local p, s = fzy.positions(needle, line, case_sensitive) - table.insert(result, vim.list({idx, vim.list(p), s})) - end - idx = idx + 1 - end - table.sort(result, function(a,b) return a[3] > b[3] end) - return vim.list(result) -end - --- The lowest value returned by `score`. --- --- In two special cases: --- - an empty `needle`, or --- - a `needle` or `haystack` larger than than `get_max_length`, --- the `score` function will return this exact value, which can be used as a --- sentinel. This is the lowest possible score. -function fzy.get_score_min() - return SCORE_MIN -end - --- The score returned for exact matches. This is the highest possible score. -function fzy.get_score_max() - return SCORE_MAX -end - --- The maximum size for which `fzy` will evaluate scores. -function fzy.get_max_length() - return MATCH_MAX_LENGTH -end - --- The minimum score returned for normal matches. --- --- For matches that don't return `get_score_min`, their score will be greater --- than than this value. -function fzy.get_score_floor() - return MATCH_MAX_LENGTH * SCORE_GAP_INNER -end - --- The maximum score for non-exact matches. --- --- For matches that don't return `get_score_max`, their score will be less than --- this value. -function fzy.get_score_ceiling() - return MATCH_MAX_LENGTH * SCORE_MATCH_CONSECUTIVE -end - --- The name of the currently-running implmenetation, "lua" or "native". -function fzy.get_implementation_name() - return "lua" -end - -return fzy diff --git a/config/vim/lua/lua-plugin-settings/aerial-nvim-config.lua b/config/vim/lua/lua-plugin-settings/aerial-nvim-config.lua deleted file mode 100644 index 11fd1e9..0000000 --- a/config/vim/lua/lua-plugin-settings/aerial-nvim-config.lua +++ /dev/null @@ -1,18 +0,0 @@ - -if HasPlug('github-nvim-theme') then - require('aerial').setup({ - -- optionally use on_attach to set keymaps when aerial has attached to a buffer - layout = { - width = 50, - default_direction = "right", - preserve_equality = true, - }, - on_attach = function(bufnr) - -- Jump forwards/backwards with '{' and '}' - vim.keymap.set('n', '{', 'AerialPrev', { buffer = bufnr }) - vim.keymap.set('n', '}', 'AerialNext', { buffer = bufnr }) - end - }) - -- You probably also want to set a keymap to toggle aerial - vim.keymap.set('n', 'v', 'AerialToggle!') -end diff --git a/config/vim/lua/lua-plugin-settings/github-nvim-theme-config.lua b/config/vim/lua/lua-plugin-settings/github-nvim-theme-config.lua deleted file mode 100644 index e68dbef..0000000 --- a/config/vim/lua/lua-plugin-settings/github-nvim-theme-config.lua +++ /dev/null @@ -1,13 +0,0 @@ - -if HasPlug('github-nvim-theme') then - -- Example config in Lua - require("github-theme").setup({ - -- Overwrite the highlight groups - overrides = function(c) - return { - NormalFloat = { link = 'Pmenu' }, - } - end - }) -end - diff --git a/config/vim/lua/lua-plugin-settings/gitsigns-nvim-config.lua b/config/vim/lua/lua-plugin-settings/gitsigns-nvim-config.lua deleted file mode 100644 index 16a7a51..0000000 --- a/config/vim/lua/lua-plugin-settings/gitsigns-nvim-config.lua +++ /dev/null @@ -1,50 +0,0 @@ - -if HasPlug('gitsigns.nvim') then - require('gitsigns').setup({ - signcolumn = true, -- Toggle with `:Gitsigns toggle_signs` - numhl = false, -- Toggle with `:Gitsigns toggle_numhl` - linehl = false, -- Toggle with `:Gitsigns toggle_linehl` - word_diff = false, -- Toggle with `:Gitsigns toggle_word_diff` - on_attach = function(bufnr) - local gs = package.loaded.gitsigns - local function map(mode, l, r, opts) - opts = opts or {} - opts.buffer = bufnr - vim.keymap.set(mode, l, r, opts) - end - - -- Navigation - map('n', ']c', function() - if vim.wo.diff then return ']c' end - vim.schedule(function() gs.next_hunk() end) - return '' - end, { expr = true }) - - map('n', '[c', function() - if vim.wo.diff then return '[c' end - vim.schedule(function() gs.prev_hunk() end) - return '' - end, { expr = true }) - - -- Actions - map({ 'n', 'v' }, 'hs', ':Gitsigns stage_hunk') - map({ 'n', 'v' }, 'hr', ':Gitsigns reset_hunk') - map('n', 'hS', gs.stage_buffer) - map('n', 'hu', gs.undo_stage_hunk) - map('n', 'hR', gs.reset_buffer) - map('n', 'hp', gs.preview_hunk) - map('n', 'hb', function() gs.blame_line { full = true } end) - map('n', 'tb', gs.toggle_current_line_blame) - map('n', 'hd', gs.diffthis) - map('n', 'hD', function() gs.diffthis('~') end) - map('n', 'td', gs.toggle_deleted) - - -- Text object - map({ 'o', 'x' }, 'ih', ':Gitsigns select_hunk') - end - }) - vim.fn['theme#addCleanBg']({ 'GitSignsAdd', 'GitSignsStagedChange', - 'GitSignsStagedDelete', 'GitSignsDelete', 'GitSignsChange', - 'GitGutterAdd', 'GitGutterChange', 'GitGutterDelete', 'GitGutterChangeDelete', - }) -end diff --git a/config/vim/lua/lua-plugin-settings/impatient-nvim-config.lua b/config/vim/lua/lua-plugin-settings/impatient-nvim-config.lua deleted file mode 100644 index 7b57c1b..0000000 --- a/config/vim/lua/lua-plugin-settings/impatient-nvim-config.lua +++ /dev/null @@ -1,4 +0,0 @@ - -if HasPlug('impatient.nvim') then - require('impatient') -end diff --git a/config/vim/lua/lua-plugin-settings/indent-blankline-nvim-config.lua b/config/vim/lua/lua-plugin-settings/indent-blankline-nvim-config.lua deleted file mode 100644 index 690a0e8..0000000 --- a/config/vim/lua/lua-plugin-settings/indent-blankline-nvim-config.lua +++ /dev/null @@ -1,12 +0,0 @@ - -if not Animation_enable then - if HasPlug('indent-blankline.nvim') then - -- Example config in Lua - require("ibl").setup { - exclude = { - buftypes = {"lspinfo", "packer", "checkhealth", - "help", "man", "", "startify"}, - } - } - end -end diff --git a/config/vim/lua/lua-plugin-settings/init.lua b/config/vim/lua/lua-plugin-settings/init.lua deleted file mode 100644 index 118de41..0000000 --- a/config/vim/lua/lua-plugin-settings/init.lua +++ /dev/null @@ -1,60 +0,0 @@ --------------------OPTIONS----------------------- - --- enable animation of command like "" and "", or cursor --- jump animation. (Performence will be effected) -Animation_enable = vim.g.animation_enable -High_performence = vim.g.high_performence - --- false basicly enable plugins like noice, nvim-notify etc. -Classic_vim_ui = vim.g.classic_vim_ui - - -------------------VIM OPTIONS----------------------- - -vim.o.signcolumn = 'auto:2' - -------------------UTILITIES---------------------- - -Vim_version = vim.version() -Vim_version_minor = Vim_version['minor'] - -function HasPlug(name) - return vim.fn['utils#hasplug'](name) -end - --- use to print object -function _G.put(...) - local objects = {} - for i = 1, select('#', ...) do - local v = select(i, ...) - table.insert(objects, vim.inspect(v)) - end - - print(table.concat(objects, '\n')) - return ... -end - -Which_key = nil -function Wk_register(opt) - if Which_key == nil then - return - end - Which_key.register(opt) -end - -Show_icon = false -if HasPlug('nvim-web-devicons') then - Show_icon = true -end - - -----------------CONFIGURATION-------------------- - -local plugin_setting_paths = vim.fn.split(vim.fn.glob(vim.g.dotvimdir - .. "/lua/lua-plugin-settings/*config.lua"), '\n') -local plugin_settings = vim.fn.map(plugin_setting_paths, 'fnamemodify(v:val, ":t:r")') - -for _idx, name in pairs(plugin_settings) do - require('lua-plugin-settings.'..name) -end - diff --git a/config/vim/lua/lua-plugin-settings/iron-nvim-config.lua b/config/vim/lua/lua-plugin-settings/iron-nvim-config.lua deleted file mode 100644 index 9381fdb..0000000 --- a/config/vim/lua/lua-plugin-settings/iron-nvim-config.lua +++ /dev/null @@ -1,50 +0,0 @@ - -if HasPlug('iron.nvim') then - local iron = require("iron.core") - - iron.setup { - config = { - -- Whether a repl should be discarded or not - scratch_repl = true, - -- Your repl definitions come here - repl_definition = { - sh = { - -- Can be a table or a function that - -- returns a table (see below) - command = { "zsh" } - } - }, - -- How the repl window will be displayed - -- See below for more information - repl_open_cmd = require('iron.view').bottom(40), - }, - -- Iron doesn't set keymaps by default anymore. - -- You can set them here or manually add keymaps to the functions in iron.core - keymaps = { - send_motion = "sc", - visual_send = "sc", - send_file = "sf", - send_line = "sl", - send_mark = "sm", - mark_motion = "mc", - mark_visual = "mc", - remove_mark = "md", - cr = "s", - interrupt = "s", - exit = "sq", - clear = "cl", - }, - -- If the highlight is on, you can change how it looks - -- For the available options, check nvim_set_hl - highlight = { - italic = true - }, - ignore_blank_lines = true, -- ignore blank lines when sending visual select lines - } - - -- iron also has a list of commands, see :h iron-commands for all available commands - vim.keymap.set('n', 'rs', 'IronRepl') - vim.keymap.set('n', 'rr', 'IronRestart') - vim.keymap.set('n', 'rf', 'IronFocus') - vim.keymap.set('n', 'rh', 'IronHide') -end diff --git a/config/vim/lua/lua-plugin-settings/leap-nvim-config.lua b/config/vim/lua/lua-plugin-settings/leap-nvim-config.lua deleted file mode 100644 index 86f186a..0000000 --- a/config/vim/lua/lua-plugin-settings/leap-nvim-config.lua +++ /dev/null @@ -1,4 +0,0 @@ - -if HasPlug('leap.nvim') then - require('leap').add_default_mappings() -end diff --git a/config/vim/lua/lua-plugin-settings/lualine-nvim-config.lua b/config/vim/lua/lua-plugin-settings/lualine-nvim-config.lua deleted file mode 100644 index a02b548..0000000 --- a/config/vim/lua/lua-plugin-settings/lualine-nvim-config.lua +++ /dev/null @@ -1,108 +0,0 @@ - -if HasPlug('lualine.nvim') then - - -- custom lualine plugin show coc lsp status - local function cocstatus() - local loading = { "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" } - local step = #loading - local ok, result = pcall(vim.fn.CocAction, 'services') - if not ok then - return - end - local ft = vim.bo.filetype - local state, id - for _, entry in ipairs(result) do - if entry['languageIds'][1] == ft then - state = entry['state'] - id = entry['id'] - break - end - end - local speed = 1600 - local loadidx = (vim.loop.now() % speed) - local msg = id - if state == "starting" then - return msg .. " " .. loading[math.floor(loadidx / (step * (speed / 100))) + 1] - elseif state == "running" then - return msg - end - return '' - end - - local _section_x = {} - local _section_y = {} - -- if HasPlug('coc.nvim') then table.insert(_section_x, cocstatus) end - table.insert(_section_x, cocstatus) - local disabled_filetypes_data = {} - if Vim_version_minor < 7 then - -- globalstatus only work for nvim >= 0.7 - disabled_filetypes_data = { -- Filetypes to disable lualine for. - statusline = {}, -- only ignores the ft for statusline. - winbar = {}, -- only ignores the ft for winbar. - 'NvimTree', - 'vista', - } - end - - local opt = { - options = { - icons_enabled = Show_icon, - theme = 'auto', -- lualine theme - -- component_separators = { left = '', right = ''}, - -- section_separators = { left = '', right = ''}, - component_separators = { left = '', right = '' }, - section_separators = { left = '', right = '' }, - always_divide_middle = false, - globalstatus = true, - disabled_filetypes = disabled_filetypes_data, - refresh = { statusline = 200 } - }, - sections = { - lualine_a = { 'mode' }, - lualine_b = {}, - lualine_c = { - { - 'buffers', - mode = 2, - max_length = function() - return vim.o.columns - 30 - end, - filetype_names = { - TelescopePrompt = 'Telescope', - dashboard = 'Dashboard', - packer = 'Packer', - fzf = 'FZF', - alpha = 'Alpha', - NvimTree = 'NvimTree', - vista = 'Vista', - }, - symbols = { - alternate_file = '', - }, - } - }, - -- lualine_x = {'encoding', 'fileformat', 'filetype'}, - lualine_x = _section_x, - lualine_y = _section_y, - lualine_z = { 'location' } - }, - } - - require('lualine').setup(opt) - - vim.fn['theme#addTransGroup']({'lualine_c_inactive', 'lualine_c_normal'}) - - vim.o.fillchars ='eob: ,vert:│,stl: ,stlnc: ,' - - for i = 1, 9 do - -- :nnoremap 1 :LualineBuffersJump 1 - vim.api.nvim_set_keymap('n', '' .. i, ':LualineBuffersJump ' .. i .. '', - { noremap = true, silent = true, nowait = true }) - end - for i = 10, 20 do - -- :nnoremap 1 :LualineBuffersJump 1 - vim.api.nvim_set_keymap('n', '' .. i, ':LualineBuffersJump ' .. i .. '', - { noremap = true, silent = true, nowait = true }) - end -end - diff --git a/config/vim/lua/lua-plugin-settings/mini-animate-config.lua b/config/vim/lua/lua-plugin-settings/mini-animate-config.lua deleted file mode 100644 index 450a9f3..0000000 --- a/config/vim/lua/lua-plugin-settings/mini-animate-config.lua +++ /dev/null @@ -1,30 +0,0 @@ - -if HasPlug('mini.animate') and Animation_enable then - local animate = require('mini.animate') - animate.setup({ - cursor = { - -- Whether to enable this animation - enable = true, - -- Timing of animation (how steps will progress in time) - -- timing = --, - }, - scroll = { - -- Whether to enable this animation - enable = true, - -- Timing of animation (how steps will progress in time) - timing = animate.gen_timing.linear({ duration = 150, unit = 'total' }), - }, - open = { - -- Whether to enable this animation - enable = false, - }, - }) - vim.api.nvim_create_autocmd("FileType", { - pattern = { "help", "alpha", "dashboard", "neo-tree", "Trouble", "lazy", "mason", - "NvimTree", "vista", "toggleterm", "noice" }, - callback = function() - vim.b.minianimate_disable = true - end, - }) -end - diff --git a/config/vim/lua/lua-plugin-settings/mini-colors-config.lua b/config/vim/lua/lua-plugin-settings/mini-colors-config.lua deleted file mode 100644 index 1368b67..0000000 --- a/config/vim/lua/lua-plugin-settings/mini-colors-config.lua +++ /dev/null @@ -1,4 +0,0 @@ - -if HasPlug('mini.colors') then - require('mini.colors').setup() -end diff --git a/config/vim/lua/lua-plugin-settings/mini-indentscope-config.lua b/config/vim/lua/lua-plugin-settings/mini-indentscope-config.lua deleted file mode 100644 index d744497..0000000 --- a/config/vim/lua/lua-plugin-settings/mini-indentscope-config.lua +++ /dev/null @@ -1,21 +0,0 @@ - -if HasPlug('mini.indentscope') then - MiniIndentscope = require('mini.indentscope') - MiniIndentscope.setup({ - symbol = '│', - -- draw = { - -- animation = MiniIndentscope.gen_animation.linear({ - -- easing = 'out', - -- duration = 150, - -- unit = 'total' - -- }) - -- }, - }) - vim.api.nvim_create_autocmd("FileType", { - pattern = { "help", "alpha", "dashboard", "neo-tree", "Trouble", "lazy", "mason", - "NvimTree", "vista", "startify", "toggleterm" }, - callback = function() - vim.b.miniindentscope_disable = true - end, - }) -end diff --git a/config/vim/lua/lua-plugin-settings/noice-nvim-config.lua b/config/vim/lua/lua-plugin-settings/noice-nvim-config.lua deleted file mode 100644 index 2c227fd..0000000 --- a/config/vim/lua/lua-plugin-settings/noice-nvim-config.lua +++ /dev/null @@ -1,47 +0,0 @@ -if not Classic_vim_ui - and HasPlug('noice.nvim') - and HasPlug('nvim-notify') - and HasPlug('nui.nvim') then - - require("noice").setup({ - lsp = { - -- override markdown rendering so that **cmp** and other plugins use **Treesitter** - override = { - ["vim.lsp.util.convert_input_to_markdown_lines"] = true, - ["vim.lsp.util.stylize_markdown"] = true, - ["cmp.entry.get_documentation"] = true, - }, - }, - presets = { - bottom_search = true, -- use a classic bottom cmdline for search - -- command_palette = true, -- position the cmdline and popupmenu together - long_message_to_split = true, -- long messages will be sent to a split - inc_rename = false, -- enables an input dialog for inc-rename.nvim - lsp_doc_border = false, -- add a border to hover docs and signature help - }, - cmdline = { - enabled = true, -- enables the Noice cmdline UI - view = "cmdline", -- view for rendering the cmdline. Change to `cmdline` to get a classic cmdline at the bottom - opts = {}, -- global options for the cmdline. See section on views - format = { - -- cmdline = false, - search_down = false, - search_up = false, - help = { pattern = '', icon = '' }, - }, - }, - messages = { - -- NOTE: If you enable messages, then the cmdline is enabled automatically. - -- This is a current Neovim limitation. - enabled = true, -- enables the Noice messages UI - view = "notify", -- default view for messages - view_error = "notify", -- view for errors - view_warn = "notify", -- view for warnings - view_history = "messages", -- view for :messages - view_search = false, -- view for search count messages. Set to `false` to disable - }, - }) - - vim.fn['theme#addTransGroup']({'NotifyERRORBody', 'NotifyWARNBody', 'NotifyINFOBody', 'NotifyDEBUGBody', 'NotifyTRACEBody', - 'NotifyERRORBorder', 'NotifyWARNBorder', 'NotifyINFOBorder', 'NotifyDEBUGBorder', 'NotifyTRACEBorder'}) -end diff --git a/config/vim/lua/lua-plugin-settings/nvim-scrollbar-config.lua b/config/vim/lua/lua-plugin-settings/nvim-scrollbar-config.lua deleted file mode 100644 index 4fb5d2a..0000000 --- a/config/vim/lua/lua-plugin-settings/nvim-scrollbar-config.lua +++ /dev/null @@ -1,17 +0,0 @@ - -if HasPlug('nvim-scrollbar') then - require("scrollbar").setup({ - excluded_filetypes = { - "prompt", - "TelescopePrompt", - "noice", - "startify", - "vista", - }, - excluded_buftypes = { - "terminal", - "nofile", - "help", - }, - }) -end diff --git a/config/vim/lua/lua-plugin-settings/nvim-tree-lua-config.lua b/config/vim/lua/lua-plugin-settings/nvim-tree-lua-config.lua deleted file mode 100644 index e0d28de..0000000 --- a/config/vim/lua/lua-plugin-settings/nvim-tree-lua-config.lua +++ /dev/null @@ -1,68 +0,0 @@ - -if HasPlug('nvim-tree.lua') then - - local api = require('nvim-tree.api') - local M = {} - - function M.print_node_path() - local node = api.tree.get_node_under_cursor() - print(node.absolute_path) - end - - function M.on_attach(bufnr) - local function opts(desc) - return { desc = 'nvim-tree: ' .. desc, buffer = bufnr, noremap = true, silent = true, nowait = true } - end - -- vim.keymap.set('n', 'u', api.node.navigate.parent, opts('Parent Directory')) - vim.keymap.set('n', 'u', api.tree.change_root_to_parent, opts('Up')) - vim.keymap.set('n', 'a', api.fs.create, opts('Create')) - vim.keymap.set('n', 'dd', api.fs.remove, opts('Delete')) - vim.keymap.set('n', 'rn', api.fs.rename_basename, opts('Rename: Basename')) - vim.keymap.set('n', 'I', api.tree.toggle_gitignore_filter, opts('Toggle Git Ignore')) - vim.keymap.set('n', 'cd', api.tree.change_root_to_node, opts('CD')) - vim.keymap.set('n', 'X', api.tree.collapse_all, opts('Collapse')) - vim.keymap.set('n', 'O', api.tree.expand_all, opts('Expand All')) - vim.keymap.set('n', 'p', M.print_node_path, opts('Print node path')) - vim.keymap.set('n', 'o', api.node.open.edit, opts('Open')) - vim.keymap.set('n', '', api.node.open.edit, opts('Open')) - end - - vim.api.nvim_set_keymap('n', 'e', ':NvimTreeFindFileToggle', - { desc = 'Toggle nvim-tree', noremap = true, silent = true, nowait = true }) - - require("nvim-tree").setup({ - sync_root_with_cwd = true, - respect_buf_cwd = true, - update_focused_file = { - enable = true, - update_root = true, - }, - sort_by = "case_sensitive", - on_attach = M.on_attach, - view = { - width = 30, - }, - filters = { - dotfiles = false, - }, - git = { - ignore = false, - }, - actions = { - open_file = { - quit_on_open = true, - resize_window = true, - window_picker = { - exclude = { - filetype = { "notify", "packer", "qf", "diff", "fugitive", "fugitiveblame", "vista" }, - buftype = { "nofile", "terminal", "help" }, - }, - }, - }, - }, - }) - - vim.fn['theme#addTransGroup']({'NvimTreeWinSeparator', 'NvimTreeNormal', 'NvimTreeNormalNC'}) - -end - diff --git a/config/vim/lua/lua-plugin-settings/nvim-treesitter-config.lua b/config/vim/lua/lua-plugin-settings/nvim-treesitter-config.lua deleted file mode 100644 index a6e8622..0000000 --- a/config/vim/lua/lua-plugin-settings/nvim-treesitter-config.lua +++ /dev/null @@ -1,17 +0,0 @@ -if HasPlug('nvim-treesitter') then - require('nvim-treesitter.configs').setup { - ensure_installed = { "c", "bash", "lua", "python", "vim" }, - sync_install = false, - auto_install = true, - highlight = { - enable = true, - additional_vim_regex_highlighting = false, - }, - indent = { - enable = true - } - } - vim.o.foldmethod = 'expr' - vim.o.foldexpr = 'nvim_treesitter#foldexpr()' -end - diff --git a/config/vim/lua/lua-plugin-settings/project-nvim-config.lua b/config/vim/lua/lua-plugin-settings/project-nvim-config.lua deleted file mode 100644 index 1a00ccf..0000000 --- a/config/vim/lua/lua-plugin-settings/project-nvim-config.lua +++ /dev/null @@ -1,26 +0,0 @@ - -if HasPlug('project.nvim') then - require("project_nvim").setup { - detection_methods = { "lsp", "pattern" }, - patterns = { ".git" }, - - -- Don't calculate root dir on specific directories - -- Ex: { "~/.cargo/*", ... } - exclude_dirs = {}, - -- Show hidden files in telescope - show_hidden = false, - -- When set to false, you will get a message when project.nvim changes your - -- directory. - silent_chdir = true, - -- Path where project.nvim will store the project history for use in - -- telescope - datapath = vim.g.vim_dir .. "/.vimproject/" - } - - -- if HasPlug('telescope.nvim') then - -- require('telescope').load_extension('projects') - -- vim.keymap.set('n', 'fp', require'telescope'.extensions.projects.projects, - -- { desc = "Lists projects" }) - -- end - -end diff --git a/config/vim/lua/lua-plugin-settings/telescope-nvim-config.lua b/config/vim/lua/lua-plugin-settings/telescope-nvim-config.lua deleted file mode 100644 index eaad70a..0000000 --- a/config/vim/lua/lua-plugin-settings/telescope-nvim-config.lua +++ /dev/null @@ -1,109 +0,0 @@ -if HasPlug('telescope.nvim') then - local actions = require("telescope.actions") - local action_state = require "telescope.actions.state" - local telescope = require("telescope") - local builtin = require('telescope.builtin') - local telescopeConfig = require("telescope.config") - local vimgrep_arguments = { unpack(telescopeConfig.values.vimgrep_arguments) } - table.insert(vimgrep_arguments, "--hidden") - - require('telescope.pickers.layout_strategies').horizontal_merged = function(picker, max_columns, max_lines, - layout_config) - local layout = require('telescope.pickers.layout_strategies').horizontal(picker, max_columns, max_lines, - layout_config) - layout.prompt.title = '' - layout.results.title = '' - -- layout.prompt.borderchars = { '─', '│', '─', '│', '┌', '┐', '┘', '└' } - return layout - end - telescope.setup { - pickers = { - colorscheme = { - enable_preview = true, - mappings = { - i = { - [""] = function(bufnr) - local selection = action_state.get_selected_entry() - actions.select_default() - local bg = vim.o.background - vim.fn['theme#setColor'](bg, selection.value) - end, - }, - }, - } - }, - defaults = { - hidden = true, - vimgrep_arguments = vimgrep_arguments, - file_ignore_patterns = {"^node_modules/", "^.git/"}, - layout_config = { - -- prompt_position = "top", - }, - layout_strategy = "horizontal_merged", - }, - extensions = { - fzf = { - fuzzy = true, -- false will only do exact matching - override_generic_sorter = true, - override_file_sorter = true, - case_mode = "smart_case", -- or "ignore_case" or "respect_case" - } - } - } - if HasPlug('telescope-fzf-native.nvim') then - telescope.load_extension('fzf') - end - - vim.fn['theme#addCleanBg']({ 'TelescopeNormal', 'TelescopeBorder', 'TelescopePromptNormal', - 'TelescopePromptBorder', 'TelescopePromptPrefix', 'TelescopeResultsTitle', 'TelescopePreviewTitle', - 'TelescopePromptTitle', 'TelescopePromptCounter' }) - - vim.keymap.set('n', 'ff', builtin.find_files, { desc = "Search files inside cwd" }) - -- need to install ripgrep - vim.keymap.set('n', 'fr', builtin.live_grep, { desc = "Regex search inside files" }) - vim.keymap.set('n', 'fb', builtin.buffers, { desc = "Search buffers" }) - vim.keymap.set('n', 'fc', builtin.colorscheme, { desc = "Search colorscheme" }) - vim.keymap.set('n', 'fs', builtin.treesitter, { desc = "Lists Function names, variables, from Treesitter!" }) - vim.keymap.set('n', 'fh', builtin.highlights, { desc = "Lists highlight" }) - vim.keymap.set('n', 'fd', builtin.help_tags, { desc = "Lists highlight" }) - - Wk_register({ ["f"] = { name = "+Telescope" } }) - - vim.api.nvim_create_autocmd("User", { - pattern = "TelescopePreviewerLoaded", - command = "setlocal wrap number" - }) - - -- options picker - local pickers = require "telescope.pickers" - local finders = require "telescope.finders" - local conf = require("telescope.config").values - - function _G.telescope_option_picker() - local opts = require("telescope.themes").get_dropdown {} - pickers.new(opts, { - prompt_title = "Options", - finder = finders.new_table { - results = vim.fn['options#getAll'](), - entry_maker = function(entry) - return { - value = entry, - display = entry[2], - ordinal = entry[2], - } - end - }, - sorter = conf.generic_sorter(opts), - attach_mappings = function(prompt_bufnr, map) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - vim.fn['options#toggle'](selection['value'][1]) - end) - return true - end, - }):find() - end - - vim.keymap.set('n', 'fo', telescope_option_picker, { desc = "Lists Function names, variables, from Treesitter!" }) -end diff --git a/config/vim/lua/lua-plugin-settings/toggleterm-nvim-config.lua b/config/vim/lua/lua-plugin-settings/toggleterm-nvim-config.lua deleted file mode 100644 index 60f3ef4..0000000 --- a/config/vim/lua/lua-plugin-settings/toggleterm-nvim-config.lua +++ /dev/null @@ -1,79 +0,0 @@ - -if HasPlug('toggleterm.nvim') then - require("toggleterm").setup({ - - open_mapping = [[]], - direction = 'float', - float_opts = { - border = 'rounded', - width = function(term) return math.floor(vim.o.columns * 0.5) end, - height = function(term) return math.floor(vim.o.lines * 0.5) end, - winblend = 20, - row = vim.o.lines * 0.5 - 3, - col = vim.o.columns * 0.5, - }, - }) - function _G.set_terminal_keymaps() - local opts = { buffer = 0 } - vim.keymap.set('t', '', [[]], opts) - vim.keymap.set('t', 'jk', [[]], opts) - vim.keymap.set('t', '', [[wincmd h]], opts) - vim.keymap.set('t', '', [[wincmd j]], opts) - vim.keymap.set('t', '', [[wincmd k]], opts) - vim.keymap.set('t', '', [[wincmd l]], opts) - vim.keymap.set('t', '', [[]], opts) - end - - -- vim.cmd('autocmd TermOpen term://* lua set_terminal_keymaps()') - vim.cmd('autocmd FileType toggleterm lua set_terminal_keymaps()') - - local Terminal = require('toggleterm.terminal').Terminal - - local ipythonId = 779 - local ipython = Terminal:new({ - size = function(term) - if term.direction == "horizontal" then - return 15 elseif term.direction == "vertical" then - return vim.o.columns * 0.4 - end - end, - cmd = "ipython", - hidden = true, - direction = "vertical", - close_on_exit = false, - auto_scroll = true, - id = ipythonId, - }) - - function _ipython_toggle() - local currentWindow=vim.fn.winnr() - ipython:toggle(vim.o.columns * 0.5, 'vertical') - vim.cmd(currentWindow .. "wincmd w") - end - - vim.api.nvim_set_keymap("n", "tp", "lua _ipython_toggle()", { noremap = true, silent = true }) - - vim.api.nvim_set_keymap("n", "tl", string.format("ToggleTermSendCurrentLine %d", ipythonId), - { noremap = true, silent = true }) - -- sends all the (whole) lines in your visual selection - vim.api.nvim_set_keymap("v", "tl", string.format(":ToggleTermSendVisualLines %d", ipythonId), - { noremap = true, silent = true }) - -- sends only the visually selected text (this can be a block of text - vim.api.nvim_set_keymap("x", "tl", string.format(":ToggleTermSendVisualSelection %d", ipythonId), - { noremap = true, silent = true }) - - - print(vim.o.shell) - if vim.o.shell == 'pwsh' or vim.o.shell == 'powershell' then - local powershell_options = { - shellcmdflag = "-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;", - shellredir = "-RedirectStandardOutput %s -NoNewWindow -Wait", - shellpipe = "2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode", - shellquote = "", - shellxquote = "", - } - for option, value in pairs(powershell_options) do - vim.opt[option] = value - end - end -end diff --git a/config/vim/lua/lua-plugin-settings/vim-illuminate-config.lua b/config/vim/lua/lua-plugin-settings/vim-illuminate-config.lua deleted file mode 100644 index 12d0d88..0000000 --- a/config/vim/lua/lua-plugin-settings/vim-illuminate-config.lua +++ /dev/null @@ -1,30 +0,0 @@ -if HasPlug('vim-illuminate') then - local illuminate = require('illuminate') - illuminate.configure({ - providers = { - 'lsp', - 'treesitter', - 'regex', - }, - delay = 0, - filetype_overrides = {}, - filetypes_denylist = { - 'dirvish', - 'fugitive', - 'NvimTree', - 'help', - 'vista', - 'aerial', - }, - filetypes_allowlist = {}, - modes_denylist = {}, - modes_allowlist = {}, - providers_regex_syntax_denylist = {}, - providers_regex_syntax_allowlist = {}, - under_cursor = true, - large_file_cutoff = nil, - large_file_overrides = nil, - min_count_to_highlight = 1, - }) -end - diff --git a/config/vim/lua/lua-plugin-settings/which-key-nvim-config.lua b/config/vim/lua/lua-plugin-settings/which-key-nvim-config.lua deleted file mode 100644 index 16bf4fd..0000000 --- a/config/vim/lua/lua-plugin-settings/which-key-nvim-config.lua +++ /dev/null @@ -1,11 +0,0 @@ - -if HasPlug('which-key.nvim') then - Which_key = require("which-key") - Which_key.setup({ - triggers_blacklist = { - i = { "j", "k" }, - v = { "j", "k" }, - c = { "w" }, - }, - }) -end diff --git a/config/vim/plugin/config.vim b/config/vim/plugin/config.vim deleted file mode 100644 index b7155e1..0000000 --- a/config/vim/plugin/config.vim +++ /dev/null @@ -1,9 +0,0 @@ - -if exists("g:loaded_vim_config") - finish -endif -let g:loaded_vim_config = 1 - -let os = os#getOS() - -call options#init() diff --git a/config/vim/vim-plugin-settings/Copilot.vim.config.vim b/config/vim/vim-plugin-settings/Copilot.vim.config.vim deleted file mode 100644 index b1ca52f..0000000 --- a/config/vim/vim-plugin-settings/Copilot.vim.config.vim +++ /dev/null @@ -1,6 +0,0 @@ - -if utils#hasplug('Copilot.vim') - " imap (copilot-next) - " imap (copilot-prev) -endif - diff --git a/config/vim/vim-plugin-settings/coc-fzf.config.vim b/config/vim/vim-plugin-settings/coc-fzf.config.vim deleted file mode 100644 index 6a77a14..0000000 --- a/config/vim/vim-plugin-settings/coc-fzf.config.vim +++ /dev/null @@ -1,8 +0,0 @@ - -if utils#hasplug('coc-fzf') - - let g:coc_fzf_preview = 'right:50%' - nnoremap fs :CocFzfList outline - let s:preview_exe = expand(g:dotvimdir.'/bin/preview.py') - let g:coc_fzf_opts = ['--border-label', 'Coc Outlines', '--border-label-pos', '9', '--no-scrollbar', '--no-hscroll', '--no-separator'] -endif diff --git a/config/vim/vim-plugin-settings/coc.nvim.config.vim b/config/vim/vim-plugin-settings/coc.nvim.config.vim deleted file mode 100644 index 89ea77c..0000000 --- a/config/vim/vim-plugin-settings/coc.nvim.config.vim +++ /dev/null @@ -1,184 +0,0 @@ -if utils#hasplug('coc.nvim') -" let g:coc_global_extensions = ['coc-pyright', 'coc-tsserver', 'coc-vimlsp', -" \ 'coc-marksman'] - -" for tabline info -" coc-sumneko-lua offers autocomplete for neovim lua api -let g:coc_global_extensions = ['coc-nav', 'coc-sumneko-lua'] - -" warning that coc work best for vim >= 8.3 -let g:coc_disable_startup_warning = 1 - -let g:coc_data_home = g:vim_dir . '/coc' -let g:coc_config_home = g:vim_dir . '/coc' - -" Use to trigger completion. -if has('nvim') - inoremap coc#refresh() -else - inoremap coc#refresh() -endif - -set updatetime=300 - -" Make auto-select the first completion item and notify coc.nvim to -" format on enter, could be remapped by other vim plugin -inoremap pumvisible() ? coc#_select_confirm() - \: "\u\\=coc#on_enter()\" - -" GoTo code navigation. -nmap gd (coc-definition) -nmap gy (coc-type-definition) -nmap gi (coc-implementation) -nmap gr (coc-references) - -" Use K to show documentation in preview window. -nnoremap K :call show_documentation() - -function! s:show_documentation() - if CocAction('hasProvider', 'hover') - call CocActionAsync('doHover') - else - call feedkeys('K', 'in') - endif -endfunction - - -" Symbol renaming. -nmap rn (coc-rename) - -" Formatting selected code. -xmap f (coc-format-selected) -nmap f (coc-format-selected) - -augroup mygroup - autocmd! - " Setup formatexpr specified filetype(s). - autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected') - " Update signature help on jump placeholder. - autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp') -augroup end - -" Apply AutoFix to problem on the current line. -nmap qf (coc-fix-current) - -" Remap and for scroll float windows/popups. -if has('nvim-0.4.0') || has('patch-8.2.0750') - nnoremap coc#float#has_scroll() ? coc#float#scroll(1) : "\" - nnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" - inoremap coc#float#has_scroll() ? "\=coc#float#scroll(1)\" : "\" - inoremap coc#float#has_scroll() ? "\=coc#float#scroll(0)\" : "\" - vnoremap coc#float#has_scroll() ? coc#float#scroll(1) : "\" - vnoremap coc#float#has_scroll() ? coc#float#scroll(0) : "\" -endif - -" Mappings for CoCList -" Show all diagnostics. -nnoremap a :CocList diagnostics -" Manage extensions. -" nnoremap e :CocList extensions -" Show commands. -nnoremap c :CocList commands -" Find symbol of current document. -nnoremap o :CocList outline -" Search workspace symbols. -nnoremap s :CocList -I symbols -" Do default action for next item. -nnoremap j :CocNext -" Do default action for previous item. -nnoremap k :CocPrev -" Resume latest coc list. -nnoremap p :CocListResume - -"COC LSP SETTING -let g:coc_user_config = { -\ 'suggest.noselect': v:true, -\ 'suggest.enablePreselect': v:false, } - -call coc#config("java.jdt.ls.vmargs", '-javaagent:' . g:dotfiledir . '/config/coc/java/lombok-1.18.26.jar') -call coc#config("java.jdt.ls.lombokSupport.enabled", v:false) -call coc#config("java.inlayHints.parameterNames.enabled", v:false) -call coc#config("inlayHint.enable", v:false) - -if has('nvim') - " nvim has tree-sitter - call coc#config("semanticTokens.enable", v:false) -else - call coc#config("semanticTokens.enable", v:true) -endif - -call coc#config("sumneko-lua.enableNvimLuaDev", v:true) - -for section in ['suggest', 'diagnostic', 'signature', 'hover'] - call coc#config(section.'.floatConfig.border', v:true) - call coc#config(section.'.floatConfig.rounded', v:true) - call coc#config(section.'.floatConfig.highlight', 'Normal') - - " transparent setting (only for neovim) - " call coc#config(section.'.floatConfig.winblend', 6) -endfor - -function! CocHighlight() - hi! CocErrorHighlight guifg=#E74C3C term=underline,bold gui=underline,bold cterm=underline,bold - hi! CocErrorSign guifg=#E74C3C - - hi! CocWarningHighlight guifg=#E74C3C term=underline gui=underline cterm=underline - hi! CocWarningSign guifg=#E67E22 - - hi CocInfoHighlight term=underline gui=underline cterm=underline - hi CocHintHighlight term=underline gui=underline cterm=underline - hi CocUnusedHighlight term=underline gui=underline cterm=underline -endfunction - -call theme#addCleanBg(['CocWarningSign', 'CocErrorSign']) - -augroup CocHighlight - autocmd! - autocmd ColorScheme * call CocHighlight() -augroup END - -function! Breadcrumbs() - if ! exists('b:coc_nav') - return '' - endif - let items = b:coc_nav - " let t = '  ' - let t = ' ' - let c = 0 - for obj in items - let hi = obj['highlight'] - let name = obj['name'] - if c == 0 - let t ..= '%#'.. hi ..'#' .. name .. '%#Normal#' - else - let t ..= '  %#'.. hi ..'#' .. name .. '%#Normal#' - endif - let c += 1 - endfor - return t -endfunction - -func! s:sigbar_enable() - set tabline=%#Normal#🌠%{%Breadcrumbs()%} - set showtabline=2 -endfunc - -func! s:sigbar_disable() - set tabline= - set showtabline=1 -endfunc - -" set tabline=%=%#Normal#%=%{%Breadcrumbs()%} -" set showtabline=2 - -let sigbar_opt = { - \ 'desc': 'Show function signature bar', - \ 'enablefunc': function('s:sigbar_enable'), - \ 'disablefunc': function('s:sigbar_disable'), - \ 'isEnabled': 0, - \ } -call options#add('signature bar', sigbar_opt) - -call theme#addTransGroup(['CocFloating']) - -endif diff --git a/config/vim/vim-plugin-settings/codi.vim.config.vim b/config/vim/vim-plugin-settings/codi.vim.config.vim deleted file mode 100644 index da69883..0000000 --- a/config/vim/vim-plugin-settings/codi.vim.config.vim +++ /dev/null @@ -1,3 +0,0 @@ -if utils#hasplug('coc.nvim') - let g:codi#virtual_text = 0 -endif diff --git a/config/vim/vim-plugin-settings/ctrlp.vim.config.vim b/config/vim/vim-plugin-settings/ctrlp.vim.config.vim deleted file mode 100644 index 7927352..0000000 --- a/config/vim/vim-plugin-settings/ctrlp.vim.config.vim +++ /dev/null @@ -1,4 +0,0 @@ - -if utils#hasplug('ctrlp.vim') - let g:ctrlp_map = 'ff' -endif diff --git a/config/vim/vim-plugin-settings/everforest.config.vim b/config/vim/vim-plugin-settings/everforest.config.vim deleted file mode 100644 index 96c97fc..0000000 --- a/config/vim/vim-plugin-settings/everforest.config.vim +++ /dev/null @@ -1,32 +0,0 @@ - -if utils#hasplug('everforest') - let g:everforest_better_performance = 1 - let g:everforest_background = 'hard' - " let g:everforest_enable_italic = 1 - function! Everforest_trans_enable() - let g:everforest_transparent_background = 2 - colorscheme everforest - call theme#setStlColor(&background, 'everforest') - " hack to fix caret characters appearing in the statusline when StatusLine - " and StatusLineNC has same highlight(https://vi.stackexchange.com/questions/15873/carets-in-status-line) - hi StatusLine guifg=#d3c6aa ctermfg=223 - endfunction - function! Everforest_trans_disable() - let g:everforest_transparent_background = 0 - colorscheme everforest - call theme#setStlColor(&background, 'everforest') - endfunction - function! CB_dark_tb_enable_everforest() - call Everforest_trans_enable() - endfunction - function! CB_light_tb_enable_everforest() - call Everforest_trans_enable() - endfunction - function! CB_dark_tb_disable_everforest() - call Everforest_trans_disable() - endfunction - function! CB_light_tb_disable_everforest() - call Everforest_trans_disable() - endfunction - -endif diff --git a/config/vim/vim-plugin-settings/fzf.vim.config.vim b/config/vim/vim-plugin-settings/fzf.vim.config.vim deleted file mode 100644 index 079d00d..0000000 --- a/config/vim/vim-plugin-settings/fzf.vim.config.vim +++ /dev/null @@ -1,121 +0,0 @@ - -if utils#hasplug("fzf") && utils#hasplug("fzf.vim") - " [Buffers] Jump to the existing window if possible - let g:fzf_buffers_jump = 1 - "let $FZF_DEFAULT_COMMAND='find . \( -name node_modules -o -name .git \) -prune -o -print' - - " - CTRL-/ will toggle preview window. - let g:fzf_preview_window = ['right:50%'] - - hi! fzfborderhi term=bold cterm=bold ctermbg=236 gui=bold guibg=#272c42 - hi! fzfqueryhi term=underline cterm=underline gui=underline - - let g:fzf_force_termguicolors = 1 - - if g:os != 'Windows' - let $FZF_DEFAULT_COMMAND = "find . -type f -not -path '*/\.git/*'" - endif - - let s:preview_exe = expand(g:dotvimdir.'/bin/preview.py') - let s:color_opts = ['--color', 'gutter:-1,bg+:-1,bg:-1,preview-bg:-1,preview-fg:-1,fg+:-1'] - - " check if ripgrep is installed - function! FzfRg() - let s:previewcmd = join([utils#get_usable_py(), s:preview_exe, &bg, '{}']) - if ! executable('rg') - let cmd = 'grep -R --line-number --exclude-dir=".git;.svn" --color=always -- '.shellescape('') - else - let cmd = "rg --column --line-number --no-heading --color=always --smart-case -- ".shellescape('') - endif - - let options = s:color_opts + ['--border-label', 'Grep', '--border-label-pos', '9', '--no-scrollbar', - \ '--no-hscroll', '--no-separator', '--preview', s:previewcmd] - let with_preview = fzf#vim#with_preview() - if len(with_preview) == 0 - let with_preview = {'options':['--preview-window','right:50%' ] + options} - else - " make fzf preview repect colorsheme - let with_preview.options = with_preview.options[:-3] + options - endif - call fzf#vim#grep(cmd, 1, with_preview, 0) - endfunction - - function! FzfFiles(...) - let s:previewcmd = join([utils#get_usable_py(), s:preview_exe, &bg, '{}']) - let options = s:color_opts + ['--border-label', 'Files', '--border-label-pos', '9', '--no-scrollbar', - \ '--no-hscroll', '--no-separator', '--preview', s:previewcmd] - let with_preview = fzf#vim#with_preview() - if len(with_preview) == 0 - " in windows with_preview return empty dict - let with_preview = {'options':['--preview-window','right:50%' ] + options} - else - let with_preview.options = with_preview.options[:-3] + options - endif - let dir = '' - if a:0 >= 1 && isdirectory(expand(a:1)) - let dir = a:1 - endif - call fzf#vim#files(dir, with_preview, 0) - endfunction - - function! FzfColorSelect(color_name) - call theme#setColor(&bg, a:color_name) - endfunction - - function! FzfAirlineColorSelect(color_name) - call theme#setStlColor(&background, a:color_name) - endfunction - - let $FZF_DEFAULT_OPTS='--color=' . s:color_opts[1] - - function! FzfHelpTags() - let s:previewcmd = join([utils#get_usable_py(), s:preview_exe, &bg, '{}']) - let options = s:color_opts + ['--border-label', 'Files', '--border-label-pos', '9', '--no-scrollbar', - \ '--no-hscroll', '--no-separator'] - let with_preview = fzf#vim#with_preview({ "placeholder": "--tag {2}:{3}:{4}" }) - if len(with_preview) == 0 - " in windows with_preview return empty dict - let with_preview = {'options':['--preview-window','right:50%' ] + options} - else - let with_preview.options = with_preview.options + options - endif - call fzf#vim#helptags(with_preview, 0) - endfunction - - let s:optionmap = {} - let s:feedfzf = [] - func! s:optioncb(str) - call options#toggle(s:optionmap[a:str]) - endfunc - func! FzfOptions() - let s:feedfzf = [] - let s:optsource = options#getAll() - for e in s:optsource - let s:optionmap[e[1]] = e[0] - call add(s:feedfzf, e[1]) - endfor - call fzf#run(fzf#wrap({ - \ 'source': s:feedfzf, - \ 'sink': function('s:optioncb'), - \ 'options': ['--border-label', 'Options'], - \ 'window': { 'width': 0.4, 'height': 0.6 } - \ })) - endfunc - - " noremap fo :call FzfOptions() - " noremap fr :call FzfRg() - " noremap ff :call FzfFiles() - noremap fh :call FzfHelpTags() - " noremap fb :BLines - noremap fu :call FzfFiles('~') - - if utils#hasplug('fzf-color-preview') - let g:FzfColorComfirmCb = function('FzfColorSelect') - let g:FzfAirlineComfirmCb = function('FzfAirlineColorSelect') - noremap fa :AirlinePreview - noremap fc :ColorsPreview - else - noremap fc :Colors - endif -endif - diff --git a/config/vim/vim-plugin-settings/goyo.vim.config.vim b/config/vim/vim-plugin-settings/goyo.vim.config.vim deleted file mode 100644 index 5972bcc..0000000 --- a/config/vim/vim-plugin-settings/goyo.vim.config.vim +++ /dev/null @@ -1,16 +0,0 @@ - -if utils#hasplug('goyo.vim') - nnoremap g :Goyo - let g:goyo_width= floor(&co * 0.65) - - function! s:fix() - " resize the goyo after being messed up by other plugins - au BufEnter * if winnr('$') == '5' | exe "normal \=" | endif - endfunction - augroup GoyoAu - au! - augroup END - - autocmd User GoyoEnter au GoyoAu BufEnter * if winnr('$') == '5' | exe "normal \=" | endif - autocmd User GoyoLeave augroup GoyoAu | au! | augroup END -endif diff --git a/config/vim/vim-plugin-settings/indentLine.config.vim b/config/vim/vim-plugin-settings/indentLine.config.vim deleted file mode 100644 index 76a40ea..0000000 --- a/config/vim/vim-plugin-settings/indentLine.config.vim +++ /dev/null @@ -1,5 +0,0 @@ - -if utils#hasplug('indentLine') - let g:indentLine_char = '│' - let g:indentLine_setConceal = 0 -endif diff --git a/config/vim/vim-plugin-settings/lightline.vim.config.vim b/config/vim/vim-plugin-settings/lightline.vim.config.vim deleted file mode 100644 index 85e5f4f..0000000 --- a/config/vim/vim-plugin-settings/lightline.vim.config.vim +++ /dev/null @@ -1,136 +0,0 @@ - -" giveup -if utils#hasplug('lightline.vim') - set noshowmode - set laststatus=2 - - " enable bufferline - " let g:bufferline_echo = 1 - - let g:bufferline_inactive_highlight = 'Search' - let g:bufferline_active_highlight = 'Search' - let g:bufferline_forbided_col = 32 - - let g:lightline = { - \ 'colorscheme': 'wombat', - \ 'active': { - \ 'left': [ [ 'mode'], - \ [ 'bufferline'] ], - \ 'right': [['lineinfo'], ['cocstatus']], - \ }, - \ 'inactive': { - \ 'left': [], - \ 'right': [], - \ }, - \ 'component_expand': { - \ 'bufferline': 'BufferlineStr', - \ }, - \ 'component_function': { - \ 'cocstatus': 'AirlineCocStatus', - \ }, - \ } - - - function! s:restore() - let g:lightline.active = { - \ 'left': [ [ 'mode'], - \ [ 'bufferline'] ], - \ 'right': [['lineinfo'], ['cocstatus']], - \ } - call lightline#init() - call lightline#update() - endfunction - - let s:special_ft = ['nerdtree', 'vista'] - let s:special_bt = ['nofile'] - function! s:lightlineInit() - let g:lightline.active = { - \ 'left': [], - \ 'right': [], - \ } - call lightline#init() - call lightline#update() - echom 'hello'. &bt - autocmd WinLeave * ++once call s:restore() - endfunction - - " \ 'bufferline': 'lightline#bufferline#buffers' - augroup Lightline - autocmd! - " autocmd BufWinEnter * call s:lightlineInit() - " autocmd WinNew * call s:funck() - autocmd FileType nerdtree call s:lightlineInit() - " autocmd BufWritePost,TextChanged,TextChangedI,BufNew,BufEnter * call lightline#update() - augroup END - - function! BufferlineStr() - call bufferline#get_echo_string() - let s = bufferline#get_status_string() - return s - endfunction - - function! s:lightline_update() - if !exists('g:loaded_lightline') - return - endif - try - if g:colors_name =~# 'wombat\|solarized\|landscape\|jellybeans\|seoul256\|Tomorrow' - let g:lightline.colorscheme = - \ substitute(substitute(g:colors_name, '-', '_', 'g'), '256.*', '', '') - call lightline#init() - call lightline#colorscheme() - call lightline#update() - endif - catch - endtry - endfunction - - augroup LightlineColorscheme - autocmd! - autocmd ColorScheme * call s:lightline_update() - augroup END - - function! AirlineCocStatus() - if ! exists('*CocAction') - return - endif - let loading = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] - try - let result = CocAction('services') - catch - " call timer_start(200, {->execute('AirlineRefresh')}) - return 'no coc ' - endtry - let state = '' - let id = '' - for e in result - if e['languageIds'][0] == &ft - let state = e['state'] - let id = e['id'] - endif - endfor - if id == '' - return 'no lsp ' - endif - - " messy way to get time in millisecond in vim - let time = float2nr(str2float(reltime()->reltimestr()[4:]) * 1000) - let speed = 800 - let loadidx = time % speed - let msg = id - if state == "starting" - if ! exists('s:cocstatustimer') || len(timer_info(s:cocstatustimer)) == 0 - let s:cocstatustimer = timer_start(100, {->execute('AirlineRefresh')}, {'repeat': 800}) - endif - return msg . " " . loading[loadidx/(speed/10)] . " " - elseif state == "running" - if exists('s:cocstatustimer') - call timer_stop(s:cocstatustimer) - unlet s:cocstatustimer - endif - return msg . " ✔ " - endif - return '' - endfunction - -endif diff --git a/config/vim/vim-plugin-settings/minimap.vim.config.vim b/config/vim/vim-plugin-settings/minimap.vim.config.vim deleted file mode 100644 index 8452a3c..0000000 --- a/config/vim/vim-plugin-settings/minimap.vim.config.vim +++ /dev/null @@ -1,13 +0,0 @@ - -if utils#hasplug('minimap.vim') - nnoremap mm :MinimapToggle - let g:minimap_highlight_search = 1 - let g:minimap_git_colors = 1 - let g:minimap_enable_highlight_colorgroup = 1 - let g:minimap_block_filetypes = ['fugitive', 'nvim-tree', 'tagbar', 'fzf', 'telescope', 'NvimTree', 'nerdtree'] - let g:minimap_block_buftypes = ['help', 'nerdtree', 'nofile', 'nowrite', 'quickfix', 'terminal', 'prompt', 'NvimTree'] - let g:minimap_close_filetypes = ['startify', 'netrw', 'vim-plug', 'NvimTree'] - let g:minimap_range_color = 'Visual' - let g:minimap_cursor_color = 'Cursor' -endif - diff --git a/config/vim/vim-plugin-settings/nerdtree.config.vim b/config/vim/vim-plugin-settings/nerdtree.config.vim deleted file mode 100644 index 80a7094..0000000 --- a/config/vim/vim-plugin-settings/nerdtree.config.vim +++ /dev/null @@ -1,53 +0,0 @@ -if utils#hasplug('nerdtree') - if utils#hasplug('vim-nerdtree-syntax-highlight') - let g:NERDTreeLimitedSyntax = 1 - endif - let g:NERDShutUp=1 - - " work around for nerdtree bug: https://github.com/preservim/nerdtree/issues/1321 - let g:NERDTreeMinimalMenu = v:true - let g:NERDTreeMinimalUI = v:true - - function! NERDTreeFindToggle() - let has_nerdtree = 0 - let winfo = getwininfo() - for obj in winfo - let bufnr = obj['bufnr'] - let ft = getbufvar(bufnr, '&filetype') - if ft == 'nerdtree' - let has_nerdtree = 1 - break - endif - endfor - if has_nerdtree - :NERDTreeClose - else - " we cannot use NERDTreeFind on startify as it is not a file - if &ft == 'startify' || &ft == '' - :NERDTreeToggle - else - :NERDTreeFind - " NERDTreeToggleVCS - endif - endif - endfunction - nnoremap e :call NERDTreeFindToggle() - - "let NERDTreeShowBookmarks=1 - let NERDTreeChDirMode = 0 - let NERDTreeQuitOnOpen = 1 - let NERDTreeMouseMode = 2 - let NERDTreeShowHidden = 1 - - " remapping - let g:NERDTreeMapOpenExpl = '' - if utils#hasplug('vim-devicons') || utils#hasplug('nerdfont.vim') - let NERDTreeDirArrowCollapsible = '' - let NERDTreeDirArrowExpandable = '' - else - " let NERDTreeDirArrowCollapsible = '' - " let NERDTreeDirArrowExpandable = '' - endif - " Exit Vim if NERDTree is the only window remaining in the only tab. - autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() | quit | endif -endif diff --git a/config/vim/vim-plugin-settings/papercolor-theme.config.vim b/config/vim/vim-plugin-settings/papercolor-theme.config.vim deleted file mode 100644 index 7a843a0..0000000 --- a/config/vim/vim-plugin-settings/papercolor-theme.config.vim +++ /dev/null @@ -1,24 +0,0 @@ - -if utils#hasplug('papercolor-theme') - function! CB_dark_tb_enable_PaperColor() - let g:PaperColor_Theme_Options = { - \ 'theme': {'default.dark': { 'transparent_background': 1 }}} - colorscheme PaperColor - endfunction - function! CB_light_tb_enable_PaperColor() - let g:PaperColor_Theme_Options = { - \ 'theme': {'default.light': { 'transparent_background': 1 }}} - colorscheme PaperColor - endfunction - function! CB_dark_tb_disable_PaperColor() - let g:PaperColor_Theme_Options = { - \ 'theme': {'default.dark': { 'transparent_background': 0 }}} - colorscheme PaperColor - endfunction - function! CB_light_tb_disable_PaperColor() - let g:PaperColor_Theme_Options = { - \ 'theme': {'default.light': { 'transparent_background': 0 }}} - colorscheme PaperColor - endfunction -endif - diff --git a/config/vim/vim-plugin-settings/tagbar.config.vim b/config/vim/vim-plugin-settings/tagbar.config.vim deleted file mode 100644 index d668a98..0000000 --- a/config/vim/vim-plugin-settings/tagbar.config.vim +++ /dev/null @@ -1,14 +0,0 @@ -if utils#hasplug('tagbar') - let g:tagbar_width = 30 - let g:tagbar_sort = 0 - let g:tagbar_compact = 2 - let g:tagbar_autoshowtag = 1 - let g:tagbar_foldlevel = 99 - let g:tagbar_no_status_line = 1 - let g:tagbar_visibility_symbols = { - \ 'public' : '+', - \ 'protected' : '#', - \ 'private' : '-' - \ } - nnoremap v TagbarToggle -endif diff --git a/config/vim/vim-plugin-settings/vim-airline.config.vim b/config/vim/vim-plugin-settings/vim-airline.config.vim deleted file mode 100644 index 8e15860..0000000 --- a/config/vim/vim-plugin-settings/vim-airline.config.vim +++ /dev/null @@ -1,159 +0,0 @@ - -if utils#hasplug("vim-airline") - - " Extensions - function! AirlineCocStatus() - if ! exists('*CocAction') - return - endif - let loading = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] - try - let result = CocAction('services') - catch - " call timer_start(200, {->execute('AirlineRefresh')}) - return 'no coc ' - endtry - let state = '' - let id = '' - for e in result - if e['languageIds'][0] == &ft - let state = e['state'] - let id = e['id'] - endif - endfor - if id == '' - return 'no lsp ' - endif - - " messy way to get time in millisecond in vim - let time = float2nr(str2float(reltime()->reltimestr()[4:]) * 1000) - let speed = 800 - let loadidx = time % speed - let msg = id - if state == "starting" - if ! exists('s:cocstatustimer') || len(timer_info(s:cocstatustimer)) == 0 - let s:cocstatustimer = timer_start(100, {->execute('AirlineRefresh')}, {'repeat': 800}) - endif - return msg . " " . loading[loadidx/(speed/10)] . " " - elseif state == "running" - if exists('s:cocstatustimer') - call timer_stop(s:cocstatustimer) - unlet s:cocstatustimer - endif - return msg . " ✔ " - endif - return '' - endfunction - - function! AirlineBufferNumber() - return len(g:index_to_buffer) - endfunction - - " This must use my fork version of bufferline - " the number of cols bufferline cannot use out of max of screen cols - let g:bufferline_forbided_col = 32 - - let g:airline_experimental = g:vim_v >= 900 ? 1 : 0 - - function! AirlineInit() - " call airline#parts#define_function('bufnum', 'AirlineBufferNumber') - call airline#parts#define_function('cocstatus', 'AirlineCocStatus') - call airline#parts#define_minwidth('mode', 10) - let _airline_section_y = '' - if utils#hasplug('coc.nvim') - " let _airline_section_y = airline#section#create(['cocstatus']) - endif - let g:airline_section_a = airline#section#create(['mode']) - let g:airline_section_b = '' - let g:airline_section_error = '' - let g:airline_section_warning = '' - " let g:airline_section_x = airline#section#create(['bufnum']) - let g:airline_section_x = '' - let g:airline_section_y = _airline_section_y - let g:airline_section_z = airline#section#create(['cocstatus', '│ ', '%(%l:%c%)']) - - endfunction - - function! AirlineColouriseSplits() - " get rid of the vertical split between two windows in statusline - hi! link StatusLine airline_z - hi! link StatusLineNC airline_z_inactive - endfunction - - augroup AirlineAu - autocmd! - autocmd ColorScheme * call AirlineColouriseSplits() - autocmd User AirlineAfterInit ++once call AirlineInit() - augroup end - - " let g:airline_left_sep = '' - " let g:airline_left_alt_sep = '' - " let g:airline_right_sep = '' - " let g:airline_right_alt_sep = '' - - function s:airline_refresh(...) - " this has to be set late otherwise it will cause 'mode' extension be - " skipped at startup - let g:airline_skip_empty_sections = 1 - endfunction - call RegisterLateInit(function('s:airline_refresh'), 1) - - " let g:airline_skip_empty_sections = 1 - - let g:airline_inactive_collapse = 1 - let g:airline_focuslost_inactive = 0 - let g:airline_extensions = ['bufferline'] - - let g:airline_filetype_overrides = { - \ 'vista': ['Vista', ''], - \ 'minimap': ['', ''], - \ 'nerdtree': [ get(g:, 'NERDTreeStatusline', 'NERD'), ''], - \ } - - " hide airline in startify - function! HideStartify(...) - let ctx = a:2 - if ! ctx.active - return 1 - end - if &filetype == 'startify' - let builder = a:1 - call builder.add_section('Normal', '') - return 1 - endif - if &filetype == 'help' - let builder = a:1 - call builder.add_section('airline_a_bold', ' Help ') - call builder.add_section('airline_c', ' %f') - return 1 - endif - - endfunction - call airline#add_statusline_func('HideStartify') - - " " without this airline will overwrite some setting like bufferline_active_buffer_left, etc. - let g:airline#extensions#bufferline#overwrite_variables = 0 - " call theme#addTransGroup(['airline_c', 'airline_c_bold']) - " let g:airline_mode_map = { - " \ '__' : '-', - " \ 'c' : 'C', - " \ 'i' : 'I', - " \ 'ic' : 'I', - " \ 'ix' : 'I', - " \ 'n' : 'N', - " \ 'multi' : 'M', - " \ 'ni' : 'N', - " \ 'no' : 'N', - " \ 'R' : 'R', - " \ 'Rv' : 'R', - " \ 's' : 'S', - " \ 'S' : 'S', - " \ '' : 'S', - " \ 't' : 'T', - " \ 'v' : 'V', - " \ 'V' : 'V', - " \ '' : 'V', - " \ } - -endif - diff --git a/config/vim/vim-plugin-settings/vim-bufferline.config.vim b/config/vim/vim-plugin-settings/vim-bufferline.config.vim deleted file mode 100644 index 446303e..0000000 --- a/config/vim/vim-plugin-settings/vim-bufferline.config.vim +++ /dev/null @@ -1,17 +0,0 @@ - -if utils#hasplug("vim-bufferline") - let g:bufferline_echo = 0 - let g:bufferline_modified = '+' - - " scrolling with fixed current buffer position - - let g:bufferline_active_buffer_left = '[' - let g:bufferline_active_buffer_right = ']' - if utils#hasplug("vim-airline") - let g:bufferline_inactive_highlight = 'airline_c' - let g:bufferline_active_highlight = 'airline_c_bold' - elseif ! utils#hasplug("vim-global-statusline") - call bufferline#init_echo() - endif -endif - diff --git a/config/vim/vim-plugin-settings/vim-devicons.config.vim b/config/vim/vim-plugin-settings/vim-devicons.config.vim deleted file mode 100644 index e330a1e..0000000 --- a/config/vim/vim-plugin-settings/vim-devicons.config.vim +++ /dev/null @@ -1,5 +0,0 @@ - -if utils#hasplug("vim-devicons") - let g:webdevicons_enable_airline_statusline = 0 -endif - diff --git a/config/vim/vim-plugin-settings/vim-floaterm.config.vim b/config/vim/vim-plugin-settings/vim-floaterm.config.vim deleted file mode 100644 index 6c1dcad..0000000 --- a/config/vim/vim-plugin-settings/vim-floaterm.config.vim +++ /dev/null @@ -1,53 +0,0 @@ - -if utils#hasplug('vim-floaterm') - let g:floaterm_keymap_toggle = '' - let g:floaterm_wintype = 'float' - let g:floaterm_position = 'bottomright' - let g:floaterm_width = 0.5 - let g:floaterm_height = 0.5 - let g:floaterm_autohide = 2 - - call theme#addCleanBg(['FloatermBorder', 'Floaterm']) - - autocmd QuitPre * :FloatermKill! - - " press ener normal mode in terminal. autocmd prevent this key map - " in other plugin like fzf - autocmd FileType floaterm tmap N - - function! s:hasterm(name) - let bufs = floaterm#buflist#gather() - for bufnr in bufs - let bufinfo = getbufinfo(bufnr)[0] - let termname = bufinfo['variables']['floaterm_name'] - if termname == a:name - return v:true - endif - endfor - return v:false - endfunction - - function! ToggleRepl() - let name = 'REPL' - let currentWindow=winnr() - if s:hasterm(name) - execute('FloatermToggle ' . name) - else - :FloatermNew --name=REPL --width=0.5 --wintype=vsplit --position=botright --autoclose=2 ipython - endif - exe currentWindow . "wincmd w" - endfunction - - function! ToggleNormal() - let name = 'normalterm' - if s:hasterm(name) - execute('FloatermToggle ' . name) - else - :FloatermNew --name=normalterm --width=0.5 --height=0.5 --wintype=float --position=bottomright --autoclose=2 - endif - endfunction - - nnoremap tp :call ToggleRepl() - nnoremap tn :call ToggleNormal() - vnoremap tl :FloatermSend --name=REPL -endif diff --git a/config/vim/vim-plugin-settings/vim-gitgutter.config.vim b/config/vim/vim-plugin-settings/vim-gitgutter.config.vim deleted file mode 100644 index bfaa09a..0000000 --- a/config/vim/vim-plugin-settings/vim-gitgutter.config.vim +++ /dev/null @@ -1,5 +0,0 @@ - -if utils#hasplug('vim-gitgutter') - call theme#addCleanBg(['GitGutterAdd', 'GitGutterChange', 'GitGutterDelete', 'GitGutterChangeDelete']) - nnoremap gt :GitGutterBufferToggle -endif diff --git a/config/vim/vim-plugin-settings/vim-gutentags.config.vim b/config/vim/vim-plugin-settings/vim-gutentags.config.vim deleted file mode 100644 index f40a509..0000000 --- a/config/vim/vim-plugin-settings/vim-gutentags.config.vim +++ /dev/null @@ -1,10 +0,0 @@ - -if utils#hasplug("vim-gutentags") - if exists("*gutentags#statusline()") - set statusline+=%{gutentags#statusline()} - endif - let g:gutentags_trace = 1 - let g:gutentags_cache_dir=g:vim_dir . '/.vimtags/' - let g:gutentags_project_root=['.git', '.hg', '.svn', '.bzr', '_darcs', '_FOSSIL_', '.fslckout', 'src'] -endif - diff --git a/config/vim/vim-plugin-settings/vim-illuminate.config.vim b/config/vim/vim-plugin-settings/vim-illuminate.config.vim deleted file mode 100644 index fd1da18..0000000 --- a/config/vim/vim-plugin-settings/vim-illuminate.config.vim +++ /dev/null @@ -1,35 +0,0 @@ - -if utils#hasplug('vim-illuminate') && g:vim_type == 'vim' " nvim doesn't need this config - let g:Illuminate_highlightUnderCursor = 1 - let g:Illuminate_ftHighlightGroups = { - \ 'vim:blacklist': ['vimLet', 'vimFuncKey', 'vimNotFunc', 'vimOperParen', 'vimLineComment'], - \ 'java:blacklist' : [ 'javaType', 'javaScopeDecl', 'javaMethodDecl', - \ 'javaComment', 'javaStorageClass', 'javaClassDecl', 'javaExternal', - \ 'javaTypedef', 'javaLineComment', 'javaStatement', 'javaCommentTitle', 'javaDocComment' ], - \ 'lua:blacklist' : [ 'luaComment', 'luaCond', 'luaStatement', 'luaFunction' ] - \ } - let g:Illuminate_ftwhitelist = ['vim', 'sh', 'python', 'rust', 'java', - \ 'c', 'cpp', 'javascript', 'typescript', 'lua'] - - " ugly workaround for the bug that illuminate not working after first enter vim - " { - function s:init_illuminate(...) - let bgType = theme#getBgType() - let bg = theme#getHiTerm('Visual', bgType) - if bg != 'NONE' && &bg == 'dark' - execute('hi illuminatedWord '.bgType.'='.bg) - execute('hi illuminatedCurWord '.bgType.'='.bg) - else - hi illuminatedWord cterm=underline gui=underline - hi illuminatedCurWord cterm=underline gui=underline - end - endfunction - call RegisterLateInit(function('s:init_illuminate'), 0) - " } - - augroup illuminate_augroup - autocmd! - autocmd ColorScheme * call s:init_illuminate() - augroup END - -endif diff --git a/config/vim/vim-plugin-settings/vim-matchup.config.vim b/config/vim/vim-plugin-settings/vim-matchup.config.vim deleted file mode 100644 index 9bf46cb..0000000 --- a/config/vim/vim-plugin-settings/vim-matchup.config.vim +++ /dev/null @@ -1,5 +0,0 @@ - -if utils#hasplug('vim-matchup') - let g:matchup_matchparen_offscreen = {} - call theme#addCleanBg('MatchWord') -endif diff --git a/config/vim/vim-plugin-settings/vim-rooter.config.vim b/config/vim/vim-plugin-settings/vim-rooter.config.vim deleted file mode 100644 index 2548501..0000000 --- a/config/vim/vim-plugin-settings/vim-rooter.config.vim +++ /dev/null @@ -1,8 +0,0 @@ - -if utils#hasplug("vim-rooter") - let g:rooter_patterns = ['.vscode', '.git', '*.sln', 'src'] - let g:rooter_change_directory_for_non_project_files = '' - let g:rooter_silent_chdir = 0 - " let g:rooter_manual_only = 1 -endif - diff --git a/config/vim/vim-plugin-settings/vim-sneak.config.vim b/config/vim/vim-plugin-settings/vim-sneak.config.vim deleted file mode 100644 index c4c8311..0000000 --- a/config/vim/vim-plugin-settings/vim-sneak.config.vim +++ /dev/null @@ -1,5 +0,0 @@ -if utils#hasplug("vim-sneak") - let g:sneak#label = 1 - " map f Sneak_s - " map F Sneak_S -endif diff --git a/config/vim/vim-plugin-settings/vim-startify.config.vim b/config/vim/vim-plugin-settings/vim-startify.config.vim deleted file mode 100644 index 7c36c08..0000000 --- a/config/vim/vim-plugin-settings/vim-startify.config.vim +++ /dev/null @@ -1,58 +0,0 @@ - -if utils#hasplug("vim-startify") - if has('nvim') - let buffer_str_len = (&columns - 60) / 2 - let buf_str = repeat(' ', buffer_str_len) - let ascii_art = [ - \ buf_str . '', - \ buf_str . '', - \ buf_str . ' __ __ ________ ______ __ __ ______ __ __ ', - \ buf_str . '| \ | \| \ / \ | \ | \| \| \ / \', - \ buf_str . '| $$\ | $$| $$$$$$$$| $$$$$$\| $$ | $$ \$$$$$$| $$\ / $$', - \ buf_str . '| $$$\| $$| $$__ | $$ | $$| $$ | $$ | $$ | $$$\ / $$$', - \ buf_str . '| $$$$\ $$| $$ \ | $$ | $$ \$$\ / $$ | $$ | $$$$\ $$$$', - \ buf_str . '| $$\$$ $$| $$$$$ | $$ | $$ \$$\ $$ | $$ | $$\$$ $$ $$', - \ buf_str . '| $$ \$$$$| $$_____ | $$__/ $$ \$$ $$ _| $$_ | $$ \$$$| $$', - \ buf_str . '| $$ \$$$| $$ \ \$$ $$ \$$$ | $$ \| $$ \$ | $$', - \ buf_str . ' \$$ \$$ \$$$$$$$$ \$$$$$$ \$ \$$$$$$ \$$ \$$', - \] - else - let buffer_str_len = (&columns - 30) / 2 - let buf_str = repeat(' ', buffer_str_len) - let ascii_art = [ - \ buf_str . '', - \ buf_str . '', - \ buf_str . ' __ __ ______ __ __ ', - \ buf_str . '| \ | \| \| \ / \', - \ buf_str . '| $$ | $$ \$$$$$$| $$\ / $$', - \ buf_str . '| $$ | $$ | $$ | $$$\ / $$$', - \ buf_str . ' \$$\ / $$ | $$ | $$$$\ $$$$', - \ buf_str . ' \$$\ $$ | $$ | $$\$$ $$ $$', - \ buf_str . ' \$$ $$ _| $$_ | $$ \$$$| $$', - \ buf_str . ' \$$$ | $$ \| $$ \$ | $$', - \ buf_str . ' \$ \$$$$$$ \$$ \$$', - \] - endif - - let g:startify_padding_left = &columns / 2 - &columns / 4 - &columns / 8 - let g:startify_custom_header = ascii_art - let g:startify_change_to_dir = 0 - let g:startify_files_number = 5 - - let g:startify_bookmarks = [ g:dotfiledir . 'main.vim' ] - let g:startify_lists = [ - \ { 'header': startify#pad([' RECENT']), 'type': 'files' }, - \ { 'header': startify#pad([' SESSIONS']), 'type': 'sessions' }, - \ { 'header': startify#pad([' BOOKMARKS']), 'type': 'bookmarks' }, - \ ] - - " session related KeyBinding. These KeyBinding uses function from startify - nnoremap s :SSave! - nnoremap l :SLoad - nnoremap d :SDelete! - nnoremap c :SClose - - au VimLeave * SSave! last - -endif - diff --git a/config/vim/vim-plugin-settings/vim-tmux-navigator.config.vim b/config/vim/vim-plugin-settings/vim-tmux-navigator.config.vim deleted file mode 100644 index e895f28..0000000 --- a/config/vim/vim-plugin-settings/vim-tmux-navigator.config.vim +++ /dev/null @@ -1,11 +0,0 @@ - -if utils#hasplug('vim-tmux-navigator') - let g:tmux_navigator_no_mappings = 1 - - noremap :TmuxNavigateLeft - noremap :TmuxNavigateDown - noremap :TmuxNavigateUp - noremap :TmuxNavigateRight - " noremap {Previous-Mapping} :TmuxNavigatePrevious -endif - diff --git a/config/vim/vim-plugin-settings/vim9/fuzzyy.config.vim b/config/vim/vim-plugin-settings/vim9/fuzzyy.config.vim deleted file mode 100644 index 4a470bd..0000000 --- a/config/vim/vim-plugin-settings/vim9/fuzzyy.config.vim +++ /dev/null @@ -1,28 +0,0 @@ -vim9script - -highlight link fuzzyyMatching error -g:fuzzyy_dropdown = 1 -g:enable_fuzzyy_MRU_files = 1 -g:fuzzyy_window_layout = { -FuzzyFiles: { - width: 0.8, -}, -FuzzyMRUFiles: { - preview: 1, -}, -FuzzyBuffers: { - preview: 1, - width: 0.8, - preview_ratio: 0.5, -}, -FuzzyGrep: { - preview: 1, - width: 0.8, - preview_ratio: 0.5, -}, -} -g:fuzzyy_buffers_keymap = { -'delete_buffer': "\", -'close_buffer': "\", -} -nnoremap fl :FuzzyCmdHistory diff --git a/config/vim/vim-plugin-settings/vim9/vim-global-statusline.config.vim b/config/vim/vim-plugin-settings/vim9/vim-global-statusline.config.vim deleted file mode 100644 index ecd1ccc..0000000 --- a/config/vim/vim-plugin-settings/vim9/vim-global-statusline.config.vim +++ /dev/null @@ -1,188 +0,0 @@ -vim9script - -if utils#hasplug('vim-global-statusline') - - g:stl_nonbtbg = 'folded' - g:stl_bg = 'normal' - g:bufferline_forbided_col = 32 - - def ReverseHl(name: string, hl: string) - var hl_terms = theme#getHiTerms(hl) - var normal_terms = theme#getHiTerms('normal') - for [term, val] in items(hl_terms) - if val == 'NONE' - hl_terms[term] = normal_terms[term] - endif - endfor - exe 'hi ' .. name .. ' guibg=' .. hl_terms['guifg'] .. ' guifg=' - .. hl_terms['guibg'] .. ' ctermbg=' .. hl_terms['ctermfg'] - .. ' ctermfg=' .. hl_terms['ctermbg'] - enddef - - def StlHighlight() - hi normalModeGstl cterm=reverse gui=reverse - ReverseHl('insertModeGstl', 'function') - ReverseHl('visualModeGstl', 'statement') - ReverseHl('commandModeGstl', 'number') - enddef - autocmd ColorScheme * StlHighlight() - var mode_color = { - n: 'normalModeGstl', - i: 'insertModeGstl', - v: 'visualModeGstl', - V: 'visualModeGstl', - c: 'commandModeGstl', - } - var mode_str = { - n: ' NORMAL ', - i: ' INSERT ', - v: ' VISUAL ', - V: ' V-LINE ', - c: ' COMMAND ', - } - mode_str[nr2char(22)] = ' V-BLOCK ' - mode_color[nr2char(22)] = 'curSearch' - def Modestr(): void - var m = mode() - if has_key(mode_str, m) - g:StlSetPart(0, mode_str[m], mode_color[m], 'mode') - else - echom char2nr(m) - g:StlSetPart(0, ' ' .. &ft .. ' ', 'TabLineSel', 'mode') - endif - g:StlRefresh() - enddef - - def Fnstr(): void - g:StlSetPart(10, 'filename: ' .. bufname(), '', 'filename') - g:StlRefresh() - enddef - - def Bufstr(): void - var bufstr = bufferline#get_echo_string() - g:StlSetPart(9, ' ' .. bufstr, '', 'bufstr') - g:StlRefresh() - enddef - - def Lncol(): void - var col = virtcol(".") - var ln = line('.') - var m = mode() - var color = '' - if has_key(mode_color, m) - color = mode_color[m] - else - color = 'TabLineSel' - endif - g:StlSetPart(&co - 9, printf(" %d:%d", ln, col), color, 'linenr') - g:StlRefresh() - enddef - - var cocstatustimer = -1 - - def Cocstatus(): string - const loading = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] - var results = [] - var result = '𐄂' - var fticon = '𐄂' - try - if exists('g:CocAction') - results = g:CocAction('services') - endif - catch - endtry - var state = '' - var id = '' - if len(results) == 0 - timer_start(100, function(Lsp)) - endif - for e in results - if e['languageIds'][0] == &ft - state = e['state'] - id = e['id'] - endif - endfor - - # messy way to get time in millisecond in vim - var time = float2nr(str2float(reltime()->reltimestr()[4 : ]) * 1000) - var speed = 800 - var loadidx = time % speed - var msg = id - if state == "starting" - if len(timer_info(cocstatustimer)) == 0 - cocstatustimer = timer_start(100, function(Lsp), {'repeat': 800}) - endif - fticon = loading[loadidx / (speed / 10)] - elseif state == "running" - if len(timer_info(cocstatustimer)) != 0 - timer_stop(cocstatustimer) - cocstatustimer = -1 - endif - if exists('g:WebDevIconsGetFileTypeSymbol') - fticon = g:WebDevIconsGetFileTypeSymbol() - endif - endif - # return fticon .. ' ' .. result - return 'lsp ' .. fticon - enddef - - def Lsp(...timer: list): void - var s = Cocstatus() - g:StlSetPart(&co - 17, ' ' .. s .. ' ', '', 'lsp') - g:StlRefresh() - enddef - - var fancytimer = 0 - def Fancy(...timer: list): void - var expressions = [' (◕_◕)', ' (◕‿◕)', '\(◕◡◕\)', ' (◣_◢)', ' (◣‿◢)', '\(◣◡◣\)', ' (◠‿◠)', ' (◠_◠)', '\(◠◡◠\)', ' (◡‿◡)', ' (◡_◡)', '\(◡◡◡\)', ' (┳Д┳)', ' (个_个)', ' ( ≧Д≦)', ' 흫_흫', ' 句_句'] - - # var letters = [𝔞 𝔟 𝔠 𝔡 𝔢 𝔣 𝔤 𝔥 𝔦 𝔧 𝔨 𝔩 𝔪 𝔫 𝔬 𝔭 𝔮 𝔯 𝔰 𝔱 𝔲 𝔳 𝔴 𝔵 𝔶 𝔷] - - # string "I love you" using unicode letters - var lang = '' - if &ft == 'python' - lang = '𝕻𝖞𝖙𝖍𝖔𝖓' - elseif &ft == 'java' - lang = '𝕵𝖆𝖛𝖆' - elseif &ft == 'javascript' - lang = '𝕵𝖆𝖛𝖆𝖘𝖈𝖗𝖎𝖕𝖙' - elseif &ft == 'lua' - lang = '𝕷𝖚𝖆' - elseif &ft == 'vim' - lang = '𝓥𝓲𝓶 𝓢𝓬𝓻𝓲𝓹𝓽' - else - lang = &ft - endif - var str = lang .. ' 𝔦𝔰 𝔱𝔥𝔢 𝔟𝔢𝔰𝔱 𝔩𝔞𝔫𝔤𝔲𝔞𝔤𝔢' - - # fancytimer = (fancytimer + 1) % len(str) - g:StlSetPart(&co - 27 - strcharlen(str), str, '', 'fancy') - enddef - - def Theme(): void - # const light = '☀' - # const dark = '☽' - const light = '🌕' - const dark = '🌑' - var theme = &bg == 'light' ? light : dark - g:StlSetPart(&co - 23, '│ ' .. theme, '', 'bgc') - g:StlRefresh() - enddef - - def EnterInit(): void - # Theme() - Lncol() - Lsp() - # autocmd GlobalStl ColorScheme * Theme() - enddef - - augroup GlobalStl - autocmd! - autocmd VimEnter,ModeChanged * Modestr() | Lncol() - autocmd BufEnter,BufDelete,BufWritePost * Bufstr() | Modestr() - autocmd CursorHold * Lncol() - autocmd BufEnter,BufReadPost * Lsp() - autocmd VimEnter * EnterInit() - augroup END - -endif diff --git a/config/vim/vim-plugin-settings/vimtex.config.vim b/config/vim/vim-plugin-settings/vimtex.config.vim deleted file mode 100644 index 1e52737..0000000 --- a/config/vim/vim-plugin-settings/vimtex.config.vim +++ /dev/null @@ -1,7 +0,0 @@ -if utils#hasplug('vimtex') - noremap lc :VimtexCompile - noremap lv :VimtexView - if g:os == 'Darwin' - let g:vimtex_view_method = 'skim' - endif -endif diff --git a/config/vim/vim-plugin-settings/vista.vim.config.vim b/config/vim/vim-plugin-settings/vista.vim.config.vim deleted file mode 100644 index b83ddfe..0000000 --- a/config/vim/vim-plugin-settings/vista.vim.config.vim +++ /dev/null @@ -1,60 +0,0 @@ - -if utils#hasplug('vista.vim') - let g:vista_default_executive = 'vim_lsp' - if utils#hasplug('coc.nvim') - let g:vista_default_executive = 'coc' - elseif executable('ctags') - let g:vista_default_executive = 'ctags' - endif - nnoremap v :Vista!! - let g:vista_cursor_delay = 0 - let g:vista_echo_cursor = 0 - let g:vista_echo_cursor_strategy = 'floating_win' - let g:vista_close_on_jump = 0 - let g:vista_floating_delay = 0 - let g:vista_ignore_kinds = ['Variable', 'Field', 'EnumMember', - \ 'String', 'Object', 'Array', 'Constant', 'Package', 'Boolean', 'Number' - \ ] - let g:vista_floating_border = 'rounded' - let g:vista_disable_statusline = 1 - " let g:vista_keep_fzf_colors = 1 - let g:vista_update_on_text_changed_delay = 0 - let g:vista_update_on_text_changed = 1 - let g:vista#renderer#enable_kind = 1 - let g:vista#renderer#enable_icon = 1 - - " return to last position of vista - let g:vista_last_row = v:null - function! VistaCursorJump() - " let found = vista#util#BinarySearch(g:vista.raw, line('.'), 'line', '') - let found = g:vista_last_row - if empty(found) - return - endif - let vlnum = get(found, 'vlnum', v:null) - call cursor(vlnum, 3) - endfunction - - " save tag for VistaCursorJump use - function! VistaH2() - if exists('*vista#util#BinarySearch') - let bufs = map(filter(copy(getbufinfo()), 'v:val.listed'), 'v:val.bufnr') - if index(bufs, bufnr('%')) < 0 - return - endif - let found = vista#util#BinarySearch(g:vista.raw, line('.'), 'line', '') - if empty(found) - return - endif - let g:vista_last_row = found - endif - endfunction - - augroup VistaAu - autocmd! - autocmd BufLeave * call VistaH2() - autocmd FileType vista call VistaCursorJump() - augroup END - -endif - diff --git a/config/vim/vim-plugin-settings/wilder.nvim.config.vim b/config/vim/vim-plugin-settings/wilder.nvim.config.vim deleted file mode 100644 index c54535b..0000000 --- a/config/vim/vim-plugin-settings/wilder.nvim.config.vim +++ /dev/null @@ -1,31 +0,0 @@ - -if utils#hasplug('wilder.nvim') - - call wilder#setup({ - \ 'modes': [':'], - \ 'next_key': '', - \ 'previous_key': '', - \ 'enable_cmdline_enter': 0, - \ }) - - call wilder#set_option('pipeline', [ - \ wilder#debounce(10), - \ wilder#branch( - \ wilder#cmdline_pipeline({'language': g:vim_type == 'nvim' ? 'python' : 'vim'}), - \ ), - \ ]) - - if g:vim_type == 'vim' - call wilder#set_option('renderer', wilder#popupmenu_renderer()) - else - call wilder#set_option('renderer', wilder#popupmenu_renderer( - \ wilder#popupmenu_border_theme({ - \ 'highlights': { - \ 'default': 'Normal', - \ }, - \ 'pumblend': 20, - \ 'border': 'rounded', - \ }))) - endif -endif - diff --git a/config/vim/vim-plugin-settings/winresizer.config.vim b/config/vim/vim-plugin-settings/winresizer.config.vim deleted file mode 100644 index a1f4d17..0000000 --- a/config/vim/vim-plugin-settings/winresizer.config.vim +++ /dev/null @@ -1,8 +0,0 @@ - -if utils#hasplug("winresizer") - let g:winresizer_vert_resize = 2 - let g:winresizer_horiz_resize = 2 - " nnoremap r :WinResizerStartResize - let g:winresizer_start_key = 'r' -endif - diff --git a/config/vim/vim-plugin-settings/zoxide.vim.config.vim b/config/vim/vim-plugin-settings/zoxide.vim.config.vim deleted file mode 100644 index 2d182b8..0000000 --- a/config/vim/vim-plugin-settings/zoxide.vim.config.vim +++ /dev/null @@ -1,3 +0,0 @@ -if utils#hasplug("zoxide.vim") - -endif diff --git a/config/wezterm/.wezterm.lua b/config/wezterm/.wezterm.lua deleted file mode 100644 index 53be375..0000000 --- a/config/wezterm/.wezterm.lua +++ /dev/null @@ -1 +0,0 @@ -local wezterm = require 'wezterm' diff --git a/configg b/configg deleted file mode 100644 index e69de29..0000000 diff --git a/install.sh b/install.sh index 04cf6d8..5e2e400 100755 --- a/install.sh +++ b/install.sh @@ -1,375 +1,155 @@ #!/usr/bin/env bash -############################ SETUP PARAMETERS +set -Eeuo pipefail -app_name='dotfiles' +readonly APP_NAME='dotfiles' +readonly REPO_URI="${REPO_URI:-https://github.com/Donaldttt/dotfiles.git}" +readonly REPO_BRANCH="${REPO_BRANCH:-main}" -[ -z "$APP_PATH" ] && APP_PATH="$HOME/.$app_name" -[ -z "$REPO_URI" ] && REPO_URI="https://github.com/Donaldttt/$app_name" -[ -z "$REPO_BRANCH" ] && REPO_BRANCH='main' -# [ -z "$REPO_URI" ] && REPO_URI="https://gitlab.com/tangnachuan1208/$app_name" -# [ -z "$REPO_BRANCH" ] && REPO_BRANCH='gitlab' -[ -z "$VIM_RTPATH" ] && VIM_RTPATH="$HOME/.vim" +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" 2>/dev/null && pwd -P || true)" +if [[ -n "$SCRIPT_DIR" && -e "$SCRIPT_DIR/.git" ]]; then + APP_PATH="${APP_PATH:-$SCRIPT_DIR}" +else + APP_PATH="${APP_PATH:-$HOME/.$APP_NAME}" +fi +readonly APP_PATH +readonly VIM_PATH="${VIM_PATH:-$HOME/.vim}" +readonly MANAGED_START='# >>> dotfiles >>>' +readonly MANAGED_END='# <<< dotfiles <<<' +info() { printf '\033[34m[•]\033[0m %s\n' "$*"; } +success() { printf '\033[32m[✔]\033[0m %s\n' "$*"; } +warn() { printf '\033[33m[!]\033[0m %s\n' "$*" >&2; } +die() { printf '\033[31m[✘]\033[0m %s\n' "$*" >&2; exit 1; } -############################ BASIC SETUP TOOLS -msg() { - printf '%b\n' "$1" >&2 +usage() { + cat <<'EOF' +Usage: ./install.sh [all|vim|shell|tmux]... + +With no arguments, installs every component. Components can be combined, for +example: ./install.sh vim tmux +EOF } -success() { - msg "\33[32m[✔]\33[0m ${1}${2}" +require() { + command -v "$1" >/dev/null 2>&1 || die "Required program not found: $1" } -fail() { - msg "\33[31m[✘]\33[0m ${1}${2}" +ensure_repo() { + require git + if [[ -d "$APP_PATH/.git" ]]; then + return + fi + [[ ! -e "$APP_PATH" ]] || die "$APP_PATH exists but is not a Git repository." + info "Cloning $REPO_URI into $APP_PATH" + git clone --branch "$REPO_BRANCH" --depth 1 "$REPO_URI" "$APP_PATH" } -fatal_error() { - msg "\33[31m[✘]\33[0m ${1}${2}" - exit 1 +backup_path() { + local target=$1 + if [[ -e "$target" || -L "$target" ]]; then + local backup="${target}.backup.$(date +%Y%m%d_%H%M%S)" suffix=0 + while [[ -e "$backup" || -L "$backup" ]]; do + ((suffix += 1)) + backup="${target}.backup.$(date +%Y%m%d_%H%M%S).$suffix" + done + mv -- "$target" "$backup" + warn "Backed up $target to $backup" + fi } -program_exists() { - local ret='0' - command -v $1 >/dev/null 2>&1 || { local ret='1'; } - - # fail on non-zero return value - if [ "$ret" -ne 0 ]; then - return 1 - fi - return 0 +link_config() { + local source=$1 target=$2 current='' + if [[ -L "$target" ]]; then + current=$(readlink "$target" || true) + [[ "$current" == "$source" ]] && return + fi + backup_path "$target" + ln -s "$source" "$target" + success "Linked $target -> $source" } -# check if file $2 contain string $1 -# return 0 if exists -# 1 not contain string -# 2 file not exist -# when using this function: -# file path should not be quoted but like this: -# file_contains 'abc' file_path -file_contains(){ - if [ -f "$2" ]; then - a=`grep "$1" $2` - [ "$a" != '' ] && return 0 - return 1 - fi - return 2 +remove_managed_block() { + local file=$1 temp + [[ -f "$file" ]] || return + temp=$(mktemp) + awk -v start="$MANAGED_START" -v end="$MANAGED_END" ' + $0 == start { managed = 1; next } + $0 == end { managed = 0; next } + !managed { print } + ' "$file" > "$temp" + cat "$temp" > "$file" + rm -f "$temp" } -program_must_exist() { - program_exists $1 +install_vim() { + require vim + require curl + if ! vim --clean -Nu NONE -n -es \ + '+if v:version < 900 | cquit | endif' '+qall'; then + die 'Vim 9 or newer is required.' + fi - # throw error on non-zero return value - if [ "$?" -ne 0 ]; then - fatal_error "You must have '$1' installed to continue." - fi + link_config "$APP_PATH/.vimrc" "$HOME/.vimrc" + mkdir -p "$VIM_PATH/autoload" + local temp + temp=$(mktemp) + curl --fail --location --silent --show-error \ + https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim \ + --output "$temp" + mv "$temp" "$VIM_PATH/autoload/plug.vim" + vim -Nu "$APP_PATH/.vimrc" -n -es \ + '+set nomore' '+PlugInstall --sync' '+qall' + success 'Installed Vim configuration and plugins.' } -env_set() { - if [ -z "$1" ]; then - fatal_error "You must have your $1 environmental variable set to continue." - exit 1 - fi +install_shell() { + local bashrc="$HOME/.bashrc" quoted_source + touch "$bashrc" + remove_managed_block "$bashrc" + printf -v quoted_source '%q' "$APP_PATH/bash_tools.sh" + { + printf '\n%s\n' "$MANAGED_START" + printf '[ -r %s ] && source %s\n' "$quoted_source" "$quoted_source" + printf 'command -v zoxide >/dev/null 2>&1 && eval "$(zoxide init bash)"\n' + printf '%s\n' "$MANAGED_END" + } >> "$bashrc" + success "Installed managed Bash block in $bashrc" } -try_symlink() { - local source_path="$1" - local symlink_path="$2" - if [ -e "$source_path" ]; then - ln -sf "$source_path" "$symlink_path" - msg "Create symlink $symlink_path points to $source_path" - return 0 - fi - return 1 +install_tmux() { + require tmux + link_config "$APP_PATH/.tmux.conf" "$HOME/.tmux.conf" + local tpm="$HOME/.tmux/plugins/tpm" + if [[ ! -d "$tpm/.git" ]]; then + [[ ! -e "$tpm" ]] || die "$tpm exists but is not a Git repository." + mkdir -p "$(dirname "$tpm")" + git clone --depth 1 https://github.com/tmux-plugins/tpm "$tpm" + fi + success 'Installed tmux configuration and TPM.' } -############################ SETUP FUNCTIONS +main() { + case "${1:-}" in + -h|--help) usage; return ;; + esac -backup_file() { - local original_file=$1 - if [ -f "$original_file" ] && [ ! -L "$original_file" ]; then - today=`date +%Y%m%d_%s` - mv -v "$original_file" "$original_file.$today"; - success "Your file $original_file has been backed up as $original_file.$today" - fi + ensure_repo + local components=("$@") component + ((${#components[@]})) || components=(all) + for component in "${components[@]}"; do + case "$component" in + all) + install_vim + install_shell + install_tmux + ;; + vim) install_vim ;; + shell) install_shell ;; + tmux) install_tmux ;; + *) usage; die "Unknown component: $component" ;; + esac + done } -# Usage: sync_repo path url -# -# This function try to clone git repo host in @url -# to @path. If @path alreay exsits, it will simply -# update the repo -sync_repo() { - local repo_path="$1" - local repo_uri="$2" - local repo_branch="$3" - local repo_name="$4" - - if [ ! -e "$repo_path" ]; then - msg "Trying to clone $repo_name" - mkdir -p "$repo_path" - git clone -b "$repo_branch" "$repo_uri" "$repo_path" - ret="$?" - success "Successfully cloned $repo_name." - else - msg "Trying to update $repo_name" - cd "$repo_path" && git pull origin "$repo_branch" - ret="$?" - success "Successfully updated $repo_name" - fi -} - -# simply clone a repo -sync_repo_default() { - local repo_uri="$1" - local repo_path="$2" - - if [ ! -e "$repo_path" ]; then - msg "Trying to clone repo" - mkdir -p "$repo_path" - git clone "$repo_uri" "$repo_path" - ret="$?" - success "Successfully cloned repo." - else - msg "Trying to update repo" - cd "$repo_path" && git pull - ret="$?" - success "Successfully updated repo" - fi -} - -setup_vimplug() { - - # if vimplug is already installed - # comment out since this can update vimplug - #if [ -e "~/.vim/autoload/plug.vim" ]; then - # return 0 - #fi - - mkdir -p "$VIM_RTPATH/autoload" - # setup for vim - curl -fLo ~/.vim/autoload/plug.vim --create-dirs \ - https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim > /dev/null 2>&1 - - local system_shell="$SHELL" - export SHELL='/bin/sh' - - vim \ - "+set nomore" \ - "+PlugInstall!" \ - "+qall" - - export SHELL="$system_shell" - success "Plugins' updated/installed using vim-plug \n(Be careful some plugins may not be installed since they require to use neovim or higher vim version. To intall them, run :PlugInstall inside correct version)" -} - -set_up_nvim() { - if program_exists "nvim"; then - nvim_dir="$HOME/.config/nvim" - nvim_config="$nvim_dir/init.vim" - mkdir -p $nvim_dir - msg "Found neovim." - if [ -f "$nvim_config" ]; then - msg "Found init.vim. backing up it" - mv $nvim_config "${nvim_config}.backup" - fi - echo "set runtimepath^=~/.vim runtimepath+=~/.vim/after -let &packpath=&runtimepath -source ~/.vimrc" > $nvim_config - success "Neovim config setup successed" - else - fail "Neovim config is not setup(neovim not installed)" - fi -} - -# tmux plugin manager -set_up_tpm() { - - echo "Install TPM(tmux plugin manager)?('y' install; 'other keys' nope)" - read -r respond - if [ "$respond" = "y" ] || [ "$respond" = "yes" ]; then - local url="https://github.com/tmux-plugins/tpm" - sync_repo_default "$url" "$HOME/.tmux/plugins/tpm" - success "TPM installed" - else - fail "TPM not installed" - fi -} - -set_up_tmux() { - if program_exists "tmux"; then - backup_file "$HOME/.tmux.conf" - try_symlink "$APP_PATH/.tmux.conf" "$HOME/.tmux.conf" && \ - success "Tmux config setup successed" - set_up_tpm - else - fail "Tmux config is not setup(tmux not installed)" - fi -} - -set_up_vim() { - if ! program_exists "vim" && ! program_exists "nvim" ; then - fatal_error "You must have 'vim' or 'nvim(neovim)' installed to continue." - fi - program_must_exist "git" - program_must_exist "curl" - - sync_repo "$APP_PATH" \ - "$REPO_URI" \ - "$REPO_BRANCH" \ - "$app_name" - - backup_file "$HOME/.vimrc" - backup_file "$HOME/.vimrc.bundles" - - try_symlink "$APP_PATH/.vimrc" "$HOME/.vimrc" - try_symlink "$APP_PATH/.vimrc.bundles" "$HOME/.vimrc.bundles" - - success "Setting up symlinks for vim configuration" - set_up_nvim - setup_vimplug -} - -# zoxide requres extra shell configuration setup -set_up_zoxide_shell_config() { - local source_cmd_zsh='eval "$(zoxide init zsh)"' - local source_cmd_bash='eval "$(zoxide init bash)"' - if program_exists "zsh"; then - # if not already contain source command - file_contains "$source_cmd_zsh" ~/.zshrc - status_code=$? - if [ "$status_code" != '0' ]; then - echo "Install zoxide source command ($source_cmd_zsh) for zsh shell?('y' install; others no)" - read -r respond - if [ "$respond" = "y" ] || [ "$respond" = "yes" ]; then - echo "$source_cmd_zsh" >> $HOME/.zshrc - success "add ($source_cmd_zsh) to zsh" - else - fail "not adding ($source_cmd_zsh) to zsh" - fi - else - success "($source_cmd_zsh) is already in zsh" - fi - fi - - if program_exists "bash"; then - # if not already contain source command - file_contains "$source_cmd_bash" ~/.bashrc - status_code=$? - if [ "$status_code" != '0' ]; then - echo "Install zoxide source command ($source_cmd_bash) for bash shell?('y' install; others no)" - read -r respond - if [ "$respond" = "y" ] || [ "$respond" = "yes" ]; then - echo "$source_cmd_bash" >> $HOME/.bashrc - success "add ($source_cmd_bash) to bash" - else - fail "not adding ($source_cmd_bash) to bash" - fi - else - success "($source_cmd_bash) is already in bash" - fi - fi -} - -set_up_zoxide() { - # https://github.com/ajeetdsouza/zoxide - - if program_exists "zoxide"; then - success "zoxide is already installed" - set_up_zoxide_shell_config - return 0 - fi - - echo "Install zoxide (smart cd like autojump)?('y' install; 'other keys' nope)" - read -r respond - if [ "$respond" = "y" ] || [ "$respond" = "yes" ]; then - program_must_exist "curl" - # This will install zoxide into ~/.local - curl -sS https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | bash - set_up_zoxide_shell_config - - else - fail "zoxide is not installed" - fi -} -set_up_fish(){ - local source_cmd="source $APP_PATH/config/fish/config.fish" - local fish_config="$HOME/.config/fish/config.fish" - if program_exists "fish"; then - # if not already contain source command - file_contains "$source_cmd" $fish_config - status_code=$? - if [ "$status_code" != '0' ]; then - echo "Install fish configuration script for fish shell?('y' install; 'other keys' nope)" - read -r respond - if [ "$respond" = "y" ] || [ "$respond" = "yes" ]; then - echo "$source_cmd" >> $fish_config - success "fish configuration is sourced in $fish_config" - else - fail "Configuration is not sourced in fish" - fi - else - success "fish script is already sourced" - fi - fi -} - -set_up_bash_tool(){ - local source_cmd="source $APP_PATH/bash_tools.sh" - local source_cmd2="source ~/.$app_name/bash_tools.sh" - if program_exists "zsh"; then - # if not already contain source command - file_contains "$source_cmd" ~/.zshrc - status_code=$? - if [ "$status_code" != '0' ]; then - file_contains "$source_cmd2" ~/.zshrc - status_code=$? - fi - if [ "$status_code" != '0' ]; then - echo "Install terminal configuration script for zsh shell?('y' install; 'other keys' nope)" - read -r respond - if [ "$respond" = "y" ] || [ "$respond" = "yes" ]; then - echo "$source_cmd" >> $HOME/.zshrc - success "Terminal configuration is sourced in zsh" - else - fail "Configuration is not sourced in zsh" - fi - else - success "zsh script is already sourced" - fi - fi - - if program_exists "bash"; then - # if not already contain source command - file_contains "$source_cmd" ~/.bashrc - status_code=$? - if [ "$status_code" != '0' ]; then - file_contains "$source_cmd2" ~/.bashrc - status_code=$? - fi - if [ "$status_code" != '0' ]; then - echo "Install terminal configuration script for bash shell?('y' install; 'other keys' nope)" - read -r respond - if [ "$respond" = "y" ] || [ "$respond" = "yes" ]; then - echo "$source_cmd" >> $HOME/.bashrc - success "Terminal configuration is sourced in bash" - else - fail "Configuration is not sourced in bash" - fi - else - success "bash script is already sourced" - fi - fi -} - -############################ MAIN() -env_set "$HOME" - -set_up_vim -set_up_tmux -set_up_bash_tool -set_up_fish -set_up_zoxide - -msg "\nThanks for installing $app_name." +main "$@" diff --git a/main.vim b/main.vim deleted file mode 100644 index 71749e6..0000000 --- a/main.vim +++ /dev/null @@ -1,305 +0,0 @@ -" (jump to the topic) -" -" OPTIONS -" PLUGIN_INSTALL -" UTILITIES -" PLUGIN_CONFIGURATION " THEME_CONFIGURATION -" KEY_MAPS -" OTHER_CONFIGS - -let g:high_performence = v:false -let g:autocomplte_enable = v:true -let g:copilot_enable = v:true - -" only in nvim (using which-key) -let g:key_prompt = v:false - -" only used by neovim -let g:classic_vim_ui = v:true -let g:animation_enable = v:false - -let g:swap_dict = [ - \ ['v:false', '0', 'dark', 'false' ], - \ ['v:true' , '1', 'light', 'true']] -" convinient function to swap between two options -nmap t :call utils#swapword() - -"""""" PLUGIN_INSTALL """""" - -let g:dotvimdir = expand(g:dotfiledir . 'config/vim/') -let g:plugin_dir = expand(g:vim_dir . 'plugged/') - -let g:theme_config_path = expand(g:vim_dir . ".config.vim") - -call plug#begin(g:plugin_dir) - " https://github.com/junegunn/vim-plug/wiki/tips - function! Cond(cond, ...) - let opts = get(a:000, 0, {}) - return a:cond ? opts : extend(opts, { 'on': [], 'for': [] }) - endfunction - let g:animation_enable = g:high_performence ? v:false : g:animation_enable - - if !g:high_performence - Plug 'aditya-azad/candle-grey' - Plug 't184256/vim-boring' - Plug 'tek256/simple-dark' - Plug 'sainnhe/everforest' - Plug 'bluz71/vim-moonfly-colors', { 'as': 'moonfly' } - Plug 'cocopon/iceberg.vim' - Plug 'catppuccin/nvim', Cond( has('nvim-0.8.2') \|\| g:vim_v >= 900 , { 'as': 'catppuccin' }) - Plug 'NLKNguyen/papercolor-theme' - Plug 'EdenEast/nightfox.nvim', Cond(has('nvim-0.5')) - Plug 'projekt0n/github-nvim-theme', Cond(has('nvim-0.5'), { 'tag': 'v0.0.7' }) - Plug 'folke/tokyonight.nvim', Cond(g:vim_type == 'nvim', { 'branch': 'main' }) - Plug 'andymass/vim-matchup' - endif - Plug 'Donaldttt/fuzzyy' - " Plug '~/repo/PR/fuzzyy-files' - " let g:fuzzyy_files_ignore_file = ['configg'] - " let g:fuzzyy_files_ignore_dir = ['config', '.git'] - " let g:fuzzyy_files_ignore_file = [] - " let g:fuzzyy_files_ignore_dir = [] - Plug 'tpope/vim-repeat' - Plug 'tpope/vim-fugitive' - Plug 'tpope/vim-surround' - " Plug 'lervag/vimtex' - Plug 'github/copilot.vim', Cond(( g:vim_type == 'nvim' \|\| g:vim_v >= 900 ) - \ && g:copilot_enable && executable('node')) - - Plug 'nanotee/zoxide.vim', Cond(executable('zoxide')) - - Plug 'godlygeek/tabular' - - Plug 'preservim/vim-markdown' - - Plug 'dstein64/vim-startuptime', Cond(!g:high_performence) - Plug 'simeji/winresizer', Cond(!g:high_performence) - " Plug 'rust-lang/rust.vim', { 'for': ['rust'] } - - Plug 'rhysd/conflict-marker.vim' - - Plug 'jiangmiao/auto-pairs' - " Plug 'mg979/vim-visual-multi' - Plug 'RRethy/vim-illuminate', Cond(!g:high_performence) - " Plug 'ludovicchabant/vim-gutentags' - " Plug 'ctrlpvim/ctrlp.vim' - - "" ESSENTIAL_PLUGINS "" - - Plug 'mhinz/vim-startify' - Plug 'christoomey/vim-tmux-navigator' - " Comment stuff out - Plug 'tpope/vim-commentary' - Plug 'vim-scripts/restore_view.vim' - - " vim only plugins - Plug 'scrooloose/nerdtree', Cond(g:vim_type == 'vim' \|\| !has('nvim-0.8'), { 'on' : ['NERDTreeToggle', 'NERDTreeFind'] }) - Plug 'tiagofumo/vim-nerdtree-syntax-highlight', Cond(g:vim_type == 'vim' && !g:high_performence) - - Plug 'neoclide/coc.nvim', Cond(g:autocomplte_enable && executable('node'), {'branch': 'release'}) - " only work with vim - if g:vim_type == 'vim' - if executable('ctags') - Plug 'preservim/tagbar' - else - Plug 'liuchengxu/vista.vim', Cond(!g:high_performence) - endif - - Plug 'airblade/vim-rooter' - " Plug 'justinmk/vim-sneak' - Plug 'airblade/vim-gitgutter' - Plug 'chriskempson/base16-vim' - " Plug 'Yggdroot/indentLine' - " Plug 'Donaldttt/fzf-color-preview', Cond(g:vim_v >= 800, { 'on': ['ColorsPreview', 'AirlinePreview'] }) - - Plug 'markonm/traces.vim' - " Plug 'voldikss/vim-floaterm', Cond(has('terminal') && g:vim_type == 'vim') - set encoding=UTF-8 - " Plug 'junegunn/fzf', { 'do': { -> fzf#install() } } - " Plug 'junegunn/fzf.vim' - " Plug 'antoinemadec/coc-fzf', Cond(g:os != 'Windows', {'on': ['CocFzfList']}) - - Plug 'Donaldttt/vim-bufferline' - - Plug 'Donaldttt/vim-global-statusline', { 'branch': 'vim9' } - " Plug 'vim-airline/vim-airline' - " Plug 'vim-airline/vim-airline-themes' - - Plug 'ryanoasis/vim-devicons' - " Plug 'wfxr/minimap.vim', Cond(executable('code-minimap'), {'on' : ['MinimapToggle']}) - endif - - if g:vim_type == 'nvim' - Plug 'RRethy/nvim-base16' - - if has('nvim-0.5') - " Plug 'hkupty/iron.nvim' - " Plug 'metakirby5/codi.vim' - Plug 'lukas-reineke/indent-blankline.nvim', Cond(!g:animation_enable) - Plug 'echasnovski/mini.indentscope', Cond(g:animation_enable) - Plug 'echasnovski/mini.animate', Cond(g:animation_enable) - - Plug 'nvim-lualine/lualine.nvim' - Plug 'petertriho/nvim-scrollbar', Cond(g:animation_enable) - Plug 'folke/which-key.nvim', Cond(!g:high_performence && g:key_prompt) - Plug 'ahmedkhalf/project.nvim' - endif - if has('nvim-0.7') - Plug 'stevearc/aerial.nvim' - Plug 'nvim-treesitter/nvim-treesitter', Cond(executable('make'), {'do': ':TSUpdate'}) - - " for telescope - Plug 'nvim-lua/plenary.nvim' - Plug 'nvim-telescope/telescope.nvim', Cond(g:vim_type == 'nvim', { 'branch': '0.1.x' }) - " c plugin for telescope to make it faster - Plug 'nvim-telescope/telescope-fzf-native.nvim', Cond(executable('make'), { 'do': 'make' }) - - " comment out this plugin if the machine doesn't have required - " font install - Plug 'nvim-tree/nvim-web-devicons' - " Plug 'akinsho/toggleterm.nvim', Cond(g:vim_type == 'nvim', {'tag' : '*'}) - - Plug 'ggandor/leap.nvim' - endif - if has('nvim-0.8') - Plug 'nvim-tree/nvim-tree.lua' - Plug 'lewis6991/gitsigns.nvim' - - Plug 'rcarriga/nvim-notify', Cond(!g:high_performence && !g:classic_vim_ui) - Plug 'folke/noice.nvim', Cond(!g:high_performence && !g:classic_vim_ui) - Plug 'MunifTanjim/nui.nvim', Cond(!g:high_performence && !g:classic_vim_ui) - endif - - " nvim theme - if has('nvim-0.9') - Plug 'rebelot/kanagawa.nvim' - Plug 'rose-pine/neovim', { 'as': 'rose-pine' } - endif - endif - - " custom plugin - Plug g:dotvimdir -call plug#end() - - -augroup InitConfig - " Automatically install missing plugins at startup - autocmd VimEnter * - \ if len(filter(values(g:plugs), '!isdirectory(v:val.dir)')) - \| PlugInstall --sync | q - \| endif -augroup end - -"""""" UTILITIES """""" - -" a list of funcref that will be initilized late -let g:post_init_func = [] - -function RegisterLateInit(func, delay, ...) - let Funcref = type(a:func) == 10 ? func : function(a:func) - let obj = [Funcref, a:delay, a:000] - call add(g:post_init_func, obj) -endfunction - -function s:executeLateInit() - function s:lateInitHelper(...) - for obj in g:post_init_func - let Funcref = obj[0] - let delay = obj[1] - let args = obj[2] - if delay == 0 - if len(args) > 0 - call Funcref(args) - else - call Funcref() - endif - else - call timer_start(delay, Funcref) - endif - endfor - endfunction - autocmd VimEnter * call s:lateInitHelper() -endfunction - -" source lua library - -"""""" THEME_CONFIGURATION """""" -nmap db :call utils#showHiGroup() - - """ THEME_OPTIONS """ - -call theme#Init() - -"""""" KEY_MAPS """""" -" (This doesn't include plugin specific mapping. -" For them check plugin Preferences) - -nnoremap ws :call utils#trimwhitespace() - -" Toggle dark/light theme -noremap cbg :call theme#toggleBg() - -" Toggle transparent background -noremap ctb :call theme#toggleTransparent() - -" Buffer navigation -nnoremap q :bprevious -nnoremap e :bnext - -" leader s change all occurence -nnoremap s :%s/\<\>/ - -noremap h :noh " turn off highlight - -" disable two easily mispressed yet useless key -nnoremap q: -nnoremap Q - -" we often press shift key by mistake -command WQ wq -command Wq wq -command W w -command Q q - -" leader num change tab -" only for vim or nvim without lualine - -if (g:vim_type == 'vim' || !has('nvim-0.5')) && utils#hasplug('vim-bufferline') - for i in range(1, 9) - execute "nnoremap " . i . - \ " :call bufferline#jump(" . i . ")" - endfor - for i in range(10, 20) - execute "nnoremap " . i . - \ " :call bufferline#jump(" . i . ")" - endfor -end - -" split window comform with other window management shortcuts -nnoremap % :vsplit -nnoremap " :split - -" source all vim specific config eg. gui vim -for f in split(glob(g:dotvimdir.'/configs/*-config.vim'), '\n') - exe 'source' f -endfor - -" source all vim plugin config -for f in split(glob(g:dotvimdir.'/vim-plugin-settings/*.config.vim'), '\n') - exe 'source' f -endfor - -" source all vim9 plugin configs -if g:vim_v >= 900 -for f in split(glob(g:dotvimdir.'/vim-plugin-settings/vim9/*.config.vim'), '\n') - exe 'source' f -endfor -endif - -" source lua plugins if in neovim -if has('nvim') - lua require('lua-plugin-settings') -endif - - -call s:executeLateInit() diff --git a/test.vim b/test.vim deleted file mode 100644 index c075384..0000000 --- a/test.vim +++ /dev/null @@ -1,32 +0,0 @@ -vim9script - -def Fuzzysearch9(li: list, pattern: string, limit: number): list - var opts = {} - if limit > 0 - opts['limit'] = limit - endif - var results: list = matchfuzzypos(li, pattern, opts) - var strs = results[0] - var poss = results[1] - var scores = results[2] - - # if limit > 0 - # strs = strs[: limit] - # poss = poss[: limit] - # scores = scores[: limit] - # endif - - var str_list = [] - var hl_list = [] - var idx = 0 - for str in strs - add(str_list, str) - add( - hl_list, - [idx + 1, reduce(poss[idx], (acc, val) => add(acc, val + 1), [])]) - idx += 1 - endfor - return [str_list, hl_list] -enddef - -Fuzzysearch9(['foo', 'bar', 'baz'], 'ba', 0) diff --git a/uninstall.sh b/uninstall.sh index 905321f..398666b 100755 --- a/uninstall.sh +++ b/uninstall.sh @@ -1,18 +1,41 @@ -#!/usr/bin/env sh +#!/usr/bin/env bash -app_dir="$HOME/dotfiles" +set -Eeuo pipefail -warn() { - echo "$1" >&2 +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" 2>/dev/null && pwd -P || true)" +if [[ -n "$SCRIPT_DIR" && -e "$SCRIPT_DIR/.git" ]]; then + APP_PATH="${APP_PATH:-$SCRIPT_DIR}" +else + APP_PATH="${APP_PATH:-$HOME/.dotfiles}" +fi +readonly APP_PATH +readonly MANAGED_START='# >>> dotfiles >>>' +readonly MANAGED_END='# <<< dotfiles <<<' + +remove_managed_link() { + local target=$1 expected=$2 + if [[ -L "$target" && "$(readlink "$target")" == "$expected" ]]; then + rm -- "$target" + printf 'Removed %s\n' "$target" + fi } -die() { - warn "$1" - exit 1 +remove_managed_block() { + local file=$1 temp + [[ -f "$file" ]] || return + temp=$(mktemp) + awk -v start="$MANAGED_START" -v end="$MANAGED_END" ' + $0 == start { managed = 1; next } + $0 == end { managed = 0; next } + !managed { print } + ' "$file" > "$temp" + cat "$temp" > "$file" + rm -f "$temp" } -rm $HOME/.vimrc -rm $HOME/.vimrc.bundles -rm $HOME/.vim +remove_managed_link "$HOME/.vimrc" "$APP_PATH/.vimrc" +remove_managed_link "$HOME/.tmux.conf" "$APP_PATH/.tmux.conf" +remove_managed_block "$HOME/.bashrc" -rm -rf $app_dir +printf '%s\n' 'Dotfile links and the managed Bash block were removed.' +printf '%s\n' 'The repository, Vim data/plugins, TPM, and backups were retained.' diff --git a/vimreset.sh b/vimreset.sh deleted file mode 100755 index bc2fab7..0000000 --- a/vimreset.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash - -rm -rf ~/.vim/.vim* -rm ~/.viminfo diff --git a/win-install.py b/win-install.py index 3cb6c93..7094647 100644 --- a/win-install.py +++ b/win-install.py @@ -1,87 +1,88 @@ -""" cross platform installation script -""" +"""Install the Vim 9 configuration on Windows.""" + +from pathlib import Path +from shutil import which import subprocess -import os +import time import urllib.request -from os.path import expanduser, join -from shutil import which -home = expanduser("~") -app_name = 'dotfiles' -APP_PATH = join(home, '.' + app_name) -REPO_URL = 'https://github.com/Donaldttt/' + app_name -REPO_BRANCH = 'main' -VIM_RTPATH = join(home, '.vim') +HOME = Path.home() +SCRIPT_PATH = Path(__file__).resolve().parent +DEFAULT_APP_PATH = HOME / ".dotfiles" +APP_PATH = SCRIPT_PATH if (SCRIPT_PATH / ".git").exists() else DEFAULT_APP_PATH +REPO_URL = "https://github.com/Donaldttt/dotfiles.git" +REPO_BRANCH = "main" +VIM_PATH = HOME / "vimfiles" +VIMRC = HOME / "_vimrc" -def exist(app): - return which(app) is not None -def program_must_exist(app): - if not exist(app): - fatal_error("must be installed to continue") +def run(command, cwd=None): + subprocess.run(command, cwd=cwd, check=True) -def fatal_error(msg): - print('Error:', msg) - exit() -def msg(msg): - print(msg) +def require(program): + if which(program) is None: + raise SystemExit(f"Error: {program} must be installed.") -def execute(cmd, cwd=None): - out = subprocess.check_output( - cmd, - stderr=subprocess.STDOUT, - shell=True, - cwd=None + +def ensure_repo(): + if (APP_PATH / ".git").exists(): + return + if APP_PATH.exists(): + raise SystemExit(f"Error: {APP_PATH} exists but is not a Git repository.") + print(f"Cloning dotfiles into {APP_PATH}...") + run( + [ + "git", + "clone", + "--branch", + REPO_BRANCH, + "--depth", + "1", + REPO_URL, + str(APP_PATH), + ] ) - print(out) -def sync_repo(repo_path, repo_url, repo_branch, repo_name): - if not os.path.exists(repo_path): - msg('Trying to clone ' + repo_name) - cmd = "git clone -b {} {} {}".format(repo_branch, repo_url, repo_path) - execute(cmd) - else: - msg('Trying to update ' + repo_name) - cmd = "git pull origin {}".format(repo_branch) - execute(cmd, cwd=APP_PATH) -def setup_vimplug(): +def check_vim_version(): + result = subprocess.run( + ["vim", "--clean", "-Nu", "NONE", "-n", "-es", "+if v:version < 900 | cquit | endif", "+qall"] + ) + if result.returncode: + raise SystemExit("Error: Vim 9 or newer is required.") - vimplug_path = VIM_RTPATH + "\\autoload\\plug.vim" - if not os.path.isdir(os.path.dirname(vimplug_path)): - os.makedirs(os.path.dirname(vimplug_path)) - urllib.request.urlretrieve("https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim", vimplug_path) - print("Please execute :PlugInstall in vim") -def setup_nvim(): - if exist('nvim'): - nvim_dir = home + '\\AppData\\Local\\nvim\\' - nvim_config = nvim_dir + 'init.vim' - if not os.path.isdir(nvim_dir): - os.mkdir(nvim_dir) - msg('Setting up neovim config') - with open(nvim_config, 'w') as f: - f.write('''set runtimepath^=~/.vim runtimepath+=~/.vim/after - let &packpath=&runtimepath - source ~/.vimrc''') +def install_vim_plug(): + target = VIM_PATH / "autoload" / "plug.vim" + target.parent.mkdir(parents=True, exist_ok=True) + urllib.request.urlretrieve( + "https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim", + target, + ) -def setup_vim(): - if not exist('vim') and not exist('nvim'): - fatal_error('Error: vim or nvim has to be installed.') - program_must_exist('git') - sync_repo(APP_PATH, REPO_URL, REPO_BRANCH, app_name) - path = join(home, '.vimrc') - if os.path.exists(path): - os.remove(path) - os.symlink(join(APP_PATH, '.vimrc'), join(home, '.vimrc')) - path = join(home, '.vimrc.bundles') - if os.path.exists(path): - os.remove(path) - os.symlink(join(APP_PATH, '.vimrc.bundles'), join(home, '.vimrc.bundles')) - setup_nvim() - setup_vimplug() - msg("Done!") -setup_vim() +def install_vimrc(): + config_path = (APP_PATH / ".vimrc").as_posix().replace("'", "''") + source_line = f"execute 'source ' . fnameescape('{config_path}')" + if VIMRC.exists() and VIMRC.read_text(encoding="utf-8", errors="ignore").strip() != source_line: + backup = VIMRC.with_name(f"{VIMRC.name}.{int(time.time())}.backup") + VIMRC.replace(backup) + print(f"Backed up existing Vim config to {backup}") + VIMRC.write_text(source_line + "\n", encoding="utf-8") + + +def main(): + require("git") + require("vim") + check_vim_version() + ensure_repo() + install_vimrc() + install_vim_plug() + run(["vim", "-Nu", str(APP_PATH / ".vimrc"), "+set nomore", "+PlugInstall --sync", "+qall"]) + print("Vim configuration installed.") + + +if __name__ == "__main__": + main()