Welcome, guest | Sign In | My Account | Store | Cart

Reformat the clipboard text.

Python, 42 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
  + This code reformats:

abc def
ghi kjl
ioe.

hoa aho
ulm dij.

  + into:

abc def ghi kjl ioe.

hoa aho ulm dij.
"""
import win32clipboard as w 
import win32con,re

def getText(): 
    w.OpenClipboard() 
    d=w.GetClipboardData(win32con.CF_TEXT) 
    w.CloseClipboard() 
    return d 
 
def setText(aType,aString): 
    w.OpenClipboard()
    w.EmptyClipboard()
    w.SetClipboardData(aType,aString) 
    w.CloseClipboard() 

def changeClipboardBy(aFunction):
    result=aFunction(getText().replace('\r\n','\n'))
    setText(win32con.CF_TEXT,result.replace('\n','\r\n'))

def paragraph(aString):
    aString=re.sub(r'(?m)^\s*$','',aString)
    aString=re.sub(r'(?<!\n)\n(?!\n|$)',' ',aString)
    return aString

if __name__=='__main__':
    changeClipboardBy(paragraph)

Sometimes you need to reformat a piece of text, which is newlined on every n-th column like e-mail or usenet post texts, so that each paragraph has one single newline characters.

Use this code on win32. Make a shortcut icon on your desktop and assign a hotkey(from the properties window). Just select any area of text which you want to reformat and then press the hotkey. You can now paste the reformatted text anywhere you want to.

This module is reusable where you want to replace some piece of text on the fly. For example, you can use this module along with Reindenter in Tools/Scripts/reindent.py to reformat a piece of python code with clipboard ; you might need to fake file objects with StringIO in this case, since the class accepts file objs and writes on file objs, too.

1 comment

Michael Jackson 12 years, 8 months ago  # | flag

Cross platform solution using Tkinter:

from Tkinter import Tk

r = Tk()

r.withdraw()

result = r.selection_get(selection = "CLIPBOARD")

r.clipboard_clear()

r.clipboard_append('i can has clipboardz?')

r.destroy()

http://stackoverflow.com/questions/579687/how-do-i-copy-a-string-to-the-clipboard-on-windows-using-python