2

Alt+Shift+3 can only comment out, on subsequent invocations simply adding multiple comment characters (hashes) instead of toggling on / off the comment. How to uncomment a previously commented line or toggle the comments?

5
  • bind -l | grep comment doesn't show anything but insert-comment.
    – choroba
    Dec 26, 2023 at 12:14
  • 1
    It's alt + #, not alt + shift + 3. You only think that because on your keyboard, # is shift + 3 but this isn't true for other keyboard layouts.
    – UTF-8
    Dec 26, 2023 at 21:22
  • Alt+a and then Del?
    – Cyrus
    Dec 26, 2023 at 21:30
  • 1
    @Cyrus You mean Ctrl+a (and then Ctrl+d).
    – JoL
    Dec 27, 2023 at 0:19
  • @JoL: Almost. I meant Ctrl+a and then Del.
    – Cyrus
    Dec 27, 2023 at 0:23

2 Answers 2

5

The question is tagged . This answer is specifically for Bash. Tested in GNU Bash 5.2.15.

Define the following shell function:

function _toggle_comment {
case "$READLINE_LINE" in
   \#* )
        ((READLINE_POINT--))
        READLINE_LINE="${READLINE_LINE###}"
        ;;
   *   )
        READLINE_LINE="#$READLINE_LINE"
        ((READLINE_POINT++))
        ;;
esac
}

and bind it to Alt+#:

bind -x '"\e#":_toggle_comment'

(If in your keyboard layout # is in fact Shift+3 then the binding will re-define Alt+Shift+3 you mentioned.)

READLINE_LINE and READLINE_POINT are exactly for this kind of tricks. Upon Alt+#, depending on whether a leading # is there or not in the command line, the function removes it or adds it, and moves the insertion point accordingly.

1
  • Excellent. Note that if you put the bind command in a .sh file (e.g. together with the toggle function to make the key binding persist e.g. from ~/.bashrc), you need to source the shell script (to avoid bind: warning: line editing not enabled).
    – mirekphd
    Dec 27, 2023 at 10:07
3

Use a more powerful code editor than that built into Terminal, such as Kate. CtrlShiftD removes comment (CtrlD comments the line). See ShortcutsWorld for more.

There are numerous code editors with features far beyond those of Terminal itself; some can be installed as the Terminal editor.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .