Autohotkey: Paste/write a simple line of text with a keyboard shortcut? - autohotkey

This is a super simple thing I am trying to get my head around
I want to use something like WINKEY + ALT + C to paste ** - words** so that I can sign-off my posts or whatever using the three-key combo

Not sure what exactly you want, maybe something like this?
Press WINKEY + ALT + C to paste the clipboard contents:
#!c::
SendInput, ^v
Return
Press WINKEY + ALT + C to paste "Some random text"
#!c::
SendInput, Some random text
Return

Instead of Sendinput which will type each characters you can use a clipboard paste approach. See for example https://github.com/tdalon/ahk/blob/59a8ab2a8fd497b4a5b5a85e73e32ff95d5d4425/Lib/Clip.ahk
Clip_Paste(sText,restore := True) {
; Syntax: Clip_Paste(sText,restore := True)
If (restore)
ClipBackup:= ClipboardAll
Clipboard := sText
WinClip.Paste()
If (restore)
Clip_Restore(ClipBackup)
} ; eofun
; ---------------------------------------------------------------------------
Clip_Restore(ClipBackup) {
Clip_Wait() ; in order not to overwrite running clipboard action like pasting
Clipboard:= ClipBackup
} ;eofun
; ---------------------------------------------------------------------------
Clip_Wait(){
Sleep, 150
while DllCall("user32\GetOpenClipboardWindow", "Ptr")
Sleep, -1
} ; eofun

Related

Surrounding Clipboard with quotes in URL

Warning: I'm very new to this.
I'd like to make Google searches quicker by assigning a hotkey to search a text selection (in web browser) and surrounding that search with quotes (to get exact matches).
I've tried using bits of code I have found, but so far I can only search the selected text on Google, but don't know how to surround the selected text in quotes in the search.
^!d:: ;
prevClipboard := ClipboardAll
SendInput, ^c
ClipWait, 1
if !(ErrorLevel) {
Clipboard := RegExReplace(RegExReplace(Clipboard, "\r?\n"," "), "(^\s+|\s+$)")
If SubStr(ClipBoard,1,7)="http://"
Run, % Clipboard
else
Run, % "https://www.google.com/search?q=" Clipboard
}
Clipboard := prevClipboard
return
This simply opens a google search with the clipboard.
I cannot find out how to make it so "Clipboard" is searched instead of Clipboard.
Any suggestions? Thanks!
Run is a command and variables in commands have to be enclosed in percent signs.
To include an quote, specify two consecutive quotes twice:
Run, http://www.google.com/search?q=""%Clipboard%""
If you want to do a "Phase google search" from any Selected Text (And From Out Everywhere, on your Computer System.)
Then you can try this AHK Script.
you can [Select any Text] and then you can click the [F1] key from your Keyboard Device.
The Computer Find automatic out where it can do the Query Search (us 100x results) and what Browser it must use.
Example1.ahk
;#notrayicon
#SingleInstance force
GroupAdd, Browser, ahk_class Chrome_WidgetWin_1 ; Chrome or Iron
GroupAdd, Browser, ahk_class IEFrame ; Internet Explorer
GroupAdd, Browser, ahk_class MozillaWindowClass ; FireFox
GroupAdd, Browser, ahk_class ApplicationFrameWindow ; Edge
; here you can change the variable into exact search [
quote1 = "
; here you can change the variable into exact search ]
quote2 = "
; here you can change the variables intitle: - inurl: - inanchor: - allinurl: - allinanchor:
insearch = allintitle:
; + = Shift
; ! = Alt
; ^ = Ctrl
; # = Win (Windows logo key)
esc::exitapp ;You can click the (esc) key to stop the script.
f1::
If WinActive("ahk_group Browser")
{
sendinput ^c ;copy the selected text to clipboard memory
sleep 150
sendinput ^t ;CTRL+t make a new tab + goto address bar - use CTRL+L for the active tab + goto address bar
sleep 150
texta = https://www.google.com/?gfe_rd=cr&gws_rd=cr#q=%insearch%%quote1%
textb = %clipboard%%quote2% ;selected text
textc = &lr=lang_us&hl=us&num=100 ; google parameters
clipboard=%texta%%textb%%textc%
sleep 150
sendinput ^v ; paste the selected text
sleep 250
send {enter}
clipboard=%textb%
} else {
sendinput ^c ;copy the selected text to clipboard memory
sleep 150
texta = https://www.google.com/?gfe_rd=cr&gws_rd=cr#q=%insearch%%quote1%%quote1%
textb = %clipboard%%quote2%%quote2%%quote2% ;selected text
textc = &lr=lang_us&hl=us&num=100 ; google parameters
clipboard=%texta%%textb%%textc%
run %clipboard%
clipboard=%textb%
}
return

Join lines automatically using autohotkey

Long paragraphs in Adobe Acrobat results in a line break when text is copied to clipboard and pasted in Word.
To deal with this, I manually paste the copied-text in Notepad ++ > select all > ctrl+J (join lines) > select all > Copy...... and then paste it into my Word document.
I would like to automate this join line using autohotkey as I have a large body of documents to go through. I can't seem to find any examples online in dealing with this directly within autohotkey script.
Ex.
Data structures with labeled axes supporting automatic or explicit data alignment.
This prevents common errors resulting from misaligned data and working with
differently-indexed data coming from different sources.
After manually joining in Notepad ++
Data structures with labeled axes supporting automatic or explicit data alignment. This prevents common errors resulting from misaligned data and working with differently-indexed data coming from different sources.
This works:
#Persistent
OnClipboardChange("ClipChanged")
return
ClipChanged() {
If (WinActive("ahk_exe AcroRd32.exe")) {
For e, v in StrSplit(clipboard, "`n", "`r")
x .= v " "
clipboard := trim(x)
}
}
Try this:
#Persistent
return
OnClipboardChange:
If WinActive("ahk_exe AcroRd32.exe")
{
clipboard =
Send, {Ctrl down}c{Ctrl up}{Esc}
ClipWait
clip := RegExReplace(clipboard, "(\S.*?)\R(.*?\S)", "$1 $2") ; strip line breaks and replace them with spaces
clipboard = %clip%
StringReplace clipboard, clipboard, % " ", % " ", A ; replace double spaces with single spaces
ClipWait
ControlClick, x0 y0, A
}
return
EDIT
Or this:
#Persistent
return
OnClipboardChange:
If WinActive("ahk_class AcrobatSDIWindow")
{
clipboard := ""
Send, {Ctrl down}c{Ctrl up}{Esc}
ClipWait
clip := RegExReplace(clipboard, "(\S.*?)\R(.*?\S)", "$1 $2") ; strip line breaks and replace them with spaces
StringReplace clip, clip, % " ", % " ", A ; replace double spaces with single spaces
clipboard := ""
clipboard = %clip%
ClipWait 2
If !(ErrorLevel)
{
ToolTip, lines joined
Sleep 500
ToolTip
}
}
return
I added functionality considering lines ending with a hyphen.
Before:
This occurs in elec-
tricity generation
systems.
After:
This occurs in electricity generation systems.
Code:
#Persistent
return
OnClipboardChange:
If WinActive("ahk_exe AcroRd32.exe")
{
clipboard := ""
Send, {Ctrl down}c{Ctrl up}{Esc}
ClipWait
clip := RegExReplace(clipboard, "(\S.*?)-\R(.*?\S)", "$1$2") ; strip line breaks with hyphen
clip := RegExReplace(clip, "(\S.*?)\R(.*?\S)", "$1 $2") ; strip line breaks and replace them with spaces
StringReplace clip, clip, % " ", % " ", A ; replace double spaces with single spaces
clipboard := ""
clipboard = %clip%
ClipWait 2
If !(ErrorLevel)
{
ToolTip, lines joined
Sleep 500
ToolTip
}
}
return

MATLAB auto completing start and end statements of code body?

Is it possible in MATLAB to automatically insert start and end of a code body ?
For example: classdef and end; function and end; methods and end.
classdef Circle
properties
radius
end
methods
function dia = FindDia(obj)
dia = [obj.radius]*2;
end
function %no automatic insertion of 'end'
end
end
Since I work regularly in so many different editors, I don't rely on any one editor's features. It's a pain to learn them all and keep the configuration for all these editors in sync, on all my machines. Often, it's useful to have the same feature set I'm used to, in editors not even meant for code (like MS Word, or here on Stack Overflow).
Therefore, I use AutoHotkey for this kind of thing (and Autokey on Linux).
For functions and classes, I use a paste function to paste a specific template file, depending on whether I'm at work or at home, and which project I'm working on. A small GUI then asks me for the function or class name, which it then populates the template with. I can share that too if you want.
Below are a few AutoHotkey functions and hotstrings I use for including the end keyword. Note that this might all seem overly complex just to put an end there, and in this case, it probably is. But the clipCopy, clipPaste and getIndent functions have proven their usefulness in the rest of my programming snippets, and I hope they might be for you too.
I've thrown in the error functions as well, just because.
; Copy selected text
; More robust than C-c/C-x/C-v; see
; https://autohotkey.com/board/topic/111817-robust-copy-and-paste-routine-function/
clipCopy(dontRestoreClipboard := 0)
{
prevClipboard := Clipboard
Clipboard := ""
copyKey := "vk43sc02E" ; Copy
SendInput, {Shift Down}{Shift Up}{Ctrl Down}{%copyKey% Down}
ClipWait, 0.25, 1
SendInput, {%copyKey% Up}{Ctrl Up}
str := Clipboard
if (dontRestoreClipboard == 0)
Clipboard := prevClipboard
return str
}
clipPaste(ByRef txt, dontBackupClipboard := 0)
{
if (txt != "")
{
prevClipboard := ""
pasteKey := "vk56sc02F" ; Paste
if (dontBackupClipboard == 0) {
prevClipboard := Clipboard
Clipboard := ""
}
Clipboard := txt
ClipWait, 1.00, 1
; Start pressing paste key
SendInput, {Shift Down}{Shift Up}{Ctrl Down}{%pasteKey% Down}
; Wait until clipboard is ready
startTime := A_TickCount
while (DllCall("GetOpenClipboardWindow") && (A_TickCount - startTime < 1000)) {
Sleep, 50
}
; Release paste key
SendInput, {%pasteKey% Up}{Ctrl Up}
; TODO: a manual delay still seems necessary...this vlaue needs to be this large, to also have
; correct behavior in superslow apps like MS Office, Outlook, etc. Sadly, the SetTimer approach
; does not seem to work (doesn't correctly restore the clipboard); to be investigated.
Sleep 333
; Put previous clipboard content back onto the clipboard
Clipboard := prevClipboard
}
}
; Get current indentation level in an editor-independent way
getIndent(dontRestoreClipboard := 0)
{
; Select text from cursor to start of line
SendInput, +{Home}
indent := clipCopy(dontRestoreClipboard)
numsp := 0
if (indent != "")
indent := RegExReplace(indent, ".", " ", numsp)
; Undo selection (this is tricky; different editors often have
; different behavior for Home/End keys while text is selected
SendInput, {Right}{Left}{Home}
; NOTE: don't use {End}, because we might be in the middle of a sentence
; Use the "right" key, repeatedly
Loop, %numsp% {
SendInput, {Right}
}
return indent
}
mBasic(str)
{
current_indent := getIndent()
SendInput, %str% (){Enter}+{Home}%current_indent%{Space 4}{Enter}+{Home}%current_indent%end{Up 2}{End}{Left}
}
mErrfcn(str)
{
current_indent := getIndent()
spaces := RegExReplace(str, ".", " ")
clipPaste(str . "([mfilename ':default_errorID'],...`r`n" . current_indent . spaces . " 'Default error string.');")
return current_indent
}
; MATLAB Hotstrings for basic control structures
:o:mfor::
mBasic("for")
return
:o:mpar::
mBasic("parfor")
return
:o:mwhile::
mBasic("while")
return
:o:spmd::
mBasic("spmd")
return
:o:mif::
mBasic("if")
return
; ...etc.
; error, warning, assert
:o:merr::
:o:merror::
mErrfcn("error")
SendInput, {Up}{End}{Left 21}
return
:o:mwarn::
:o:mwarning::
mErrfcn("warning")
SendInput, {Up}{End}{Left 21}
return
_mlAssert()
{
current_indent := mErrfcn("assert")
SendInput, {Up}{End}{Left 34}true,...{Enter}+{Home}%current_indent%{Space 7}{Up}{End}{Left 8}
}
:o:massert::
_mlAssert()
return

Autohotkey if in clipboard

So I am trying to look for a specific text on the webpage and do a thing if the text was found, here is my current script:
!m::
clipboard =
text = my text here
Send, {Ctrl}+A
Sleep, 100
Send, {Ctrl}+C
var1 = %clipboard%
IfInString, var1, %text%
msgbox found the text
else
msgbox no text found
And regardless if the text is on the webpage or not, it always returns "no text found"
Any help on this?
P.S. I've also tried "if contains" and removing line breaks from the variable but the result is the same :(
StringReplace, var1, var1, `r `n, All
The send commands are not correct.
A command {Ctrl}+A, will press Ctrl, release it, and then press A. The lower case letter should also be used.
You should use either:
Send, {Ctrl down}{a}{Ctrl up}
or
Send, ^{a}
Do this for both Send commands.
A return commend should also be included as the end of the hotkey code
sequence:
...
else
msgbox no text found
return
Try this:
!m::
clipboard := "", MyText := "Hello World"
cmds := ["{Ctrl down}", "a", "c", "{ctrl up}"]
Loop % cmds.MaxIndex() {
Send % cmds[A_Index]
if (A_index == 2)
sleep 100
}
MsgBox % clipboard ~= "i)" MyText ? "Found" : "Not Found"

Autohotkey script to bookmark to a specific folder

I'm using Firefox and I was looking for an autohotkey script which would enable me to skip the whole series of clicks when I bookmark a page in a specific folder and replace it with a single keyboard shortcut.
Although I've read forum threads on Autohotkey forum and here I still don't know how to make a working script that would reduce bookmarking a page to hitting a keyboard shortcut and the initial letter of the folder where I want to store that page. Using KeyWait command I've made it work for a single folder and don't know how to make it work for any letter or a number that I could possibly use as a name for a bookmark folder. Say I have a folder named XXXX, this script does send the webpage to the XXXX folder after hitting the assigned shortcut and the letter x (MouseClick command is needed to focus the window with folder in the Bookmark Dialog pane):
!+^w::
Send,^d
Sleep,400
MouseClick,Left,864,304
Sleep,400
KeyWait, x ,D
Sleep, 400
Send,^{Enter}
return
I don't know how to make this script work for any letter or number, not only for a single one. Also a big problem with this script is that it blocks the keyboard until I hit X key. If I have that page bookmarked already, hitting escape to remove the bookmark pane will block the keyboard and I can unblock it only if I rerun the autohotkey script.
I've also tried using Input command as the contributors the Autohotkey forum pages suggested, but it didn't work either, because I don't understand how the Input command works. I did make it work for a single letter as the above script with KeyWait, but that's the best I could do. This script also blocks the keyboard until the letter is hit:
!+^w::
Send,^d
MouseClick,Left,864,304
Sleep,400
Input, Character, L1
If Character = t
Send, t
Sleep,400
Send,^{Enter}
return
Hope someone can help me with this, it would be convenient simplifying the bookmarking process in Firefox this way.
I have a nice idea. This will open the add bookmark dialog and navigate you into the folder selection part and expand all folders.
All you need to do is enter the folders name (or a part of it) and it will get selected automatically. When you're done, just hit enter.
!+^w:: ;Hotkey: Ctrl+Alt+Shift+w
Send, ^d ;send Ctrl+d to open the add-bookmark dialog
Sleep, 500 ;wait for the dialog to open
Send, {Tab}{Tab}{Enter} ;navigate into the folder selection
Sleep, 300 ;wait to make sure we are there
Send,{Home} ;select the first item in the list
;The following line should expand all the folders so that you can just type the folders name to search for it
Loop, 100 { ;Increase the number if it doesn't expand all folders
SendInput, {Right}{Down} ;expand folders
}
Send, {Home} ;navigate to the first item in the list again
Input, L, V L1 T2 ;wait until you start typing a folder name (if you just wait 2 seconds, the bookmark won't be created)
If (ErrorLevel = "Timeout") {
Send, {Tab 5} ;press tab 5 times to navigate to the cancel button
Send, {Enter} ;cancel the bookmark
Return ;end of the hotkey
}
Loop { ;wait until you haven't typed a new letter for 0.4 seconds
Input, L, V L1 T0.4
If (ErrorLevel = "Timeout")
Break
}
Send, {Tab 4} ;press tab 4 times to navigate to the enter button
Send, {Enter} ;save the bookmark
Return
My variant.
Press f1 to create bookmark in folder test1.
Press f2 to create bookmark in folder test2.
SetBatchLines, -1
Folders := {F1: "test1", F2: "test2"}
#IfWinActive, ahk_class MozillaWindowClass
F1::
F2::
Folder := Folders[A_ThisHotkey]
Send, ^d
AccFirefox := Acc_ObjectFromWindow(WinExist("ahk_class MozillaWindowClass"))
AccElem := SearchElement(AccFirefox, ROLE_SYSTEM_LISTITEM := 0x22, Folder, "")
AccElem.accDoDefaultAction(0)
sleep 100
Send {Enter}
msgbox done
return
#IfWinActive
SearchElement(ParentElement, params*)
{
found := 1
for k, v in params {
(k = 1 && ParentElement.accRole(0) != v && found := "")
(k = 2 && ParentElement.accName(0) != v && found := "")
(k = 3 && ParentElement.accValue(0) != v && found := "")
}
if found
Return ParentElement
for k, v in Acc_Children(ParentElement)
if obj := SearchElement(v, params*)
Return obj
}
Acc_Init()
{
Static h
If Not h
h:=DllCall("LoadLibrary","Str","oleacc","Ptr")
}
Acc_ObjectFromWindow(hWnd, idObject = 0)
{
Acc_Init()
If DllCall("oleacc\AccessibleObjectFromWindow", "Ptr", hWnd, "UInt", idObject&=0xFFFFFFFF, "Ptr", -VarSetCapacity(IID,16)+NumPut(idObject==0xFFFFFFF0?0x46000000000000C0:0x719B3800AA000C81,NumPut(idObject==0xFFFFFFF0?0x0000000000020400:0x11CF3C3D618736E0,IID,"Int64"),"Int64"), "Ptr*", pacc)=0
Return ComObjEnwrap(9,pacc,1)
}
Acc_Query(Acc) { ; thanks Lexikos - www.autohotkey.com/forum/viewtopic.php?t=81731&p=509530#509530
try return ComObj(9, ComObjQuery(Acc,"{618736e0-3c3d-11cf-810c-00aa00389b71}"), 1)
}
Acc_Error(p="") {
static setting:=0
return p=""?setting:setting:=p
}
Acc_Children(Acc) {
if ComObjType(Acc,"Name") != "IAccessible"
ErrorLevel := "Invalid IAccessible Object"
else {
Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
Loop %cChildren%
i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i), Children.Insert(NumGet(varChildren,i-8)=9?Acc_Query(child):child), NumGet(varChildren,i-8)=9?ObjRelease(child):
return Children.MaxIndex()?Children:
} else
ErrorLevel := "AccessibleChildren DllCall Failed"
}
if Acc_Error()
throw Exception(ErrorLevel,-1)
}