Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to copy a line in sublime text without moving the cursor?

Tags:

sublimetext3

Say I have this code

body {
     margin: 0;
     padding: 0;
}

.navbar {
     margin: 0;
     padding: 0;
     background: rgba(0,0,0,0.1);
}

div {

}

Inside div I want to put the line, 'background: rgba(0,0,0,0.1);' so I can just copy it from above. I was wondering if there is a way to copy the line above without the cursor having to go up there copy and going back. I know I can just do ctrl-c and ctrl-v to cut and paste quickly but I thought it be much faster if I can just tell sublime which line I want to copy and insert it where my cursor is currently.

like image 455
user3904534 Avatar asked Aug 15 '14 17:08

user3904534


1 Answers

Yep it's possible. Though you have to make a plugin for that.
I tried to do it, so I'n not saying it is the easiest way ever, but it works.

Here is the snippet of code:

import sublime_plugin

class PromptCopyLineCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # prompt fo the line # to copy
        self.view.window().show_input_panel(
            "Enter the line you want to copy: ",
            '',
            self.on_done,  # on_done
            None,          # on_change
            None           # on_cancel
        )

    def on_done(self, numLine):
        if not numLine.isnumeric():
            # if input is not a number, prompt again
            self.view.run_command('prompt_copy_line')
            return
        else:
            numLine = int(numLine)

        # NOL is the number of line in the file
        NOL = self.view.rowcol(self.view.size())[0] + 1
        # if the line # is not valid
        # e.g. 0 or less, or more that the number of line in the file
        if numLine < 1 or numLine > NOL:
            # prompt again
            self.view.run_command('prompt_copy_line')
        else:
            # retrieve the content of numLine
            view = self.view
            point = view.text_point(numLine-1, 0)
            line = view.line(point)
            line = view.substr(line)
            # do the actual copy
            self.view.run_command("copy_line", {"string": line})

class CopyLineCommand(sublime_plugin.TextCommand):
    def run(self, edit, string):
        # retrieve current offset
        current_pos = self.view.sel()[0].begin()
        # retrieve current line number
        CL = self.view.rowcol(current_pos)[0]
        # retrieve offset of the BOL
        offset_BOL = self.view.text_point(CL, 0)
        self.view.insert(edit, offset_BOL, string+'\n')

Just save this in a python file under Package/User/ (for example CopyLine.py)
You can also define a shortcut for it like so:

{ "keys": ["ctrl+shift+c"], "command": "prompt_copy_line"}

If you have any question about this, please ask.

PS: Demo
enter image description here

like image 190
Xælias Avatar answered Nov 15 '22 08:11

Xælias