2022-07-18 Making some things more legible

Continuing the topic of one of the last posts, let me talk about another way to make dealing with a bank easier. In emails or web pages concerning payments people often have bank account numbers. Such a number consists (at least in Poland) of 26 digits. The first two are check digits, and the rest are the “basic bank account number”. Oftentimes people just paste the string of 26 digits, which is very difficult to read (and I sometimes do want to actually read the number, for example to make sure that two numbers agree). To solve that, it is customary to group these digits into sets of four (so the pattern is: two check digits and then six sets of four), divided by spaces. However, often I receive an email where there are just 26 digits lumped together.

Let’s make them look better. The idea is to write some Elisp code to find all occurrences of 26 digits in a row and put an overlay over them so that they show as if there were spaces in the suitable places. Nothing is changed in the buffer (which is good, since e.g. a buffer showing an email is read-only), if you copy the account number to the kill ring, you get no spaces (because they are only a display feature) etc. – but what you see is readable.

(defun spacify-Polish-ibans ()
  "Display (Polish) IBANs with spaces."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward "[0-9]\\{26\\}" nil t)
      (let* ((match-beginning (match-beginning 0))
	     (match-end (match-end 0))
	     (match (match-string 0))
	     (spaced (with-temp-buffer
		       (insert match)
		       (goto-char 3)
		       (dotimes (_ 6)
			 (insert " ")
			 (forward-char 4))
		       (buffer-substring-no-properties (point-min) (point-max)))))
	(overlay-put
	 (make-overlay match-beginning match-end)
	 'display
	 spaced)))))

The code is pretty simple – it has some assumptions hardcoded (like that there are 26 digits in the account number), but I’m fine with that. I used the classical Emacs way of manipulatiing strings – insert them with-temp-buffer, do stuff, get buffer-substring-no-properties. I also used the display overlay property, which – with a value being a string – displays that very string in place of the text covered by the overlay.

One gotcha I encountered was that I wasn’t aware that you must call match data functions (match-string and friends) in the same buffer you performed the search. It’s ugly, but it’s well documented, so that’s it.

And that’s also pretty much it for today. The point is – again! – that it is very easy to make Emacs help you with minor everyday tasks. (Coding this took me about 20 minutes, and it would be much faster if not for the match data issue I mentioned above.) In fact, these days I am back to coding little Emacs lifehacks – the plan is that I hope to get some inspiration to add some material to a certain book you must be tired of hearing about. ;-)

CategoryEnglish, CategoryBlog, CategoryEmacs