How to search and replace globally, starting from the cursor position and wrapping around the end of file, in a single command invocation in Vim?

前端 未结 6 1329
攒了一身酷
攒了一身酷 2020-12-22 18:42

When I search with the / Normal-mode command:

/\\vSEARCHTERM

Vim starts the search from the cursor position and continues downwa

6条回答
  •  一个人的身影
    2020-12-22 19:24

    I am late to the party, but I relied too often on such late stackoverflow answerrs to not do it. I gathered hints on reddit and stackoverflow, and the best option is to use the \%>...c pattern in the search, which matches only after your cursor.

    That said, it also messes up the pattern for the next replacement step, and is hard to type. To counter those effects, a custom function must filter the search pattern afterwards, thus resetting it. See below.

    I have contended myself with a mapping that replaces the next occurence and jumps to the following after, and not more (was my goal anyway). I am sure, building on this, a global substitution can be worked out. Keep in mind when working on a solution aiming at something like :%s/.../.../g that the pattern below filters out matches in all lines left to the cursor position — but is cleaned up after the single substitution completes, so it loses that effect directly after, jumps to the next match and thus is able to run through all matches one by one.

    fun! g:CleanColFromPattern(prevPattern)
        return substitute(a:prevPattern, '\V\^\\%>\[0-9]\+c', '', '')
    endf
    nmap n m`:s/\%>=col(".")-1c=g:CleanColFromPattern(getreg("/"))/~/&:call setreg("/", g:CleanColFromPattern(getreg("/")))``n
    

提交回复
热议问题