# Is there a way to make a shortcut comment the current line?

I'm used to CtrlD commenting the current line rather than duplicating it.

This is easy enough to change in the user preferences, however it only works when there is a highlighted selection.

Is it possible to make this work even when nothing is highlighted, so the line with the cursor is commented?

You could create a custom operator and map the following to a shortcut.

bpy.ops.text.move(type='LINE_BEGIN')
bpy.ops.text.insert(text="#")


or if selecting the line is tiresome you can just automate the selection step then comment

bpy.ops.text.select_line()
bpy.ops.text.comment_toggle()


Creating a custom operator would look something like this

import bpy

class CommentLineOperator(bpy.types.Operator):
bl_idname = 'text.comment_line'
bl_label = 'Comment a line'

def execute(self, context):
bpy.ops.text.select_line()
bpy.ops.text.comment() >> bpy.ops.text.comment_toggle() since 2.8

return {'FINISHED'}

bpy.utils.register_class(CommentLineOperator)
bpy.utils.unregister_class(CommentLineOperator)


After that, you should be able to map a shortcut easily to text.comment_line.

To have this load at startup, just save it with a .py extension and drop it into your scripts/startup/ folder. See How could a single Python script run when Blender is started?.