如何基于Vim中光标下方的字符在函数中执行某些操作? [英] How to do something in a function based on the character under the cursor in Vim?

查看:43
本文介绍了如何基于Vim中光标下方的字符在函数中执行某些操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个在LaTeX中编辑特定环境的函数.

I’m writing a function that edits a certain environment in LaTeX.

环境基本上是这样的:

\begin{quicktikz}
    ...some stuff...
\end{quicktikz}

或这样:

\begin*{quicktikz}
    ...some stuff...
\end{quicktikz}

我想编写一个从环境中调用时在两者之间切换的函数.由于我的Vim知识还不是全部,因此我想出一个简单的解决方案:

I want to write a function that toggles between the two, when called from within the environment. Since my Vim knowledge ain’t all that, I’m coming up with a simple solution:

  1. 通过 let save_cursor = getpos(.")获取光标位置.
  2. 使用以下代码向后搜索 \ begin {quicktikz} :\\\ begin {quicktikz} \ | \\ begin \ * {quicktikz} .
  3. 搜索 {,然后使用以下代码向左移动: normal 0f {h .
  4. 检查光标下的项目是否等于 * :
    • 如果这样做,请执行 normal x ;
    • 如果不是,请执行 normal a *< esc> .
  1. Get cursor position with let save_cursor=getpos(".").
  2. Backward search for \begin{quicktikz} using: ?\\begin{quicktikz}\|\\begin\*{quicktikz}.
  3. Search for the { and move left using: normal 0f{h.
  4. Check if the item under cursor equals *:
    • if it does, do normal x;
    • if it doesn’t, do normal a*<esc>.

我知道如何执行步骤3以外的所有操作.如何检查光标下的字符是否等于 * ?

I know how to do all of this except for step 3. How can I check if the char under the cursor equals to * or not?

如果您知道更好的方法,欢迎共享.

If you know a better way of doing this, sharing this would be welcome.

推荐答案

我认为在光标下检索char的最简单方法是:

I think the easiest way to retrieve the char under cursor is:

getline(".")[col(".")-1]

或者,您也可以使用 strpart()

strpart(getline("."), col(".")-1, 1)


第一个表达式首先调用函数 getline() 传递." 为参数,表示将返回光标所在的行.然后,我们使用所谓的 expr8 expr-[] (请参见 col() 它返回当前的光标列.当索引从0开始时,将减去1.


The first expression first calls the function getline() passing "." as argument which means the line where the cursor is positioned will be returned. Then we use the so called expr8 or expr-[] (see the help) to retrieve a single character. The number passed comes from another function, col() which returns the current cursor column. As indexes start in 0, one is subtracted.

您可以像使用它

if getline(".")[col(".")-1] == '*'
        ...

这篇关于如何基于Vim中光标下方的字符在函数中执行某些操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆