Skip to content

Instantly share code, notes, and snippets.

@lf-araujo
Created December 23, 2021 22:59
Show Gist options
  • Save lf-araujo/9b3e239757d6f48a564d75818b46f17c to your computer and use it in GitHub Desktop.
Save lf-araujo/9b3e239757d6f48a564d75818b46f17c to your computer and use it in GitHub Desktop.
R IDE for R statistics, data analysis and a bit of Nim
This is the second version of my R as an IDE for stats using R. It is built on three tools: treesitter, lsp, and Nvim-R.
One has to manually run :TSInstall markdown, :TSInstall R, and :LspInstall R. Will update this with more time in the future
but the code is mostly self explaining:
```vimscript
" Installation {{{
call plug#begin(stdpath('data') . 'vimplug')
Plug 'EdenEast/nightfox.nvim'
Plug 'kristijanhusak/orgmode.nvim'
Plug 'scrooloose/nerdtree'
Plug 'github/copilot.vim'
Plug 'skywind3000/asynctasks.vim'
Plug 'skywind3000/asyncrun.vim'
Plug 'jistr/vim-nerdtree-tabs'
Plug 'nvim-lua/plenary.nvim'
Plug 'nvim-lua/popup.nvim'
Plug 'nvim-telescope/telescope.nvim'
Plug 'neovim/nvim-lspconfig'
Plug 'kabouzeid/nvim-lspinstall'
Plug 'glepnir/lspsaga.nvim'
Plug 'nvim-treesitter/nvim-treesitter', {'do': ':TSUpdate'}
Plug 'nvim-treesitter/nvim-treesitter-textobjects'
Plug 'lifepillar/vim-mucomplete'
Plug 'glepnir/galaxyline.nvim', { 'branch': 'main' }
Plug 'kyazdani42/nvim-web-devicons' " needed for galaxyline icons
Plug 'tpope/vim-ragtag'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-unimpaired'
Plug 'imkmf/ctrlp-branches'
Plug 'hara/ctrlp-colorscheme'
Plug 'simplenote-vim/simplenote.vim'
Plug 'tpope/vim-eunuch'
Plug 'tpope/vim-fugitive'
Plug 'rhysd/vim-grammarous'
Plug 'yegappan/greplace'
Plug 'tomtom/tcomment_vim'
Plug 'ompugao/ctrlp-locate'
Plug 'endel/ctrlp-filetype.vim'
Plug 'suy/vim-ctrlp-commandline'
Plug 'mbbill/desertex'
Plug 'mhinz/vim-startify'
Plug 'jalvesaq/Nvim-R'
Plug 'metakirby5/codi.vim'
Plug 'ctrlpvim/ctrlp.vim'
Plug 'ryanoasis/vim-devicons'
Plug 'tacahiroy/ctrlp-funky'
Plug 'dbeecham/ctrlp-commandpalette.vim'
Plug 'dense-analysis/ale'
Plug 'https://github.com/prashanthellina/follow-markdown-links'
Plug 'phongnh/ctrlp-fzy-matcher'
Plug 'halkn/ripgrep.vim'
call plug#end()
" }}}
" General settings {{{
if exists('+termguicolors')
let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
set termguicolors
endif
colorscheme duskfox
set guifont=Iosevka:h12
let g:molokai_original=1
let g:blamer_enabled = 1
let g:webdevicons_enable_ctrlp = 1
let g:disco_nobright = 1
let g:disco_red_error_only = 1
set bg=dark
let g:yui_comments = "fade"
let g:mapleader = "\<Space>"
let maplocalleader = "\<Space>"
set autochdir
set sessionoptions-=blank " This fixes a problem with nerdtree and sessions
set modelines=1
set spell
set spelllang=en
set mouse=a " Enable mouse support in insert mode.
set clipboard+=unnamedplus " Use clipboard
set guioptions+=a
set backspace=indent,eol,start " To make backscape work in all conditions.
set ma " To set mark a at current cursor location.
" set number " To switch the line numbers on.
set expandtab " To enter spaces when tab is pressed.
set smarttab " To use smart tabs.
set tabstop=2 " Two chars for a tab
set shiftwidth=2
set autoindent " To copy indentation from current line
set si " To switch on smart indentation.
set ignorecase " To ignore case when searching.
set smartcase " When searching try to be smart about cases.
set hlsearch " To highlight search results.
set incsearch " To make search act like search in modern browsers.
set magic " For regular expressions turn magic on.
set showmatch " To show matching brackets when text indicator
set mat=2 " How many tenths of a second to blink
syntax enable " Enable syntax highlighting.
set encoding=utf-8 fileencodings=ucs-bom,utf-8,gbk,gb18030,latin1 termencoding=utf-8
"set nobackup " Turn off backup.
"set nowb " Don't backup before overwriting a file.
"set noswapfile " Don't create a swap file.
"set ffs=unix,dos,mac " Use Unix as the standard file type.
"au! BufWritePost $MYVIMRC source % " auto source when writing to init.vm alternatively you can run :source $MYVIMRC
autocmd CursorHold,CursorHoldI * update " Saves when changing from insert mode
set undofile " Maintain undo history between sessions
set undodir=~/.vim/undodir
" Return to last edit position when opening files
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
" Reload vimrc on save
au BufWritePost ~/.config/nvim/*.{vim,lua} so $MYVIMRC
"map q :quit<CR> " Quit with q
" FIXME: (broken) ctrl s to save
noremap <C-S> :update<CR>
vnoremap <C-S> <C-C>:update<CR>
inoremap <C-S> <Esc>:update<CR>
" exit insert mode
" inoremap <C-c> <Esc>
" Find
map <C-f> /
" indent / deindent after selecting the text with (⇧ v), (.) to repeat.
vnoremap <Tab> >
vnoremap <S-Tab> <
" Cut, Paste, Copy
vmap <C-x> d
vmap <C-v> p
vmap <C-c> y
" Undo, Redo (broken)
nnoremap <C-z> :undo<CR>
inoremap <C-z> <Esc>:undo<CR>
nnoremap <C-y> :redo<CR>
inoremap <C-y> <Esc>:redo<CR>
" This mapping makes Ctrl-Tab switch between tabs.
" Ctrl-Shift-Tab goes the other way.
noremap <C-Tab> :tabnext<CR>
noremap <C-S-Tab> :tabprev<CR>
map <C-t> :tabnew<cr>
" switch between tabs with cmd+1, cmd+2,..."
map <C-1> 1gt
map <C-2> 2gt
map <C-3> 3gt
map <C-4> 4gt
map <C-5> 5gt
map <C-6> 6gt
map <C-7> 7gt
map <C-8> 8gt
map <C-9> 9gt
" until we have default MacVim shortcuts this is the only way to use it in
" insert mode
imap <C-1> <esc>1gt
imap <C-2> <esc>2gt
imap <C-3> <esc>3gt
imap <C-4> <esc>4gt
imap <C-5> <esc>5gt
imap <C-6> <esc>6gt
imap <C-7> <esc>7gt
imap <C-8> <esc>8gt
imap <C-9> <esc>9gt
set completeopt=noselect,noinsert,menuone,preview
" >> Lsp key bindings
nnoremap <silent> gd <cmd>lua vim.lsp.buf.definition()<CR>
nnoremap <silent> <C-]> <cmd>lua vim.lsp.buf.definition()<CR>
nnoremap <silent> gD <cmd>lua vim.lsp.buf.declaration()<CR>
nnoremap <silent> gr <cmd>lua vim.lsp.buf.references()<CR>
nnoremap <silent> gi <cmd>lua vim.lsp.buf.implementation()<CR>
nnoremap <silent> K <cmd>Lspsaga hover_doc<CR>
nnoremap <silent> <C-l> <cmd>lua vim.lsp.buf.signature_help()<CR>
nnoremap <silent> <C-k> <cmd>Lspsaga diagnostic_jump_prev<CR>
nnoremap <silent> <C-j> <cmd>Lspsaga diagnostic_jump_next<CR>
nnoremap <silent> gf <cmd>lua vim.lsp.buf.formatting()<CR>
nnoremap <silent> gn <cmd>lua vim.lsp.buf.rename()<CR>
nnoremap <silent> ga <cmd>Lspsaga code_action<CR>
xnoremap <silent> ga <cmd>Lspsaga range_code_action<CR>
nnoremap <silent> gs <cmd>Lspsaga signature_help<CR>
lua <<EOF
require("lsp")
require("treesitter")
require("statusbar")
EOF
" require("completion")
" }}}
" R configuration - Nvim-R {{{
let g:rout_follow_colorscheme = 1 " R output is highlighted with current colorscheme
let g:Rout_more_colors = 1 " R commands in R output are highlighted
let g:R_pdfviewer="evince"
" let R_show_args = 1 " show the arguments for functions with autocompletion
let g:R_objbr_opendf = 0
let g:R_objbr_openlist = 0
" let R_set_omnifunc = ["rnoweb", "rhelp", "rrst"]
autocmd VimLeave * if exists("g:SendCmdToR") && string(g:SendCmdToR) != "function('SendCmdToR_fake')" | call RQuit("nosave") | endif " exit R when you exit the vim
autocmd FileType rmd set foldmarker=```{,```
autocmd FileType rmd setlocal foldmethod=marker
vmap <Space><Space> <Plug>RDSendSelection
nmap <Space><Space> <Plug>RDSendLine
" Workaround to get auto omni completion FIXME very buggy
" from so/q/35837990/
" function! OpenCompletion()
" if ((v:char >= 'a' && v:char <= 'z') || (v:char >= 'A' && v:char <= 'Z'))
" call feedkeys("\<C-x>\<C-o>", 'n')
" endif
" endfunction
"
" autocmd FileType rmd autocmd InsertCharPre * call OpenCompletion()
" autocmd FileType r autocmd InsertCharPre * call OpenCompletion()
" autocmd FileType Rmd autocmd InsertCharPre * call OpenCompletion()
" autocmd FileType R autocmd InsertCharPre * call OpenCompletion()
" }}}
" CtrlP interface {{{
if executable('rg')
let g:ctrlp_user_command = 'rg --files %s'
let g:ctrlp_use_caching = 0
let g:ctrlp_working_path_mode = 'rw'
endif
let g:ctrlp_match_func = { 'match': 'fzy_matcher#match' }
let g:ctrlp_map = '<C-p>'
let g:ctrlp_cmd = 'CtrlPCommandPalette'
let g:ctrlp_extensions = ['mixed', 'line', 'filetype', 'commandline', 'colorscheme', 'funky', 'branches']
let g:ripgrep_options='--hidden
\ -g "!/cache/*"
\ -g "!/data/*"
\ -g "!/reports/*"
\ -g "!/.git/*"
\ -- '
let g:commandPalette = {
\ 'Ignorecase: Toggle': 'set ignorecase!',
\ 'File: save and close': 'wq',
\ 'Start R': 'call StartR("R")',
\ 'Start Object Browser': 'call RObjBrowser()',
\ 'Start Inim': 'T inim',
\ 'Search files': 'CtrlPMixed',
\ 'MRU': 'CtrlPMRU',
\ 'Search within project': 'call feedkeys(":CtrlPRg ")',
\ 'Search in this file': 'CtrlPLine',
\ 'Commend lines': 'TComment',
\ 'Check grammar': 'GrammarousCheck',
\ 'Set filetype': 'CtrlPFiletype',
\ 'Bye!': 'qa!',
\ 'Command history': 'call ctrlp#init(ctrlp#commandline#id())',
\ 'Find file anywhere in system': 'CtrlPLocate',
\ 'Colorschemes': 'CtrlPColorscheme',
\ 'Unfold all lines': 'call feedkeys("\<Space>zR\<CR>")',
\ 'Fold all lines': 'call feedkeys("\<Space>zM\<CR>")',
\ 'Unfold here': 'call feedkeys("\<Space>zo\<CR>")',
\ 'Navigate sections of this file': 'CtrlPFunkyMulti',
\ 'Run!': 'call feedkeys("\<Space>B\<CR>")',
\ 'More!': 'Telescope builtin',
\ 'Branches': 'CtrlPBranches'}
let g:ctrlp_match_window = 'results:100'
set wildignore+=*/.git/*,*/.hg/*,*/.svn/*
" }}}
" Startify {{{
function! s:gitModified()
let files = systemlist('git ls-files -m 2>/dev/null')
return map(files, "{'line': v:val, 'path': v:val}")
endfunction
" same as above, but show untracked files, honouring .gitignore
function! s:gitUntracked()
let files = systemlist('git ls-files -o --exclude-standard 2>/dev/null')
return map(files, "{'line': v:val, 'path': v:val}")
endfunction
let g:startify_lists = [
\ { 'type': 'files', 'header': [' MRU'] },
\ { 'type': 'sessions', 'header': [' Sessions'] },
\ ]
" }}}
" Nerdtree {{{
nnoremap <C-n> :NERDTreeTabsToggle<CR>
" Start NERDTree when Vim starts with a directory argument.
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists('s:std_in') |
\ execute 'NERDTree' argv()[0] | wincmd p | enew | execute 'cd '.argv()[0] | endif
"autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif
" Exit Vim if NERDTree is the only window left.
autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() |
\ quit | endif
let g:NERDTreeChDirMode = 2
" If another buffer tries to replace NERDTree, put it in the other window, and bring back NERDTree.
autocmd BufEnter * if bufname('#') =~ 'NERD_tree_\d\+' && bufname('%') !~ 'NERD_tree_\d\+' && winnr('$') > 1 |
\ let buf=bufnr() | buffer# | execute "normal! \<C-W>w" | execute 'buffer'.buf | endif
autocmd BufWinEnter * silent NERDTreeMirror " Open the existing NERDTree on each new tab.
" }}}
" ALE {{{
let g:ale_linters = {
\ 'nim': ['nimlsp', 'nimcheck'],
\ 'sh': ['shellcheck']
\}
let g:ale_fixers = {
\ '*': ['remove_trailing_lines', 'trim_whitespace'],
\ 'rmd': ['styler'],
\ 'nim': ['nimpretty'],
\}
let g:ale_fix_on_save = 1
let g:ale_linters_explicit = 1
let g:ale_set_loclist = 0
let g:ale_set_quickfix = 1
let g:ale_lint_on_text_changed = 'never'
let g:ale_lint_on_insert_leave = 0
let g:ale_fix_on_save = 1
let g:ale_sign_error = '✖✖'
let g:ale_sign_warning = '⚠⚠'
highlight ALEErrorSign guifg=Red
highlight ALEWarningSign guifg=Yellow
" }}}
" Nim configuration - asyncomplete {{{
au User asyncomplete_setup call asyncomplete#register_source({
\ 'name': 'nim',
\ 'whitelist': ['nim'],
\ 'completor': {opt, ctx -> nim#suggest#sug#GetAllCandidates({start, candidates -> asyncomplete#complete(opt['name'], ctx, start, candidates)})}
\ })
" }}}
" Nim configuration - CodeRunner and TREPL {{{
let g:CodeRunnerCommandMap = {
\ 'nim' : 'nim c -r $fileName'
\}
let g:code_runner_save_before_execute = 1
let g:neoterm_callbacks = {}
function! g:neoterm_callbacks.before_new()
if winwidth('.') > 100
let g:neoterm_default_mod = 'botright vertical'
else
let g:neoterm_default_mod = 'botright'
end
endfunction
nmap <silent><leader>B <plug>CodeRunner
autocmd FileType nim nmap <leader>d :TREPLSendLine<CR>
" }}}
" Grammarous {{{
"let $PATH.=':/usr/lib64/openjdk-11/bin/'
"let $MYVIMRC='/home/luis/.config/nvim/init.vim'
"let g:SimplenoteUsername = ""
let g:SimplenotePassword = ""
" }}}
" MUCOMPLETE {{{
let g:mucomplete#enable_auto_at_startup = 1
let g:mucomplete#chains = {
\ 'default' : ['omni', 'path', 'c-n'],
\ }
let g:mucomplete#chains['rmd'] = {
\ 'default' : ['user', 'path', 'uspl'],
\ 'rmdrChunk' : ['omni', 'path'],
\ }
" }}}
" Async Run {{{
augroup renderRmd | au!
autocmd BufWritePost *.Rmd call Render()
augroup end
function! Render() abort
:AsyncTask render
endfunction
" function! Render() abort
" :tabnew | te Rscript -e "rmarkdown::render(<afile>:p:S)"
" :tabprev
" endfunction
let g:asyncrun_open = 6
" }}}
" Treesitter {{{
lua << EOF
local parser_config = require "nvim-treesitter.parsers".get_parser_configs()
parser_config.org = {
install_info = {
url = 'https://github.com/milisims/tree-sitter-org',
revision = 'main',
files = {'src/parser.c', 'src/scanner.cc'},
},
filetype = 'org',
}
require'nvim-treesitter.configs'.setup {
-- If TS highlights are not enabled at all, or disabled via `disable` prop, highlighting will fallback to default Vim syntax highlighting
highlight = {
enable = true,
disable = {'org'}, -- Remove this to use TS highlighter for some of the highlights (Experimental)
additional_vim_regex_highlighting = {'org'}, -- Required since TS highlighter doesn't support all syntax features (conceal)
},
ensure_installed = {'org'}, -- Or run :TSUpdate org
}
require('orgmode').setup({
org_agenda_files = {'~/Documents/org/*'},
org_default_notes_file = '~/Documents/org/refile.org',
})
EOF
" }}}
" vim:foldmethod=marker:foldlevel=0
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment