0

I'd like to have an emacs-lisp function that comments or uncomments the line the cursor is on.

At the very least, it needs to work in latex-mode and emacs-lisp-mode, as well as in org-mode inside latex and emacs-lisp source code blocks. Of course, it would be nice if the function worked generally, but as a stopgap, just the above situations would be helpful.

There's a built in function, comment-line, whose documentation suggests that it would perform this function, but it's too buggy to be useful.

I've found about a dozen attempts in forum posts and blogs, but none of them works correctly.

I wrote my own comment function that seems to work generally to comment lines. However, it doesn't uncomment. I'd rather not have to take the time to write the uncomment functionality if someone out there has already done it.

To elaborate on what I mean by "too buggy to be useful", if in an org mode latex source block with

 \commandA \commandB \commandC 

I position my cursor on \commandB and execute comment-line, the following results:

 \commandA % \commandB % \ commandC 

There are numerous other anomalies, and this kind of strange behavior seems to occur more than half the time, so I don't consider comment-line a useful command.

8
  • 3
    For clarity: Is the problem specific to indented org-mode code blocks? Commented Apr 22, 2024 at 6:10
  • (And if so, I suggest you also check for an existing org-mode issue, and raise a new one if one does not already exist.) Commented Apr 22, 2024 at 6:11
  • Does github.com/remyferre/comment-dwim-2 do what you want? Commented Apr 22, 2024 at 8:37
  • @mmmmmm comment-dwim-2 has problems similar to comment-line. It seems likely the Emacs function comment-region, is where the problem is. All the other functions are calling comment-region. The comment-line function I wrote doesn't do so; it just directly writes the appropriate comment characters to the current line. Commented Apr 22, 2024 at 12:36
  • 4
    (I'm trying to narrow down your question. If your problem is less "commenting doesn't work" and more "commenting doesn't work in this specific scenario", you're liable to get better help.) Commented Apr 22, 2024 at 15:48

2 Answers 2

0

As phils notes in the comments, the problem is related to indenting. I've found the following kludge seems to work:

(defun comment-line-kludge (n) (interactive "p") (let ((org-src-preserve-indentation t)) (comment-line n))) 
0
(defun comment-or-uncomment (n) (interactive "*p") (if (or (region-active-p) (save-excursion (beginning-of-line) (looking-at "\\s-*$"))) (call-interactively 'comment-dwim) (comment-or-uncomment-region (line-beginning-position) (line-end-position n)))) 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.