How to automatically align comments in different pieces of code?

As tungd said, align-regexp is good for this sort of thing.

(defun my-align-comments (beginning end)
  "Align instances of // within marked region."
  (interactive "*r")
  (let (indent-tabs-mode align-to-tab-stop)
    (align-regexp beginning end "\\(\\s-*\\)//")))

Which is like the interactive call:
M-x align-regexp RET // RET

Or for a more language-agnostic version:

(defun my-align-comments (beginning end)
  "Align comments within marked region."
  (interactive "*r")
  (let (indent-tabs-mode align-to-tab-stop)
    (align-regexp beginning end (concat "\\(\\s-*\\)"
                                        (regexp-quote comment-start)))))

Here's the code:

(defvar c-current-comment-col 30)
(defun c-set-comment-col ()
  (interactive)
  (setq c-current-comment-col (current-column)))
(defun c-comment-to-col ()
  (interactive)
  (beginning-of-line)
    (when (re-search-forward "//" (line-end-position) t)
      (backward-char 2)
      (let ((delta (- c-current-comment-col
                      (current-column))))
        (if (plusp delta)
            (insert (make-string delta ? ))
          (if (looking-back
               (format "\\( \\{%d\\}\\)" (- delta)))
              (delete-region
               (match-beginning 1)
               (match-end 1))
            (message
             "I'm sorry Dave, I afraid can't do that.")))))
    (next-line 1))
(global-set-key [C-f6] 'c-set-comment-col)
(global-set-key [f6] 'c-comment-to-col)

I've added a next-line call to the end. Now you can do C-f6 f3 f6 M-0 f4 to align until end of buffer.


Not exactly an answer to your question, but to achieve the desired goal you can just mark the region and use align-regexp.