1

When my cursor is inside a brace, e.g.,

(( "Hello World!⣿" ))

where is my cursor, and I use %, I will automatically select the first opening (. Is there some way to make the % only jump if it's currently on a opening or closing brace?

3

There is not option for this, but you can remap % like so:

nnoremap <expr> % index(["(", "{", "[", ")", "}", "]"], getline(".")[col(".")-1]) > -1 ? "%" : ""

The <expr> keyword makes Vim evaluate an expression (i.e. a snippet of VimScript), rather than a fixed set of normal commands. The result of this expression is then used as the mapping.

In this expression we check if the current character is one of the brace characters ((, {, or [), and if it is, it evaluates to %, if it's not, it evaluates to nothing. Perhaps it is easier to understand if we turn it into a function:

fun! Percent()
    " Get current character
    let current_char = getline(".")[col(".")-1]

    " Match these braces
    let match = ["(", "{", "[", ")", "}", "]"]

    " Find current_chat in match
    if index(match, current_char) > -1
        return "%"
    " No match, do nothing
    else
        return ""
    endif
endfun

nnoremap <expr> % Percent()

Both ways behave exactly the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.