10

We can center text with M-x center-region and M-o M-s. Is there something similar for right-alignment?

Example before:

Item 0: value                                                       |
Item 100: value                                                     |
Item 30: value                                                      |

after:

                                                       Item 0: value|
                                                     Item 100: value|
                                                      Item 30: value|
                                                       fill-column  ^

What's easiest way to right-align text?

1 Answer 1

13

According to the manual node on Filling, several of the fill functions take an optional JUSTIFY argument that you can use. So, for example, to fill a paragraph with right justification, you can use (fill-paragraph 'right).

You can also use (justify-current-line 'right) for a single line.

If you plan to use these options a lot, you could wrap them in functions, such as the following, and then bind these functions to the keys of your choice:

(defun right-justify-current-line ()
  "Right-justify this line."
  (interactive)
  (justify-current-line 'right))

(defun right-fill-paragraph ()
  "Fill paragraph with right justification."
  (interactive)
  (fill-paragraph 'right))

Here's a function you might drop in as a replacement for fill-paragraph. With various prefixes, it allows you to decide what kind of justification to use on the paragraph you're filling:

(defun fill-paragraph-dwim (&optional arg)
  "Fills the paragraph as normal with no prefix. With C-u,
right-justify.  With C-u C-u, center-justify.  With C-u C-u C-u,
full-justify."
  (interactive "p")
  (fill-paragraph (cond ((= arg 4)  'right)
                        ((= arg 16) 'center)
                        ((= arg 64) 'full))))

If you don't want to fill when you're right-aligning, you can use the following function, which is cribbed directly from the center-region function with a single-line change to make it align right instead:

(defun right-region (from to)
  "Right-justify each nonblank line starting in the region."
  (interactive "r")
  (if (> from to)
      (let ((tem to))
    (setq to from from tem)))
  (save-excursion
    (save-restriction
      (narrow-to-region from to)
      (goto-char from)
      (while (not (eobp))
    (or (save-excursion (skip-chars-forward " \t") (eolp))
        ;; (center-line))              ; this was the original code
        (justify-current-line 'right)) ; this is the new code
    (forward-line 1)))))
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.