vim

Table of Contents

1. vim   project

1.1. neovim 0.9

vim.treesitter.query.get_query() is deprecated, use vim.treesitter.query.get()
cmp_nvim_lsp.update_capabilities is deprecated, use cmp_nvim_lsp.default_capabilities instead
[NvimTree] “open_on_setup behaviour has been deprecated, please see https://github.com/nvim-tree/nvim-tree.lua/wiki/Open-At-Startup
https://www.reddit.com/r/neovim/comments/12fidjh/comment/jffldq4/

Error executing vim.schedule lua callback: /usr/share/nvim/runtime/lua/vim/treesitter/query.lua:259: query: invalid node type at position 21 for language markdown_inline

1.1.1. Más errores

Error executing lua: vim/_editor.lua:0: nvim_exec2(): Vim:Error executing Lua callback: .../share/nvim/lazy/plenary.nvim/lua/plenary/popup/init.lua:122: Vim:[Telescope-Frecency] init() never returns during the time
stack traceback:
        [C]: in function 'nvim_create_buf'
        .../share/nvim/lazy/plenary.nvim/lua/plenary/popup/init.lua:122: in function 'create'
        ...share/nvim/lazy/telescope.nvim/lua/telescope/pickers.lua:519: in function '_create_window'
        ...share/nvim/lazy/telescope.nvim/lua/telescope/pickers.lua:94: in function 'mount'
        ...share/nvim/lazy/telescope.nvim/lua/telescope/pickers.lua:551: in function 'find'
        ...vim/lazy/telescope-frecency.nvim/lua/frecency/picker.lua:110: in function 'start'
        ...nvim/lazy/telescope-frecency.nvim/lua/frecency/klass.lua:97: in function <...nvim/lazy/telescope-frecency.nvim/lua/frecency/klass.lua:81>
        ...share/nvim/lazy/telescope.nvim/lua/telescope/command.lua:193: in function 'run_command'
        ...share/nvim/lazy/telescope.nvim/lua/telescope/command.lua:259: in function 'load_command'
        ...ocal/share/nvim/lazy/telescope.nvim/plugin/telescope.lua:108: in function <...ocal/share/nvim/lazy/telescope.nvim/plugin/telescope.lua:107>
        [C]: in function 'nvim_exec2'
        vim/_editor.lua: in function 'cmd'
        /home/julian/.config/nvim/lua/user/telescope.lua:159: in function 'on_project_selected'
        ...-project.nvim/lua/telescope/_extensions/project/main.lua:90: in function 'run_replace_or_original'
        ...re/nvim/lazy/telescope.nvim/lua/telescope/actions/mt.lua:65: in function 'key_func'
        ...hare/nvim/lazy/telescope.nvim/lua/telescope/mappings.lua:293: in function <...hare/nvim/lazy/telescope.nvim/lua/telescope/mappings.lua:292>
stack traceback:
        [C]: in function 'nvim_exec2'
        vim/_editor.lua: in function 'cmd'
        /home/julian/.config/nvim/lua/user/telescope.lua:159: in function 'on_project_selected'
        ...-project.nvim/lua/telescope/_extensions/project/main.lua:90: in function 'run_replace_or_original'
        ...re/nvim/lazy/telescope.nvim/lua/telescope/actions/mt.lua:65: in function 'key_func'
        ...hare/nvim/lazy/telescope.nvim/lua/telescope/mappings.lua:293: in function <...hare/nvim/lazy/telescope.nvim/lua/telescope/mappings.lua:292>
Error in decoration provider treesitter/highlighter.win:
Error executing lua: /usr/share/nvim/runtime/lua/vim/treesitter/query.lua:252: Query error at 20:2. Invalid node type "luacode_environment":
(luacode_environment
 ^

stack traceback:
        [C]: in function '_ts_parse_query'
        /usr/share/nvim/runtime/lua/vim/treesitter/query.lua:252: in function 'fn'
        /usr/share/nvim/runtime/lua/vim/func/_memoize.lua:58: in function 'fn'
        /usr/share/nvim/runtime/lua/vim/func/_memoize.lua:58: in function 'get'
        /usr/share/nvim/runtime/lua/vim/treesitter/languagetree.lua:128: in function 'new'
        /usr/share/nvim/runtime/lua/vim/treesitter/languagetree.lua:511: in function 'add_child'
        /usr/share/nvim/runtime/lua/vim/treesitter/languagetree.lua:395: in function '_add_injections'
        /usr/share/nvim/runtime/lua/vim/treesitter/languagetree.lua:447: in function 'parse'
        /usr/share/nvim/runtime/lua/vim/treesitter/languagetree.lua:460: in function 'parse'
        /usr/share/nvim/runtime/lua/vim/treesitter/highlighter.lua:404: in function </usr/sh

1.3. why vim?

Because vim is the gamification of text editing
Text editing is a chore you have to do to get things done but would rather not do, so by gamifying you do it efficiently
Vim creates a language for text editing that becomes second nature. Without that, you switch between solving the problem at hand and making the necessary edits and interrupts the thought process. If you master that language, you avoid all this cognitive load and enhances mental clarity

1.3.1. Use vim / touch type to avoid multi tasking

Since you spend less time typing/editing text, you have more time to think about the code
You are also able to type/edit code faster, but the real deal is spend less time editing and more time thinking
https://blog.ploeh.dk/2018/09/17/typing-is-not-a-programming-bottleneck/
http://www.more-onions.com/tech/2016/7/30/the-cult-of-vim

1.3.1.1. Hypothesis → you lose focus very quickly

Using vim, text editing doesn’t let you lose your focus. If you have to think how to edit whatever, then you lose focus and this efects compounds

  1. https://roosterdan.medium.com/how-to-type-100-words-per-minute-a780fd80fd27

    Most adults read 250 words per minute and speak 120 words per minute so our thought process is at least as fast as that. Regular typing behavior interrupts our thought process as it’s too intentional rather than an automatic subconscious activity. We switch back and forth between thinking about the real problem to thinking about typing and this interrupts our flow. Reducing the cognitive load provides greater mental clarity and enables us to focus on the problem rather than on typing.

1.3.2. Modal config makes sense when you spend a lot of time in each mode

Like batching applied to text editing (batch together similar tasks)

1.3.3. Dependencies of vim

  1. Touch typing
  2. American Keyboard (use altgr layout if you can get away with a few non-english characters)

1.6. Resources

1.6.9. Vim-commands1.gif

Megachuleta

1.6.11. https://github.com/damassi/learn-vim

The 11 steps to learning vim

1.6.13. vim.help

→ vim help in html format

1.6.17. Vim Conf

1.6.17.1. Watch “VimConf.live - Vim Speed and Excellence” on YouTube

https://youtu.be/tCktGgPQ3D0
qwerty is better for vim than dvorak!

1.6.17.2. Ver “Learning Vim: The Path to Mastery (Vim Conf 2020) (Matt Boehm)” en YouTube
  1. https://youtu.be/SZ-xHGD7sMc?t=839 → remap : to ;
  2. https://github.com/wellle/targets.vim → use n to move to next (cinw change inside next word)
1.6.17.3. Watch “What can’t you do in Neovim? VimConf.live 2020” on YouTube

https://youtu.be/78WrSwEKNuM
colores, personalizacion de temas, color picker

1.6.17.4. Let Vim Do the Typing - YouTube

tldr
:h compl-current & :h ins-completion

1.6.17.5. Vim as an IDE (VimConf 2020 Talk)

1.6.18. Damian Conway, “More Instantly Better Vim” - OSCON 2013 - YouTube

1.6.19. Cheat Sheets

1.6.19.1. Vim Cheat Sheet
1.6.19.3. Ultimate Vim Keyboard Shortcuts (new comprehensive cheat sheet!)

1.6.22. Ver “Vim Can Save You Hours Of Work” en YouTube

1.6.23. Ver “Vim: Tutorial on Editing, Navigation, and File Management (2018)” en YouTube

https://youtu.be/E-ZbrtoSuzw

  • 0:00 :: Intro
  • 3:29 :: Why Vim?
  • 7:00 :: Demo 1 - Impractical Vim Usage
  • 9:10 :: Operators, Text Objects, Motions
  • 12:44 :: Demo 2 - Practical Vim Usage with Operators, Text Objects, Motions
  • 14:52 :: Advanced Navigation
  • 15:55 :: Advanced Navigation - Scrolling and Other Motions
  • 16:48 :: Advanced Navigation - Editing
  • 17:36 :: Advanced Navigation - Searching
  • 18:04 :: Advanced Navigation - Marks
  • 18:41 :: Advanced Navigation - Tags
  • 19:15 :: Advanced Navigation - Jumplist / Changelist
  • 20:22 :: Demo 3 - Practical Vim Usage with Advanced Navigation
  • 29:32 :: Project Management
  • 30:50 :: Project Management - Buffers
  • 32:28 :: Project Management - Windows
  • 33:02 :: Project Management - Tabs
  • 34:06 :: Demo 4 - Practical Vim Usage with Project Management (Vim as an IDE)
  • 43:36 :: Clipboard Synchronization
  • 48:17 :: Hotkeys + Misc.
  • 50:05 :: Screen Multiplexing (tmux)
  • 51:27 :: Answer to Important Question
  • 52:14 :: Brief Touch on Abduco + Dvtm as a Tmux Alternative
  • 52:51 :: Questions

1.6.25. Why Learn (Neo)Vim? · so much space

1.6.26. At least one Vim trick you might not know • Hillel Wayne

1.6.28. Games / Exercises

1.6.28.1. https://www.vimgolf.com/

Pick a challenge, fire up Vim, and show us what you got.

1.6.28.3. https://github.com/jmoon018/PacVim

→ pacman game in vim

1.6.29. History of Vim

1.6.31. Introductory

1.6.31.1. Steps to learn Vim | Joren Blog

1.6.32. List of list of neovim plugins

1.6.32.1. neovimcraft

https://neovimcraft.com/
Recopilación de plugins estilo marketplace

1.6.33. vimrc tips

1.6.33.1. Configuración nvim documentada

Tengo un fods (LibreOffice) para poner los atajos más básicos: la mayoría los uso en modo normal, y hay algunos de otros motos
My vim cheatsheet My vim cheatsheet My vim cheatsheet
Para los comandos que tienen más de una pulsación (secuencias de atajos) tiene sentido exportar todo desde un org-mode, para mostrar todo el árbol, pensando más en cosas estilo SPC <x> <y> <z> como lo que tiene doom
(Quizás también poner las cosas estilo d→a→w y demás en árbol, aunque no sean comandos de SPC)

  1. A really cool Vim mode state Flowchart
1.6.33.2. Separar config complicada de vim para poder instalar en los servidores (minimal)

Hacer un vimrc separado sin plugins, o utilizar una variable externa al estilo work.el
Your Vim is Only for You → vim without plugins compatible

1.7. python-vim

1.7.1. Configuración que uso (cheatsheet)

C-backslash
Lanzar terminal flotante
SPC e
Lanzar explorador
SPC b
Buscar en buffers
SPC f,F
Buscar nombre de archivos, buscar en contenido
C-q
Cuando tienes los resultados, añadir a la quickfixlist global
SPC l c
Cerrar ventanas flotantes que se quedan colgadas
K
abrir man o documentación de lo que hay bajo el cursor (también funciona en python)
Añadir un nuevo proyecto
Ahora hago addpro en el directorio que quiero lua print(require("project_nvim.utils.path").historyfile) → editarlo a mano
vim-autosource

Añadir un entorno virtual al path (las terminales de neomux tienen el entorno virtual, para desactivarlo workon klipper; deactivate porque deactivate no está definido)

  let $PATH=printf("%s:%s", $HOME . "/.virtualenvs/venv/bin", $PATH)
  let $VIRTUAL_ENV=$HOME . "/.virtualenvs/venv"
(no term)
nvim-tree
https://github.com/kyazdani42/nvim-tree.lua#default-actions
I
will toggle visibility of hidden folders / files
H
will toggle visibility of dotfiles (files/folders starting with a .)
1.7.1.1. nvim-tree
Default actions

    <CR> or o on the root folder will cd in the above directory
    <C-]> will cd in the directory under the cursor
    <BS> will close current opened directory or parent
    type a to add a file. Adding a directory requires leaving a leading / at the end of the path.

        you can add multiple directories by doing foo/bar/baz/f and it will add foo bar and baz directories and f as a file

    type r to rename a file
    type <C-r> to rename a file and omit the filename on input
    type x to add/remove file/directory to cut clipboard
    type c to add/remove file/directory to copy clipboard
    type y will copy name to system clipboard
    type Y will copy relative path to system clipboard
    type gy will copy absolute path to system clipboard
    type p to paste from clipboard. Cut clipboard has precedence over copy (will prompt for confirmation)
    type d to delete a file (will prompt for confirmation)
    type D to trash a file (configured in setup())
    type ]c to go to next git item
    type [c to go to prev git item
    type - to navigate up to the parent directory of the current file/directory
    type s to open a file with default system application or a folder with default file manager (if you want to change the command used to do it see :h nvim-tree.setup under system_open)
    if the file is a directory, <CR> will open the directory otherwise it will open the file in the buffer near the tree
    if the file is a symlink, <CR> will follow the symlink (if the target is a file)
    <C-v> will open the file in a vertical split
    <C-x> will open the file in a horizontal split
    <C-t> will open the file in a new tab
    <Tab> will open the file as a preview (keeps the cursor in the tree)
    I will toggle visibility of hidden folders / files
    H will toggle visibility of dotfiles (files/folders starting with a .)
    R will refresh the tree
    Double left click acts like <CR>
    Double right click acts like <C-]>
    W will collapse the whole tree
    S will prompt the user to enter a path and then expands the tree to match the path
1.7.1.2. Configuración de proyectos → crear un .git vacío para que lo detecte como proyecto

Con chezmoi no tiene sentido tener en control de versiones todos los directorios de .config, pero sí que le puedo meter un .git (que es como detecta los proyectos) e incluso meterlo en la config por que es parte de la configuración
Es una buena manera de detectar proyectos aunque esté vacío

1.7.1.3. Investigar cómo recargar LSP con entorno virtual   project someday_20230330

Incluso con vim-autosource si tengo un .vimrc está pensado para que navegue a esa carpeta de manera normal y luego lance neovim desde allí
Por ejemplo LSP no me detecta las librerías salvo que haga :e!, pero entonces me muestra doble texto virtual (el de antes, que no me reconoce las librerías del entorno virtual asociado, y el de después, ya habiendo cargado esas librerías)

  1. Source $MYVIMRC without duplicating LSPs
  2. WhoIsSethDaniel/toggle-lsp-diagnostics.nvim: Neovim plugin for toggling the LSP diagnostics.
1.7.1.4. Instalación de LSPs

Probar si no está funcionando el lenguaje en cuestión

:LSPInstall <lang>
1.7.1.5. Neomux
tb
open in new tab (t conflicts)
s
open in horizontal split
vs
open in vertical split
vw <number> file
open file in numbered window
wvp <number>
print contents of numbered window to stdout (pipe it to another command, or execute it via bash)
vc <register>
copy stdin to register
vp <register>
past register into stdout

1.7.2. Neomux, or why you don’t need tmux | nikvdp

As a long-time vim user, one of the things I’ve always been background level jealous of is the claim, sometimes made by our long-lost emacs brethren, that emacs is an operating system and vim is just a text editor.

Parece un buen principio de diseño neovim-remote, intentar anidar lo mínimo posible

1.7.3. Configurar PyLint   project someday_20230330

https://docs.pylint.org/en/1.6.0/run.html → se intala con pip
Ejecutas pylint <archivo> y te muestra la comparación con la versión anterior (Your code has been rated at 6.90/10 (previous run: 5.71/10, +1.19))
Recomendado por pythonspeed:

1.7.3.1. Why Pylint is both useful and unusable, and how you can use it
1.7.3.3. My Pylint
[FORMAT]
max-line-length=120
  • [ ] Me da error de variables de dos letras porque no sigue el snake_case. Esto parece que es tema de la regex que utiliza

1.7.5. vim-autosource

.vimrc.lua

vim.cmd([[
let $PATH=printf("%s:%s", "/home/julian/.local/share/venvs/71a7e2e214fa6400c06d3bc937b3c740/venv/bin", $PATH)
let $VIRTUAL_ENV=$HOME . "/home/julian/.local/share/venvs/71a7e2e214fa6400c06d3bc937b3c740/venv/"
set colorcolumn=100
]])

local null_ls_status_ok, null_ls = pcall(require, "null-ls")
if not null_ls_status_ok then
	return
end

-- https://github.com/jose-elias-alvarez/null-ls.nvim/tree/main/lua/null-ls/builtins/formatting
local formatting = null_ls.builtins.formatting
-- https://github.com/jose-elias-alvarez/null-ls.nvim/tree/main/lua/null-ls/builtins/diagnostics
local diagnostics = null_ls.builtins.diagnostics

null_ls.setup({
	debug = false,
	sources = {
		formatting.prettier.with({ extra_args = { "--no-semi", "--single-quote", "--jsx-single-quote" } }),
		formatting.black.with({ extra_args = { "--fast", "--line-length", "100" } }),
		formatting.isort,
		diagnostics.flake8,
	},
})

-- vim: ft=lua

1.7.6. DAP

1.7.6.2. Configuración con vim-autosource

https://github.com/mfussenegger/nvim-dap/wiki/Debug-Adapter-installation#Python
No estoy seguro de cuál es el requisito (si debugpy tiene que estar en el mismo entorno virtual que las dependencias de tu proyecto, o pueden ser separados)
Parece que no hay problema:

      -- debugpy supports launching an application with a different interpreter then the one used to launch debugpy itself.
      -- The code below looks for a `venv` or `.venv` folder in the current directly and uses the python within.
      -- You could adapt this - to for example use the `VIRTUAL_ENV` environment variable.

En el entorno virtual pip install debugpy

lua << EOF
    local dap = require('dap')
    dap.configurations.python = {
      {
        type = 'python';
        request = 'launch';
        name = "Launch file";
        program = "${file}";
        pythonPath = function()
          return os.getenv('HOME') .. '/.virtualenvs/mail/bin/python'
        end;
      },
    }
    local dap = require('dap')
    dap.adapters.python = {
      type = 'executable';
      command = os.getenv('HOME') .. '/.virtualenvs/mail/bin/python';
      args = { '-m', 'debugpy.adapter' };
    }
EOF
1.7.6.4. Official page for Debug Adapter Protocol
1.7.6.6. “Why I prefer Neovim over VSCode” → DAP Plugins
1.7.6.7. Lista de plugins para probar con dap

1.7.7. Remote neovim

1.7.7.1. Using Neovim inside (Docker) containers   project someday_20230330

Aquí proponen conectarse por ssh, si pongo ssh como interfaz común a todo a lo que voy a acceder y utilizar siempre distant.nvim para conectarme a máquina remota o a contenedor local
https://www.reddit.com/r/neovim/comments/thr1n2/using_neovim_inside_docker_containers/

1.7.7.3. Utilizar neovim remoto

Distrubución sencilla que pueda descargarse de una vez con todo lo necesario, como un binario
Utilizar neovim-remote o algo similar para sólamente tener que conectarse a un servidor
Si tengo acceso por ssh, me vale con un túnel ssh al puerto en el que esté escuchando
https://hlfshell.ai/posts/repeatable-ros-environments/

1.7.8. Configuracion cuando no se lía con el cwd

Hay un comando lcd que está mal en esta ruta

cd ~/.local/state/nvim/view
rg -F "code/azure-devops" -uuu | rg 'rest'
# Nombres de archivo extraños como este:
# ~=+Work=+1projects=+ctz=+rest=+.gitignore=
# lcd ~/Work/1projects/ctz/rest

1.7.9. Configuración treesitter

:echo nvim_get_runtime_file('parser', v:true)

Si hay más de uno hay que borrar el otro
/usr/share/nvim/runtime/parser me sale extra
El único que tiene que haber es /home/julian/.local/share/nvim/lazy/nvim-treesitter/parser

1.7.11. TODO Revisar config vs https://github.com/LunarVim/nvim-basic-ide

Empezar por plugins.lua como punto de entrada

1.7.12. TODO Archivos renombrados/borrados/nuevos en telescope-frecency

1.7.13. TODO Poner nvim como PAGER

Tiene que funcionar con los caracteres de escape de colores:
https://github.com/lucc/nvimpager

1.7.14. TODO Añadir tokenización a ripgrep en neovim

1.7.15. TODO Mirar debugger de lua interactivo

Con Lazy parece que ya lo carga bien, pero no consigo poner un breakpoint
https://github.com/slembcke/debugger.lua

1.7.16. TODO Mirar mason.nvim PSA

Es lo que instala todas las dependencias que van por fuera
https://www.reddit.com/r/neovim/comments/122ow0u/psa_changes_to_the_masonnvim_registry/

1.7.17. TODO Añadir javascript y html

No tienen bien puesto los espacios de las tabs (shiftwidth y tabstop)
Formateo html no está configurado

1.7.18. TODO Configuración pair programming

1.7.19. TODO Mejoras de Primeagen How to Vim in 2023: Tips and Tricks - YouTube

  • fugitive o similar
  • Context TreeSitter
  • Undo Tree → y usarlo en emacs
  • Algo para Bookmarks (Ctrl+J Ctrl+K ya están pillados)

1.7.20. TODO Jupyter con vim

1.7.22. Deshabilitar vim.lsp y treesitter para archivos muy grandes → hacer un toggle de estos

lua vim.lsp.stop_client()
lua vim.treesitter.stop()
lua vim.lsp.buf_detach_client(0, 2)

Me suena que había algo para quitar el LSP y/o recargarlo, nativo

:lua vim.treesitter.stop()

Esto de abajo no sé si hace algo:
:lua require(“user.lsp.handlers”).capabilities.semanticTokensProvider = nil

1.7.23. Telescope archivos muy grandes

1.7.24. Conflictos en git no funcionan

Cuando utilizo los colores gui, me deja de funcionar los conflictos de git, y creo que nunca han ido en modo claro
Probar esta extensión que parece que tiene lo mismo
https://github.com/akinsho/git-conflict.nvim

1.7.26. Errores nvim fold

Creo que es porque utilizo nvim-ufo y treesitter combinados y se lía nvim
https://www.reddit.com/r/neovim/comments/160e4nt/nvimufo_fold_automatically_closes_when_editing/
También muy interesante nvim -V1 con el conmando de Telescope que comentan

1.7.29. DONE Controlar moviemientos de ratón horizontales

Si está un split de terminal abierto, aunque tengas foco en otra ventana que sí es de código, se envían caracteres de control extraños a la terminal
Una cosa que se puede hacer es prefijar cada uno de esos comandos con:
Iterando por todos los buffers de terminal:

  1. Guardar el estado actual del modo de ese buffer
  2. Cambiar el modo de buffer a modo normal (en vez de modo terminal)
  3. Ejecutar el comando de ratón
  4. Volver a dejar cada buffer como estaba

1.7.30. DONE Controlar clicks en cambio de pantalla

Por ejemplo si hago C-\ C-n y luego gT funciona bien, pero no con click → era por kitty

1.7.31. DONE Corregir bookmarks siempre están en /home/julian/

Hay que ejecutar primero SPC bL y luego SPC bl ya funciona bien
Parece que es que no se entienden bien bookmarks.nvim y telescope

1.7.33. Lista de cosas a instalar/probar   try

1.7.33.3. Configurar Refactorización   project try someday_20230330

https://github.com/python-rope/rope/wiki/Rope-in-Vim-or-Neovim
El que está mejor es ropevim, con lsp no está maduro, los keybindings son interesantes (SPC c a)

  1. https://github.com/python-rope/pylsp-rope
  2. https://github.com/python-rope/ropevim
  3. https://github.com/ThePrimeagen/refactoring.nvim

    Lo probé extrayendo una función pero no reconoce que la función se usa en múltiples sitios

  4. https://github.com/nvim-treesitter/nvim-treesitter-refactor
  5. Configuración ropevim
    g = {
    		U = { "<Esc><Cmd>RopeUndo<CR>", "Rope Undo" },
    		R = { "<Esc><Cmd>RopeUndo<CR>", "Rope Redo" },
    		n = {
    			name = "Rope Create",
    			m = { "<Esc><Cmd>RopeCreateModule<CR>", "Rope Create Module" },
    			p = { "<Esc><Cmd>RopeCreatePackage<CR>", "Rope Create Package" },
    			f = { "<Esc><Cmd>RopeCreateFile<CR>", "Rope Create File" },
    			d = { "<Esc><Cmd>RopeCreateDirectory<CR>", "Rope Create Directory" },
    		},
    		r = { "<Esc><Cmd>RopeRename<CR>", "Rope Rename" },
    		l = { "<Esc><Cmd>RopeExtractVariable<CR>", "Rope Extract Variable" },
    		m = { "<Esc><Cmd>RopeExtractMethod<CR>", "Rope Extract Method" },
    		i = { "<Esc><Cmd>RopeInline<CR>", "Rope Inline" },
    		v = { "<Esc><Cmd>RopeMove<CR>", "Rope Move" },
    		x = { "<Esc><Cmd>RopeRestructure<CR>", "Rope Restructure" },
    		s = { "<Esc><Cmd>RopeChangeSignature<CR>", "Rope Change Signature" },
    		p = {
    			name = "Move",
    			r = { "<Esc><Cmd>RopeRenameCurrentModule<CR>", "Rope Rename Current Module" },
    			v = { "<Esc><Cmd>RopeMoveCurrentModule<CR>", "Rope Move Current Module" },
    			p = { "<Esc><Cmd>RopeModuleToPackage<CR>", "Rope Module to Package" },
    		},
    		g = {
    			name = "Rope Generate",
    			m = { "<Esc><Cmd>RopeGenerateModule<CR>", "Rope Generate Module" },
    			p = { "<Esc><Cmd>RopeGeneratePackage<CR>", "Rope Generate Package" },
    			f = { "<Esc><Cmd>RopeGenerateFile<CR>", "Rope Generate File" },
    			d = { "<Esc><Cmd>RopeGenerateDirectory<CR>", "Rope Generate Directory" },
    		},
    	}
    
1.7.33.4. Trucos avanzados surround   project try someday_20230330

vim.cmd [[ let b:surround_{char2nr('F')} = "function() return \r end" ]]
So to illustrate, if I have the text:

foo('bar')

And I do siWF, I get this:

function() return foo('bar') end
1.7.33.5. Poner que cuando guarde un requirements.in me compile los requirements   project try someday_20230330

Esto ahora lo tengo más claro, con un autocommand

1.7.33.6. Sincronizar tags y proyectos   project try someday_20230330

En un crontab o algo así, añadir los repos que no estén en el historyfile para que sea automático
Los repos los mantengo por tags

1.7.33.7. Search in buffer with fzf   project try someday_20230330
  1. Looking for a plugin to list all search results in a buffer, similar to Sublime Text
1.7.33.8. Configurar movimientos de gh, gj, gk en nvim-tree   project try someday_20230330

Como en los árboles de org mode

1.7.33.9. Narrow en vim   project try someday_20230330
1.7.33.10. Poner > en folding en vez de en números   project try someday_20230330

Con la próxima versión de neovim ya se podría
https://github.com/kevinhwang91/nvim-ufo/issues/4

1.7.33.11. Fold horizontal (esconder líneas muy largas)   project try someday_20230330
1.7.33.12. Instalar dim unused imports   project try someday_20230330
1.7.33.13. ReplaceWithRegister   project try someday_20230330

1.7.34. Se puede utilizar easymotion con comandos estilo ]m ?

Parece que no, no sé por qué es así. Funciona con treesitter?

1.7.35. Cosas a corregir

1.7.37. Errores

1.7.37.2. DONE Since updating to 0.7 I can no longer cycle through LSP completions with ctrl-n and ctrl-p

https://www.reddit.com/r/neovim/comments/uehlkq/since_updating_to_07_i_can_no_longer_cycle/
https://www.reddit.com/r/neovim/comments/u7ak90/do_you_get_a_bad_argument_error_on_max/
https://github.com/hrsh7th/nvim-cmp/issues/920
No me pasa porque utiliza C-j, C-k, pero me da este otro error:

Error executing vim.schedule lua callback: ...te/pack/packer/start/nvim-cmp/lua/cmp/view/docs_view.lua:38: bad argument #1 to 'min' (number expected, got nil)
stack traceback:
        [C]: in function 'min'
        ...te/pack/packer/start/nvim-cmp/lua/cmp/view/docs_view.lua:38: in function 'open'
        ...re/nvim/site/pack/packer/start/nvim-cmp/lua/cmp/view.lua:229: in function 'callback'
        .../site/pack/packer/start/nvim-cmp/lua/cmp/utils/async.lua:95: in function ''
        vim/_editor.lua: in function <vim/_editor.lua:0>
1.7.37.3. Arreglar :bd con múltiples tabs y con múltiples splits (windows)   project someday_20230330

Cuando hago :bd o ZC/ZB para cerrar un buffer pero tengo un split o tabs, me cierra todo!
Creo que tengo que investigar más a fondo el sistema de buffers/windows/splits para ver qué está pasando
La opción es ver que hace :bdelete (comando completo, con :help)
https://vim.fandom.com/wiki/Deleting_a_buffer_without_closing_the_window → parece que es bastante común
Con :bprev, :bnext se puede hacer también

1.7.37.4. Iniciar la terminal en la misma carpeta en la que estoy ejecutando la shell   project someday_20230330
1.7.37.5. Configurar neovim-remote para que confirme salir de terminal   project someday_20230330

A veces hago C-w q y la lío

1.7.38. Mejoras pequeñas

1.7.38.1. DONE Arreglar el jaleo de paths que tengo

Al final era por el .profile por defecto de Ubuntu carga el .bashrc independientemente de la terminal que tengas configurada, así que
Creo que es porque tengo configurada bash como terminal
Por ejemplo cosas como ~/.cargo no me las cogía, pero ni poniéndolo en en .bashrc me lo reconoce → Todo esto es porque al ejecutarlo no interactivamente no lee el .bashrc, entonces le va a dar igual que lo pongas ahí
Si hago Alactritty→zsh→nvim sí que me sale el path completo, pero la manera de lanzar las terminales con neomux no va bien

1.7.38.2. https://github.com/windwp/windline.nvim → mejor performance
1.7.38.3. Probar Neo-tree 2.0 → no se rompe tanto como nvim-tree

https://www.reddit.com/r/neovim/comments/tnkg65/neotree_20_released/
https://github.com/nvim-neo-tree/neo-tree.nvim
Quiero poner que / haga lo que hace en el resto de plugins, pero no lo he conseguido. Lo que sí que funciona es que :vim pattern te busca como si hicieses / → ya funciona!

1.7.38.4. Hacer que Python reconozca cosas extrañas con sys.path

Esto puede ir en el .vimrc.lua porque es por cada proyecto

1.7.38.5. Utilizar legendary.nvim para gestionar los atajos (ahora utilizo which-key)   project someday_20230330
1.7.38.6. Buscar en un workspace en telescope/añadir una carpeta como workspace en Telescope sobre la marcha
1.7.38.7. Renombrar proyectos de Telescope/project.nvim
1.7.38.9. Mejorar buffers de terminal

1.7.39. Pijadas

1.7.39.1. Instalar equivalentes en lua de los plugins en vimscript   project someday_20230330
  1. Which vim plugins do not have a lua equivalent yet? : neovim
1.7.39.2. Configuración de colores de indentación   project someday_20230330

https://github.com/lukas-reineke/indent-blankline.nvim
Viene de este en vscode: https://marketplace.visualstudio.com/items?itemName=pinage404.better-readability-extension-pack
Que tiene eso + resaltar caracteres de espacio en blanco cuando lo seleccionas (un toggle también está chulo)

1.7.39.3. Hacer un link a la ayuda de vim en emacs y en (neo)vim   project someday_20230330

Links estilo [ [ :h vim-modes ] ] , también [ [ :help vim-modes ] ]

1.7.39.4. Cosas chulas

Threading graph / Asyncio graph en Pycharm (Running, waiting for lock, running with lock, deadlock)
Diagramas de clases y de llamadas en vim?
Alternativas Sourcetrail

1.7.39.5. range-highlight.nvim : neovim

Si pones :15,30 que te resalte las líneas seleccionadas como si fuese visual line mode

1.7.40. Resources

1.7.40.1. Control for Global, Leader for Local

Control + Leader (Space) then makes sense??

1.7.40.2. LSP attach keybindings

Redefine keys using lsp attach so that they only work in certain buffers and it still works fine everywhere else
Por ejemplo K para que cuando estás en un lenguaje te salga la definición de lo que tienes bajo el cursor pero que siga funcionado en el resto de sitios

1.7.40.3. Types of vim users
  1. Minimalist - almost stock configuration, barely any plugins;
  2. Standard - some plugins, but not so many that it becomes hard to port;
  3. Plugin junkies - 500+ line vimrc, and 50+ plugins.

If you’re in group (3), then I’d say you favor lots of scriptability as opposed to things Vim values like minimalism and portability; if this is the case, then I’d take a look at Emacs, which is built specifically for that.

1.7.40.6. IPython con vim
1.7.40.7. LSP neovim
  1. Ver “Why Neovim builtin LSP?” en YouTube

    https://youtu.be/ArwDgvYEZYk
    Goals of the project, what you can do with it

  2. Ver “Neovim” en YouTube
  3. Why I’m switching to Native LSP over CoC
    • LSP is builtin, ton of docs, builtin has more community support
  4. TICKLER https://github.com/bash-lsp/bash-language-server/issues/252 → zsh lang server   track
  5. Interesting LSP symbols: navigation and show context
  6. https://matklad.github.io/2023/10/12/lsp-could-have-been-better.html
  7. What are LSP snippets and should I disable them if I use a snippet plugin?
  8. Syntax Tree Preview
    1. simrat39/symbols-outline.nvim: A tree like view for symbols in Neovim using the Language Server Protocol. Supports all your favourite languages.
    2. liuchengxu/vista.vim: Viewer & Finder for LSP symbols and tags
    3. preservim/tagbar: Vim plugin that displays tags in a window, ordered by scope
1.7.40.8. LSP Engines

https://crispgm.com/page/neovim-is-overpowering.html
There are popular Vim LSP clients include ale, coc.vim, LanguageClient-neovim, and vim-lsp, which tries to bring language servers to Vim/Neovim. But Neovim 0.5 embeds a built-in LSP client by itself instead of plugins. Because LSP is built for editors and “we can have nice things”.

  1. ALE (Asynchronous Lint Engine)

    https://github.com/dense-analysis/ale
    https://www.reddit.com/r/Python/comments/jar4rd/linters_which_one/

    • If somebody here is using Vim as an Python editor, there is very good plugin ALE (Asynchronous Lint Engine) which can run all of them (flake8, pylint, mypy) on the background and highlight all problematic lines.
1.7.40.10. Navigation
  1. https://github.com/ray-x/navigator.lua

    Easy code navigation, view diagnostic errors, see relationships of functions, variables (LSP + Treesitter)

  2. https://github.com/ThePrimeagen/harpoon

    https://www.youtube.com/watch?v=Qnos8aApa9g
    With git worktree ⇒ harpooned files per branch
    ↓ No marks inside files, only per file
    ↑ good tmux integration
    Alternatives: https://pablopunk.com/posts/i-made-a-neovim-plugin-because-i-missed-a-feature-from-vscode

1.7.40.14. vim REPL
  1. GitHub - erietz/vim-terminator: Run your code in an output buffer or a vim terminal very conveniently
  2. Run your code with vim-terminator
  3. iron.nvim/iron.txt at master · hkupty/iron.nvim

    https://github.com/hkupty/iron.nvim/blob/master/doc/iron.txt
    Iron is a helper plugin that allows you to manage and interact with live
    Read-Eval-Print-Loops (REPLs) directly from Neovim, through terminal buffers.
    Iron mostly interacts with plugins via stdin/stdout, with few exceptions.

  4. kassio/neoterm: Wrapper of some vim/neovim’s :terminal functions.
    1. neoterm in lua
      1. nyngwang/NeoTerm.lua: You can attach a terminal-buffer for each buffer.
      2. itmecho/neoterm.nvim: Neovim lua plugin for managing a floating terminal window
  5. Usar IPython como interfaz común a múltiples kernels
1.7.40.16. Neovim TreeSitter
  1. Aprender Treesitter   learn
    1. Intentos previos
      git clone https://github.com/tree-sitter/tree-sitter-python --depth 1
      cd tree-sitter-python
      npm install --global node-gyp
      node-gyp configure
      tree-sitter generate && node-gyp build
      
      # Para instalarlo, al final:
      pip3 install tree_sitter
      python -c "from tree_sitter import Language; print(Language.build_library('build/python.so', [\"$PWD\"]))"
      
      # Tiene que existir un python.so en:
      ls "$XDG_DATA_DIRS/tree-sitter/parsers"
      ls "$XDG_DATA_HOME/tree-sitter/parsers"
      

      Todas estas cosas de instalación al final son muy complicadas

      https://sr.ht/~wintershadows/tsquery/ → hacer una query sobre stdin (de momento no soporta archivos). Puede estar interesante pasarle un cierto formato json o así para posterior proceso. Yo pensaba que sacaba simplemente el texto
      https://github.com/BrianHicks/tree-grepper → grep utilizando tree-sitter
      https://github.com/mergestat/treequery → no me funciona, es curiosamente del mismo que hace askgit
      https://www.bearer.com/blog/tips-for-using-tree-sitter-queries
      https://stackoverflow.com/questions/67550226/how-to-do-case-insensitive-query-in-tree-sitter
      Encontrar las funciones que se llaman function_name:
      Funciona en Playground pero no en tsquery, no entiendo nada

      ((function_definition
          name: (identifier) @funcname) @param1
        (#match? @funcname "^function_name$"))
      

      Mucho más sencillo, en python puro:

      python -c "from inspect import getsource; import make_index; print(getsource(make_index.build_index))"
      
    2. Tree-sitter|Playground
  2. Syntax Tree
  3. CodeQL

    Data Flow, un nivel por encima de AST, te dice cómo fluyen los datos
    https://github.com/pwntester/codeql.nvim

    1. Rule Writing for CodeQL and Semgrep | Spaceraccoon’s Blog
  4. tree-sitter/tree-sitter-graph: Construct graphs from parsed source code
  5. Treesitter movements
    1. nvim-treesitter-textsubjects: Plugin which determines the text object you meant based on your location in the syntax tree
    2. https://www.reddit.com/r/neovim/comments/z2iv9p/introduce_treesj_neovim_plugin_for/
  6. Structural search and replace : neovim
  7. Sacar estadísticas agrupando por función/método etc

    Estilo Prioritizing Technical Debt as If Time & Money Matters • Adam Tornhill • GOTO 2022 - YouTube

    • Git blame para saber quiénes han escrito una función
    • Estadísticas de git de cuánto cambia cada archivo/función
    • Estadísticas de cuántos errores tiene cada función
    • Estadísticas de vulnerabilidades por cada función (esto es un poco lo que hacer CodeQL)
  8. atusy/tsnode-marker.nvim
1.7.40.17. Unix as IDE
  1. Series: Unix as IDE « Arabesque
1.7.40.18. Configurar comentarios y resaltado de sintaxis en markdown/org mode por cada lenguaje   project someday_20230330

Que me ponga resaltado de sintaxis si creo un bloque ```<lang> y que me ponga el comentario correcto
Fenced

  1. GitHub - Shougo/context_filetype.vim: Context filetype library for Vim script (syntax highlighting for different languages in the same file/buffer)

    https://github.com/Shougo/context_filetype.vim
    SQL Syntax inside py files, js syntax in HTML files

1.7.41. Evaluar lua de manera rápida / Breakpoints

lua=<código>

1.7.42. ldelossa/litee.nvim: A framework for building “IDE-lite” experiences in Neovim

1.7.42.1. Calltree

https://github.com/ldelossa/litee-calltree.nvim
Analogous to VSCode’s “Call Hierarchy” tool, this plugin exposes an explorable tree of incoming or outgoing calls for a given symbol.
Unlike other Neovim plugins, the tree can be expanded and collapsed to discover “callers-of-callers” and “callees-of-callees” until you hit a leaf.

1.7.42.2. Symboltree

https://github.com/ldelossa/litee-symboltree.nvim
Analogous to VSCode’s “Outline” tool, this plugin exposes a live tree of document symbols for the current file.
The tree is updated as you move around and change files.

1.7.42.3. Filetree

https://github.com/ldelossa/litee-filetree.nvim
Analogous to VSCode’s “Explorer”, this plugin exposes a full feature file explorer which supports recursive copies, recursive moves, and proper renaming of a file (more on this in the appropriate section).

1.7.42.4. Bookmarks

https://github.com/ldelossa/litee-bookmarks.nvim
This plugin exposes a way to create Bookmarks, pinnable areas of important code, and organize them into one or more Notebooks.
Notebooks allow you to open and close sets of Bookmarks depending on what you’re working on that day.

1.7.43. DONE Idea de gestión de venvs   idea

1.7.43.1. Un venv en el PATH delante de la versión de python que sean hard links a otros paquetes

Tener un directorio fijo donde pongo los entornos virtuales con hard links.
Exportar al PATH delante del python de sistema, y lo voy cambiando sobre la marcha

  1. Cuando no está activo ningún entorno se puede borrar
  2. Es muy general y resuelve el problema de los venvs
  3. Se presta a setups en los que te creas tu propio venv a cachos, con partes del venv con los requirements del proyecto y partes con los requirements-dev (linters, formateadores, etc)
  4. Puedes crearte un <project>/venv como hard link para mayor compatibilidad
  1. Cosas sueltas / Implementación ?

    Makefiles que se ejecutan al inicio? → Investigar

1.7.43.2. pip no me pilla el del entorno virtual sino el del entorno de ~/.local/bin

1.7.44. Instalación de LunarVim   ARCHIVE

  • Pruebo pyright y instalarlo a mano, pero luego ya utilizé LunarVim
curl -sl https://deb.nodesource.com/setup_14.x | sudo bash -
sudo apt-get install -y nodejs
# intento npm i -g pyright, pero me pide sudo. entonces:
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
nvm install node
sudo apt remove -y nodejs # Sólo la utilizo para bajarme nvm, porque si no npm no va a ir sin sudo (???) No estoy seguro de si lo tengo que quitar o no
sudo apt install -y lua5.4 cargo
npm i -g pyright # Esto me hizo falta ejecutarlo alguna vez, porque lunarvim no lo instalaba y petaba
bash <(curl -s https://raw.githubusercontent.com/lunarvim/lunarvim/master/utils/installer/install.sh)

Al final instalo LunarVim, que tene pocas dependencias más (node, npm y cargo que está en repos. También le instalé lua5.4)
https://www.chrisatmachine.com/Neovim/27-native-lsp/

1.7.45. Instalación Neovim from Scratch   ARCHIVE

  • Instalar Prettier

      npm install --save-dev --save-exact prettier
      # tengo que hacer un alias en ~/.local/bin/prettier
    
  • Instalar stylua

      cargo install stylua
    

1.7.46. nvr_wrapper no funciona en dentro de kitty

Se lanza mal, parece que no tiene color. Lo que se puede hacer es simplemente rm ~/.local/share/nvim/site/pack/packer/start/neomux/plugin/Linux.x86_64.bin/nvr

1.7.47. Pasarse a neovide?

1.9. config sobre la marcha vim   onthefly

  • Relative number in vim
    • :set rnu nu
  • Highlight current line, column
    • :set cul
    • :set cuc
  • vi mode in bash
    Ojo que no tiene diw por ejemplo, hay que hacer de
    • set -o vi
  • indentación
" tabstop, number of visual spaces per TAB
set ts=4
" softtabstop, number of spaces in tab when editing
set sts=4
" shiftwidth, number of spaces per level of indentation
set sw=4

1.10. ThePrimeagen (vim channel)

1.10.1. Tech Weekly #1 : NeoVim Terminal - YouTube

Jump to file with line/char offset (C-w F with offset, C-w f without offset)
Also gF, going back with C-^ C-o
init.vim
Crea una g:win_ctrl_buf_list

[[<job_id>, <buffer_id>], 0, 0, 0]

Para saltar a cada buffer y enviar comandos a cada terminal
Al final local vimrc https://andrew.stwrt.ca/posts/project-specific-vimrc/

1.10.2.

1.10.3. Primeagen configs

1.10.3.1. https://github.com/ThePrimeagen/.dotfiles/blob/874636dad3cbcad6ca96982047025181684993f2/nvim/.config/nvim/init.vim
" Plebvim lsp Plugins
Plug 'neovim/nvim-lspconfig'
Plug 'hrsh7th/cmp-nvim-lsp'
Plug 'hrsh7th/cmp-buffer'
Plug 'hrsh7th/nvim-cmp'
Plug 'tzachar/cmp-tabnine', { 'do': './install.sh' }
Plug 'onsails/lspkind-nvim'
Plug 'github/copilot.vim'

" Plug 'nvim-lua/completion-nvim'
Plug 'glepnir/lspsaga.nvim'
Plug 'simrat39/symbols-outline.nvim'
" Nice icons in autocomplete like VSCode
" Plug 'tjdevries/nlua.nvim'
" Plug 'tjdevries/lsp_extensions.nvim'

" Neovim Tree shitter
Plug 'nvim-treesitter/nvim-treesitter', {'do': ':TSUpdate'}
Plug 'nvim-treesitter/playground'

" Debugger Plugins
Plug 'mfussenegger/nvim-dap'
Plug 'Pocco81/DAPInstall.nvim'
Plug 'szw/vim-maximizer'
1.10.3.2. https://github.com/ThePrimeagen/.dotfiles/blob/ca41b9e81a131cc0ac414d26d6703b5c21fd143a/nvim/.config/nvim/init.vim
" Debugger Plugins
Plug 'puremourning/vimspector'
" Visual debbugging style

1.10.4. Harpoon

1.12. neovim

1.12.1. vim language (vimscript) vs neovim lua

1.12.1.1. nanotee/nvim-lua-guide: A guide to using Lua in Neovim
1.12.1.2. Everything you need to know to configure neovim using lua | Devlog

https://vonheikemen.github.io/devlog/tools/configuring-neovim-using-lua/

vim.cmd ([[your vim commands]])
lua <<EOF
print('hello from lua')
EOF
1.12.1.3. vim.opt is now merged into master

https://www.reddit.com/r/neovim/comments/nn0b8f/vimopt_is_now_merged_into_master/

vim.opt is the lua alternative to VimL’s set command. Before this PR, if you are configuring neovim in lua with vim.bo, vim.wo, you have to be aware of the scope like buffer, window before setting the options.
You can read the PR’s description for more clarification :)

https://github.com/neovim/neovim/pull/13479

1.12.3. Fennel (Functional lua)   try

1.12.3.1. Emacs to Neovim
  1. Olical/aniseed: Neovim configuration and plugins in Fennel (Lisp compiled to Lua)

    Aniseed bridges the gap between Fennel (a Lisp that compiles to Lua) and Neovim

  2. Olical/nvim-local-fennel: Execute local Fennel Lisp files in Neovim upon startup

    Run Fennel inside Neovim on startup with Aniseed.

1.12.3.2. 🍊 Tangerine - Painless Fennel integration in Neovim
1.12.3.3. One more nvim config with fennel, I am glad I moved (from vimscript)

1.13. Tricks

  • He abierto un archivo y no soy root
    :w ! sudo tee %
  • Ejecutar comandos en las líneas selecciondas
    :<','>w !cat | sed -E 's/ *updated_at =//;s/,//' | xargs -I {} date -d @{} --iso-8601=minutes
    :.w !cat | sed -E 's/ *updated_at =//;s/,//' | xargs -I {} date -d @{} --iso-8601=minutes
  • Cambiar líneas de dos a unix
    https://stackoverflow.com/questions/82726/convert-dos-windows-line-endings-to-linux-line-endings-in-vim
    :e ++ff=dos | set ff=unix | w!
  • Quiero reseleccionar la última selección
    gv
  • Quiero aplicar un comando sobre la última selección
    :*
  • Quiero abrir la url que hay bajo el cursor
    gx
  • Quiero abrir el archivo bajo el cursor
    gf, c-w gf en nueva ventana, c-w f en nueva ventana, y utilizando F salta a la línea exacta (formato archivo:linea)
    https://vi.stackexchange.com/questions/7958/open-files-with-whitespace-names-from-within-vim-with-gx (con espacio es un poco más complicado)
  • Comentar/descomentar sin plugins
    • ^v, seleccionar las primeras lineas para comentar, I# ESC
    • ^v, seleccionar las primeras lineas para descomentar, 2x ESC (2dl ESC alternativo)
  • Revertir los cambios que has hecho
    e! %
  • Pasar tu archivo por un programa externo, por ejemplo formateo
    :%!jq .
  • Empipar datos con (neo)vim (vim necesita argumento - para procesar entrada de stdin, nvim no)
    cat file | nvim, cat file | vim -
    Si quieres pasar después la información a otra pipe, necesitas vipe que está en moreutils:
    https://stackoverflow.com/questions/10686183/pipe-vim-buffer-to-stdout
    cat file | vipe | xargs -I _ rm -rf "_"
  • Copiar las lineas que matchean a un archivo
    :g/Plug '/:.w >> plugins.lua → . significa línea actual, si no escribe el archivo entero
  • Recargar config de vim
    :source $MYVIMRC
  • Aplicar patrón a las líneas impares (para pasar una lista de 2 campos a csv)
    Si son lineas impares, lo indento
    https://stackoverflow.com/questions/55668102/how-to-indent-even-odd-numbered-lines-of-a-text-file-using-vim
    :g/^/if line('.') % 2==1 | :normal! >> | endif
    (Lo intenté hacer todo de una vez con J pero peta porque cambia el número de líneas, y aparte cuando entro en modo INSERT no puedo salir a NORMAL)
    Sustituyo los 4 espacios más salto de linea por una coma y listo
    :%s/\n /,
  • Abrir ayuda de vim sin split, pantalla completa
    :help <loquesea> | only
  • Copiar en portapapeles el path del archivo actual
    :let @+=expand("%:p")
  • “Guardar como” el archivo actual
    :w <nuevo nombre> | :e <nuevo nombre>
    :w <nuevo nombre> | :call delete(expand('%')) | :e <nuevo nombre> si además quieres borrar el archivo original
  • Fullscreen ventana actual
    Ctrl+W_ will maximize a window vertically.
    Ctrl+W| will maximize a window horizontally.
    Ctrl+W= will resize all windows to equal sizes.
  • Renombrar buffer actual (útil para terminales por ejemplo)
    :file new name of buffer
  • Ver ruta del archivo actual
    https://vi.stackexchange.com/questions/104/how-can-i-see-the-full-path-of-the-current-file
  • Surround sin plugins:
    En una selección visual, surround con (): c()<ESC>P

1.14. Text Editing

1.14.1. Movements

1.14.1.1. Cursor Movement in Vim

https://vim.works/2019/03/03/cursor-movement-in-vim/
Comprehensive guide to cursor movements within a line

  1. j,k vs +,-
    • = j0
    • = k0
  2. gj, gk, g0, g$

    (not in org-mode)
    move by visual line, not line, when text is wrapped

  3. gq

    split long line into multiple lines

  4. gv: visual select previous selection
  5. gJ: join with no space in between
  6. g&: make previous substitution global
1.14.1.2. Page Movement in Vim

https://vim.fandom.com/wiki/All_the_right_moves

zt, zz, zb scroll to set cursor on top, middle, bottom
L, M, H jump the cursor to low, middle, high without scrolling
Ctrl-D  move half-page down
Ctrl-U  move half-page up
Ctrl-B  move backwards
Ctrl-F  move forwards
Ctrl-O  jump to older cursor position
Ctrl-I  jump to next cursor position (after Ctrl-O)
Ctrl-Y  move one line upwards, keep cursor
Ctrl-E  move on line downwards, keep cursor

:help scroll.txt

  1. Keep cursor position relative
1.14.1.3. which jump plugin are you using now? : neovim
  • Snapshot:
    • 126 (33.4%) hop.nvim
    • 88 (23.3%) lightspeed.nvim
    • 63 (16.7%) leap.nvim (*)
    • 44 (11.7%) vim-easymotion
    • 34 (9.0%) vim-sneak
    • 22 (5.8%) pounce.nvim
    • (*) Leap is an actual fork of Lightspeed, intending to replace it eventually
  • Grouped by basic approach:
    • 207 (54.8%) “minimalist”: Sneak, Lightspeed, Leap, Pounce
    • 170 (45.2%) “many methods”: EasyMotion, Hop
  • Family trees:
    • 185 (49%) Sneak -> Lightspeed, Leap
    • 170 (45.2%) EasyMotion -> Hop
  • Special stuff / superpowers:
    • “clairvoyance”: Lightspeed, Leap
    • fuzzy search: Pounce
    • limitless extensibility: Hop, Leap
1.14.1.4. vim-sneak, vim-easymotion
1.14.1.5. phaazon/hop.nvim: Neovim motions on speed!

Hop is a complete from-scratch rewrite of EasyMotion,

1.14.1.7. https://github.com/phaazon/hop.nvim

Hop is an EasyMotion-like plugin allowing you to jump anywhere in a document with as few keystrokes as possible. It does so by annotating text in your buffer with hints, short string sequences for which each character represents a key to type to jump to the annotated text.

1.14.1.8. ggandor/leap.nvim: 🦘 Neovim’s answer to the mouse: a “clairvoyant” interface that makes on-screen jumps quicker and more natural than ever

Leap allows you to jump to any positions in the visible window / tab page area by entering a 2-character search pattern, and then potentially a “label” character to choose among multiple matches, similar to Sneak. The novel idea in Leap is its “clairvoyant” ability: it maps possible futures, and shows you which key(s) you will need to press before you actually need to do that.

1.14.1.9. rlane/pounce.nvim: Incremental fuzzy search motion plugin for Neovim

Pounce is a motion plugin similar to EasyMotion, Sneak, Hop, and Lightspeed. It’s based on incremental fuzzy search

1.14.2. Language of vim

1.14.2.1. Structure
  • verbs
    • transitive (operators)
      • verb modifier object (dip, di{, das)
      • verb motion (ce, d$, v0)
    • non-transitive
      execute the command right away
    • v is transitive and non-transitive at the same time
      pressing v gets you into visual mode but also accepts motions
  • motions
    they actually move the cursor
    can be thought of as non-transitive verbs
    • simple/non-transitive (w, e, b)
    • compound/transitive (t<char>, f<char>)
  • objects
    are defined by regexs (e.g. in dt“, ” is not an object)
1.14.2.2. Verbs Modifiers Objects
  1. Learn to speak vim
  2. List of examples
    1. verbs
      key function verb form
      v visual select transitive
      c change (delete+insert mode) transitive
      d delete transitive
      y yank transitive
      gu,gU make lower,upper case transitive
      >, < inc,dec indentacion level transitive
      x cut non-transitive
      i insert (before) non-transitive
      a append (insert after) non-transitive
      p paste non-transitive
      n,N find next,prev match non-transitive
      ~ swap case non-transitive
    2. modifiers
      key function
      a around
      i inside
      t till find a character (not including)
      f find a character (including)
      ? find upwards
    3. objects
      key function
      w word
      s sentence
      b block/parenthesis
      p paragraph
      t tag (html/xml)
      "’` quotes `’"
      ([{ parenthesis/brakets/braces }])
      G go to last line
      #G go to #
      gg go to 1
      0, ^ beggining of line, beggining of line after blank
      $ end of line
  3. https://takac.github.io/2013/01/30/vim-grammar/

    Tiene más sentido 2d4w / 4d2w (no sé la diferencia, creo que son iguales) que 8dw cuando borras IPs 127.0.0.1

  4. Qué regex usa vim para word/paragraph y demás?

    :h cursor-motions

  5. Operations and motions are orthogonal

    https://whileimautomaton.net/2008/11/vimm3/operator

    operators and motions are orthogonal, so:
    Once you learn a new motion,
    you can do edit on various portions of text with operators you learned.
    Once you learn a new operator,
    you can do new kind of edit with various motions you learned.

  6. Objetos para moverse en treesiter   idea

    Moverse siguiendo la sintaxis del archivo, para reemplazar todos los movimientos
    Ahora dependen un poco de los detalles de la sintaxis y de cómo hayas separado el archivo (di{ por ejemplo no es tan útil en python, dip depende de cómo estructures el archivo)

1.14.2.3. Argument and method objets in vim

Integrate somehow with LSP? Change order of arguments easily
Also change the order in a method chain (move between point, also both ends)
Also change the order in a bash pipe
If each method is in one line, the it can be done at the line level (except perhaps the first and last ones)
Movimiento de vim entre cadenas de métodos (move between point, igual que el de argumentos)
Si tienes un método por línea no hace falta

  1. How can I do delete in commas, change inside periods? Basically treating periods and commas like quotation, etc.
    1. https://github.com/wellle/targets.vim → use n to move to next (cinw change inside next word)
1.14.2.4. Multiple Cursors in vim

This is often cited as contrary to the “vim way”
Useful when declarating types, which usually involves writing the same thing multiple times, at different locations
Also cursors give you immediate feedback, which macros/substitutions don’t offer (at least by default)
https://github.com/mg979/vim-visual-multi

  1. Alt click for multiple cursors?

    https://www.reddit.com/r/neovim/comments/tjvs4z/alt_click_for_multiple_cursors/
    Vim does these things differently. Here are a few ways of inserting the same text in multiple places :

    • Visual block mode followed by I or A (this is basically multi-cursors in one column, but you don’t see the output on the other lines until you press esc) - :help ctrl-v
    • Macros (let you record and replay your keypresses) - :help recording
    • The dot command - :help .
    • cgn followed by . - :help gn
      gn = visual select next match, c = change next match
    • ctrl-a in insert mode (inserts the latest thing you inserted) - :help i_ctrl-a
    • :s lets you use regex to modify all matches in a selected range - :help :substitute
    • If you have an LSP client attached: LSP rename - :help vim.lsp.buf.rename()
  2. Please, please implement multi-cursor support. For anyone that doesn’t agree, pl… | Hacker News

    https://news.ycombinator.com/item?id=7672532
    #+begin_src org
    I’ve heard the “macros is the same” sentiment many times, and usually it’s from people who have never had much experience with multiple cursors, at least not in the situations where it’s useful, and therefore don’t realize how much more convenient they are in many every-day situations.
    #+end_src org
    #+begin_src org
    The basic problem with macros and global replace is that they don’t happen immediately and don’t give you feedback. I don’t know any vim user who hasn’t had the distinct pleasure of needing 3 tries to record a macro before they got it right.
    What’s more, if I record a macro and run it, then realize after it that I want to do a small addition, I have to go through all the “setup” steps again - go back to the start, re-record, add the logical of finding the next block, and so on. I can’t just visually see the situation and say “oh yeah, why don’t I add this little tweak”.
    #+end_src org

  3. My recent ramblings about multiple cursors and similar concepts : emacs
  4. You don’t need more than one cursor in vim
  5. Do you (really) need multiple cursors? (for the 1000th time) : neovim
  6. Multiple cursors feature is equivalent of macros with live feedback : neovim

1.14.3. Macros

  • https://vim.fandom.com/wiki/Macros
  • How to Edit an Existing Vim Macro
  • q[a-z] to create a macro, q[A-Z] to append to a macro, @{a-z} to append to a macro
  • Macros are actually registers, you can see them with :registers
  • You can copy a macro between vim by using the “ register, apply with @”
  • You can “pass arguments to a macro” by using 2 macros:
    1. One macro has a parameter that can be replaced.
      Dumb example: :g/potato/:norm dd, delete all lines that match potato
    2. The other macro acts on the first macro
      Dumb example: :s/dd/jdd/ now it deletes the line below all lines that mach potato (:g/potato/:norm dd:g/potato/:norm jdd)

1.14.4. Registers

1.14.5. Command mode

Ctrl+F to edit commands itself within vim, RET to execute command
Ctrl+G, Ctrl+T to go to next/prev match without having to use n/N

1.14.5.1. Commands
1.14.5.2. Filter current buffer through external command

%!command
%!sed s/potato/tomato/

1.14.5.3. Paste external command output in buffer

:!command

1.14.5.6. :norm

:%norm ys$"A: "" executes the command in every line (for example convert into a json format)

1.14.5.7. :s
  1. Lookahead/lookbehind advanced regex

    https://web.archive.org/web/20100725091217/http://briancarper.net/blog/448/vim-regexes-are-awesome

    • :s/\v → very magic mode
    • \_. → like ., matches also \n
    • :s\v\<[^<]+\>/\L&/g → lowercase everything between <>
    Lookaround (Perl) Lookaround (vim) Name What it Does
    (?=foo) (atom)\@= Lookahead Asserts that what immediately follows the current position in the string is foo
    (?<=foo) (atom)\@<= Lookbehind Asserts that what immediately precedes the current position in the string is foo
    (?!foo) (atom)\@! Negative Lookahead Asserts that what immediately follows the current position in the string is not foo
    (?<!foo) (atom)\@<! Negative Lookbehind Asserts that what immediately precedes the current position in the string is not foo

    Unlike perl, “Vim allows non-fixed-width patterns.”

  2. https://vim.fandom.com/wiki/Get_the_name_of_the_current_file
    :echo @% def/my.txt directory/name of file (relative to the current working directory of /abc)
    :echo expand(’%:t’) my.txt name of file (’tail’)
    :echo expand(’%:p’) /abc/def/my.txt full path
    :echo expand(’%:p:h’) /abc/def directory containing file (’head’)
    :echo expand(’%:p:h:t’) def First get the full path with :p (/abc/def/my.txt), then get the head of that with :h (/abc/def), then get the tail of that with :t (def)
    :echo expand(’%:r’) def/my name of file less one extension (’root’)
    :echo expand(’%:e’) txt name of file’s extension (’extension’)
  3. Global match group

    https://www.baeldung.com/linux/sed-replace-multi-line-string -> scripts de sed, puedes hacer de todo
    & te matchea todo lo que cumple (como si fuese \0)

    1. newline

      So you can’t use \0 to mean NULL, so you use \n
      So you can’t use \n to mean \n, so you use \r.
      So you can’t use \r to mean \r, but I don’t know who would want to add that char on purpose.

      https://stackoverflow.com/questions/71417/why-is-r-a-newline-for-vim

1.14.5.9. :v

invert match
Like global, but only apply on those lines that do NOT match

1.14.5.10. sed
1.14.5.11. :/, :?
  1. Ajustes finos de búsqueda

    https://vimhelp.org/pattern.txt.html#search-offset

    • flags de búsqueda (mueve el cursor no al match sino a lo que se especifique, como pequeñas correciones de movimiento)
    • +n, -n para ir n lineas arriba o abajo de un match
    • e[±n] para ir n caracteres después/antes del final (end) del match
    • s[±n] para ir n caracteres después/antes del inicio (start) del match. También vale con b en vez de s
  2. \%V regex atom

    https://vimmer.io/tip/searching-inside-visual-range
    This atom limits matches to within the visual area, so instances of the pattern outside of the visual area aren’t picked up

    • visually select the lines with visual-line mode (V)
    • re-enter normal mode (<esc>)
    • initiate a forward search (/)
    • use the \%Vfoo search pattern
1.14.5.12. Ex Mode

Q en modo normal, :visual para salir
\q ?q para buscar
https://vi.stackexchange.com/questions/457/does-ex-mode-have-any-practical-use

1.14.6. vim regexes

1.14.6.1. Are vim substitutions the same format as sed substitutions?

https://www.reddit.com/r/vim/comments/ttqeer/are_vim_substitutions_the_same_format_as_sed/
The best place to learn about Vim regex flavor is inside the help pages, :help pattern-overview

1.14.6.3. vim regexes are awesome

Recopilación de muchas cosas

1.14.7. g commands

gx
open url
gf
open file
K
open man page

1.14.8. insert mode shortcuts

1.14.8.1. :help ins-special
  • Alt-<key> = ESC <key>
  • insert previously inserted text
  • insert previous inserted text, ESC
  • backspace <BS>
  • <Tab>
  • New Line
  • Next/Previous Completions
  • show contents of <register>
  • insert into <register>
  • C-X mode (:h ins-completion)
  • insert caracter above/below
1.14.8.2. :help ins-special-special
C-O
Insert Normal mode (execute next command in normal mode, go back to insert)
1.14.8.3. Shift+arrows

Like Ctrl+Arrows

1.14.8.4. C-t, C-g on search

n, N, without having to exit search mode

1.14.8.5. Increment/Decrement

Ctrl-A, Ctrl-X to Increment, Decrement

1.14.8.6. C-r insert register contents
1.14.8.7. Indent/Deindent

C-t, C-d to Indent/Deindent

1.14.9. git diff

1.14.9.1. Diffview.nvim - Cycle through diffs for all modified files for any git rev
1.14.9.2. New diff option for better 2 and 3 buffer diff views :linematch

https://www.reddit.com/r/neovim/comments/nchmrn/new_diff_option_for_better_2_and_3_buffer_diff/
Conflictos muy bien gestionados, mínimos cambios posibles
Es un fork de neovim

  1. TICKLER Cubic Diff https://github.com/neovim/neovim/pull/14537   track

1.15. Navigation

1.15.1. Jumps

1.15.1.1. jumps
C-]
Jump to definition
gC-]
Jump to definition (with a list of possible definitions)
C-t
Jump back up the tag stack
1.15.1.2. My Jumps
  • i3 marks
  • Global marks (persistent)
  • Bookmarks (persistent)
  • Quickfix list
  • alternate file
  • next, prev buffer
  • jump back, forward (persistent)
  • next, previous tag (LSP folows tags)
  • Local Quickfix list (Location list)
  • Local diagnostics
  • Next git hunk
  • Next, previous match (persistent)
  • Local marks
  • A list of vim lists

1.15.2. Marks

https://vim.fandom.com/wiki/Using_marks
m{mark}
To jump to a mark enter an apostrophe (' ) or backtick (`) followed by a letter. Using an apostrophe jumps to the beginning of the line holding the mark, while a backtick jumps to the line and column of the mark.

Command Description
`. jump to position where last change occurred in current buffer
`" jump to position where last exited current buffer
`0 jump to position in last file edited (when exited Vim)
`1 like `0 but the previous file (also `2 etc)
'' jump back (to line in current buffer where jumped from)
`` jump back (to position in current buffer where jumped from)
`[ or `] jump to beginning/end of previously changed or yanked text
`< or `> jump to beginning/end of last visual selection

1.15.3. Tabs

https://vim.fandom.com/wiki/Using_tab_pages

:tabe
new tab
:tabe <new-file|%>
open new file | current file in new tab
gt,gT <n>gT
tab navigation (next, previous, nth tab)
:tab sp
split and open in new tab
:tabe <UP>
autocomplete from history

1.15.4. Window splits

https://www.linux.com/training-tutorials/vim-tips-using-viewports/
:h window

  • C-w r, C-W R to rotate split
  • C-w s, C-w v → horizontal split, vertical split
  • [N]C-w s → make a vertical split N lines tall
  • C-w H J K L → move active window to a full split

1.15.5. Buffers

1.15.5.1. Buffer centric workflow
  • utilizar una una tab por cada conjunto de archivos no, por cada archivo
  • utilizar la lista de argumentos para definir los archivos a los que quieres ir (puedes editar esta lista si quieres con un comando específico)

1.15.6. Snippets

Ruta de los snippets (son archivos de texto)

/usr/share/vim/addons/snippets/

1.15.7. A list of vim lists

https://www.vi-improved.org/a-list-of-vims-lists/

  • Jump list
  • Change list
  • Quickfix list
  • Location list
  • Buffer list
  • Argument list
  • Tag stack
  • Tag match list

1.16. Projects

1.16.1. Sessions

https://bocoup.com/blog/sessions-the-vim-feature-you-probably-arent-using

  • :makesession <file> → :mks <file>
  • :mks! <file> para sobreescribirlo
  • :source <file>, vim -S <file> para cargarlo
1.16.1.4. Persistent higlights across sessions
1.16.1.5. Persistent quickfixlists across sessions   project maybe_20230330

Change quickfixlist on a based of saved queries, per project

1.16.1.6. possession.nvim: flexible & extensible session management   try

1.16.2. Project Marks / Bookmarks

1.16.2.1. https://github.com/cbochs/grapple.nvim

tags are like file-level marks
https://github.com/cbochs/grapple.nvim#grapple-api
Note: only one tag can be created per scope per file. If a tag already exists for the given file or buffer, it will be overridden with the new tag.
https://github.com/cbochs/grapple.nvim/issues/58
Grapple only allows one tag per file. This is because your cursor location is tracked on a per-file basis. If you’d like to mark specific locations within a file, I’d recommend using :h mark

1.16.2.3. MattesGroeger/vim-bookmarks: Vim bookmark plugin
  • Toggle bookmarks per line ⚑
  • Add annotations per line ☰
  • Navigate all bookmarks with quickfix window
  • Bookmarks will be restored on next startup
  • Bookmarks per working directory (optional)
  • Fully customisable (signs, sign column, highlights, mappings)
  • Integrates with Unite’s quickfix source if installed
  • Integrates with ctrlp.vim if installed
  • Works independently from vim marks
  1. tom-anders/telescope-vim-bookmarks.nvim: Integrates vim-bookmarks into telescope.nvim
1.16.2.4. crusj/bookmarks.nvim: Remember file locations and sort by time and frequency.

The data file is based on the cwd of each project for separate storage.
Not very fast/intuitive, maybe faster marks harpoon style
Stored under ~/.local/share/nvim/bookmarks/ as a lua file
Example of data:

require("bookmarks.list").load{
	id = 'ee8975e08a14b60719c728793889565c',
    filename = '/home/julian/code/orgzly-integrations/git-sync.sh',
    line = 127,
    line_md5 = 'cbb184dd8e05c9709e5dcaedaa0495cf',
    updated_at = 1677347136,
    fre = 1,
    description = 'test bookmark',
    rows = 280,
}
1.16.2.5. SOMEDAY Links de emacs a bookmarks.nvim

Abrir nvim con bookmarks precargado e incluso con cosas ya abiertas, como sesiones de trabajo (pero que no te abra por defecto lo de la última vez)
Que se pueda lanzar en una instancia existente o en una nueva
Puede ser cambiar un archivo en ~/.local/nvim, en bookmarks.nvim, cambiag XDG_DIR…

1.16.3. Quickfix List

  • Apply to all lines matching in a file or in all project a s,g command
  • Lines match regex or some lsp condition
  • Quickfixlist: search with fzf/fzy, add to qfix
  • Global: search results across all project
  • Local: linting, local to window, search in file
  • copen, cnext, cprev (global): C-q, C-j, C-k
  • lopen, lnext, lprev (local): SPC q, SPC j, SPC k
  • cdo, ldo → Apply a command
  • Execute a command and save in the quickfixlist :cexpr system('grep -n xyz *')

https://www.youtube.com/watch?v=IoyW8XYGqjM
https://github.com/tpope/vim-dispatch
The quickfix and location lists in Vim

  1. Link al vídeo de prime que no funciona
1.16.3.1. Plugins to filter/edit the quickfixlist   try
  1. tommcdo/vim-lister: A collection of commands for manipulating Vim’s lists
  2. itchyny/vim-qfedit: Edit the quickfix/location list freely
  3. romainl/vim-qf: Tame the quickfix window.
  4. romainl/vim-qlist: Persist the results of :ilist and related commands via the quickfix list.
  5. sk1418/QFGrep: a vim plugin to filter entries in Quickfix
  6. stevearc/qf_helper.nvim: A collection of improvements for the quickfix buffer
    • Why another quickfix plugin?

    Why not just use vim-qf, nvim-bqf, QFEnter, etc?
    Those are all great plugins, but I wanted two features that I could not find:

    1. Keep the quickfix location in sync with cursor location in the file
    2. Have one keybinding for next/prev that intelligently chooses between quickfix and loclist
1.16.3.4. Save differents kinds of quickfixlists, multiple quickfixlists, like bookmarks

1.16.4. Terminal mode

https://vimhelp.org/terminal.txt.html#Terminal-mode
Como tmux, pero no interpreta las cosas exactamente igual. Por ejemplo el prompt lo interpreta como parte de la línea
Está bien para tener terminal con vim en un servidor random
C-\ C-N para salir a modo normal (C-W N no me ha funcionado)

1.16.4.1. NoCLC.nvim: Simple NeoVim plugin for disabling the cursor-line/column in unused windows/buffers.

https://www.reddit.com/r/neovim/comments/n3m4fc/noclcnvim_simple_neovim_plugin_for_disabling_the/

augroup cursorline
  autocmd!
  autocmd WinEnter,BufEnter * setlocal cursorline cursorcolumn
  autocmd WinLeave,BufLeave * setlocal nocursorline nocursorcolumn
augroup END
1.16.4.2. WaylonWalker/Telegraph.nvim: Send commands system commands in an elegant way   project try someday_20230330
  • The Problem
    I want to bind hotkeys to run shell commands with context about my current file, line, word, or working directory without parsing all of that each time I want to make a new binding.
  • The other Problem
    I often want these commands sent to a tmux session that I can get to quickly. Doing this often requires the same couple of lines that is more than a single line.

1.16.5. tmux+vim

1.16.5.1. nvim vs tmux
1.16.5.2. Editar el buffer de la terminal

https://github.com/neovim/neovim/issues/8805
https://stackoverflow.com/questions/34885550/can-one-edit-a-terminal-buffer-in-normal-mode-in-neovim
https://www.reddit.com/r/neovim/comments/3ng0cw/editable_term/
Parece que no se puede remplazar el texto de la terminal
https://vi.stackexchange.com/questions/7898/is-it-possible-to-edit-a-terminal-buffer-in-normal-mode

  • Una cosa que tiene más sentido es añadir esto a la config de zsh:

      bindkey -a '  ' edit-command-line # SPC SPC para editar en nvim
    
  • Un workaround es añadir esto con xdotool a la config de i3:
    1. Asumir que estamos en selección de línea, con el comando ya editado
    2. Copiar con y, salir del modo normal de neovim con a
    3. Ejecutar C-c para limpiar la terminal actual
    4. Pegar

1.17. colors and icons

1.17.1. It was always painful for me to pick colors from 256-color palette. Finally, I wrote tiny online color picker to ease vim and terminal palettes tuning. I’m so happy now that I could not help sharing it

1.17.4. Icon set using nonicons for neovim plugins and settings

1.18. Books

1.18.1. Mastering Vim Quickly

Seems more like a collection of tricks than an actual comprehensive reference book for starters
https://jovicailic.org/mastering-vim-quickly/

1.18.2. iggredible/Learn-Vim: A book for learning the Vim editor the smart way.

1.18.3. Practical Vim

1.19. Vim Distributions / Configuration frameworks

1.19.0.2. veonim/onivim/oni2

Parece que el desarrollador es bastante troll? veonim ya no existe y estaba lleno de memes
https://github.com/veonim/veonim → se renombró a https://github.com/smolck/uivonim
https://www.onivim.io/
https://github.com/onivim/oni2
Compatibilidad con extensiones de VSCode(?)

The goal of this project is to build an editor that doesn’t exist today - the speed of a native code editor like Sublime, the power of modal editing, and the rich tooling that comes with a lightweight editor like VSCode.

1.20. Hacer un mapeo entre evil-mode y nvim   project someday_20230330

GOAL: Tener un setup compartido entre [[id:e5919047-c3b8-4791-9e50-f90fef349dcd][vim]] y [[id:f45722ee-41e9-4df2-afb3-2d10e392f6e7][emacs]]

Qué plugin de nvim se corresponde con tal otro plugin o config de evil-mode?
https://github.com/hlissner/doom-emacs/tree/develop/modules/editor/evil → aquí se puede empezar
De momento utilizo por ejemplo:

1.20.1. vim-surround

1.20.2. vim-sneak vim-seek

https://github.com/justinmk/vim-sneak
https://github.com/goldfeld/vim-seek

z → 12 |ah123 → 3 (en nvim hace |ah123 → 23)

d

x → 12 |ah123 → 123

1.20.2.1. Poner igual doom y nvim en sneak

1.20.3. Break undo

1.20.3.1. Poner Break undo en emacs

1.20.4. textobj-line

1.20.5. Todas las cosas de Alt+HJKL, las tengo por ahí en el init.vim

1.21. Vimscript

1.21.1. Mapping vs Command vs Function

https://youtu.be/6LPBpmkQdw8?t=569

Operation Speed
       ↑ +----------+
  High | |  Mapping |
       | +----------+
       |
       |
       |             +---------------+
       |             |    Command    |
       |             +---------------+
       |
       |
       |                             +------------------+
       |                             |     Function     |
   Low |                             +------------------+
       |------------------------------------------------→    Expresiveness
          Low                                   High

1.21.2. Vim Variables

https://www.cs.oberlin.edu/~kuperman/help/vim/variables.html

:set - shows vars different from defaults
:set all - shows all values
:set foo? - shows the value of foo
:set foo+=opt - add opt to the value w/o changing others
:set foo-=opt - remove opt from value
:set foo& - reset foo to default value
:setlocal foo - only the current buffer

:verbose set foo? - tells you where it was last set!

1.22. Plugins

1.22.1. Scroll

1.22.1.1. DONE Curso de Vim: Haz que #Vim tenga un “scroll” fluido con vim-smoothie – Victorhck in the free world
1.22.1.2. Curso de Vim: Sincronizar el “scroll” en dos ventanas del editor #Vim – Victorhck in the free world

1.22.2. Entrenamiento de vim

1.22.2.1. Evil/vim Motion Training

1.22.3. Search keybindings (like which key in emacs)

1.22.3.1. liuchengxu/vim-which-key: Vim plugin that shows keybindings in popup
  1. Spelling suggestions plugin for which-key
1.22.3.3. [nvim-mapper] a Telescope extension to help you find and manage your keymaps !

https://www.reddit.com/r/neovim/comments/os96la/nvimmapper_a_telescope_extension_to_help_you_find/

1.22.3.4. cheatsheet.nvim: A cheatsheet plugin with a telescope interface : neovim
1.22.3.5. What does Ctrl + \ do?

1.22.9. Vim-maximizer

That last one, <ctrl-w> o is useful for getting a bigger view of a single one of your splits. I use this often. But a frustrating aspect of it is that there’s no easy way to go back to the intricate split setup I had prior. Well, there is a plugin for that actually and it’s now become an integral part of my workflow. The vim-maximizer plugin adds a command you can use to toggle the current split to fill the entire screen.
Meter tmux-maximize

1.22.10. roshnivim/init.lua → collection of nvim plugins

1.22.15. CamelCaseMotion

https://github.com/bkad/CamelCaseMotion
Por ejemplo que w funcione sólo dentro de las palabras delimitadas por camelCase
Normalmente delimita por - y _

1.22.17. ISuckAtSpelling.nvim: A NeoVim plugin that auto-corrects spelling mistakes in various natural and programming languages!

1.22.17.1. Update on ISuckAtSpelling.nvim: the project (now named AbbrevMan.nvim) changed its scope!

1.22.18. GitHub - nanotee/zoxide.vim: A small (Neo)Vim wrapper for zoxide

1.22.19. jvgrootveld/telescope-zoxide: An extension for telescope.nvim that allows you operate zoxide within Neovim.

1.22.21. https://github.com/kosayoda/nvim-lightbulb

Code actions on a given line

1.22.24. DONE tpope/vim-unimpaired: unimpaired.vim: Pairs of handy bracket mappings

Complementary mappings using [<letter ]<letter>

1.22.26. Vim without plugins (How to do 90% of What Plugins Do)

1.22.26.1. Use ctags instead of IDE go to definition (faster)
1.22.26.2. Autocomplete
1.22.26.3. Use keyboard macros instead of snippets

:read <your file>

1.23. DONE Highlight cursor line after cursor jump

1.23.1. Highlight cursor line after cursor jump | Vim Tips Wiki | Fandom

1.23.1.1. jumphl.vim - Highlight cursor line after cursor jump : vim online

1.24. Ideas   idea

1.24.1. Hay un vim pero com swipe?

Un teclado intuitivo para el móvil que te permita editar palabras a nivel del que lo hace vim

1.24.2. Hacer remap <tab> → za

El problema es que interpreta <c-i> como <tab> sí o sí (en modo normal, no habría c-i, c-o)
https://vi.stackexchange.com/questions/16161/how-to-map-c-i-separate-from-tab

1.24.3. 2daw hacia atrás en vim

https://www.reddit.com/r/vim/comments/24wbuz/command_to_delete_one_full_word_backwards/

  • v to toggle exclusiveness → e dvb dvb dvb
  • Another one is daw h daw h daw h daw h (macro), works in the middle of the word

1.24.4. key bindings - How to add accent to letters in normal mode? - Vi and Vim Stack Exchange

Como ~ pero con tildes (en español como sólo hay tildes de un tipo es muy sencillo y útil)

1.24.5. Hay en vim crop?

Que sólo te mantenga lo que has seleccionado y borre el resto

1.25. Floaterm

1.25.2. GitHub - mcchrish/nnn.vim: File manager for vim/neovim powered by n³

Floaterm file manager
https://github.com/mcchrish/nnn.vim
nnn.vim, vim-floaterm nnn wrapper and nnn.nvim (neovim exclusive).

1.26. vim en excel

https://github.com/kjnh10/ExcelLikeVim
También hay otras como https://github.com/andmarti1424/sc-im pero son más primitivas
https://www.reddit.com/r/vim/comments/7yq561/a_microsoft_excel_plugin_for_vim_keybindings/ → quizás sacar una lista de posibles keybindings y tips de los links

1.28. https://www.visidata.org/ → spreadsheet in terminal   project try someday_20230330

1.29. Which new Neovim pairing plugin do you prefer: nvim-autopairs or pears.nvim?

1.30. org mode en vim   project someday_20230330

1.30.1. Orgmode.nvim - Orgmode clone written in Lua for Neovim 0.5

https://www.reddit.com/r/neovim/comments/o8zp0k/orgmodenvim_orgmode_clone_written_in_lua_for/
Instalármelo y configurarle todos los atajos de teclado para que sean lo más parecidos posibles a doom
Se instala un lsp custom de org mode, tendría que ir en lua/user/lsp, o en lua/user/lsp/settings

local parser_config = require("nvim-treesitter.parsers").get_parser_configs()
parser_config.org = {
	install_info = {
		url = "https://github.com/milisims/tree-sitter-org",
		revision = "f110024d539e676f25b72b7c80b0fd43c34264ef",
		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
})

1.30.3. Tree-sitter grammar for org-mode

https://www.reddit.com/r/orgmode/comments/tyfxnf/treesitter_grammar_for_orgmode/
Para neovim, dicen que no se puede representar bien

1.30.4. Meter Alt+hjkl y demás en vim   project someday_20230330 someday_20230330

Se pueden hacer en cualquier contexto, pero en orgmode en emacs sólo las puedo hacer en listas → buscar si hay manera de que sean globales, a veces he hecho una lista para luego deshacerla
Hacer cosas de este estilo:

" Swap text without copying it (ddp, xp, ...)
" Since we use the system register, the unnamed register is fine to store it
vnoremap H ""x2h""p
vnoremap J :m '>+1<cr>gv=gv
vnoremap K :m '<-2<cr>gv=gv
vnoremap L ""x""p

nnoremap <leader>h ""x2h""p
nnoremap <leader>j :m .+1<cr>==
nnoremap <leader>k :m .-2<cr>==
nnoremap <leader>l ""x""p

inoremap <c-h> <esc>h ""x2h""pa
inoremap <c-k> <esc>:m .-2<cr>==a
inoremap <c-j> <esc>:m .+1<cr>==a
inoremap <c-l> <esc> ""x""pa:set

Lo malo de esto es que genera conflicto con c-j, c-k, spc j, spc k para quickfixlist

1.30.6. Errores de SPC ss en nvim org mode no funcionan

1.30.7. Tips org mode

Refile con telescope con preview y que te va al heading
https://github.com/joaomsa/telescope-orgmode.nvim → anclar a funciones en vez de org mode
https://github.com/crispgm/telescope-heading.nvim

1.34. Dokuwiki

1.34.1. vim

1.34.1.2. Añadir
  • https://stackoverflow.com/questions/235839/indent-multiple-lines-quickly-in-vi

      >>   Indent line by shiftwidth spaces
      <<   De-indent line by shiftwidth spaces
      5>>  Indent 5 lines
      5==  Re-indent 5 lines
    
      >%   Increase indent of a braced or bracketed block (place cursor on brace first)
      =%   Reindent a braced or bracketed block (cursor on brace)
      <%   Decrease indent of a braced or bracketed block (cursor on brace)
      ]p   Paste text, aligning indentation with surroundings
    
      =i{  Re-indent the 'inner block', i.e. the contents of the block
      =a{  Re-indent 'a block', i.e. block and containing braces
      =2a{ Re-indent '2 blocks', i.e. this block and containing block
    
      >i{  Increase inner block indent
      <i{  Decrease inner block indent
    
1.34.1.3. Notes
  w -> word, e -> end of word, b->back, W,E,B (vim word vs WORD)
  find (f, F)
  % matching parenthesis/brackets (go to left paren if the cursor is not at one)
  0, $ start/end of line, gg, G start/end of file (^ start of line after indentation)
  *, # find word under cursor
  Goto line 4G 5G goto line 4, 5 (also :4, :5) Ctrl+G see current line
  /, ? search, search backwards; n, N next, previous match, also Ctrl+O, Ctrl+I
  i/I, a/A, o, O insert (before), append (after), insert newline below, insert newline above
  x, X delete character under cursor, to the left
  r, d, R replace, delete, Replace (switch to insert mode and overwrite)
  . repeat previous command
  u, Ctrl+R undo, redo. U to undo all line at once
  gt, gT next,previous tab (cyclic) {n}gT go to n tab
  d2w (the repeat command goes in the middle)
  c -> change
  ce -> change to the end of the word (cut to end of word and insert)
  c$ -> change to the end of line (cut to end of line and insert)
  :(\d,\d)?s/search/replace/<flags>
  <flags>: g->multireplace per line c->prompt for each replace
  !command -> execute external command
  visual select + ESC :w -> save only that part/lines of the file
  :r FILE -> retrieve file (paste at cursor), also :r !COMMAND
  j$ -> move to next line end of line
  yw, ye yank from cursor to start/end of word
  fix typos moving characters
  xp -> move character under cursor forward
  x2hp -> move character under cursor backward
  swap two lines
  ddp ->  swap with line below
  dd2kp -> swap with line above
  Y, (^y$, $y^ complicated)  -> yank line without newline
  Advanced
   "g-" and "g+" commands -> multibranch undo/redo history

Author: Julian Lopez Carballal

Created: 2025-01-12 Sun 03:09