I have written a small elisp script which should put oneline or multiline comments based on the current buffer's major mode. The source file is here: https://github.com/amirteymuri/Com/blob/master/com.el

The insert-comm+ function which should insert the multiline comments however puts the ending multline-comment string not at the end of the marked region, but some characters before it (depending on major-mode the amount of characters change also). Can someone see where the problem is happening? This is the insert-comm+ definition:

(defun insert-comm+ ()
  "Inserts multiliners to a marked region or a line."
  (let* ((comm-list (comm+))
     (comm-begin (concat (first comm-list) "\n"))
     (comm-end (concat "\n" (second comm-list))))
    (if (use-region-p)
      (let ((b (region-beginning))
            (e (region-end)))
        (goto-char b)
        (insert comm-begin)
        (goto-char (1+ e))
        (insert comm-end)))
       (insert comm-begin)
       (insert comm-end)
       (backward-char (length comm-end))))))

1 Answer 1


You set e to the value of (region-end), which is the position of the end of the region at the time you call the function. Then you insert comm-begin somewhere before e. So e is no longer at the end of the region, but n characters before where n is the length of comm-begin. I guess you tried to compensate by using (1+ e) instead of e, but that only gives the right result if comm-begin is a single character.

The proper fix is simple: retrieve the region boundaries only when you need them.

You should also decide whether you want to end up with the comment delimiters inside or outside the region and use insert-before-markers accordingly. Use it to insert the beginning delimiter to keep the delimiters outside the region, or to insert the end delimiter to keep the delimiters inside.

(if (use-region-p)
      (goto-char (region-beginning))
      (insert-before-markers comm-begin)
      (goto-char (region-end))
      (insert comm-end))
  (insert comm-begin)
  (insert-before-markers comm-end))

Also, you should wrap this function in save-excursion so that it leaves the point in place instead of moving it to the end.

Overall, I don't understand what you're trying to do. Emacs already knows how to begin and end a comment in all major modes: the information is in the variables comment-start and comment-end. And Emacs already has commands to comment out a region.

Your Answer

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