Skip to content

Instantly share code, notes, and snippets.

@anonymous1184
Last active March 19, 2024 18:42
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save anonymous1184/4b5463e2e37c4a8e6873eb580a3a7f0f to your computer and use it in GitHub Desktop.
Save anonymous1184/4b5463e2e37c4a8e6873eb580a3a7f0f to your computer and use it in GitHub Desktop.
AHK Debugging with Visual Studio Code

AHK Debugging with Visual Studio Code

Created on 2021/11/03 with VSCode version 1.53.
Last revision on 2022/06/30 with VSCode version 1.68.2.

I'm not a native English speaker, so please report inconsistencies to u/anonymous1184 (or send a .patch of the source).

Table of Contents

  1. TL;DR: 5-minute cookbook recipe
  2. Choosing a version
  3. Installing VSCode
  1. Extensions
  1. Usage Examples
  1. Profiles
  2. Misc. configurations

TL;DR: 5-Minute cookbook recipe

  1. Download, install, and run VSCode.
  2. Pres Ctrl+p and type/paste ext install mark-wiemer.vscode-autohotkey-plus-plus then press Enter to install extension that handles .ahk files.
  • Optionally this one1: Press Ctrl+p type/paste ext install zero-plusplus.vscode-autohotkey-debug then press Enter.
  1. Press Ctrl+n to create a new document and type/paste:
Untitled-1
#Warn All, OutputDebug
hello := "Hello "
world := "World!"
OutputDebug % hello world
OutputDebug % test123test
  1. Save the document with .ahk as the extension.
  2. Press F9 to debug and see the:
Debug Console

Happy debugging! (as if...)

1: If you want the optional benefits of the second extension.

Choosing a version

Depending on your OS and type of processor, you are better off with the corresponding architecture; so if you have a 64-bit OS, use the x64 version as it would have speed improvements2 over the x86 version.

Upon clicking the Windows button (instead of the specific build), the website will make an educated guess and deliver what it considers best.

A more specific installation can be chosen between a System and User type of installation; the first option places the application in %ProgramFiles% while the other places it in %LocalAppData%.

2: Not life-changing improvements, when compiled the instruction sets on the processor are taken into account to have more stability rather than raw speed.

Installing VSCode

This is your basic run-of-the-mill installer with a License Agreement and a few screens, in the end you're presented with the option to launch the installed application (please do). The process is shown below:

License Agreement
Destination Location
Start Menu Folder
Additional Tasks
Ready to Install
Completed

Portable version

The AutoUpdate.ahk script below takes care of everything, just put it in an empty folder and run it, no need for manual download/decompression.


If you want to use VSCode with the same settings on more than one computer but also don't want to log in to an account or don't have administrator access (or simply feel more in control with a stand-alone installation) download either the x64 or the x86 zip archive.

Once uncompressed, create an empty directory called data (and if you desire to keep temporal files outside the current user environment create a tmp directory inside).

The possible downside of this method of "installation" is that updates are not automatic, they need to be done manually. For that purpose, placing this script in the directory will do the job:

AutoUpdate.ahk
;
; Configuration ↓
;

#NoTrayIcon ; Don't show an icon

x64 := true ; Use 64 bit

;
; Configuration ↑
;

; No sleep
SetBatchLines -1

; Check if running
if (WinExist("ahk_exe " A_ScriptDir "\Code.exe")) {
    MsgBox 0x40024, Continue?, VSCode is running`, continue wit the update?
    IfMsgBox No
        ExitApp 1
}

; Get latest version information
x64 := (x64 && A_Is64bitOS)
url := "https://update.code.visualstudio.com/latest/win32" (x64 ? "-x64-" : "-") "archive/stable"
whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
whr.Open("HEAD", url, false), whr.Send()
headers := whr.GetAllResponseHeaders()
Sort headers

; Extract relevant information
regex := "is)(?<Name>[^""]+\.zip).*Length: (?<Size>\d+)"
RegexMatch(headers, regex, file)
if (!fileName || !fileSize) {
    MsgBox 0x40010, Error, Couldn't get the information from the link.
    ExitApp 1
}

; Check if already updated
FileCreateDir % A_ScriptDir "\data"
fileName := A_ScriptDir "\data\" fileName
FileGetSize currSize, % filename
if (FileExist(fileName) && !currSize) {
    MsgBox 0x40040, Updated, Already up-to-date.
    ExitApp
}

; Remove last downloaded version
FileDelete % A_ScriptDir "\data\VSCode-*.zip"

; Filesize
mb := Round(fileSize / 1024 / 1024, 2)

; Progress Window
Gui Download:New, +AlwaysOnTop +HWNDhGui -SysMenu +ToolWindow
Gui Font, q5 s11, Consolas
Gui Add, Text,, % "Downloading...    " ; +4
Gui Show,, % "> Downloading " mb " MiB"
Hotkey IfWinActive, % "ahk_id" hGui
Hotkey !F4, WinExist

; Download
SetTimer Percentage, 50
UrlDownloadToFile % url, % fileName
if (ErrorLevel) {
    MsgBox 0x40010, Error, Error while downloading.
    FileDelete % A_ScriptDir "\data\VSCode-*.zip"
    ExitApp 1
}
SetTimer Percentage, Delete
Gui Download:Destroy

; Close if running
WinKill % "ahk_exe " A_ScriptDir "\Code.exe"

; Extract
shell := ComObjCreate("Shell.Application")
items := shell.Namespace(fileName).Items
shell.Namespace(A_ScriptDir).CopyHere(items, 16 | 256)

; Truncate the file
FileOpen(fileName, 0x1).Length := 0

; Empty temp files
if (FileExist(A_ScriptDir "\data\tmp")) {
    FileRemoveDir % A_ScriptDir "\data\tmp", 1
    FileCreateDir % A_ScriptDir "\data\tmp"
}

; Run
Run Code.exe, % A_ScriptDir


ExitApp ; Finished


; Progress
Percentage:
    FileGetSize size, % fileName
    GuiControl Download:, Static1, % "Downloaded: " Round(size / fileSize * 100, 2) "%"
return

Extensions

The core functionality of VSCode can be easily extended with the Extensions Marketplace; it is a well-established ecosystem with a wide variety of additions for different programming languages, spoken languages, data/file types, et cetera... worth exploring.

AutoHotkey support in VSCode is not bundled out of the box, thus extensions allow full utilization of IDE features (such as syntax highlighting, IntelliSense, formatting, contextual help, debug...).

While there are a few AutoHotkey-related extensions available, the one made by Mark Wiemer is the most up-to-date and actively developed. It has everything most users might need to write and debug AutoHotkey scripts. For more advanced usage look into the extension referred to in the next subtopic. It is advised to read as much as possible about what can be accomplished with the extension.

To install the required extension click "Extensions" in the "Activity Bar" (the 5th icon on the left bar, or press Ctrl+Shift+x). Type (or copy and paste) the extension id: mark-wiemer.vscode-autohotkey-plus-plus and press Enter.

AutoHotkey++

Extension: AutoHotkey Plus Plus

In order to test create a new file (press Ctrl+n) and type/paste:

test.ahk
#Warn All, OutputDebug
hello := "Hello "
world := "World!"
OutputDebug % hello world
OutputDebug % test123test

Save the file with .ahk as extension and press F93 to test the debugger. The expected result is a very unoriginal Hello World! and a warning that in the line #5 an undefined variable was called:

Debug Console

Normally a MsgBox would have been issued for the warning:

Warning

3: Oddly, this shortcut is a default binding in the extension but also overrides toggling breakpoints; to address the issue refer to Fix F9 overlap.

Optional

The following are a few extensions that have a positive impact on the overall coding experience IMO (as always YMMV). The procedure to install them is the same as before:

  1. Press (Ctrl+p).
  2. Type/paste ext install followed by a space and the extension ID.
  3. Hit Enter and after a few seconds, the extension is installed.

However, you could also take the scenic route to find out more about the extension's details. In that case, try the following instead:

  1. Click "Extensions" in the "Activity Bar" (or press Ctrl+Shift+x).
  2. Type/paste the extension ID, press Enter, and review.
  3. If you wish to proceed, click on the small install button.

Bookmarks

Jumping between sections of code is something you'll always find yourself doing when dealing with files that require you to scroll is a nuance. There are of course methods to avoid manually looking through a file like the "Code Outline", "Go to Definition" or "Go to References", but what happens when you need to jump between parts in the middle of a "node"? Or simply to avoid using the mouse? Well, Bookmarks is exactly for that.

  • ID: alefragnani.bookmarks

Diff

VSCode has inline Diff support but only when working in a project with SCM configured, for chunk-based diff (with Clipboard support) Partial Diff is useful.

  • ID: ryu1kn.partial-diff

When dealing with a file as a whole and inline changes or side-to-side comparison is needed Diff will provide access to the built-in feature normally only available through the command line (Code.exe --diff path1 path2).

  • ID: fabiospampinato.vscode-diff

Overtype

This is the first editor I've used without native support for overtype, weird.

  • ID: adammaras.overtype

Sublime Text keymap

If you ever used Sublime Text Editor and got used to its bindings, a must is to keep consistency or avoid re-training muscle memory. A big plus of this extension is that it imports/translates the configuration of Sublime Text into VSCode.

  • ID: ms-vscode.sublime-keybindings

vscode-autohotkey-debug

While Mark's extension is more than enough for the majority of users, I've found that the (unnamed) extension provided by zero-plusplus has a broader set of functionality aimed at more nitpicking/advanced users. Again, take your time to read and consider if this extension provides an improvement over what's already on the table (a comparison between the two is out of the scope of this guide).

  • ID: zero-plusplus.vscode-autohotkey-debug

Usage Examples

This is not a comprehensive tutorial, but a quick guide aimed at covering the basics of how to effectively enable and utilize AHK debugging support in VSCode.

OutputDebug

OutputDebug simply sends an evaluated expression in the form of a string to the connected debugger for display in the console:

test.ahk
foo := {}
foo.bar := "Hello "
foo["baz"] := "World!"
OutputDebug Hello World!               ; Plain string
OutputDebug % foo["bar"] foo.baz       ; Object properties
OutputDebug % "Hello" A_Space "World!" ; String concatenation
Debug Console

(Mixed properties declaration/call in the object are intentional).

Additional benefits against methods like:

  • MsgBox: it doesn't halt code execution.
  • ToolTip: you can print/review several lines.
  • FileAppend: no need to keep "tailing" a log file.

To halt code execution, we have:

Breakpoints

Breakpoints allow the user to stop at any given line and inspect the code mid-execution, enabling manual review and modification of variables on-the-fly for any scope.

To set a breakpoint click to the left of the line numbers, or set up a keyboard shortcut (look for Debug: Toggle Breakpoint) the default F9 is overwritten but you can fix it.

Breakpoints can be set in any line but if they are set in comments or directives the interpreter will stop in the next available statement. In the following example, a breakpoint is set inside a loop, inside a function.

After setting the breakpoint, start the debugger by:

  • Press F5.
  • From the menu: Run > Start Debugger.
  • Clicking the "play" button on the top right corner.
Start of the loop
loop, second iteration
loop, third iteration
loop, last iteration
Session finished

Debug Actions

The basic actions on the vast majority of debuggers are:

  • Continue: Resumes the execution until the next breakpoint or end of the thread.
  • Step Over: Evaluates the next statement ahead.
  • Step Into: Goes inside the next statement (if user-defined).
  • Step Out: Continues to the upper layer in the stack.

More

For a more robust guide, please refer to the VSCode Documentation where you can read about Evaluation (directly in the console), "Variable Watch", "Call Stack", how to monitor variable values and set (Conditional4) Breakpoints at different layers of the stack when "tracing".

After this point, virtually every debugging tutorial explains the same concepts (once you remove language from the equation). For even more details: search engines, forums, subreddits, IRC/Discord servers, etc. can be of great help.

4: Only with vscode-autohotkey-debug extension.

Profiles

Profiles can be set to test various versions of AHK (ANSI, Unicode x86/x64, AHK_H, v2) and to start debugging a specific file (instead of the one currently in the editor). Click the "Run" icon in the "Activity Bar" (or press Ctrl+Shift+d) and click on the create a launch.json file link, a boilerplate will be created:

launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "ahk",
      "request": "launch",
      "name": "AutoHotkey Debugger",
      "program": "${file}",
      "stopOnEntry": true
    }
  ]
}
  • type: must be ahk.
  • name: is a free label.
  • request: must be launch.
  • program: a path to a script supports predefined variables12.
  • runtime: is the binary used to start the debugging process12.
  • stopOnEntry: true to stop on the first line even without a breakpoint.
Predefined Variables
${workspaceFolder}         // Path of the folder opened.
${workspaceFolderBasename} // Name of the folder opened (without any slashes).
${file}                    // Current opened file.
${relativeFile}            // Current opened file relative to workspaceFolder.
${relativeFileDirname}     // Current opened file's dirname relative to workspaceFolder.
${fileBasename}            // Current opened file's basename.
${fileBasenameNoExtension} // Current opened file's basename with no file extension.
${fileDirname}             // Current opened file's dirname.
${fileExtname}             // Current opened file's extension.
${cwd}                     // Task runner's current working directory on startup.
${lineNumber}              // Current selected line number in the active file.
${selectedText}            // Current selected text in the active file.
${execPath}                // Path to the running VSCode executable.
${defaultBuildTask}        // Name of the default build task.

12: Paths in windows use a backslash, JSON format needs a backslash escaped with another backslash. Another option is to use a single forward slash *NIX-style.

To add profiles just add objects into the configurations array:

Profiles example
{
  "type": "ahk",
  "name": "v1 U64",
  "request": "launch",
  "program": "${workspaceFolder}\\test.ahk",
  "runtime": "C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe",
  "stopOnEntry": false
},
{
  "type": "ahk",
  "name": "AHK_H U32",
  "request": "launch",
  "program": "${workspaceFolder}/test.ahk",
  "runtime": "D:/repos/ahkdll/bin/Win32w/AutoHotkey.exe",
  "stopOnEntry": true
}

Misc. configurations

  1. Workspace trust
  2. Fix F9 overlap
  3. Inline values
  4. Always use BOM
  5. Replace PowerShell

Workspace trust

The feature is annoying and even the authors acknowledge it. To disable open the Settings (Ctrl+,) in the search bar, paste/type security.workspace.trust.enabled and remove the check mark.

Fix F9 overlap

Fixing the overlapping F9 is far easier via editing the configuration rather than going through the UI. Press Ctrl+p, type/paste > Preferences: Open KeyboardShortcuts (JSON) and press Enter; the .json configuration for key bindings will open. Add the following inside the brackets:

keybindings.json
{
    "key": "f9",
    "command": "-ahk++.debug",
    "when": "editorLangId == 'ahk'"
},

After saving, you should have the defaults:

  • F5 to start debugging.
  • F9 to toggle breakpoints.

Inline values

To have an overlay with the parsed values of the expressions as soon as you step over them, open Settings (Ctrl+,) in the search bar, paste/type debug.inlineValues, and check the appropriate checkbox. Bear in mind that this can be both useful and overwhelming (too much information on-screen).

Always use BOM

AutoHotkey only plays nice with Unicode characters if scripts have the proper character encoding (see Byte Order Mark). To enable it, on the "Command Palette" (Ctrl+p) type/paste > Preferences: Open Settings (JSON) and add the following:

settings.json
"[ahk]": {
  "files.encoding": "utf8bom"
}

Replace PowerShell

To change the slower PowerShell for the command prompt (ie cmd.exe) or any other shell installed, open Settings (Ctrl+,) in the search bar, type/paste terminal.integrated.defaultProfile.windows, and select the terminal of your choice in the drop-down.

@UtaVile
Copy link

UtaVile commented Jun 29, 2022

You're a genius, this is incredibly useful!

@mark-wiemer
Copy link

Hi @anonymous1184 thanks for writing this, I'm honored! You'll be happy to know I've updated the default keybinding for AHK++, so there's no more overlap :) ref mark-wiemer-org/ahkpp#280

@OvercastBTC
Copy link

adammaras.overtype has been depreciated, new one is:
DrMerfy.overtype

@tdalon
Copy link

tdalon commented Feb 2, 2024

Somehow the AutoUpdate.ahk does not work anymore. It seems download location for portable has changed to sthg like : https://vscode.download.prss.microsoft.com/dbazure/download/insider/.

@OvercastBTC
Copy link

Update:
Also use the AutoHotkey2 Language Support extension by thqby (don't forget to review and star it)
https://marketplace.visualstudio.com/items?itemName=thqby.vscode-autohotkey2-lsp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment