Search code examples
sublimetext3sublimetext

Center text at top of page in Sublime Text


In Sublime Text, one can recenter the current line at the center of a page with the show_at_center shortcut. Is there a way to do the same but with the current line moved to the top of the page?


Solution

  • There is no such command by default, although it's easy to create one via a plugin:

    import sublime
    import sublime_plugin
    
    
    class SelectionToTopCommand(sublime_plugin.TextCommand):
        """
        Jump the viewport in the file so that the selection is at the top of the
        file display area. Handy while conducting reviews.
        """
        def run(self, edit):
            position = self.view.sel()[0]
    
            offs = self.view.rowcol(position.begin())[0] * self.view.line_height()
            self.view.set_viewport_position((0.0, offs), True)
    
            self.view.sel().clear()
            self.view.sel().add(position)
    

    This defines a new command named selection_to_top that shifts the view of the current file so that the selection (which is just the cursor) is at the top of the viewport.

    You can bind it to any key that you find handiest for something like this, or add it to the command palette, etc.

    See how to use plugins in Sublime if you're unsure of how to add a new plugin and how to add commands to the command palette if you'd like to add the command there.