Skip to content

Instantly share code, notes, and snippets.

@ericosur
Forked from anonymous1184/VSCode.md
Created November 21, 2021 06:30
Show Gist options
  • Save ericosur/467a1b024c9e24236e2cd62ed1eef8f0 to your computer and use it in GitHub Desktop.
Save ericosur/467a1b024c9e24236e2cd62ed1eef8f0 to your computer and use it in GitHub Desktop.
AHK Debugging with Visual Studio Code

AHK Debugging with Visual Studio Code

Guide created on 11/03/21 with VSCode version 1.53 (stable). Last tested with version 1.62.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: 5min Cookbook Recipe
  2. Choosing a Version
  3. Installing VSCode
  4. Extensions
  5. Usage Examples
    1. OutputDebug
    2. Breakpoints
    3. Debug Actions
    4. More
  6. Profiles
  7. Misc. Configurations
    1. Inline Values
    2. Replace PowerShell
    3. Always Use BOM
    4. Fix F9 Overlap

TL;DR: 5min Cookbook Recipe

  1. Download, install and run VSCode.

  2. On the "Command Palette" (Ctrl+p) type/paste ext install mark-wiemer.vscode-autohotkey-plus-plus then press Enter.

    • Optionally this one1: Press Ctrl+p type/paste ext install zero-plusplus.vscode-autohotkey-debug then press Enter.
  3. Press Ctrl+n to create a new document and type/paste:

    test.ahk
    #Warn All, OutputDebug
    hello := "Hello "
    world := "World!"
    OutputDebug % hello world
    OutputDebug % test123test
  4. Save the document with .ahk as the extension.

  5. Press F9 to see the:

    Debug Console

Happy debugging! (as if...)

1: If you want the optional benefits/quirks 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 x64 OS, use the x64 version as it would have speed improvements2 over the x32 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 - 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 version?

args := "--reuse-window --disable-crash-reporting"
; VSCode command line arguments when running.

;
; Configuration ↑
;

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
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()

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

; Check if already updated
if FileExist(fileName)
{
	MsgBox 0x40040, Updated, Already up-to-date.
	ExitApp
}

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

; Progress Window
Gui New, +AlwaysOnTop +HwndGuiId -SysMenu +ToolWindow
Gui Font, s11 q5, Consolas
Gui Add, Text,, % "Downloading...    "
Gui Show,, % "> Downloading " mb " MB"
Hotkey IfWinActive, % "ahk_id" guiId
Hotkey !F4, WinExist

; Download
SetTimer Percentage, 1
UrlDownloadToFile % url, % fileName
if (ErrorLevel)
{
	MsgBox 0x40010, Error, Error while downloading.
	FileDelete % A_ScriptDir "\data\VSCode-*.zip"
	ExitApp 1
}
SetTimer Percentage, Delete
Gui 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)

; Empty the file
FileOpen(fileName, 0x1).Write("")

; Run
Run % "Code.exe " args, % A_ScriptDir


ExitApp ; Finished


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

Extensions

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

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

While there are quite 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 to extension referred in the next subtopic. It is advised to read as much as possible of 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.

AHK++

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 anywhere 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 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 actually have a positive impact on the overall coding experience IMO (as always YMMV). The procedure to install them is the same as before:

  1. Open the "Command Palette" (Ctrl+p).
  2. Type/paste ext install followed by the extension ID.
  3. Hit Enter and after a few seconds 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 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 are 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 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 actually 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 any improvement over the existing one. 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 (string) to the connected debugger for display.

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 on the editor margin, or setup 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 clicking the "play" button on the top right corner, or from the menu : Run > Start Debugger (or press F5).

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" and "Call Stack" and how to monitor variable values and set (Conditional4) Breakpoints at different layers of the Stack when "tracing".

After this point, virtually every debugging video/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 in 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 like in *NIX.

To add profiles just add objects into the configurations array:

Profiles examples
{
    "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. Inline Values
  2. Fix F9 Overlap
  3. Always Use BOM
  4. Replace PowerShell

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).

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.

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"
}

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:

settings.json
{
    "key": "ctrl+shift+b",
    "command": "editor.debug.action.toggleBreakpoint",
    "when": "debuggersAvailable && editorTextFocus"
}

After saving, you'll have:

  • F5 to start current debugging profile.
  • F9 to start debugging the current file.
  • Ctrl+Shift+b to toggle breakpoints (same as Eclipse).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment