4

I find it very useful to visually distinguish every 3 digit group of numbers in source code so that I can read it. For example something if I see 1000000 it is fairly easy to see that this is 1M rather than 10M or 100k. Basically I want to made digits 4-6, 10-12... look different from the others.

In vim I could do this via a custom syntax rule.

match SpellRare /\d\{1,3}\ze\%(\%(\d\{3}\)\{2}\)*\d\{3}\>/

This relies on zero-length lookaheads to work. Emacs highlighting doesn't appear to have these so the best I could do was multiple highlight-regexp calls.

(add-hook 'prog-mode-hook (lambda ()
    (highlight-regexp "\\([0-9]\\{1,3\\}\\)\\([0-9]\\{3\\}\\|\\)\\>" font-lock-warning-face 1)
    (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{9\\}\\>" font-lock-warning-face 1)
    (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{15\\}\\>" font-lock-warning-face 1)
    (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{21\\}\\>" font-lock-warning-face 1)
    (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{27\\}\\>" font-lock-warning-face 1)
    (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{33\\}\\>" font-lock-warning-face 1)
    (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{39\\}\\>" font-lock-warning-face 1)))

This mostly works for the number lengths I have defined (although it doesn't always update correctly when editing the number). Is there a better solution to this?

  • You could use an "anchored" font-lock rule to match the number and highlight rules to highlight the groups of three characters you want to match. It might require some elisp to do this, but it wouldn't be too hard. – Lindydancer Dec 23 '19 at 21:50
3

You can simulate the \ze construct using repeated matching. See also (info "(elisp) Search-based Fontification").

(defun my-matcher (limit)
  (when (re-search-forward
         "\\([0-9]\\{1,3\\}\\)\\(?:[0-9]\\{6\\}\\)*\\(?:[0-9]\\{3\\}\\)\\_>" limit t)
    (goto-char (match-beginning 1))
    (re-search-forward "[0-9]+" (match-end 1))))

(font-lock-add-keywords nil '((my-matcher 0 font-lock-warning-face)))
| improve this answer | |

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.