Search code examples
sqlemacskey-bindings

Emacs keybinding to comment selection/multiple lines for SQL file?


I have a .sql file that I am editing in Emacs 24, and I am looking for a way to comment out a selection or a line. Basically, I want a keybinding to add -- at the line start (for single line comments) or /* and */ around the selected region (for variable line comments).

Perhaps there is something that I can add to my .emacs to enable such a keybinding? (I am a bit of a novice to Emacs) Thanks.

EDIT

After a little exploring, I found M-x comment-region to do the trick for single line comments. This was also very helpful: Comment Guide in Emacs

Still, how can I do variable line comments?


Solution

  • FWIW, I use comment-dwim only for end-of-line comments (e.g., ; at the end of a Lisp line). I use it there to create the comment and also to reindent it.

    I do not use comment-dwim to comment or uncomment a block of text, even though it does let you do that to some extent (it is limited in this regard, especially regarding nesting and the number of comment chars to use).

    I prefer comment-region for that. I bind comment-region to C-x C-;. It lets me control or change the number of ; chars to use for commenting (in Lisp mode). And it lets me easily uncomment a block of text. And it lets me comment a block of text that already contains commented blocks of text (nesting). And it lets me uncomment a block of text a given level (unnesting a given level).

    I cannot speak particularly about SQL mode commenting, but try comment-region and see if it doesn't do what you want. Be sure to learn the use of different prefix arg possibilities.

    FWIW, I don't know what you mean by "variable line comments". If you mean (un)commenting a block of text, then see above. If you mean something different, then please elaborate.

    Note that in SQL code --- just as in Lisp code --- you can use the single-line comment syntax (-- for SQL; ; for Lisp) to comment out a block of text. You need not use /*...*/ in SQL for that. I do that in my SQL code, for instance.