Go to middle of line in vim

13

1

I know 0 goes to the beginning of line and $ goes to the end, but is there something for the middle?

teggy

Posted 2010-11-29T20:15:44.087

Reputation: 233

Answers

11

:call cursor(0, len(getline('.'))/2)

ephemient

Posted 2010-11-29T20:15:44.087

Reputation: 20 750

4This would be fairly useful if it were mapped, e.g: :nnoremap gm :call cursor(0, len(getline('.'))/2)<cr> – Heptite – 2010-11-29T22:55:36.817

3virtcol('$')/2 is enough. – Luc Hermitte – 2010-11-30T01:34:34.603

@Luc Hermitte: Nice, but not exactly the best behavior when hard tabs are involved. – ephemient – 2010-11-30T03:54:42.120

That's why I use virtcol instead of col. :). But indeed we should use | and not cursor(). BTW, len() won't give any better result. Moreover, len will give other troubles with multi-bytes characters. – Luc Hermitte – 2010-11-30T09:05:17.863

8

Typing gm would do it, but it moves by screen lines. In order to get it working in with text lines, one can remap this command:

map gm :call cursor(0, virtcol('$')/2)<CR>

JooMing

Posted 2010-11-29T20:15:44.087

Reputation: 774

gm seems to move cursor to middle of screen, but if my line of text is shorter than the length of the screen, it doesn't take me to the middle. Sorry for not clarifying. – teggy – 2010-11-29T20:56:54.847

@teggy: I see. I modified my solution to remap gm to go to the middle of text line. As you can see, it combines solutions from ephemient and Luc Hermitte. – JooMing – 2010-11-30T09:55:52.863

As ephemient pointed out, it still has an issue with hard tarbs as cursor() counts them as one character each. Moreover, it won't work with multi-bytes characters either. – Luc Hermitte – 2010-11-30T10:24:49.543

7

Here is a solution that will respect hardtabs, and multi-bytes characters as well.

:exe 'normal '.(virtcol('$')/2).'|'

Luc Hermitte

Posted 2010-11-29T20:15:44.087

Reputation: 1 575

1

Here is the best solution that I have found. Jumping exactly to the middle of the line is not very practical. You will most likely still need to move the cursor a few positions after moving to the middle. What if you could jump to a specific character? Many people just search for the character, then hit "next" until they reach it. This is slow. The Easy-motion plugin offers a better solution.

My favorite is <leader><leader>s then the character you want to jump to. Easy Motion replaces all matches with different letters for you to choose from. See the tutorial. Its a life-changing plugin...

Sam Ruberti

Posted 2010-11-29T20:15:44.087

Reputation: 111