Sublime Forum

From clipboard get list of line number => put cursor on them

#1

I wanted to make a plugin.py

Text with line numbers in clipboard => cursor on the beginning of each that lines

Text with line number in clipboard for example:

18
190
200
210
220
230
240
250
26

I am trying to begin writing, but my knowledge is very poor.

import sublime, sublime_plugin

class CursorPluginCommand(sublime_plugin.WindowCommand):
    def run(self):            
        print('selection_plugin__ called')

        window = self.window
        view = window.active_view()
        sel = view.sel().view.sel()
        view.sel().add(sublime.Region(1,1))
0 Likes

#2
import sublime
import sublime_plugin


class CursorPluginCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # Get the content of the clipboard, trim leading and trailing white
        # space and then split it into lines; turn the resulting value (a list
        # of strings) into a list of integers that represent the line numbers.
        try:
            clipboard = sublime.get_clipboard().strip().split('\n')
            lines = [int(n) for n in clipboard]
        except:
            self.view.window().status_message('clipboard contains non-numerics')
            return

        # The values we have are lines; convert them into positions into the
        # buffer at which each of those lines would start; the values we pass
        # are zero based.
        points = [self.view.text_point(line - 1, 0) for line in lines]

        # Using the points, clear the selection and then add in a new selection
        # region for each; this positions a cursor at the start of each line.
        self.view.sel().clear()
        for point in points:
            self.view.sel().add(sublime.Region(point))

This will do what you want, though I would recommend looking at the API documentation to see the methods used here and why/how they’re doing what they’re doing.

This includes some simple error checking for making sure that the contents of the clipboard is only numbers.

Additionally, if the clipboard contains lines that don’t exist, the cursor will get placed at the next closest line (so for example if the clipboard contained 30 but the file only has 27 lines, the cursor ends up on line 27). If you don’t want that then you need to limit the values in the lines array to values smaller than self.view.rowcol(len(self.view))[0]+1, which is the 1 based line number of the last line of the file.

Cursors that end up at the same position are merged together automatically by Sublime.

3 Likes

#3

You are genius!!!
What I needed.

thank you

0 Likes