I am using comment-dwim-line
to comment out multiple lines. For this, I automatically move cursor always to the beginning of a line. I just want to use this behavior if the cursor is at beginning of a line or multiple line is selected.
If the cursor is in the middle of a line, I just want to add a comment character where the cursor is located.
The code I am using:
(defun comment-dwim-line (&optional arg)
"Replacement for the comment-dwim command.
If no region is selected and current line is not blank and we are not at the end of the line,
then comment current line.
Replaces default behaviour of comment-dwim, when it inserts comment at the end of the line."
;; http://www.opensubscriber.com/message/[email protected]/10971693.html
(interactive "*P")
(comment-normalize-vars)
(if (and (not (region-active-p)) (not (looking-at "[ \t]*$")))
(comment-or-uncomment-region (line-beginning-position) (line-end-position))
(comment-dwim arg)))
(global-set-key (kbd "C-c C-;") 'comment-dwim-line)
Here it is possible to apply normal comment out behavior if the cursor is not at the beginning of a line:
def main():
x = 10
(^)
|__ cursor is here when `comment-dwim-line` is applied it becomes
This is ok
.
def main():
# x = 10
But for the following example:
def main():
x = 10 my commment
(^)
|__ cursor is here when `comment-dwim-line` is applied
# x = 10 my commment
It becomes:
def main():
# x = 10 my commment
wanted behavior would be: x = 10 # my commment
as:
def main():
x = 10 # my commment
pid = os.getpid() #
is this normal? – alper Feb 28 '23 at 17:58#
to be added to end of line right after the latest character but it adds. #
instead of just#
. Like if the cursor is at the end of the line and if there is no character after it ; it adds many empty space followed by#
– alper Feb 28 '23 at 20:55comment-column
) – C4ffeine Add1ct Feb 28 '23 at 21:37<cursor> first_character
becomes<cursor># first_character
instead of<cursor> # first_character
– alper Feb 28 '23 at 22:22pid = os.getpid()<cursor>
->pid = os.getpid() # <cursor>
and<cursor> pid = os.getpid()
-># pid = os.getpid()
, are both of these not what you expect? – C4ffeine Add1ct Mar 01 '23 at 09:19<tab>pid = os.getpid()
, comment added before the tab not after. – alper Mar 01 '23 at 10:29