惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News | PayPal Newsroom
H
Hackread – Cybersecurity News, Data Breaches, AI and More
雷峰网
雷峰网
NISL@THU
NISL@THU
V
Vulnerabilities – Threatpost
P
Privacy International News Feed
博客园_首页
P
Privacy & Cybersecurity Law Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Cloudflare Blog
Know Your Adversary
Know Your Adversary
小众软件
小众软件
人人都是产品经理
人人都是产品经理
WordPress大学
WordPress大学
博客园 - 聂微东
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tor Project blog
C
Cybersecurity and Infrastructure Security Agency CISA
V
V2EX
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
J
Java Code Geeks
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
T
The Blog of Author Tim Ferriss
美团技术团队
Jina AI
Jina AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 最新话题
Cloudbric
Cloudbric
Webroot Blog
Webroot Blog
V2EX - 技术
V2EX - 技术
爱范儿
爱范儿
S
Securelist
MyScale Blog
MyScale Blog
B
Blog
AI
AI
L
LINUX DO - 热门话题
Security Archives - TechRepublic
Security Archives - TechRepublic
The Register - Security
The Register - Security
I
Intezer
有赞技术团队
有赞技术团队
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
H
Help Net Security
D
DataBreaches.Net
K
Kaspersky official blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
The Last Watchdog
The Last Watchdog
Attack and Defense Labs
Attack and Defense Labs
酷 壳 – CoolShell
酷 壳 – CoolShell

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN Mintty Tips and Configurations Generating Table of Contents for Markdown with Tagbar Convert Python Script to Exe on Windows with Pyinstaller Ubuntu on Windows Missing after Windows Update 使用代理加速 Mac 终端下载速度 My Experience with Several Zsh Plugin Managers 深圳租房小记 How to Install zplug inside Docker Container Why don't settings inside bashrc or bash_profile take effect? Setting Up Locale in Linux 谷歌 Adsense 申请及在 Hugo 中的配置 How to Write Algorithm Pseudo Code in LaTeX Nifty Nvim Techniques That Make My Life Easier -- Series 4 A Few Grammar Questions in Writing How to Read and Write Images with Unicode Paths in OpenCV Creating A Professional Table in LaTeX with booktabs How to Create Proper Folding for Vim/Nvim Configuration Linux Tips and Tricks -- s1 JPEG Image Orientation and Exif How Do I Show the Current File Path In Neovim? JPEG Image Quality in PIL Difference between view, reshape, transpose and permute in PyTorch Convert PIL or OpenCV Image to Bytes without Saving to Disk Fast Movement and Navigation Inside Vim or Neovim Unintuitive Behaviour of Case Sensitivity in Python glob Binding Keys in Zsh 几把机械键盘试用体验 Nvim Autocompletion with Deoplete Converting Markdown to Beautiful PDF with Pandoc Exclusive and Inclusive Motion in Neovim/Vim Nifty Nvim Techniques Which Make My Life Easier -- Series 3 Why Doesn't Jedi Autocompletion Work for Some Methods Vim-like Editing inside Browser Markdown 生成 HTML 时汉字之间出现多余空格问题 小米 9 安装谷歌商店(Google Play Store)与相关配置 Spell Checking in Nvim English Words Completion inside Neovim/Vim How to Use Python Inside Vim Script with Neovim Nifty Little Nvim Techniques to Make My Life Easier -- Series 2 Setting up Ultisnips for Neovim Mac 上罗技 M590 鼠标设置 Nifty Little Nvim Techniques to Make My Life Easier -- Series 1 A Complete Guide on Writing LaTeX with Vimtex in Neovim Manipulating Images with Alpha Channels in Pillow Sublime Text Regular Expression Cheat Sheet Cropping Rotated Rectangles from Image with OpenCV Boosting Your Productivity on Terminal with Zsh and Plugins 最新版 Rime 输入法使用 (2022 更新) Display Image with Pillow inside Ubuntu on Windows Faster Directory Navigation with z.lua Cmder Advanced Configurations Nvim-qt Settings on Windows 10 Tmux Plugin Install and Management How to Debug Python Code in Terminal Markdown Writing and Previewing in Neovim -- A Complete Guide Line Number Settings for More Efficient Movement in Neovim 两个大规模中文语料库介绍以及处理 Windows 系统下几款程序员不可不用的神器 我的 2018 阅读清单 A Complete Guide to Neovim Configuration for Python Development How Is Newline Handled in Python and Various Editors? Two Issues Related to ImageFont Module in PIL 在 Listary 中调用 GoldenDict 或欧路词典查单词 Reading and Writing Text Files on Windows The Mathematics behind Font Shapes --- Bézier Curves and More 快速识别图片字体:字体识别工具介绍 Deoplete Failed to Load at Startup after Updating Python neovim Package What Is The Difference between pip, pip3 and pip3.6 Shipped with Anaconda3? Windows 10 系统下 Neovim 安装与配置 How to Use shutil.move() on Windows and Linux
Create Mappings That Take A Count in Neovim
2019-04-29 · via jdhao's digital space
Mappings

Many normal mode commands accept a count, which means to repeat the motion count times. For example, 3j moves the cursor 3 lines below the current line and 4w will move the cursor four words forward. Usually, the user-defined mappings can not take a count. Even if they can, they will most probably not work the way you expect them to. In this post, I will describe what I have learned to make a fairly complex mapping repeatable with a count.

The Problem#

I find myself often doing something like adding one or two blank lines below the current line to separate the structure of the code or text. So I created a mapping for this operation after some search:

nnoremap oo :execute "normal! m`o\<Esc>``"<cr>

Unfortunately, the above mapping does not work1, it will print an error:

E114: Missing quote: “normal! m`a\

The above mapping does not work because the way we escape Esc is not correct. When you press oo, it is like we have typed :execute "normal! m`o in the command line and then press the Esc key.

You have to use either one of the following mappings to indicate that you want to press the <Esc> key, not type <, E, s, c, > literally:

nnoremap oo :execute "normal! m`o\<lt>Esc>``"<cr>
nnoremap oo :execute "normal! m`o<c-v><Esc>``"<cr>
nnoremap oo :execute "normal! m`o\e``"<cr>

This is becoming too complicated. nnoremap is actually equivalent to normal!. So we can simply the above mappings to avoid complications:

In the above mapping, we first create a mark ` for the initial cursor position, the insert a newline, go back to normal mode and restore the cursor position2. Then end result is that we insert a newline and maintain the cursor position.

But this mapping only works once, i.e., it can not take a count. In order to add two lines below, we have to press oo two times, which is not ideal for me.

After searching the Internet, I found this vim cast, which address this issue specifically. It introduced two ways to create a mapping that accepts a count.

Two Solutions#

The imperfect one – using :normal command#

The first way is to use :normal command on the right-hand side of the mapping. The :normal {expr} command will execute {expr} as normal mode command just as you have typed them in normal mode. For example, if you execute :normal G in Vim command line, the cursor will be put at the last line of current buffer.

The :normal command will take into account the mappings you have defined. If you have defined G to other command, you may not get what you want. To remedy this, Vim also provides a bang version: :normal!, which will use Vim’s default mapping for the key.

The :normal! command can take an optional {range}, which means to execute the {expr} for current cursor line as well as lines indicated by {range}3.

Combining the above knowledge, we can create the following mapping:

nnoremap oo :normal! m`o<Esc>``

This mapping can take a count. If you press 2oo in normal mode, two lines will be insert below current line. But you will notice that the position of the cursor is changed because the :normal! command with range will move the cursors:

Before executing the {commands}, the cursor is positioned in the first column of the range, for each line.

There is also a pitfall when using this mapping in the last line of current buffer. If you use a count bigger than one, you will get an error:

E16: Invalid range

since there is no lines below the current line.

The better – using the expression register @=#

Another method is to use expression register4. The expression register can store a command string or store the result of some functions. The mapping we will use is:

nnoremap oo @='m`o<C-V><Esc>``'<CR>

Here, we define the command we will use in the expression register. Note that to represent Esc, we have to precede it with <C-v>. This mapping can take a count and work as expected (the cursor is moved).

Also note that the below mappings do not work:

nnoremap oo @='m`o\<lt>Esc>``'<cr>
nnoremap oo @='m`o\e``'<cr>

I do not know why. But they just do not work any more. If anyone knows the reason, do not hesitate to tell me, please.

Update: 2019-05-12

Note if we change the single quote to double quote, the following mappings using the expression register will work as expected.

nnoremap oo @="m`o\<lt>Esc>``"<cr>
nnoremap oo @="m`o\e``"<cr>

It seems like an issue with single quote, where every character inside is interpreted literally.

The best#

Although using the expression register mapping solves the problem, it is error prone when writing such expressions without considerable familiarity with the various oddities of Vim.

I posted my question on Reddit and received a few replies. A new solution based on <expr> (see :h map-<expr>) emerged and it seems the best solution ever:

nnoremap <expr> oo 'm`' . v:count1 . 'o<Esc>``'
nnoremap <expr> OO 'm`' . v:count1 . 'O<Esc>``'

The expression mapping will evaluate the RHS string before executing it. v: count1 is a special Vim variable. It is the count you supplied to this mapping. If no count is given, it has the default value of 1 (see :h v:count1).

This mapping has two benefits. One is that it is clearer. The second is that it executes faster than expression register mappings where the mapping is repeated count times and you can see obvious lags between each mapping.

A special note about backslash in command line and Vim script#

During the process, I have also learned that the meaning of \ may change depending on the B flag in cpoptions.

Suppose that we have defined the following insert mode mapping in command line or in Vim script.

When you press <C-a> in insert mode, the output will depend on if B flag is in cpoptions.

with B flag in cpoptions#

Backslash is take literally as is. A backslash is inserted and the cursor is moved to the beginning of cursor line.

without B flag in cpotions#

Backlash will escape < the character. When you press <c-a> in insert mode, the 6 characters (i.e., <, H, o, m, e, >) is inserted.

When define mappings, the < should be handled carefully, or you will not get what you want.

Conclusion#

In this post, I have summarized how to define a map that can accept a count. Overall, defining the map via expression register is preferred and works great. Extra care must be paid when you include special keys such as Esc inside the expression register.

References#