Skip to main content

Sublime Text Plug-in to align multiple cursors.

import re
import sublime
import sublime_plugin


"""
Sublime Text command to align multiple cursors.

Usage:

    view.run_command("remove_ansi_escape")

Original: https://gist.github.com/ddlsmurf/11211940
"""


class AlignCursors(sublime_plugin.TextCommand):

    def adjust_column_for_tabs(self, view, tab_size, region, rowcol):
        line_text = view.substr(view.line(region))[:rowcol[1]]
        return rowcol[1] + (line_text.count("\t") * (tab_size - 1))

    def run(self, edit):
        view = self.view
        tab_size = int(view.settings().get('tab_size', 8))
        regions = view.sel()

        right_most = 0
        cursors = 0
        lines = set()

        if len(regions) < 2:
            sublime.error_message("Error: Must have more than one cursor active.")

        for region in regions:
            if not region.empty():
                sublime.error_message("Error: Must have no content selected.")
                return

            rowcol = view.rowcol(region.begin())

            if rowcol[0] in lines:
                sublime.error_message(
                    "Error: Cannot have more than one cursor per line (line %i has more)." % (rowcol[0] + 1))
                return

            lines = lines | set([rowcol[0]])

            col = self.adjust_column_for_tabs(view, tab_size, region, rowcol)
            if col > right_most:
                right_most = col

        for region in regions:
            rowcol = view.rowcol(region.begin())
            col = self.adjust_column_for_tabs(view, tab_size, region, rowcol)

            if col < right_most:
                view.insert(edit, region.begin(), ''.join([' '] * (right_most - rowcol[1])))