AHK script to auto replace clipboard contents

autohotkey

When I write an AHK script like this:

::abc::alphabet

It works like charm. The only thing is, when I want a copied part of text, (something that includes things I want to have auto replaced) it doesn't want to replace it.

For example:

!INS::{Ctrl Down}c{Ctrl Up}{Tab 2}{Enter}{Ctrl Down}v{Ctrl Up}

Lets me copy abc but when it is pasted, I don't get alphabet (as defined earlier).

Is there a way to make it replace the copied and pasted words? Like when I use the send command to send a line or some words that include a word I would like to auto replace?

Best Answer

Hotstrings only affect what you physically type. To perform search and replace on the Clipboard you can use the RegExReplace command.

Below is a script which copies the selected text and then pastes the modified contents (after search and replace). I believe this is what you meant:

#x:: ;[Win]+[X]

;Empty the Clipboard.
    Clipboard =
;Copy the select text to the Clipboard.
    SendInput, ^c
;Wait for the Clipboard to fill.
    ClipWait

;Perform the RegEx find and replace operation,
;where "ABC" is the whole-word we want to replace.
    haystack := Clipboard
    needle := "\b" . "ABC" . "\b"
    replacement := "XYZ"
    result := RegExReplace(haystack, needle, replacement)

;Empty the Clipboard
    Clipboard =
;Copy the result to the Clipboard.
    Clipboard := result
;Wait for the Clipboard to fill.
    ClipWait

;-- Optional: --
;Send (paste) the contents of the new Clipboard.
    SendInput, %Clipboard%

;Done!
    return
Related Question