Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic right-align function

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

  • it is hard to remember
  • it is not flexible

For instance, it doesn't work when some of the values in the first column contains a number.

And unfortunately it inserts tabs.

Now I use rectangle functions (C-xrk) quite a lot. That made me think: would it be possible to have a function that right-aligns all text in the selected rectangle?

like image 936
Michel de Ruiter Avatar asked Sep 03 '26 20:09

Michel de Ruiter


1 Answers

(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, customize the variable indent-tabs-mode.

Edit:

Here is a version that deals with indent-tabs-mode more reasonably:

(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)))
like image 151
huaiyuan Avatar answered Sep 05 '26 14:09

huaiyuan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!