Home > Back-end >  How to copy line in Sublime without new line
How to copy line in Sublime without new line

Time:08-26

In Sublime when you have nothing selected and click ctrl c you will copy whole line with the new line. How to remove that new line, so ctrl c will copy only current line.

I'm using Sublime on Windows.

CodePudding user response:

There's not a direct setting that has this effect on the copy of a line when nothing is selected (other than turning off that ability entirely) but you can still achieve this.

One would be to create a macro that selects the entire line but without the newline on the end and then does the copy (or cut if you want it to work that way too), and then bind the keys for copy and/or cut to execute the macro if the selection is empty.

An example of that can be found in: How to copy line without end of line character

This will definitely work, but it does have the effect of altering the selection to encompass the whole line, which at the least changes the location of the cursor from where it is to the end of the line.

If that is not desirable, then the way forward is a plugin that adjusts the clipboard operations to not include the newlines.

An example of that would be:

import sublime
import sublime_plugin


class ExtendedEmptyCopyPasteEventListener(sublime_plugin.EventListener):
    """
    Every time the cut or copy commands are executed in a file while all of the
    selections are empty, trim away the trailing newlines on the copied lines.
    """
    def on_post_text_command(self, view, cmd, args):
        # If copy or cut was just executed and every selection in the view was
        # empty, trigger our logic.
        if cmd in ("copy", "cut") and all([len(s) == 0 for s in view.sel()]):
            text = sublime.get_clipboard().split('\n')
            sublime.set_clipboard("\n".join([t for t in text if t != ""]))

This plugin listens for a copy or cut operation to finish, and then, if all of the selections are empty, adjusts the text on the clipboard so that it doesn't include newlines at the end of any of the copied lines.

See this YouTube video (disclaimer: created by me) on How to use plugins in Sublime Text if you're unsure of how to set the plugin up.

CodePudding user response:

I think you have to highlight the section you want to copy before hitting CTRL C. It's a default behavior to copy the entire line when there's no highlighted text, unless you learn to write an extension(plugin) that can overwrite that behavior. see here

  • Related