Sublime Forum

Trim trailing new line char when copy empty selection

#1

I frequently use the copy_with_empty_selection feature on my mac Sublime. I use cmd-c to copy a line (without highlighting it) and then I can paste it into my browser or other programs. The only downside for me is that a newline character is added at the end of the line that I copied. This can be confirmed by using this page: https://www.textmagic.com/free-tools/unicode-detector

I need to get rid of that trailing newline character. I searched for a setting in sublime but found none. I am not familiar with the concept of key bindings, but is this something that can be done? for instance, to instruct sublime to only copy the line but to trim the trailing new line char, if it exists. Perhaps using a regex or some other approach. Thanks for reading.

1 Like

#2

I don’t see anything in the settings either to do it, but it is trivial to write a plugin command which is a drop in replacement for cut with functionality to strip the trailing newline.

import sublime
import sublime_plugin

class StripTrailingNewLineCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        self.view.run_command("cut")
        contents = sublime.get_clipboard()
        sublime.set_clipboard(contents.rstrip())
 {
        "keys": ["ctrl+alt+x"],
        "command": "strip_trailing_new_line",
 },

This does the same thing as cut, the only additional thing is get’s the content of the clipboard, removes trailing \n and puts it back to the clipboard.

2 Likes

#3

Potentially, a person might want rstrip('\n') in place of rstrip(), which would trim the newline but leave any other trailing whitespace on the copied text.

That’s only necessary if a person wanted to remove the newline but other trailing whitespace on the line was important (which does not seem super likely at all).

0 Likes

#4

Yeah, for whitespace there is trim_trailing_white_space_on_save so you could set that to true to get rid of any white spaces, so the only left over thing is the \n. But yes, for more explicit one rstrip('\n')

1 Like

#5

Thank you both for your help. I got it working.

0 Likes