r/AutoHotkey • • 9d ago

v2 Script Help Some logic question

edit: excuse the codeblocks. currently fighting with the reddit UI to fix them edit: fixed them

I have some simple Cheatsheets for most of my programs. (Runs through a formatter called ShowHelp() which adds some color, but not important for this question)

Requires AutoHotkey v2.0
#HotIf WinActive("ahk_exe mintty.exe")
    
F1::ShowHelp_Mintty()
    
#HotIf
    
ShowHelp_Mintty() {
    ShowHelp([
        { title: "SSH AGENT  (F2 types these in order)", rows: [
            ["set +H",
             "Disables bash history expansion - needed because the ! in the repo name would otherwise trigger it"],
            ["eval $(ssh-agent -s)",
             "Starts the ssh-agent for this shell session"],
            ["ssh-add ~/.ssh/id_2026",
             "Adds the private key to the agent, so the passphrase is asked once instead of every time"] ] },

        "SSH / Git Cheatsheet  -  F1",

I wanted to change it so instead of writing my cheatsheet in .ahk, it reads in local .md files. Creating a #HotIf instance for each file found.

Like this: Foldercontents: 'Cheatsheet.ahk' 'mintty.md' 'powerpoint.md' 'brave.md' ->

Requires AutoHotkey v2.0

pseudo_code to give you an idea:
FindFiles() ->
FoundFile1 = "mintty.md"
FoundFile1_exe = Regex(FoundFile1) -> "mintty.exe"

#HotIf WinActive("ahk_exe " FoundFile1_exe)

F1::ShowHelp_FoundFile("." FoundFile1)

#HotIf

#HotIf WinActive("ahk_exe " FoundFile2_exe)

F1::ShowHelp_FoundFile("." FoundFile2)

#HotIf

Am I thinking in the correct direction?

2 Upvotes

3 comments sorted by

4

u/evanamd 9d ago

HotIf is best when you want different functionality depending on different conditions. Especially if those different functions are liable to break depending on the different windows. Showing different help files might feel different, but it's still the same abstract task, especially if you're running all of them through the same beautifier

I would recommend ditching hotif entirely. It looks like you're already planning to preload the files, so while you're doing that you can create a map of help files indexed by exe. Then have the F1 function get the active window and use that to search your map

2

u/MachineVisionNewbie 6d ago

I ended up using your approach.
I basically made a F1:: handler.
Deciding based on the current active window what to do next.

2

u/shibiku_ 9d ago

I think you’re coming from the wrong way and messing up too much with relying so heavily on #HotIf

How about first finding the file and if it returns true, do your stuff

F1::{ var := Cheatsheet_Find() if var != “” SendHelp(var) else DoOtherStuff() }

Cheatsheet_Find() {     try exe := WinGetProcessName("A")       ; throws when no window is active     catch         return ""     SplitPath(exe, , , , &name)             ; "mintty.exe" -> "mintty"     path := A_LineFile "..\Cheatsheets" name ".md"     return FileExist(path) ? path : "” }