0

In the help there is looking-at function which should populate match-data which could be accessed with match-end function.

So I have the text :

1. hello world

The cursor is on 1 and I issue the command M-: (looking-at "1\\. "), the result is t.

Now immediately I do M-: (match-end 0) and expect to get 3 but I get 7 (#o7, #x7, ?\C-g)

Is this approach incorrect? Should I use smth else to get the column number?

PS If I use a little bit more fancy regex in looking-at then I get crazy numbers from match-end - 653 or even 1432. Which are definitely not a column numbers.

Update if the text is a single line as above I get correct result.

1. hello world 1. hello world On the first line I get 4 On the second line I get 19

Looks like char count + 1, not the column number.

2

Emacs including the installed packages does itself some fancy matching between the two calls of M-:. With (match-data) and relatives you get the match data of the last search operation. That search-op was most certainly not yours.

If you want to get the end of your looking-at operation you should use the following command.

M-: RET (progn (looking-at "1\\. ") (match-end 0)) RET.

This gives you the character positon of the end of the match in the buffer.

If you want to get the column number you can use the following command instead:

(progn (looking-at "1\\. ") (- (match-end 0) (line-beginning-position)))

Please be aware that this does also count invisible characters.

An alternative that tries hard to give you the real display column by not counting invisible characters is:

(save-excursion (looking-at "1\\. ") (goto-char (match-end 0)) (current-column))

Still this may fail if some stretch of the text has the display text property. E.g., you can display one space as three spaces with

M-: RET (insert (propertize "\n1. " 'display "1. ")) RET

and the alternative approach above will still output 3 for the newly inserted line even if the single space character takes the space of three display columns.

  • I have got 672 (#o1240, #x2a0, ?ʠ) – Maxim Kim Dec 1 '17 at 15:33
  • Hmm, I got different results depending on position of the text – Maxim Kim Dec 1 '17 at 15:35
  • 1
    @MaximKim Yes, looking-at and the corresponding match data deliver buffer positions, not columns. If you want the column subtract (line-beginning-position). That is still fragile since there might be invisible characters. – Tobias Dec 1 '17 at 15:37
  • This does not answer the question as posed, which is about getting the column number. Please consider adding an explanation of how to do that. – Drew Dec 1 '17 at 16:20
  • @Drew: In the first line it gives you the column number. And that was the OP's original test. – Tobias Dec 1 '17 at 16:22

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.