Compare commits

..
13 Commits
Author SHA1 Message Date
gitea-admin 28b0a22706 docs: clarify Windows prerequisites and Vim startup
check / validate (push) Canceled after 0s
2026-10-19 14:47:12 +00:00
gitea-admin 9ed6df6173 docs: fix Windows clone paths and installation instructions
check / validate (push) Canceled after 0s
2026-10-19 14:06:52 +00:00
gitea-adminandClaude Fable 5.1 215c5cea44 refactor: trim configuration and drop unused plugins
check / validate (push) Canceled after 0s
- Merge sunbather dark/light into one background-aware color scheme
- Fold uninstall.sh into install.sh as a subcommand; drop clone logic
- Inline bash_tools/ helpers; remove fct and odict
- Remove TPM, tmux-sensible, and tmux-fuzzback; tmux has no plugins now
- Remove vim-repeat, vim-fugitive, vim-gitgutter, vim-tmux-navigator,
  and moonfly; everforest is the default dark theme
- Fetch vim-plug via git instead of curl; require git, not curl
- Guard termguicolors on Windows consoles without VT support and set
  nomore before the vimrc loads so headless installs cannot hang
- Fall back to sunbather when a color scheme fails to load, without
  overwriting the saved preference
- Append config/vim to runtimepath so netrw stops writing into the repo
- Fix .editorconfig Python indent; trim .gitignore; update CI and README

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NBfsAH6iJg9inkNLKq11YC
2026-09-14 01:06:39 +00:00
gitea-admin 2928ef3bc0 refactor: simplify dotfiles configuration
check / validate (push) Canceled after 0s
2026-08-12 15:57:01 +00:00
nocobase3 56b90dad19 . 2025-02-20 16:24:41 +08:00
nocobase3 faaa65d28f . 2025-01-21 21:44:04 +09:00
Donald T 6d458956c7 merge 2024-05-08 16:49:00 +08:00
Donald T 4d606b4981 Merge branch 'main' of github.com:Donaldttt/dotfiles 2024-02-08 10:20:56 +08:00
Donald T 077d3a069a . 2024-02-08 10:20:18 +08:00
nocobase3 a311601aea . 2023-12-29 19:34:35 +08:00
nocobase3 4c07c4c6a5 Merge branch 'dev' of github.com:Donaldttt/dotfiles into dev 2023-12-21 21:15:57 +08:00
nocobase3 726083eee1 . 2023-12-21 21:15:28 +08:00
nocobase3 20e05c9d35 add glazewm config 2023-12-21 21:14:52 +08:00
101 changed files with 695 additions and 5845 deletions
+18
View File
@@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.{sh,vim}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false
[*.py]
indent_style = space
indent_size = 4
+40
View File
@@ -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 bash_tools.sh
shellcheck install.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)
-7
View File
@@ -1,9 +1,2 @@
.DS_Store
*.pyc
*._*
.vim/
node_modules/
tags
.netrwhist
.vimspector.json
*.log
View File
+22 -58
View File
@@ -1,67 +1,31 @@
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
# Ctrl-H/J/K/L moves between panes.
bind-key -n C-h select-pane -L
bind-key -n C-j select-pane -D
bind-key -n C-k select-pane -U
bind-key -n C-l select-pane -R
bind-key -n 'C-\' select-pane -l
# 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
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'"
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'
+206 -241
View File
@@ -1,262 +1,227 @@
" dotfile location
let g:dotfiledir = expand(fnamemodify(resolve(expand('<sfile>: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('<sfile>: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"
else
let g:os = substitute(system('uname'), '\n', '', '')
if system('uname -r') =~ "icrosoft"
let g:isWSL = 1
endif
endif
if has('win32') || has('win64')
if executable('pwsh')
set shell=pwsh
elseif executable('powershell')
set shell=powershell
endif
endif
let mapleader = ','
let maplocalleader = '_'
set runtimepath^=~/.vim runtimepath+=~/.vim/after
let &packpath=&runtimepath
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 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') && (!has('win32') || has('vcon') || has('gui_running'))
set termguicolors
endif
" The default leader is '\', but many people prefer ',' as it's in a standard
let mapleader = ','
let maplocalleader = '_'
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//')
" General {
if has('clipboard')
if has('macunix') || has('win32') || has('win64')
set clipboard=unnamed
else
set clipboard=unnamedplus
endif
endif
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
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 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
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+=-
nnoremap j gj
nnoremap k gk
nnoremap Y y$
xnoremap < <gv
xnoremap > >gv
nnoremap <silent> <leader>h :nohlsearch<CR>
nnoremap <leader>ws :%s/\s\+$//e<CR>
nnoremap <Leader>s :%s/\<<C-r><C-w>\>/<C-r><C-w>
nnoremap <silent> <space>q :bprevious<CR>
nnoremap <silent> <space>e :bnext<CR>
nnoremap <silent> <C-w>% :vsplit<CR>
nnoremap <silent> <C-w>" :split<CR>
nnoremap q: <nop>
nnoremap Q <nop>
command! WQ wq
command! Wq wq
command! W write
command! Q quit
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
" 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'
" 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
" }
Plug 'tpope/vim-surround'
Plug 'tpope/vim-commentary'
" }
Plug 'mhinz/vim-startify'
Plug 'Donaldttt/vim-bufferline'
Plug 'Donaldttt/vim-global-statusline', { 'branch': 'vim9' }
" 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 'sainnhe/everforest'
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
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 <Tab> 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
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 <silent> <leader>fl :FuzzyCmdHistory<CR>
" }
" 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 = ''
" 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
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 <silent> <leader>e :call <SID>ToggleTree()<CR>
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
let g:bufferline_echo = 0
let g:bufferline_modified = '+'
let g:bufferline_active_buffer_left = '['
let g:bufferline_active_buffer_right = ']'
" stop inserting the current comment leader after hitting 'o' or 'O' in Normal mode
au FileType * setlocal formatoptions-=o
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'}]
set listchars=tab:•\ ,trail:•,extends:»,precedes:« " Unprintable chars mapping
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
set nospell " Spell checking off
set matchpairs+=<:> " Match, to be used with %
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
" }
augroup DotfilesUi
autocmd!
autocmd VimEnter * call theme#Init() | call <SID>StatuslineHighlights() | call <SID>StatuslineUpdate()
autocmd ModeChanged,BufEnter,BufDelete,BufWritePost * call <SID>StatuslineUpdate()
autocmd CursorHold * call <SID>StatuslineUpdate()
autocmd ColorScheme * call <SID>StatuslineHighlights()
augroup END
" Key (re)Mappings {
" Wrapped lines goes down/up to next row, rather than next line in file.
noremap j gj
noremap k gk
" Yank from the cursor to the end of the line, to be consistent with C and D.
nnoremap Y y$
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
" so when a buffer open it wouldn't be fold by default
" set nofoldenable
set foldlevelstart=99
" Visual shifting (does not exit Visual mode)
vnoremap < <gv
vnoremap > >gv
" Allow using the repeat operator with a visual selection (!)
" http://stackoverflow.com/a/8064607/127816
vnoremap . :normal .<CR>
" For when you forget to sudo.. Really Write the file.
" cmap w!! w !sudo tee % >/dev/null
" Adjust viewports to the same size
map <Leader>= <C-w>=
" Map <Leader>ff to display all lines with keyword under cursor
" and ask which one to jump to
nmap <Leader>j [I:let nr = input("Which one: ")<Bar>exe "normal " . nr ."[\t"<CR>
" 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 <silent> * :<C-u>call VisualSelection('', '')<CR>/<C-R>=@/<CR><CR>
vnoremap <silent> # :<C-u>call VisualSelection('', '')<CR>?<C-R>=@/<CR><CR>
" 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
" }
nnoremap <silent> <leader>cbg :call theme#toggleBg()<CR>
nnoremap <silent> <leader>ctb :call theme#toggleTransparent()<CR>
+104 -7
View File
@@ -1,19 +1,116 @@
# 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
- Python 3 (Windows installer)
- Optional: tmux, zoxide, ripgrep, and a Nerd Font
## Install
### Linux, WSL, and macOS (Bash)
Clone the repository, then install all components:
```bash
curl https://raw.githubusercontent.com/Donaldttt/dotfiles/dev/install.sh -L > dotfiles_install.sh && sh dotfiles_install.sh
git clone https://git.justconn.top/gitea-admin/dotfiles.git ~/.dotfiles
~/.dotfiles/install.sh
```
or
Components can be installed independently and combined:
```bash
sh <(curl https://raw.githubusercontent.com/Donaldttt/dotfiles/dev/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. It does not install zoxide; if zoxide is already available, the
managed Bash block initializes it.
### Windows (PowerShell)
Install Git, Python 3, and [Vim for Windows](https://www.vim.org/download.php)
first. Include the console version (`vim.exe`) and add each program's directory
to PATH. Open a new PowerShell window and verify:
```powershell
git --version
python --version
vim --version
```
Vim must be version 9 or newer. If a command is not recognized, fix its
installation or PATH before continuing. If Python is available through the
`py` launcher instead, use `py -3` in place of `python` below.
Clone into your user directory, then run the Windows installer:
```powershell
git clone https://git.justconn.top/gitea-admin/dotfiles.git "$HOME\.dotfiles"
python "$HOME\.dotfiles\win-install.py"
```
After installation, run `vim` in your terminal or open `gvim` for the graphical
editor. The configuration is loaded through `$HOME\_vimrc`; plugins are stored
in `$HOME\vimfiles`. Keep Git on PATH for plugin updates and Git-based file search.
The installer downloads plugins from GitHub, so that host must be reachable.
Use `$HOME` explicitly in PowerShell: `~` passed to external commands such as
Git may be treated as a literal directory name instead of your user directory.
In Command Prompt (CMD), use `%USERPROFILE%` instead:
```cmd
git clone https://git.justconn.top/gitea-admin/dotfiles.git "%USERPROFILE%\.dotfiles"
python "%USERPROFILE%\.dotfiles\win-install.py"
```
## Vim
The Vim setup includes Fuzzbox and NERDTree navigation, Startify, a compact
global statusline, and three 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
On Linux, WSL, and macOS, update safely from a clean worktree:
```bash
git -C ~/.dotfiles pull --ff-only
~/.dotfiles/install.sh
```
On Windows, update from a clean worktree in PowerShell:
```powershell
git -C "$HOME\.dotfiles" pull --ff-only
python "$HOME\.dotfiles\win-install.py"
```
On Linux, WSL, and macOS, remove managed links and the managed Bash block with:
```bash
~/.dotfiles/install.sh uninstall
```
Uninstalling intentionally retains the repository, backups, and Vim
data/plugins so user data is never removed implicitly.
+20 -63
View File
File diff suppressed because one or more lines are too long
-92
View File
@@ -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)
-228
View File
@@ -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
File diff suppressed because one or more lines are too long
-23
View File
@@ -1,23 +0,0 @@
# 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\] '
# »
-38
View File
@@ -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}$ "
-35
View File
@@ -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
Binary file not shown.
-376
View File
@@ -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")
-164
View File
@@ -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"]
-7
View File
@@ -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
-4
View File
@@ -1,4 +0,0 @@
# SETUPLIB
a python library for writing cross-platform env setup script
View File
-26
View File
@@ -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)
-4
View File
@@ -1,4 +0,0 @@
#!/bin/sh
git config --global user.name "Nachuan Tang"
git config --global user.email "tangnachuan1208@gmail.com"
-1
View File
@@ -1 +0,0 @@
theme_config.vim
@@ -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 ])
@@ -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 ])
-27
View File
@@ -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
-45
View File
@@ -1,45 +0,0 @@
let s:path = get(g:, '_config_path', fnamemodify(
\ resolve(expand('<sfile>: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
-171
View File
@@ -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 '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 <silent> <leader>fo :Options<CR>
endif
endfunction
-14
View File
@@ -1,14 +0,0 @@
func! os#getOS()
if has("win64") || has("win32") || has("win16")
return "Windows"
else
return substitute(system('uname'), '\n', '', '')
endif
endfunc
function! os#setWindows()
set updatetime=50
set shell=powershell
endfunction
+99 -361
View File
@@ -1,383 +1,121 @@
let s:path = get(g:, 'theme_config_path', fnamemodify(
\ resolve(expand('<sfile>:p')), ':h:h').'/theme_config.vim')
let s:path = get(g:, 'vim_dir', expand('~/.vim')) . '/theme.json'
let s:defaults = {
\ 'background': 'dark',
\ 'dark': {'theme': 'everforest', '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 : 'sunbather'
let s:applying = v:true
try
execute 'colorscheme ' . l:name
catch
" A scheme that fails to load (for example, one that needs true color in a
" terminal without it) must not leave Vim without a color scheme. The
" saved preference is kept so the next capable session restores it.
colorscheme sunbather
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
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('<amatch>'))
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('<amatch>'))
autocmd VimLeavePre * call theme#save()
augroup END
endfunction
-194
View File
@@ -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 <leader>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("<cword>")
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 . "\<Esc>"
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
-98
View File
@@ -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()
@@ -15,7 +15,7 @@ if exists('syntax on')
syntax reset
endif
let g:colors_name='sunbather_light'
let g:colors_name='sunbather'
let s:black = { "gui": "#000000", "cterm": "232" }
let s:medium_gray = { "gui": "#767676", "cterm": "243" }
@@ -45,19 +45,31 @@ let s:yellow = { "gui": "#F3E430", "cterm": "11" }
let s:light_yellow = { "gui": "#ffff87", "cterm": "228" }
let s:dark_yellow = { "gui": "#A89C14", "cterm": "3" }
let s:background = 'light'
let s:bg = s:actual_white
let s:bg_subtle = s:light_gray
let s:bg_very_subtle = s:lightest_gray
let s:norm = s:light_black
let s:norm_subtle = s:medium_gray
let s:pink = s:dark_pink
let s:cyan = s:dark_cyan
let s:green = s:dark_green
let s:red = s:dark_red
let s:visual = s:dark_pink
let s:yellow = s:dark_yellow
if &background ==# 'light'
let s:bg = s:actual_white
let s:bg_subtle = s:light_gray
let s:bg_very_subtle = s:lightest_gray
let s:norm = s:light_black
let s:norm_subtle = s:medium_gray
let s:pink = s:dark_pink
let s:cyan = s:dark_cyan
let s:green = s:dark_green
let s:red = s:dark_red
let s:visual = s:dark_pink
let s:yellow = s:dark_yellow
else
let s:bg = s:black
let s:bg_subtle = s:lighter_black
let s:bg_very_subtle = s:subtle_black
let s:norm = s:lighter_gray
let s:norm_subtle = s:medium_gray
let s:pink = s:light_pink
let s:cyan = s:light_cyan
let s:green = s:light_green
let s:red = s:light_red
let s:visual = s:light_pink
let s:yellow = s:light_yellow
endif
" https://github.com/noahfrederick/vim-hemisu/
function! s:h(group, style)
@@ -74,7 +86,6 @@ endfunction
call s:h("Normal", {"bg": s:bg, "fg": s:norm})
" restore &background's value in case changing Normal changed &background (:help :hi-normal-cterm)
execute "set background=" . s:background
call s:h("Cursor", {"bg": s:pink, "fg": s:norm })
call s:h("Comment", {"fg": s:bg_subtle, "gui": "italic"})
-214
View File
@@ -1,214 +0,0 @@
" Name: sunbather.vim
" Version: 0.1.0
" Maintainer: github.com/nikolvs
" License: The MIT License (MIT)
"
" A minimal pink colorscheme for Vim.
"
" Forked from paramount:
" https://github.com/owickstrom/vim-colors-paramount
"
"""
hi clear
if exists('syntax on')
syntax reset
endif
let g:colors_name='sunbather_dark'
let s:black = { "gui": "#000000", "cterm": "232" }
let s:medium_gray = { "gui": "#767676", "cterm": "243" }
let s:white = { "gui": "#F1F1F1", "cterm": "15" }
let s:actual_white = { "gui": "#FFFFFF", "cterm": "231" }
let s:subtle_black = { "gui": "#121212", "cterm": "233" }
let s:light_black = { "gui": "#262626", "cterm": "235" }
let s:lighter_black = { "gui": "#4E4E4E", "cterm": "239" }
let s:light_gray = { "gui": "#A8A8A8", "cterm": "248" }
let s:lighter_gray = { "gui": "#C6C6C6", "cterm": "251" }
let s:lightest_gray = { "gui": "#EEEEEE", "cterm": "255" }
let s:dark_pink = { "gui": "#ff5f87", "cterm": "204" }
let s:light_pink = { "gui": "#d75f87", "cterm": "168" }
let s:dark_red = { "gui": "#C30771", "cterm": "1" }
let s:light_red = { "gui": "#E32791", "cterm": "1" }
let s:orange = { "gui": "#D75F5F", "cterm": "167" }
let s:darker_blue = { "gui": "#005F87", "cterm": "18" }
let s:dark_blue = { "gui": "#008EC4", "cterm": "32" }
let s:blue = { "gui": "#20BBFC", "cterm": "12" }
let s:light_blue = { "gui": "#b6d6fd", "cterm": "153" }
let s:dark_cyan = { "gui": "#20A5BA", "cterm": "6" }
let s:light_cyan = { "gui": "#4FB8CC", "cterm": "14" }
let s:dark_green = { "gui": "#10A778", "cterm": "2" }
let s:light_green = { "gui": "#5FD7A7", "cterm": "10" }
let s:light_purple = { "gui": "#a790d5", "cterm": "140" }
let s:yellow = { "gui": "#F3E430", "cterm": "11" }
let s:light_yellow = { "gui": "#ffff87", "cterm": "228" }
let s:dark_yellow = { "gui": "#A89C14", "cterm": "3" }
let s:background = 'dark'
let s:bg = s:black
let s:bg_subtle = s:lighter_black
let s:bg_very_subtle = s:subtle_black
let s:norm = s:lighter_gray
let s:norm_subtle = s:medium_gray
let s:pink = s:light_pink
let s:cyan = s:light_cyan
let s:green = s:light_green
let s:red = s:light_red
let s:visual = s:light_pink
let s:yellow = s:light_yellow
" https://github.com/noahfrederick/vim-hemisu/
function! s:h(group, style)
execute "highlight" a:group
\ "guifg=" (has_key(a:style, "fg") ? a:style.fg.gui : "NONE")
\ "guibg=" (has_key(a:style, "bg") ? a:style.bg.gui : "NONE")
\ "guisp=" (has_key(a:style, "sp") ? a:style.sp.gui : "NONE")
\ "gui=" (has_key(a:style, "gui") ? a:style.gui : "NONE")
\ "ctermfg=" (has_key(a:style, "fg") ? a:style.fg.cterm : "NONE")
\ "ctermbg=" (has_key(a:style, "bg") ? a:style.bg.cterm : "NONE")
\ "cterm=" (has_key(a:style, "cterm") ? a:style.cterm : "NONE")
endfunction
call s:h("Normal", {"bg": s:bg, "fg": s:norm})
" restore &background's value in case changing Normal changed &background (:help :hi-normal-cterm)
execute "set background=" . s:background
call s:h("Cursor", {"bg": s:pink, "fg": s:norm })
call s:h("Comment", {"fg": s:bg_subtle, "gui": "italic"})
call s:h("Constant", {"fg": s:pink})
hi! link Character Constant
hi! link Number Constant
hi! link Boolean Constant
hi! link Float Constant
hi! link String Constant
"call s:h("Identifier", {"fg": s:dark_blue})
hi! link Identifier Normal
hi! link Function Identifier
call s:h("Statement", {"fg": s:norm_subtle})
hi! link Conditonal Statement
hi! link Repeat Statement
hi! link Label Statement
hi! link Keyword Statement
hi! link Exception Statement
call s:h("Operator", {"fg": s:norm, "cterm": "bold", "gui": "bold"})
call s:h("PreProc", {"fg": s:norm_subtle})
hi! link Include PreProc
hi! link Define PreProc
hi! link Macro PreProc
hi! link PreCondit PreProc
call s:h("Type", {"fg": s:norm})
hi! link StorageClass Type
hi! link Structure Type
hi! link Typedef Type
call s:h("Special", {"fg": s:norm_subtle, "gui": "italic"})
hi! link SpecialChar Special
hi! link Tag Special
hi! link Delimiter Special
hi! link SpecialComment Special
hi! link Debug Special
call s:h("Underlined", {"fg": s:norm, "gui": "underline", "cterm": "underline"})
call s:h("Ignore", {"fg": s:bg})
call s:h("Error", {"fg": s:actual_white, "bg": s:red, "cterm": "bold"})
call s:h("Todo", {"fg": s:pink, "gui": "underline", "cterm": "underline"})
call s:h("SpecialKey", {"fg": s:light_green})
call s:h("NonText", {"fg": s:medium_gray})
call s:h("Directory", {"fg": s:dark_blue})
call s:h("ErrorMsg", {"fg": s:red})
call s:h("IncSearch", {"bg": s:yellow, "fg": s:light_black})
call s:h("Search", {"bg": s:light_green, "fg": s:light_black})
call s:h("MoreMsg", {"fg": s:medium_gray, "cterm": "bold", "gui": "bold"})
hi! link ModeMsg MoreMsg
call s:h("LineNr", {"fg": s:bg_subtle})
call s:h("CursorLineNr", {"fg": s:pink, "bg": s:bg_very_subtle})
call s:h("Question", {"fg": s:red})
call s:h("StatusLine", {"bg": s:bg_very_subtle})
call s:h("StatusLineNC", {"bg": s:bg_very_subtle, "fg": s:medium_gray})
call s:h("VertSplit", {"bg": s:bg_very_subtle, "fg": s:bg_very_subtle})
call s:h("Title", {"fg": s:dark_blue})
call s:h("Visual", {"fg": s:norm, "bg": s:visual})
call s:h("VisualNOS", {"bg": s:bg_subtle})
call s:h("WarningMsg", {"fg": s:yellow})
call s:h("WildMenu", {"fg": s:bg, "bg": s:norm})
call s:h("Folded", {"fg": s:medium_gray})
call s:h("FoldColumn", {"fg": s:bg_subtle})
call s:h("DiffAdd", {"fg": s:green})
call s:h("DiffDelete", {"fg": s:red})
call s:h("DiffChange", {"fg": s:dark_yellow})
call s:h("DiffText", {"fg": s:dark_blue})
call s:h("SignColumn", {"fg": s:light_green})
if has("gui_running")
call s:h("SpellBad", {"gui": "underline", "sp": s:red})
call s:h("SpellCap", {"gui": "underline", "sp": s:light_green})
call s:h("SpellRare", {"gui": "underline", "sp": s:light_purple})
call s:h("SpellLocal", {"gui": "underline", "sp": s:dark_green})
else
call s:h("SpellBad", {"cterm": "underline", "fg": s:red})
call s:h("SpellCap", {"cterm": "underline", "fg": s:light_green})
call s:h("SpellRare", {"cterm": "underline", "fg": s:light_purple})
call s:h("SpellLocal", {"cterm": "underline", "fg": s:dark_green})
endif
call s:h("Pmenu", {"fg": s:norm, "bg": s:bg_very_subtle})
call s:h("PmenuSel", {"fg": s:subtle_black, "bg": s:pink})
call s:h("PmenuSbar", {"fg": s:norm, "bg": s:bg_subtle})
call s:h("PmenuThumb", {"fg": s:norm, "bg": s:bg_subtle})
call s:h("TabLine", {"fg": s:norm, "bg": s:bg_very_subtle})
call s:h("TabLineSel", {"fg": s:subtle_black, "bg": s:pink, "gui": "bold", "cterm": "bold"})
call s:h("TabLineFill", {"fg": s:norm, "bg": s:bg_very_subtle})
call s:h("CursorColumn", {"bg": s:bg_very_subtle})
call s:h("CursorLine", {"bg": s:bg_very_subtle})
call s:h("ColorColumn", {"bg": s:bg_subtle})
call s:h("MatchParen", {"bg": s:bg_subtle, "fg": s:norm})
call s:h("qfLineNr", {"fg": s:medium_gray})
call s:h("htmlH1", {"bg": s:bg, "fg": s:norm})
call s:h("htmlH2", {"bg": s:bg, "fg": s:norm})
call s:h("htmlH3", {"bg": s:bg, "fg": s:norm})
call s:h("htmlH4", {"bg": s:bg, "fg": s:norm})
call s:h("htmlH5", {"bg": s:bg, "fg": s:norm})
call s:h("htmlH6", {"bg": s:bg, "fg": s:norm})
" Syntastic
call s:h("SyntasticWarningSign", {"fg": s:yellow})
call s:h("SyntasticWarning", {"bg": s:yellow, "fg": s:black, "gui": "bold", "cterm": "bold"})
call s:h("SyntasticErrorSign", {"fg": s:red})
call s:h("SyntasticError", {"bg": s:red, "fg": s:white, "gui": "bold", "cterm": "bold"})
" which-key.nvim
call s:h("WhichKey", {"bg": s:bg, "fg": s:pink, "gui": "bold", "cterm": "bold"})
call s:h("WhichKeyDesc", {"bg": s:bg, "fg": s:norm_subtle, "gui": "bold", "cterm": "bold"})
call s:h("WhichKeySeparator", {"bg": s:bg, "fg": s:norm, "gui": "bold", "cterm": "bold"})
call s:h("WhichKeyFloat", {"bg": s:bg})
hi link WhichKeyGroup WhichKey
" Neomake
hi link NeomakeWarningSign SyntasticWarningSign
hi link NeomakeErrorSign SyntasticErrorSign
" ALE
hi link ALEWarningSign SyntasticWarningSign
hi link ALEErrorSign SyntasticErrorSign
" Signify, git-gutter
hi link SignifySignAdd LineNr
hi link SignifySignDelete LineNr
hi link SignifySignChange LineNr
hi link GitGutterAdd LineNr
hi link GitGutterDelete LineNr
hi link GitGutterChange LineNr
hi link GitGutterChangeDelete LineNr
-30
View File
@@ -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 <D-v> "+p
cnoremap <D-v> <c-r>+
inoremap <D-v> <c-r>+
else
nnoremap <C-v> "+p
cnoremap <C-v> <c-r>+
inoremap <C-v> <c-r>+
endif
endif
endif
-276
View File
@@ -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
@@ -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', '{', '<cmd>AerialPrev<CR>', { buffer = bufnr })
vim.keymap.set('n', '}', '<cmd>AerialNext<CR>', { buffer = bufnr })
end
})
-- You probably also want to set a keymap to toggle aerial
vim.keymap.set('n', '<leader>v', '<cmd>AerialToggle!<CR>')
end
@@ -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
@@ -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 '<Ignore>'
end, { expr = true })
map('n', '[c', function()
if vim.wo.diff then return '[c' end
vim.schedule(function() gs.prev_hunk() end)
return '<Ignore>'
end, { expr = true })
-- Actions
map({ 'n', 'v' }, '<leader>hs', ':Gitsigns stage_hunk<CR>')
map({ 'n', 'v' }, '<leader>hr', ':Gitsigns reset_hunk<CR>')
map('n', '<leader>hS', gs.stage_buffer)
map('n', '<leader>hu', gs.undo_stage_hunk)
map('n', '<leader>hR', gs.reset_buffer)
map('n', '<leader>hp', gs.preview_hunk)
map('n', '<leader>hb', function() gs.blame_line { full = true } end)
map('n', '<leader>tb', gs.toggle_current_line_blame)
map('n', '<leader>hd', gs.diffthis)
map('n', '<leader>hD', function() gs.diffthis('~') end)
map('n', '<leader>td', gs.toggle_deleted)
-- Text object
map({ 'o', 'x' }, 'ih', ':<C-U>Gitsigns select_hunk<CR>')
end
})
vim.fn['theme#addCleanBg']({ 'GitSignsAdd', 'GitSignsStagedChange',
'GitSignsStagedDelete', 'GitSignsDelete', 'GitSignsChange',
'GitGutterAdd', 'GitGutterChange', 'GitGutterDelete', 'GitGutterChangeDelete',
})
end
@@ -1,4 +0,0 @@
if HasPlug('impatient.nvim') then
require('impatient')
end
@@ -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
@@ -1,60 +0,0 @@
-------------------OPTIONS-----------------------
-- enable animation of command like "<C-u>" and "<C-d>", 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
@@ -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 = "<space>sc",
visual_send = "<space>sc",
send_file = "<space>sf",
send_line = "<space>sl",
send_mark = "<space>sm",
mark_motion = "<space>mc",
mark_visual = "<space>mc",
remove_mark = "<space>md",
cr = "<space>s<cr>",
interrupt = "<space>s<space>",
exit = "<space>sq",
clear = "<space>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', '<space>rs', '<cmd>IronRepl<cr>')
vim.keymap.set('n', '<space>rr', '<cmd>IronRestart<cr>')
vim.keymap.set('n', '<space>rf', '<cmd>IronFocus<cr>')
vim.keymap.set('n', '<space>rh', '<cmd>IronHide<cr>')
end
@@ -1,4 +0,0 @@
if HasPlug('leap.nvim') then
require('leap').add_default_mappings()
end
@@ -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 <silent> <Leader>1 :LualineBuffersJump 1<CR>
vim.api.nvim_set_keymap('n', '<Leader>' .. i, ':LualineBuffersJump ' .. i .. '<CR>',
{ noremap = true, silent = true, nowait = true })
end
for i = 10, 20 do
-- :nnoremap <silent> <Leader>1 :LualineBuffersJump 1<CR>
vim.api.nvim_set_keymap('n', '<Space>' .. i, ':LualineBuffersJump ' .. i .. '<CR>',
{ noremap = true, silent = true, nowait = true })
end
end
@@ -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 = --<function: implements linear total 250ms animation duration>,
},
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
@@ -1,4 +0,0 @@
if HasPlug('mini.colors') then
require('mini.colors').setup()
end
@@ -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
@@ -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
@@ -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
@@ -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', '<CR>', api.node.open.edit, opts('Open'))
end
vim.api.nvim_set_keymap('n', '<Leader>e', ':NvimTreeFindFileToggle<CR>',
{ 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
@@ -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
@@ -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', '<leader>fp', require'telescope'.extensions.projects.projects,
-- { desc = "Lists projects" })
-- end
end
@@ -1,110 +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.borderchars = { '─', '│', '─', '│', '┌', '┐', '┘', '└' }
return layout
end
telescope.setup {
defaults = {
hidden = true,
vimgrep_arguments = vimgrep_arguments,
file_ignore_patterns = {"node_modules/", ".git/"},
layout_config = {
-- prompt_position = "top",
},
layout_strategy = "horizontal_merged",
},
pickers = {
find_files = {
hidden = true,
},
colorscheme = {
enable_preview = true,
mappings = {
i = {
["<CR>"] = 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,
},
},
}
},
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', '<leader>ff', builtin.find_files, { desc = "Search files inside cwd" })
-- need to install ripgrep
vim.keymap.set('n', '<leader>fr', builtin.live_grep, { desc = "Regex search inside files" })
vim.keymap.set('n', '<leader>fb', builtin.buffers, { desc = "Search buffers" })
vim.keymap.set('n', '<leader>fc', builtin.colorscheme, { desc = "Search colorscheme" })
vim.keymap.set('n', '<leader>fs', builtin.treesitter, { desc = "Lists Function names, variables, from Treesitter!" })
vim.keymap.set('n', '<leader>fh', builtin.highlights, { desc = "Lists highlight" })
vim.keymap.set('n', '<leader>fd', builtin.help_tags, { desc = "Lists highlight" })
Wk_register({ ["<leader>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', '<leader>fo', telescope_option_picker, { desc = "Lists Function names, variables, from Treesitter!" })
end
@@ -1,65 +0,0 @@
if HasPlug('toggleterm.nvim') then
require("toggleterm").setup({
open_mapping = [[<c-\>]],
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', '<esc>', [[<C-\><C-n>]], opts)
vim.keymap.set('t', 'jk', [[<C-\><C-n>]], opts)
vim.keymap.set('t', '<C-h>', [[<Cmd>wincmd h<CR>]], opts)
vim.keymap.set('t', '<C-j>', [[<Cmd>wincmd j<CR>]], opts)
vim.keymap.set('t', '<C-k>', [[<Cmd>wincmd k<CR>]], opts)
vim.keymap.set('t', '<C-l>', [[<Cmd>wincmd l<CR>]], opts)
vim.keymap.set('t', '<C-w>', [[<C-\><C-n><C-w>]], 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", "<leader>tp", "<cmd>lua _ipython_toggle()<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "<leader>tl", string.format("<cmd>ToggleTermSendCurrentLine %d<CR>", ipythonId),
{ noremap = true, silent = true })
-- sends all the (whole) lines in your visual selection
vim.api.nvim_set_keymap("v", "<leader>tl", string.format(":ToggleTermSendVisualLines %d<CR>", ipythonId),
{ noremap = true, silent = true })
-- sends only the visually selected text (this can be a block of text
vim.api.nvim_set_keymap("x", "<leader>tl", string.format(":ToggleTermSendVisualSelection %d<CR>", ipythonId),
{ noremap = true, silent = true })
end
@@ -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
@@ -1,9 +0,0 @@
if HasPlug('vim-illuminate') then
require'nvim-treesitter.configs'.setup {
matchup = {
enable = true,
disable = { },
},
}
end
@@ -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
-13
View File
@@ -1,13 +0,0 @@
if exists("g:loaded_vim_config")
finish
endif
let g:loaded_vim_config = 1
let os = os#getOS()
if os == 'Windows'
call os#setWindows()
endif
call options#init()
@@ -1,6 +0,0 @@
if utils#hasplug('Copilot.vim')
" imap <expr> <C-n> <Plug>(copilot-next)
" imap <expr> <C-p> <Plug>(copilot-prev)
endif
@@ -1,8 +0,0 @@
if utils#hasplug('coc-fzf')
let g:coc_fzf_preview = 'right:50%'
nnoremap <silent> <leader>fs :CocFzfList outline<CR>
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
@@ -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 <c-space> to trigger completion.
if has('nvim')
inoremap <silent><expr> <c-space> coc#refresh()
else
inoremap <silent><expr> <c-@> coc#refresh()
endif
set updatetime=300
" Make <CR> auto-select the first completion item and notify coc.nvim to
" format on enter, <cr> could be remapped by other vim plugin
inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm()
\: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
" GoTo code navigation.
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" Use K to show documentation in preview window.
nnoremap <silent> K :call <SID>show_documentation()<CR>
function! s:show_documentation()
if CocAction('hasProvider', 'hover')
call CocActionAsync('doHover')
else
call feedkeys('K', 'in')
endif
endfunction
" Symbol renaming.
nmap <leader>rn <Plug>(coc-rename)
" Formatting selected code.
xmap <space>f <Plug>(coc-format-selected)
nmap <space>f <Plug>(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 <leader>qf <Plug>(coc-fix-current)
" Remap <C-f> and <C-b> for scroll float windows/popups.
if has('nvim-0.4.0') || has('patch-8.2.0750')
nnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
nnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
inoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(1)\<cr>" : "\<Right>"
inoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(0)\<cr>" : "\<Left>"
vnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
vnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
endif
" Mappings for CoCList
" Show all diagnostics.
nnoremap <silent><nowait> <space>a :<C-u>CocList diagnostics<cr>
" Manage extensions.
" nnoremap <silent><nowait> <space>e :<C-u>CocList extensions<cr>
" Show commands.
nnoremap <silent><nowait> <space>c :<C-u>CocList commands<cr>
" Find symbol of current document.
nnoremap <silent><nowait> <space>o :<C-u>CocList outline<cr>
" Search workspace symbols.
nnoremap <silent><nowait> <space>s :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent><nowait> <space>j :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent><nowait> <space>k :<C-u>CocPrev<CR>
" Resume latest coc list.
nnoremap <silent><nowait> <space>p :<C-u>CocListResume<CR>
"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
@@ -1,3 +0,0 @@
if utils#hasplug('coc.nvim')
let g:codi#virtual_text = 0
endif
@@ -1,4 +0,0 @@
if utils#hasplug('ctrlp.vim')
let g:ctrlp_map = '<leader>ff'
endif
@@ -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
@@ -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 <leader>fo :call FzfOptions()<CR>
" noremap <leader>fr :call FzfRg()<CR>
" noremap <leader>ff :call FzfFiles()<CR>
noremap <leader>fh :call FzfHelpTags()<CR>
" noremap <leader>fb :BLines<CR>
noremap <leader>fu :call FzfFiles('~')<CR>
if utils#hasplug('fzf-color-preview')
let g:FzfColorComfirmCb = function('FzfColorSelect')
let g:FzfAirlineComfirmCb = function('FzfAirlineColorSelect')
noremap <leader>fa :AirlinePreview<CR>
noremap <leader>fc :ColorsPreview<CR>
else
noremap <leader>fc :Colors<CR>
endif
endif
@@ -1,16 +0,0 @@
if utils#hasplug('goyo.vim')
nnoremap <leader><leader>g :Goyo<CR>
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 \<c-w>=" | endif
endfunction
augroup GoyoAu
au!
augroup END
autocmd User GoyoEnter au GoyoAu BufEnter * if winnr('$') == '5' | exe "normal \<c-w>=" | endif
autocmd User GoyoLeave augroup GoyoAu | au! | augroup END
endif
@@ -1,5 +0,0 @@
if utils#hasplug('indentLine')
let g:indentLine_char = '│'
let g:indentLine_setConceal = 0
endif
@@ -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
@@ -1,13 +0,0 @@
if utils#hasplug('minimap.vim')
nnoremap <silent> mm :MinimapToggle<CR>
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
@@ -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 <silent> <leader>e :call NERDTreeFindToggle()<CR>
"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
@@ -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
@@ -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 <silent> <leader>v <cmd>TagbarToggle<CR>
endif
@@ -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
@@ -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
@@ -1,5 +0,0 @@
if utils#hasplug("vim-devicons")
let g:webdevicons_enable_airline_statusline = 0
endif
@@ -1,53 +0,0 @@
if utils#hasplug('vim-floaterm')
let g:floaterm_keymap_toggle = '<C-\>'
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!<CR>
" press <c-[> ener normal mode in terminal. autocmd prevent this key map
" in other plugin like fzf
autocmd FileType floaterm tmap <buffer> <C-[> <C-w>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 <silent> <leader>tp :call ToggleRepl()<CR>
nnoremap <silent> <leader>tn :call ToggleNormal()<CR>
vnoremap <silent> <leader>tl :FloatermSend --name=REPL<CR>
endif
@@ -1,5 +0,0 @@
if utils#hasplug('vim-gitgutter')
call theme#addCleanBg(['GitGutterAdd', 'GitGutterChange', 'GitGutterDelete', 'GitGutterChangeDelete'])
nnoremap <leader>gt :GitGutterBufferToggle<CR>
endif
@@ -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
@@ -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
@@ -1,5 +0,0 @@
if utils#hasplug('vim-matchup')
let g:matchup_matchparen_offscreen = {}
call theme#addCleanBg('MatchWord')
endif
@@ -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
@@ -1,5 +0,0 @@
if utils#hasplug("vim-sneak")
let g:sneak#label = 1
" map f <Plug>Sneak_s
" map F <Plug>Sneak_S
endif
@@ -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 <silent> <leader><leader>s :SSave!<CR>
nnoremap <silent> <leader><leader>l :SLoad<CR>
nnoremap <silent> <leader><leader>d :SDelete!<CR>
nnoremap <silent> <leader><leader>c :SClose<CR>
au VimLeave * SSave! last
endif
@@ -1,11 +0,0 @@
if utils#hasplug('vim-tmux-navigator')
let g:tmux_navigator_no_mappings = 1
noremap <silent> <c-h> :<C-U>TmuxNavigateLeft<cr>
noremap <silent> <c-j> :<C-U>TmuxNavigateDown<cr>
noremap <silent> <c-k> :<C-U>TmuxNavigateUp<cr>
noremap <silent> <c-l> :<C-U>TmuxNavigateRight<cr>
" noremap <silent> {Previous-Mapping} :<C-U>TmuxNavigatePrevious<cr>
endif
@@ -1,7 +0,0 @@
vim9script
if utils#hasplug('fuzzyy')
g:files_respect_gitignore = 1
g:fuzzyy_menu_matched_hl = 'error'
g:fuzzyy_dropdown = 1
endif
@@ -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<any>): void
var s = Cocstatus()
g:StlSetPart(&co - 17, ' ' .. s .. ' ', '', 'lsp')
g:StlRefresh()
enddef
var fancytimer = 0
def Fancy(...timer: list<any>): 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
@@ -1,7 +0,0 @@
if utils#hasplug('vimtex')
noremap <leader>lc :VimtexCompile<CR>
noremap <leader>lv :VimtexView<CR>
if g:os == 'Darwin'
let g:vimtex_view_method = 'skim'
endif
endif
@@ -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 <silent> <leader>v :Vista!!<CR>
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
@@ -1,31 +0,0 @@
if utils#hasplug('wilder.nvim')
call wilder#setup({
\ 'modes': [':'],
\ 'next_key': '<tab>',
\ 'previous_key': '<S-Tab>',
\ '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
@@ -1,8 +0,0 @@
if utils#hasplug("winresizer")
let g:winresizer_vert_resize = 2
let g:winresizer_horiz_resize = 2
" nnoremap <C-w>r :WinResizerStartResize<CR>
let g:winresizer_start_key = '<C-w>r'
endif
@@ -1,3 +0,0 @@
if utils#hasplug("zoxide.vim")
endif
-1
View File
@@ -1 +0,0 @@
local wezterm = require 'wezterm'
View File
+113 -345
View File
@@ -1,375 +1,143 @@
#!/usr/bin/env bash
############################ SETUP PARAMETERS
set -Eeuo pipefail
app_name='dotfiles'
readonly APP_PATH="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
readonly VIM_PATH="${VIM_PATH:-$HOME/.vim}"
readonly MANAGED_START='# >>> dotfiles >>>'
readonly MANAGED_END='# <<< dotfiles <<<'
[ -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"
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; }
usage() {
cat <<'USAGE'
Usage: ./install.sh [all|vim|shell|tmux|uninstall]...
############################ BASIC SETUP TOOLS
msg() {
printf '%b\n' "$1" >&2
With no arguments, installs every component. Components can be combined, for
example: ./install.sh vim tmux
USAGE
}
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}"
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
}
fatal_error() {
msg "\33[31m[✘]\33[0m ${1}${2}"
exit 1
link_config() {
local source=$1 target=$2
if [[ -L "$target" && "$(readlink "$target" || true)" == "$source" ]]; then
return
fi
backup_path "$target"
ln -s "$source" "$target"
success "Linked $target -> $source"
}
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
remove_managed_link() {
local target=$1 expected=$2
if [[ -L "$target" && "$(readlink "$target")" == "$expected" ]]; then
rm -- "$target"
info "Removed $target"
fi
}
# 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 0
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 git
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
mkdir -p "$VIM_PATH/autoload"
local temp
temp=$(mktemp -d)
git clone --depth 1 --quiet https://github.com/junegunn/vim-plug "$temp"
cp "$temp/plug.vim" "$VIM_PATH/autoload/plug.vim"
rm -rf "$temp"
link_config "$APP_PATH/.vimrc" "$HOME/.vimrc"
vim -Nu "$APP_PATH/.vimrc" -n -es \
--cmd '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"
success 'Installed tmux configuration.'
}
############################ SETUP FUNCTIONS
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
uninstall() {
remove_managed_link "$HOME/.vimrc" "$APP_PATH/.vimrc"
remove_managed_link "$HOME/.tmux.conf" "$APP_PATH/.tmux.conf"
remove_managed_block "$HOME/.bashrc"
success 'Removed dotfile links and the managed Bash block.'
info 'The repository, Vim data/plugins, and backups were retained.'
}
# 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"
main() {
case "${1:-}" in
-h|--help) usage; return ;;
esac
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
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 ;;
uninstall) uninstall ;;
*) usage; die "Unknown component: $component" ;;
esac
done
}
# 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 "$@"
-300
View File
@@ -1,300 +0,0 @@
" (jump to the topic)
"
" OPTIONS
" PLUGIN_INSTALL
" UTILITIES
" PLUGIN_CONFIGURATION " THEME_CONFIGURATION
" KEY_MAPS
" OTHER_CONFIGS
let g:high_performence = v:true
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 <leader><leader>t :call utils#swapword()<CR>
"""""" 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 'jacoborus/tender.vim'
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 'junegunn/goyo.vim', { 'on': ['Goyo'] }
Plug 'andymass/vim-matchup'
endif
Plug 'Donaldttt/fuzzyy'
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 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
" source lua library
"""""" THEME_CONFIGURATION """"""
nmap <Leader>db :call utils#showHiGroup()<CR>
""" THEME_OPTIONS """
call theme#Init()
"""""" KEY_MAPS """"""
" (This doesn't include plugin specific mapping.
" For them check plugin Preferences)
nnoremap <leader>ws :call utils#trimwhitespace()<CR>
" Toggle dark/light theme
noremap <silent> <leader>cbg :call theme#toggleBg()<CR>
" Toggle transparent background
noremap <silent> <leader>ctb :call theme#toggleTransparent()<CR>
" Buffer navigation
nnoremap <silent> <space>q :bprevious<CR>
nnoremap <silent> <space>e :bnext<CR>
" leader s change all occurence
nnoremap <Leader>s :%s/\<<C-r><C-w>\>/<C-r><C-w>
noremap <leader>h :noh<CR> " turn off highlight
" disable two easily mispressed yet useless key
nnoremap q: <nop>
nnoremap Q <nop>
" 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 <silent> <nowait> <leader>" . i .
\ " :call bufferline#jump(" . i . ")<CR>"
endfor
for i in range(10, 20)
execute "nnoremap <silent> <nowait> <leader><leader>" . i .
\ " :call bufferline#jump(" . i . ")<CR>"
endfor
end
" split window comform with other window management shortcuts
nnoremap <silent> <C-w>% :vsplit<CR>
nnoremap <silent> <C-w>" :split<CR>
call s:executeLateInit()
-32
View File
@@ -1,32 +0,0 @@
vim9script
def Fuzzysearch9(li: list<string>, pattern: string, limit: number): list<any>
var opts = {}
if limit > 0
opts['limit'] = limit
endif
var results: list<any> = 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)
-18
View File
@@ -1,18 +0,0 @@
#!/usr/bin/env sh
app_dir="$HOME/dotfiles"
warn() {
echo "$1" >&2
}
die() {
warn "$1"
exit 1
}
rm $HOME/.vimrc
rm $HOME/.vimrc.bundles
rm $HOME/.vim
rm -rf $app_dir
-4
View File
@@ -1,4 +0,0 @@
#!/usr/bin/env bash
rm -rf ~/.vim/.vim*
rm ~/.viminfo

Some files were not shown because too many files have changed in this diff Show More