How can I check if the cursor is at the end of a line?

3

Gentleman,

Simple question about Vim!

How can I check if the cursor is at the end of a line using a function in vimrc?

[]'s

Eduardo Lucio

Posted 2014-03-02T13:15:28.733

Reputation: 712

1Why do you need to know? What are you trying to accomplish? Sometimes it is easier to force end of line, or use a command that doesn't care about end of line, or something else. What is the actual problem you are trying to solve, instead of your assumed solution? – Ben – 2014-03-02T16:44:42.867

Answers

7

You don't need a function to determine this, but you could wrap the following test in a function if you needed to. That would depend on what you are trying to do and what you need from the function.

The col() function returns the column of its argument. The last column of a row is col("$")-1 and the cursor column is col("."), so

echo col(".") == col("$")-1

will echo1 when the cursor is at the last column and 0 otherwise.

See:

:help col()

garyjohn

Posted 2014-03-02T13:15:28.733

Reputation: 29 085

3There's an edge case to consider: on an empty line, col(".") returns 1 and col("$") also returns 1. So you'd probably want to check if col(".") >= col("$") - 1. – dirtside – 2015-09-28T20:15:56.853

This also doesn't work if the character under the cursor is multi-byte, e.g. U+2124 (ℤ) is three bytes, so if it's the last character on a line, col('.') + 3 == col('$') – rampion – 2020-02-26T14:50:17.387