Search code examples
emacscommentsequalsregion

emacs function to uncomment regardless of mode


Main goal: making a smart "uncomment" function suitable for any mode.

(defun uncomment-mode-specific ()
  (interactive)
  (if (region-active-p)
      (comment-region (region-beginning) (region-end) -1)  ; so far so good
    (if (= ";" (line-beginning-position))                   ; here is the problem
         (message "successful")
       (message "unsuccessful"))
))

In the if statement, I would like to check for the value of the first character of the line, and if it equals the variable comment-start (which would return ";" in emacs lisp), goto beginning-of-line and delete the character. Ideas?

EDIT: More clarification as requested in a comment below follows. I would like a function to do:

1) If a region is selected, remove the comments (here that uncomment-region or comment-dwim would work as pointed out by Patrick)

ELSE:

2) If the first character of the line at point is a comment character, remove the comment character.

ELSE:

3) Search current line for comment (excluding \% or \;, mode dependent), move up to comment and kill the line starting with the comment sign.

I could not see how you would want this to work differently. It could then be bound to one key to simply remove comments, depending on the mode, using comment-start to identify the comment character.


Solution

  • I'm posting this as an alternative answer, since what you are trying to do is partly done already with the comment-dwim command. From the docs (you can find it using C-h f comment-dwim)

    comment-dwim is an interactive compiled Lisp function in `newcomment.el'.

    It is bound to M-;.

    (comment-dwim ARG)

    Call the comment command you want (Do What I Mean).
    If the region is active and transient-mark-mode is on, call comment-region (unless it only consists of comments, in which case it calls uncomment-region).
    Else, if the current line is empty, call comment-insert-comment-function if it is defined, otherwise insert a comment and indent it. Else if a prefix ARG is specified, call comment-kill. Else, call comment-indent.
    You can configure comment-style to change the way regions are commented.

    So in order to use it, simply select a region with C-SPC (set-mark-command) and move the caret to the other point and run comment-dwim.