How to set cursor position in the text editor? I found bpy.ops.text.set_cursor(), which looks like what I want, however it always sets the cursor to the end of the file.

import bpy

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

    def execute(self, context):
        t = bpy.context.space_data.text
        cursor_x = t.current_character
        cursor_y = t.current_line_index

        if t.select_end_line != t.current_line:
            # if there is a selection already, use default behavior:
            bpy.ops.text.comment()
        else:
            bpy.ops.text.select_line()
            bpy.ops.text.comment()

            print(cursor_x, cursor_y)
#            bpy.ops.text.cursor_set(x=cursor_x, y=cursor_y)
            bpy.ops.text.cursor_set(x=0, y=0)

        return {'FINISHED'}

def register():
    bpy.utils.register_class(CommentLineOperator)


def unregister():
    bpy.utils.unregister_class(CommentLineOperator)

if __name__ == "__main__":
    register()


Running the above in the text editor and assigning the newly created text.comment_line operator to a shortcut and subsequently using that shortcut in the text editor will comment the line, then move the cursor to the end of the file even when I manually specify position 0,0. 

How can I move the cursor in the text editor properly?
Yep, cursor_set appears to use a mix of 'space_data.top' and 'space_data.visible_lines' and is a might confusing.  However you can use

    bpy.ops.text.jump(line=1)
    bpy.ops.text.move(type='LINE_BEGIN')


Will move the cursor to the beginning of line 1

    bpy.ops.text.jump(line=10)
    bpy.ops.text.move(type='NEXT_WORD')


moves to the first word in in line 10, where you would add a comment #