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?

up vote 13 down vote accepted

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)))))

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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