General right alignment function

Now that I know how to vertically align columns of numeric values in Emacs, I have two problems with this solution:

  • hard to remember
  • It is not flexible.

For example, this does not work when some of the values ​​in the first column contain a number.

And unfortunately, it inserts tabs.

Now I use the rectangle ( C-x r k) functions quite a lot. This made me think: is it possible to have a function that right-aligns all the text in the selected rectangle?

+3
source share
1 answer
(defun right-justify-rectangle (start end)
  (interactive "r")
  (apply-on-rectangle (lambda (c0 c1)
                        (move-to-column c1 t)
                        (let ((start (- (point) (- c1 c0)))
                              (end (point)))
                          (when (re-search-backward "\\S-" start t)
                            (transpose-regions start (match-end 0)
                                               (match-end 0) end))))
                      start end))

To avoid Tab, configure the variable indent-tabs-mode.

Edit:

Here is a more reasonable version indent-tabs-mode:

(defun right-justify-rectangle (start end)
  (interactive "r")
  (let ((indent-tabs-mode nil))
    (apply-on-rectangle (lambda (c0 c1)
                          (move-to-column c1 t)
                          (let ((start (- (point) (- c1 c0)))
                                (end (point)))
                            (when (re-search-backward "\\S-" start t)
                              (transpose-regions start (match-end 0)
                                                 (match-end 0) end))))
                        start end))
  (when indent-tabs-mode (tabify start end)))
+8
source

All Articles