1

Some console editors distinguish between "inserting a newline" and "inserting a newline + matching the level of indentation of the current line".

For instance, the editor mg distinguishes between C-j (which matches the previous level of indentation) and C-m (which just inserts a \n) in C mode.

GNU Emacs (which mg is emulating) does more sophisticated stuff to determine the appropriate level of indentation, but I like the simple "just use the indentation level of the previous line" of mg.

If the buffer consists of (where . is space)

.....a

Then hitting C-j will do...

.....a
.....

I was wondering if there's a way (particularly a built-in way) to get the same indentation-matching behavior in vim when I hit C-j.

I have a utility function for extracting whitespace characters from the beginning of a numbered line, but I can't figure out how to package it into a command that grabs the corresponding characters from the current line, inserts a newline, and then inserts the whitespace prefix from the original line.

function! GetIndentationPrefix(linum)
    let line = getline(a:linum)
    let index = 0
    let target = strlen(line)
    let whitespace_prefix = ''
    while index <# target
        if line[index] ==# ' '
            let whitespace_prefix = whitespace_prefix . ' '
        elseif line[index] ==# '\t'
            let whitespace_prefix = whitespace_prefix . '\t'
        else
            break
        endif
        let index = index + 1
    endwhile
    return whitespace_prefix
endfunction
2

If you have set cindent or set autoindent, vim actually does match indent when you press <c-j>. But it also does when you press <cr>. To circumvent this you could make a mapping like:

inoremap <cr> <cr><c-o>i

So now <c-j> will match indent, but <cr> won't.

1

If you set ai, then <c-j> (in insert mode) will do what you want. If you want the Enter-Key to behave differently then you also can :inoremap <cr> <cr>0<c-d>

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.