Tips » single line comment syntax

Single line comment syntax


Add this function to your ~/.emacs

 ;; Comment from the point to the end of line or, if the point is at the end
 ;; of a line and not following a comment, insert one.
 ;; If the current line already ends with a comment, remove it.
 (defun caml-toggle-comment-endofline (u)
   (interactive "P")
   (if (eq u nil)
       (let ((init (point)) beg end end_comment)
           (setq end (point))
           (if (looking-back (regexp-quote comment-end))
               (progn ; remove the ending comment (naive)
                 (uncomment-region (point) end)
                 (setq end (- end (string-width comment-start)
                              (string-width comment-end)))
                 (goto-char (min init end)))
             (if (eq init end)
                 (search-forward-regexp "[^ \t]" end t)
                 (backward-char 1); now at the 1st non-space of the line
                 (setq beg (point))
                 (if (eq beg nil)
                     ;; line is composed of spaces => new comment
                     (comment-region (max init beg) end)
                     (goto-char init))
     (progn ; C-u prefix
       (insert "(**  *)")
       (forward-char 4)

(Improvements are welcome.) Then you can bind it, say to C-c,:

 (add-hook 'tuareg-mode-hook
   (function (lambda ()
      (define-key tuareg-mode-map "\C-c," 'caml-toggle-comment-endofline)
      (define-key tuareg-interactive-mode-map "\C-c,"