" standalone vimrc
" user settings
syntax on
filetype plugin indent on
set encoding=utf-8
set autoindent
set autoread
set backspace=indent,eol,start
set completeopt=menuone,noselect,preview
set expandtab
set hlsearch
set ignorecase
set incsearch
set infercase
set laststatus=2
" DONT USE MOUSE
set mouse=
set nobackup
set nocursorline
set swapfile
set directory=$XDG_CACHE_HOME/vim,$HOME/.cache/vim
" Use screenkey to show them
set noshowcmd
set nowrap
set nowrapscan
set nowritebackup
set nonumber
set shiftwidth=2
set signcolumn=yes
set showmatch
set smartindent
set tabstop=2
set virtualedit=onemore
set wildmenu

augroup vimrc#autocmd
  autocmd!
augroup END

" ref: https://zenn.dev/hokorobi/articles/98f79339d7d114
autocmd vimrc#autocmd BufEnter * if getfsize(@%) > 1024 * 1000 | setlocal syntax=OFF | endif

if has('nvim')
  set wildmode=full
  set wildoptions+=pum
else
  set wildmode=longest,full
  if has('patch-8.2.4325')
    set wildoptions+=pum
  endif
endif

if has('termguicolors')
  set termguicolors
  let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
  " TODO:
  "   If delete below on Vim, Background of terminal will be transparency
  "   but lightline will be transparency too.
  let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
endif

if has('nvim')
  let $NVIM_TUI_ENABLE_TRUE_COLOR = v:true
else
  set iminsert=2
  let &t_ti ..= "\e[1 q"
  let &t_SI ..= "\e[5 q"
  let &t_SR ..= "\e[3 q"
  let &t_EI ..= "\e[1 q"
  let &t_te ..= "\e[0 q"
endif

if has('win32') || has('mac')
  set clipboard=unnamed
elseif has('wsl')
  set clipboard=unnamedplus
else
  set clipboard=unnamed,unnamedplus
endif

" move f/b in insert mode like commandline with split undo unit
inoremap <C-f> <C-g>U<Right>
inoremap <C-b> <C-g>U<Left>

" move UP/DOWN at fold context as same as displayed
nnoremap j gj
nnoremap k gk
xnoremap j gj
xnoremap k gk

nnoremap Q <Cmd>copen<CR>

" easy force write/quit
cnoreabbrev qq quit!
cnoreabbrev ww update!
cnoreabbrev w update

" easy open memo buffer
command! Scratch new +set\ buftype=nofile\ filetype=markdown
cnoreabbrev memo Scratch

" TODO
" cnoreabbrev w:q wq

" type "&" is too hard to me on JIS keyboard

" dont use clipboard
nnoremap x "_x
nnoremap s "_s
nnoremap c "_c

"" DONT USE ARROW TO MOVE
noremap <Left> <nop>
noremap <Down> <nop>
noremap <Up> <nop>
noremap <Right> <nop>
noremap! <Left> <nop>
noremap! <Down> <nop>
noremap! <Up> <nop>
noremap! <Right> <nop>

nnoremap J gj
nnoremap gj J
xnoremap J gj
xnoremap K gk

" from other resource, vim.jp etc..
nnoremap <silent> <ESC><ESC> <Cmd>nohlsearch<CR>
nnoremap <expr> 0 getline('.')[0 : col('.') - 2] =~# '^\s\+$' ? '0' : '^'
nnoremap Y y$
nnoremap <C-s> :<C-u>%substitute@\v@@g<Left><Left><Left>
vnoremap <C-s> :substitute@\v@@g<Left><Left><Left>

cnoremap <C-f> <Right>
cnoremap <C-b> <Left>
cnoremap <C-d> <Del>
cnoremap <C-a> <Home>
inoremap <expr> <C-a> getline('.')[0 : col('.') - 2] =~# '^\s\+$' ? '<C-o>0' : '<C-o>^'
noremap!        <C-e> <End>

" Automatically indent with i and A
nnoremap <expr> i len(getline('.')) !=# 0 ? 'i' : '"_cc'
nnoremap <expr> A len(getline('.')) !=# 0 ? 'A' : '"_cc'

if has('nvim')
  " neovim terminal settings
  " tnoremap <C-w><C-w> <C-\><C-n><C-w><C-w>
  tnoremap <ESC> <C-\><C-n>
  " feed insert mode when move terminal window
  autocmd vimrc#autocmd TermOpen * startinsert
  autocmd vimrc#autocmd TermOpen * setlocal nonumber
  autocmd vimrc#autocmd WinEnter * if &buftype ==# 'terminal' | startinsert | endif
  " auto close
  autocmd vimrc#autocmd TermClose * call feedkeys('\<CR>')
  " helper commands
  command! Vterm vertical botright vnew term://${SHELL}
  command! Hterm botright new term://${SHELL}
  command! Tterm tabnew term://${SHELL}
else
  " Vim terminal settings
  tnoremap <ESC> <C-w>N
  autocmd vimrc#autocmd TerminalOpen * setlocal nonumber
  " helper commands
  command! Vterm vertical botright vnew | terminal ++curwin
  command! Hterm botright new | terminal ++curwin
  command! Tterm tabnew | terminal ++curwin
endif

if has('gui_running')
  set guifont=Firge35\ Console\ 18
  set guioptions-=r
  set guioptions-=R
  set guioptions-=l
  set guioptions-=L
  set guioptions-=b
  set guioptions-=m
  set guioptions-=T
else
  set t_Co=256
  autocmd vimrc#autocmd VimEnter * map <Nul> <C-Space>
  autocmd vimrc#autocmd VimEnter * map! <Nul> <C-Space>
endif

" use ripgrep
function! s:set_rg() abort
  if !executable('rg')
    return
  endif
  set grepprg=rg\ --vimgrep\ --no-heading
  set grepformat=%f:%l:%c:%m,%f:%l:%m
endfunction
autocmd vimrc#autocmd CmdLineEnter * ++once call <SID>set_rg()

function! s:grep_in_file() abort
  let l:query = input('grep: ')
  if empty(l:query)
    echohl WarningText
    echomsg 'vimgrep is canceled'
    echohl None
    return
  endif
  try
    silent execute $'lvimgrep {l:query} % | lw'
    " conceal has bug about wrapping
    setlocal conceallevel=3 concealcursor=nvc nowrap
    syntax match grep_internal '^.\{-}|\@=' conceal
  catch /.*/
    " if quickfix open already, close it.
    silent execute 'lclose'
    echoerr v:exception
  endtry
endfunction

" FIXME: なんかよくない気がする
nnoremap F <Cmd>call <SID>grep_in_file()<CR>

" copy buffer command
command! CopyBuffer %yank

" Disable message that show when start without args (I)
set shortmess=asTIcF

" filetype settings
" if nvim then use lua filetype module
let g:did_load_filetyps = has('nvim')

const g:filetype_m = 'mma'

" FIXME: 読み込み順の問題か/ftdetect/objcだとうまくいかない
autocmd vimrc#autocmd BufRead,BufNewFile *.m set filetype=objc
" FIXME: BufReadだと2回発火する?
" FIXME: ファイラ経由で発火すると無限に呼び出されている?
"   reproduce:
"     $ mkdir /tmp/sample && touch /tmp/sample/a.js /tmp/sample/a.ts
"     $ vim /tmp/sample
"     :Fern .
"     and open a.js
autocmd vimrc#autocmd FileType javascript call s:open_it_really()

function! s:open_it_really() abort
  let l:current_bufnr = bufnr()
  let l:tsfile = $'{expand('%:p:r')}.ts'
  if filewritable(l:tsfile)
    if confirm($'Exists {fnamemodify(l:tsfile, ':t')}. Open it?', "&Yes\n&No\n", 1) ==# 1
      execute 'edit' l:tsfile
      execute 'bwipeout' l:current_bufnr
    endif
  endif
endfunction

" Digraph
" NOTE: ref: https://qiita.com/monaqa/items/dcd43a53d3040293142a
nnoremap fj f<C-k>j
onoremap fj f<C-k>j
xnoremap fj f<C-k>j
call digraph_setlist([
      \ ['jj', 'j'],
      \ ['j(', '('],
      \ ['j)', ')'],
      \ ['j[', '「'],
      \ ['j]', '」'],
      \ ['j,', '、'],
      \ ['j.', '。'],
      \ ['j!', '!'],
      \ ['j?', '?'],
      \ ['j~', '~'],
      \ ])

" NOTE: from https://github.com/thinca/config/dotfiles/dot.vim/vimrc
" auto mkdir
autocmd vimrc#autocmd BufWritePre * call s:auto_mkdir(expand('<afile>:p:h'), v:cmdbang)
function s:auto_mkdir(dir, force) abort
  if &l:buftype !=# '' || bufname('%') =~# '^[^:]\+://'
    return
  endif
  if isdirectory(a:dir)
    return
  endif
  const l:mes = $'"{a:dir}" does not exist. Create?'
  if (a:force || confirm(l:mes, "&Yes\n&No", 1) ==# 1)
    " NOTE: original idea from: https://github.com/kat0h/dotfiles/blob/7c371cd16f39e66f0960d3c847085ff64d19881d/dot_vim%2Futils.vim#L8
    let l:dir = has('iconv') ? iconv(a:dir, &encoding, &termencoding) : a:dir
    call mkdir(l:dir, 'p')
  endif
endfunction

nnoremap qn <Cmd>cnext<CR>
nnoremap qp <Cmd>cprev<CR>

onoremap A $
cnoremap <C-o> expand('%')

if !exists('g:config_dir')
  function! s:is_pre(char)
    const l:pre = getline('.')[col('.') - 2]
    return l:pre ==# a:char
  endfunction
  " NOTE: source this file directory like `-u ...`
  inoremap <expr> " <SID>is_pre('"') ? '"' : '""<C-o>h'
  inoremap <expr> ' <SID>is_pre("'") ? '"' : "''\<C-o>h"
  inoremap ( ()<C-o>h
  inoremap [ []<C-o>h
  inoremap { {}<C-o>h
  silent! colorscheme habamax
endif

nnoremap gt gt<Plug>(vimrc-gt)
nnoremap <Plug>(vimrc-gt)t gt<Plug>(vimrc-gt)
nnoremap gT gT<Plug>(vimrc-gt)
nnoremap <Plug>(vimrc-gt)T gT<Plug>(vimrc-gt)