AutoHotkey - Rename image by desired name only by selecting it and pressing shortcut - png

I have a quite organized workflow and I have an image that always needs to have the same name. It's always a PNG (Portable Network Graphics) and no matter if it's on Desktop or in a folder.
So i just want to select the image and with a one letter shortcut (for example "L") rename it (regardless it's previous name) to "LAYOUT"

F2::
ClipSaved := ClipboardAll ; save the entire clipboard to the variable ClipSaved
clipboard := "" ; empty clipboard
Send, ^c ; copy the selected file
ClipWait, 1 ; wait for the clipboard to contain data
if (!ErrorLevel) ; If NOT ErrorLevel clipwait found data on the clipboard
{
clipboard := clipboard ; convert to text (= copy the path of the selected file)
Sleep, 300
; MsgBox, %clipboard% ; display the path
if (SubStr(clipboard, -2) != "png")
{
MsgBox, No PNG-file selected
clipboard := ClipSaved
return
}
; otherwise:
SplitPath, clipboard, name, dir
FileMove, %clipboard%, %dir%\LAYOUT.png
Sleep, 100
clipboard := ClipSaved ; restore original clipboard
}
else
{
MsgBox, No file selected
clipboard := ClipSaved
}
return

Related

AHK: Select & append words

I would like to select non-adjacent words while holding down some shortcut key, append them (space-separated) to one single string and put the final, appended string into the clipboard.
Something like:
{Control_down}::
OnDoubleClick{ my_appended_string += Str(current_text_selection) }
{Control_up}
Clipboard := my_appended_string
return
Just so it works :-)
Can you help?
; LCtrl+DoubleClick on words in text
<^LButton Up::
if (A_PriorHotKey = A_ThisHotKey and A_TimeSincePriorHotkey < DllCall("GetDoubleClickTime"))
{
; KeyWait, LCtrl ; after releasing LCtrl
clip_old := clipboard ; save the clipboard to the variable clip_old (as text))
clipboard := "" ; empty the clipboard (start off empty to allow ClipWait to detect when the text has arrived)
Click 2 ; select a word by doubleclick
Send, {Ctrl down}c{Ctrl up} ; copy the selected word
ClipWait 1 ; wait for the clipboard to contain data.
If (!ErrorLevel) ; If NOT ErrorLevel ClipWait found data on the clipboard
{
clip_new := clip_old A_Space clipboard ; append the new copied text to clip_old
clipboard := clip_new
}
else
{
MsgBox, No text copied
clipboard := clip_old
}
ToolTip, %clipboard%
Sleep, 1000
ToolTip
}
Return
EDIT:
Try also this
; Press F1 after putting the mouse pointer over the word to copy
F1 Up::
clip_old := clipboard ; save the clipboard to the variable clip_old (as text))
clipboard := "" ; empty the clipboard (start off empty to allow ClipWait to detect when the text has arrived)
Click ; on the word under the mouse pointer
Send, {Ctrl Down}{Left}{Ctrl Up}{Ctrl Down}{Shift Down}{Right}{Shift Up}{Ctrl Up} ; select the word
Sleep, 300
Send, {Ctrl down}c{Ctrl up} ; copy the selected word
ClipWait 1 ; wait for the clipboard to contain data.
If (!ErrorLevel) ; If NOT ErrorLevel ClipWait found data on the clipboard
{
clipboard := Trim(clipboard) ; remove leading/trailing spaces and tabs
clip_new := clip_old A_Space clipboard ; append the new copied text to clip_old
clipboard := clip_new
}
else
{
MsgBox, No text copied
clipboard := clip_old
}
ToolTip, %clipboard%
Sleep, 1000
ToolTip
Return

How to edit paths in Windows clipboard?

When pressing "Ctr+C" while selecting some files in the explorer, their paths are saved in the clipboard and when later pressing "Ctr+V" the files are pasted. For an AutoHotkey script I need to edit these paths in the clipboard, so the explorer pastes other files in the location of the "Ctr+V" press. So for example I want to select the file "A.txt" in "C:\Folder1" with "Ctr+C", then activate the AutoHotkey script to change the stored information in the clipboard of "A.txt" to the information about another file "B.txt", so when pressing "Ctr+V" in "C:\Folder2" the explorer copies "B.txt" instead of "A.txt".
But I have no idea how the paths of "Ctr+C" are exactly stored in the clipboard and I found no useful documentation. Different programms to access the content of the clipboard give one of the three results: 1) [Absolute nothing] 2) "C://A.txt" 3) "file:///C:/A.txt". But when editing the clipboard to "C://B.txt" or "file:///C:/B.txt" I got no reaction of the file explorer when using "Ctr+V".
So how are the paths of copied files exactly stored in the clipboard and with which programm I could edit them?
Edit: Following expamle to explain exactly what my goal is: Suppose I have a file "A.txt" in path 1, which I want to move to path 2 and another file "B.txt" in path 3, which I want to move to path 4. The normal procedure would be:
1) Copy "A.txt" with "Ctr+C" in path 1.
2) Paste "A.txt" with "Ctr+V" in path 2.
3) Copy "B.txt" with "Ctr+C" in path 3.
4) Paste "B.txt" with "Ctr+V" in path 4.
The goal of my AutoHotkey script is to allow the following alternative:
1) Copy "A.txt" with "Ctr+C+1" in path 1.
2) Copy "B.txt" with "Ctr+C+2" in path 2.
3) Paste "A.txt" with "Ctr+V+1" in path 1.
4) Paste "B.txt" wiht "Ctr+V+2" in path 2.
At first glance it might seem unnecessary, but when organising a lot of files in more complex system, it would be really convenient for me. Ideally, it should also work when I add "C.txt", "D.txt", ... to be saved in the third/fourth/... clipboard slot and even when instead of "A.txt" I want to store multiple files in one clipboard slot; later I also want to implement "Ctr+X+[n]" to cut files.
I experimented a lot and was able to save the different paths of the files from the clipboard to AutoHotkey variables. But now I have to load the paths, which are stored in the AutoHotkey variables back to the clipboard, so the corresponding files are pasted with the explorer.
So just for an example: My AutoHotkey script detects the keyboard input "Ctr+C+1" while I select A.txt in the file explorer, then sends the computer the shorcut "Ctr+C" to store the path of A.txt in the clipboard and finally saves this path as "C:/A.txt" in the AutoHotkey varibale "clip1". Then I select B.txt in the file explorer, press "Ctr+C+2", so the AutoHotkey script presses "Ctr+C" to get the file paths into the Windows clipboard and then saves ít as "C:/B.txt" in "clip2". Now I press "Ctr+V+1", so the AutoHotkey script should write the path from the variable "clip1" back in the Windows, then press "Ctr+V" to paste the file in the explorer. But the really problem is now, that it is not enough to just edit the Windows clipboard to "C:/A.txt". Then so the explorer doesnt react to the input "Ctr+V", for which he should paste the file. So, the Windows clipboard has to be edited in another format, like for example "#explorer_file:///C:/A.txt" (just a complete stupid guess, since I have no idea how it looks). I need to find this format, so my AutoHotkey script can edit the currently saved paths to another paths.
I hope that explains all confusion about this confusing problem.
I'd use something like this:
#NoEnv
#SingleInstance Force
; Create a GUI with checkboxes to save the path of the last copied files and
; copy/move selected items to another directory opened in explorer:
OnClipboardChange("files_copied")
return
files_copied(type){
global
If (type == 1) ; the Clipboard contains text or files copied
{
; https://autohotkey.com/board/topic/150291-detect-clipboard-contents-as-text-file-etc/#entry735751
If (DllCall("IsClipboardFormatAvailable", "uint", 15)) ; the Clipboard contains files
{
ToolTip, file(s) copied
Gui, destroy
Gui, Color, ControlColor, Black
Gui, Font, CDefault, Lucida Console
Gui, Add, Button, x30 y5 w100 h26 gCopy ,Copy
Gui, Add, Button, x230 y5 w100 h26 gMove ,Move
Gui, Add, CheckBox, x20 y50 vCh200 gCheckAll cYellow, Select All
Gui, Add, CheckBox, x20 y75 vCh201 gUnCheckAll cYellow, De-Select All
Loop, Parse, Clipboard, `n, `r
{
y_pos := 100 + (A_Index * 25)
Gui, Add, CheckBox, x20 y%y_pos% vCh%A_Index% cYellow, %A_LoopField%
I := A_Index ; number of copied files
}
Gui_height := 125+I*25
Gui, Show, x100 y5 w400 h%Gui_height%, Files copied ; comment out this line if you want to only show the Gui after pressing F1
Sleep 1000
ToolTip
}
}
}
; Press F1 to show the Gui if it's hidden
F1:: Gui, Show
; or If the command in the above function is commented out
; F1:: Gui, Show, x100 y5 w400 h%Gui_height%, Files copied
CheckAll:
Loop, %I%
GuiControl,, Ch%A_Index%, 1
GuiControl,, Ch200, 1
GuiControl,, Ch201, 0
return
UnCheckAll:
Loop, %I%
GuiControl,, Ch%A_Index%, 0
GuiControl,, Ch200, 0
GuiControl,, Ch201, 1
return
Copy:
Gui, submit, nohide
If !WinExist("ahk_class CabinetWClass") ; explorer
{
MsgBox, No explorer window exists
return
}
WinActivate, ahk_class CabinetWClass
WinWaitActive, ahk_class CabinetWClass, ,2
If (ErrorLevel)
{
MsgBox, explorer could not be activated
return
}
ExplorerPath := GetActiveExplorerPath()
Loop %I%
{
GuiControlGet, checked,, Ch%A_Index%, Value
If (checked = 1) ; if the control is checked
{
GuiControlGet, file,, Ch%A_Index%, Text
FileCopy, %file%, %ExplorerPath%\, 1 ; overwrite existing files
}
}
return
Move:
Gui, submit, nohide
If !WinExist("ahk_class CabinetWClass") ; explorer
{
MsgBox, No explorer window exists
return
}
WinActivate, ahk_class CabinetWClass
WinWaitActive, ahk_class CabinetWClass, ,2
If (ErrorLevel)
{
MsgBox, explorer could not be activated
return
}
ExplorerPath := GetActiveExplorerPath()
MsgBox, 262180, Move Files, Are you sure you want to move the selected files to`n`n%ExplorerPath%?
IfMsgBox No
return
New_Clipboard := ""
Loop %I%
{
GuiControlGet, checked,, Ch%A_Index%, Value
If (checked = 1) ; if the control is checked
{
GuiControlGet, file,, Ch%A_Index%, Text
FileMove, %file%, %ExplorerPath%\, 1 ; overwrite existing files
}
else
{
GuiControlGet, file,, Ch%A_Index%, Text
New_Clipboard .= file . "`n" ; concatenate the outputs
}
}
If (New_Clipboard = "")
Gui, destroy
else
ClipboardSetFiles(New_Clipboard, DropEffect := "Copy")
return
GuiClose:
Gui, Hide
return
; https://www.autohotkey.com/boards/viewtopic.php?f=6&t=69925
GetActiveExplorerPath()
{
explorerHwnd := WinActive("ahk_class CabinetWClass")
if (explorerHwnd)
{
for window in ComObjCreate("Shell.Application").Windows
{
if (window.hwnd==explorerHwnd)
{
return window.Document.Folder.Self.Path
}
}
}
}
; https://autohotkey.com/boards/viewtopic.php?p=63914#p63914
ClipboardSetFiles(FilesToSet, DropEffect := "Copy") {
; FilesToSet - list of fully qualified file pathes separated by "`n" or "`r`n"
; DropEffect - preferred drop effect, either "Copy", "Move" or "" (empty string)
Static TCS := A_IsUnicode ? 2 : 1 ; size of a TCHAR
Static PreferredDropEffect := DllCall("RegisterClipboardFormat", "Str", "Preferred DropEffect")
Static DropEffects := {1: 1, 2: 2, Copy: 1, Move: 2}
; Count files and total string length
TotalLength := 0
FileArray := []
Loop, Parse, FilesToSet, `n, `r
{
If (Length := StrLen(A_LoopField))
FileArray.Push({Path: A_LoopField, Len: Length + 1})
TotalLength += Length
}
FileCount := FileArray.Length()
If !(FileCount && TotalLength)
Return False
; Add files to the clipboard
If DllCall("OpenClipboard", "Ptr", A_ScriptHwnd) && DllCall("EmptyClipboard") {
; HDROP format
; 0x42 = GMEM_MOVEABLE (0x02) | GMEM_ZEROINIT (0x40)
hDrop := DllCall("GlobalAlloc", "UInt", 0x42, "UInt", 20 + (TotalLength + FileCount + 1) * TCS, "UPtr")
pDrop := DllCall("GlobalLock", "Ptr" , hDrop)
Offset := 20
NumPut(Offset, pDrop + 0, "UInt") ; DROPFILES.pFiles = offset of file list
NumPut(!!A_IsUnicode, pDrop + 16, "UInt") ; DROPFILES.fWide = 0 --> ANSI, fWide = 1 --> Unicode
For Each, File In FileArray
Offset += StrPut(File.Path, pDrop + Offset, File.Len) * TCS
DllCall("GlobalUnlock", "Ptr", hDrop)
DllCall("SetClipboardData","UInt", 0x0F, "UPtr", hDrop) ; 0x0F = CF_HDROP
; Preferred DropEffect format
If (DropEffect := DropEffects[DropEffect]) {
; Write Preferred DropEffect structure to clipboard to switch between copy/cut operations
; 0x42 = GMEM_MOVEABLE (0x02) | GMEM_ZEROINIT (0x40)
hMem := DllCall("GlobalAlloc", "UInt", 0x42, "UInt", 4, "UPtr")
pMem := DllCall("GlobalLock", "Ptr", hMem)
NumPut(DropEffect, pMem + 0, "UChar")
DllCall("GlobalUnlock", "Ptr", hMem)
DllCall("SetClipboardData", "UInt", PreferredDropEffect, "Ptr", hMem)
}
DllCall("CloseClipboard")
Return True
}
Return False
}

Ahk Script to find in the current folder a file or a folder with the latest change?

I often save files from Chrome to the Downloads folder or My Documents folder.
You have to look for these files later in the folder. Tell me whether it is possible to somehow make it more convenient using the ahk script. By pressing F3 for example, the last file or folder in the current folder is highlighted. How to implement it. Please help me, I'm a new
F3::
SetTitleMatchMode, 2
File := "" ; empty variable
Time := ""
Loop, Files, %A_MyDocuments%\Downloads\*.*, DF ; include files and folders
{
If (A_LoopFileTimeModified >= Time)
{
Time := A_LoopFileTimeModified ; the time the file/folder was last modified
File := A_LoopFileFullPath ; the path and name of the file/folder currently retrieved
}
}
; MsgBox, Last modified file in %A_MyDocuments%\Downloads is`n`n"%File%"
IfWinNotExist Downloads ahk_class CabinetWClass
Run % "explorer.exe /select," . File ; open containing folder and highlight this file/folder
else
{
SplitPath, File, name
MsgBox, Last modified file = "%name%"
WinActivate, Downloads ahk_class CabinetWClass
WinWaitActive, Downloads ahk_class CabinetWClass
; SelectExplorerItem(name) ; or:
SendInput, %name%
}
return
SelectExplorerItem(ItemName) { ; selects the specified item in the active explorer window, if present
; SelectItem -> msdn.microsoft.com/en-us/library/bb774047(v=vs.85).aspx
Window := ""
Static Shell := ComObjCreate("Shell.Application")
For Window In Shell.Windows
try IfWinActive, % "ahk_id " window.HWND
If (Item := Window.Document.Folder.ParseName(ItemName))
Window.Document.SelectItem(Item, 29)
Return (Item ? True : False)
}
https://autohotkey.com/docs/commands/LoopFile.htm

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

Copy to clipboard the script path with AutoHotKey

I have tried this but it's not copying the path of the folder containing the script:
If(WinActive("ahk_class ExploreWClass"))
{ ClipSaved := ClipboardAll
; save original clipboard clipboard = ; clear
clipboard Send, "%A_WorkingDir%" ; copy selected folder
ClipWait, 2 ; wait until the clipboard contains data Sleep,
100 }
Thanks for your help!
P.S: For this, I am using AHK as a bat, not as a hotkey
ClipSaved := ClipboardAll ; Save the entire clipboard to the variable ClipSaved
clipboard = %A_ScriptDir%
; ClipWait
; do sth e.g, ; SendInput, ^v
Clipboard := ClipSaved ; Restore the original clipboard
https://autohotkey.com/docs/misc/Clipboard.htm#ClipboardAll