O
should work with python and keep the current indent level. You may want to look at your indention settings and/or ensure filetype indent on
.
I set filetype plugin indent on
in my vimrc
. It is also set in defaults.vim
Whats the <fd>
??
As you can see, it is slightly different. <fd>
has changed into ý for some reason. Anyone who can explain my why this is and how I can fix it?
As @filbranden mentioned ^[<80><fd>
is a no op. In general Vim may detect/record more than you expect due to Vim's implementation and terminal behavior.
A macro who grew up to be a mapping
I'm trying to create a macro for an action that I very frequently use in Python: printing a variable in a bright color so it can easily be found in the traces while debugging.
Macros are great and they are a good first start towards building a propper mapping. Replaying macros depend on registers which tend to be ephemeral. Mappings are a great way to store such commands for later. They also use key-notation which is often easier to read and are not limited to only 26ish registers.
You could easily create a mapping for this following the same commands in your macro. I'm using \p
as an example trigger for the mapping
nnoremap \p yawA<cr>print("\u001b[35m", <esc>pA, "\u001b[0m")<esc>
For more help see:
:h key-notation
:h map-overview
Problems
However, there are problems with this mapping which may not be apparent.
- It mutates the unnamed register. This might be surprising later on
- This is a python specific mapping which it not useful for other
'filetype'
's (aka global mapping)
Side effects in your mappings
This mapping mutates the unnamed register ""
. This can be avoided a few different ways, but I am going to show you how to leverage <cword>
which is the current word the cursor is on:
nnoremap \p "=[printf('print("\u001b[35m", %s, "\u001b[0m")', expand('<lt>cword>'))]<cr>]p
This mapping uses the expression register, "=
, to evaluate a Vim expression which happens to be a printf()
statement where we use the current word, expand('<cword>')
. Wrap the expression in an array to force this to be line-wise and do a same indent-level put with ]p
For more help see:
:h "=
:h expand()
:h printf()
:h ]p
:h <cword>
:h <lt>
:h key-notation
Local Mappings
Lets make this mapping only for python
files by making it local to the <buffer>
. We can do this two different ways: use an autocmd
or use the after-director (e.g. after/ftplugin/python.vim
)
autocmd Filetype python nnoremap <buffer> \p "=[printf('print("\u001b[35m", %s, "\u001b[0m")', expand('<lt>cword>'))]<cr>]p
Or use the after-directory by putting a file here after/ftplugin/python.vim
and add the mapping:
nnoremap <buffer> \p "=[printf('print("\u001b[35m", %s, "\u001b[0m")', expand('<lt>cword>'))]<cr>]p
Using the after-directory tends to be my preference
For more help see:
:h :au
:h :map-local
:h after-directory