13

I need a way to strip leading indents (tabs and spaces) from data copied to clipboard from Notepad++.

The data in the Notepad++ document itself should keep having these leading indents and the data copied to clipboard should not.

This behavior should be initiated by CTRL+C alone and only when I'm inside Notepad++.


This is what happens in Notepad++ when I mark the text regularly with the mouse:

enter image description here

That's what should be in clipboard after I mark the text regularly and copy it:

enter image description here


Notes:

  1. The images are just to better illustrate my need - my actual codes are longer.
  2. I also asked about this here.
  3. I ask this because I can't paste indented code blocks in to Linux terminal if these codeblocks include cat heredocuments (has to do with processing of heredocument delimiters, a long story).
  • How many lines, and characters are you looking to copy? I.E. would it be feasible to remove the leading spaces, copy, and then undo the changes? – FCTW May 1 '17 at 20:09
  • what if the file or some lines in it has no leading tab? why do you want to do it always? – phuclv May 2 '17 at 11:05
  • 1
    Why do you need this? What makes the leading whitespace annoying? – mrjink May 4 '17 at 10:29
  • In the shell? That shouldn't be a problem. If it's into vim, consider :set paste. – mrjink May 4 '17 at 10:32
  • In the shell, not in Vim. It is a problem because when you paste codes with cat heredocs - It is. – JohnDoea May 4 '17 at 10:35
7
+150

Consider the following AutoHotKey (AHK) script. See the AutoHotkey Tutorial and documentation for more explanations on AutoHotkey scripts.

After installing AutoHotKey, press Ctrl+Shift+c or x within Notepad++ to copy (or cut) to the clipboard with the lines trimmed.

Note: I used Ctrl+Shift so that you could still use the original copy and cut normally with only Ctrl. If you don't like this behavior, just remove + in both +^c:: and +^v::.

See the comments (starting with ;) for an explanation. As with any coding, better leave in the comments to better understand the script when you come back to it later.

SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.

TrimClipboard()
{
    ; Split each line of the clipboard into an array. 
    ; Note: Ignoring Cr (`r) prevents duplicate rows
    linesArray := StrSplit(clipboard, "`n", "`r")

    newClip := "" ; Initialize output string

    for index, element in linesArray
    {   
        ; For each line: trim it, append it and CrLf to output string
        newClip .= trim(element) . "`r`n" 
    }
    ; Note: There is always an extra newline at this point, regardless 
    ; of if the clipboard ended in a newline.

    ; Assign value back to clipboard, without the trailing CrLf
    clipboard := SubStr(newClip, 1, -2)
}

#IfWinActive ahk_class Notepad++
; On Shift+Ctrl+C, perform copy, wait for new content, and trim clipboard
+^c::
    ; Note: ^{sc02e} is the scancode for c which works regardless of keyboard layout
    Send, ^{sc02e}
    Clipwait
    TrimClipboard()
return

;On Shift+Ctrl+X, perform copy, wait for new content, and trim clipboard
+^x::
    ; Note: ^{sc02d} is the scancode for x which works regardless of keyboard layout
    Send, ^{sc02d}
    Clipwait
    TrimClipboard()
return

; sc02e && sc02d are keyboard scan codes for the keys c and x respectively.
; The scancodes work regardless of the keyboard layout set in Windows

#IfWinActive
  • Comments are not for extended discussion; this conversation has been moved to chat. – Journeyman Geek May 5 '17 at 1:18
  • Steven I would give another 50 points bounty but for some reason I cannot. I noticed that copying while working in Hebrew, actually deletes content and then I have to do ctrl+z to retrive the deleted content. This is slightly problematic. I understand something like the following code could be utilized? if !LangID := EN { return }. Adding it in the start of the script brought error and wrapping the script with a similar version plus an else { return } after the closure didn't error but didn't work. – JohnDoea May 9 '17 at 16:28
  • 1
    You cannot put a function definition TrimClipboard(){ ... } inside of an if statement. Put the if statement inside the function, or around the commands Send, ... TrimClipboard() – Steven May 10 '17 at 18:35
  • Hi there dear Steven. In my tryings, it didn't work. Is this a bug in the language? I detailed in length here: autohotkey.com/boards/… – JohnDoea Jun 3 '17 at 22:11
  • I just published a solution in the same discussion there: autohotkey.com/boards/… – JohnDoea Jun 10 '17 at 2:14
3

Just use Alt + Mouse dragging or Alt + Shift + Arrow keys to select the column, then Ctrl+C to copy the column.

See this example : https://notepad-plus-plus.org/fr/features/column-mode-editing.html

Edit:

We can also select the whole column, or even more then one column, also we can select one or many rows.

Here is a simple way to do it:

  • Left mouse click at the beginning of the wanted selection.

  • Go to the location where the wanted selection must stop

  • Move the cursor to that second and final location, with :

    • A hit on the ALT + SHIFT keys and a left click, simultaneously, to select the desired columns and rows.

Hope this help

  • 1
    I add some more details to my previous response, hope this help. – Yacine May 2 '17 at 8:29
  • 1
    this only works if all lines have the same leading tab or spaces – phuclv May 2 '17 at 11:06
  • 1
    Actually, yes, and the question was that the lines have the same format – Yacine May 2 '17 at 11:11
1

Here's a portable-ish solution using Java

The first step is, of course, installing Java

Next, paste the following into a file named Trimmer.java in your user directory (C:\Users\your_name)

import java.awt.*;
import java.awt.datatransfer.*;

public class Trimmer{
    public static void main(String... lines) throws Exception{
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        String str = (String)clip.getContents(null).getTransferData(DataFlavor.stringFlavor);
        lines = str.split("\n");
        str = "";
        for(String line: lines) str += line.trim() + '\n';
        StringSelection selection = new StringSelection(str.substring(0,str.length()-1));
        clip.setContents(selection,selection);
    }
}

Then, open up a command prompt and type

javac Trimmer.java

You should now have a Trimmer.class file in the same folder. You can delete the Trimmer.java file now.


At this point, we have a program that will remove all leading and trailing white spaces from each line in the clipboard, but we still need a way to run it conveniently. Let's make a hotkey for it!

First, create a shortcut to the command prompt (right-click C:\Windows\System32\cmd.exe)

Then, right-click this shortcut and select "Properties." There are a few things we need to do in this window. In the "Shortcut" tab, there should be a "Target" option that says something like

%windir%\system32\cmd.exe

Change it to say

%windir%\system32\cmd.exe /C "java Trimmer"

This will cause the command prompt to simply run our program and exit when we use this shortcut.

Next, click on the "Shortcut key" box and press the hotkey you'd like to trigger the text replacement. I recommend Ctrl+Shift+C for ease of use!

Finally, change the "Run" option to "Minimized" since we don't want a window blinking onto the screen every time we make use of the shortcut.


After all this, you should be able to use the following workflow:

  1. Copy text using CtrlC
  2. Trim text using Ctrl+Shift+C
  3. Paste trimmed text using CtrlV
  • Hi Ryan. I am looking for a way to do everything with CTRL+C alone, as long as I'm in Notepad++... Also, is there a way to start this script when I'm booting Windows? – JohnDoea May 4 '17 at 10:51
0

Maybe I'm missing something but all the other answers seem to over complicate the solution. If i understood correctly all you want to do is remove leading white spaces (spaces or tabs) and you have the data available in Notepad++

In which case the solution is simple. Open your file in Notepad++ >> Search >> Replace... or Ctrl+H

Find what: ^( *)[ ]|^\t*

Replace with: leave empty

To find all leading space we use ^( *)[ ] and to find all leading tabs, we use ^\t*, as such to find all leading space or all leading tabs we use the or operator |. Make sure that Regular Expression is selected in the replace window.

It should finish rather quickly, even if it's a large file. Close the Replace Window and just Select All (Ctrl+A) >> Copy (Ctrl+C)

  • Actually no, I want to keep them in the file. I just need to clipboard version not to have them. – JohnDoea May 4 '17 at 21:21
  • @Benia yeah, i understood that. I just wouldn't save the file after copying the data since it's not needed. The reason i suggested it because personally i use Notepad++ quite heavily and altering how it's copy works would be more irritating to me than using a regex to copy and not save the file. Since it's just in this one instance where i don't want leading characters, in 90% of other cases i would. – JordanGS May 4 '17 at 21:27
0

My answer is based on the answer by Steven which I marked as correct (yet I had a few problems with it and I tried to edit though my edit was rejected).

This is the code that worked best for me:

TrimClipboard()
{
    linesArray := StrSplit(clipboard, "`n", "`r")

    newClip := ""

    for index, element in linesArray
    {   
        newClip .= trim(element) . "`r`n" 
    }

    clipboard := SubStr(newClip, 1, -2)
}

#IfWinActive ahk_class Notepad++
^c::
    Send, ^{sc02e}
    Clipwait
    TrimClipboard()
return

^x::
    Send, ^{sc02d}
    Clipwait
    TrimClipboard()
return

Differences from the original code by Steven:

  • I removed SendMode Input from the head of the command because it broke my script for some reason.
  • I removed the Shift key from both key combos because I personally prefer to work without it most of the time.
  • I replaced Send, ^c and Send, ^x with Send, ^{sc02e} and Send, ^{sc02d}, respectively. This prevents a text-deletion bug in Hebrew mode and some other non-English language modes).
  • I removed the comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.