You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Visual Studio Code中创建.ahk文件简易格式化工具的方法

嘿,这个问题我刚好折腾过!其实咱们完全可以用AutoHotkey自己写一个轻量的格式化工具,不用依赖第三方插件,步骤也不复杂,我给你拆解一下:

一、核心思路拆解
  • 用AHK脚本读取目标.ahk文件的文本内容
  • 分析代码结构:根据{、}来增减缩进层级,遇到If、Loop、While这类关键字时自动调整缩进逻辑
  • 把处理后的文本写回原文件(或者另存为新文件,避免覆盖出错)
二、简易格式化脚本示例

下面是一个可用的基础版本,注释已经写得很清楚,你可以直接用:

; AHK简易格式化工具
FormatAHK(filePath) {
    ; 读取文件内容
    FileRead, content, %filePath%
    if ErrorLevel {
        MsgBox, 无法读取文件:%filePath%
        return
    }

    ; 初始化变量:缩进层级、缩进大小(可自定义)
    indentLevel := 0
    indentSize := 4  ; 缩进用4个空格,改成`t就是制表符
    newContent := ""
    lineNum := 0

    ; 逐行处理文本
    Loop, Parse, content, `n, `r {
        lineNum++
        currentLine := A_LoopField

        ; 先处理右大括号:缩进层级先减1,再应用缩进
        if (InStr(currentLine, "}")) {
            indentLevel--
            ; 避免层级出现负数(比如多余的右括号)
            if (indentLevel < 0)
                indentLevel := 0
        }

        ; 清理原行的前导空白,添加当前层级的缩进
        trimmedLine := Trim(currentLine, " `t")
        if (trimmedLine != "") {  ; 空行保持原样
            indent := ""
            Loop, %indentLevel%
                indent .= StrRepeat(" ", indentSize)  ; 生成对应层级的缩进
            newContent .= indent . trimmedLine . "`n"
        } else {
            newContent .= "`n"
        }

        ; 处理左大括号:层级加1(排除注释里的大括号)
        if (InStr(currentLine, "{")) {
            if (!InStr(SubStr(currentLine, 1, InStr(currentLine, "{")-1), ";")) {
                indentLevel++
            }
        }
        ; 处理不带大括号的关键字(比如If/Loop后直接换行写语句)
        ; 可根据需求扩展更多关键字
        keyWords := ["If", "Loop", "While", "For", "Try", "Catch", "Else"]
        for _, key in keyWords {
            if (RegExMatch(currentLine, "^`s*" key "`s*(?!;.*)", match) && !InStr(currentLine, "{")) {
                indentLevel++
                break
            }
        }
    }

    ; 保存格式化后的内容(可改成另存为,比如%filePath%_formatted.ahk)
    FileDelete, %filePath%
    FileAppend, %newContent%, %filePath%
    MsgBox, 格式化完成!
}

; 辅助函数:重复生成指定次数的字符串
StrRepeat(str, times) {
    out := ""
    Loop, %times%
        out .= str
    return out
}

; 调用逻辑:拖放AHK文件到脚本上即可触发格式化
#SingleInstance Force
if (A_Args.Length() > 0) {
    FormatAHK(A_Args[1])
} else {
    MsgBox, 请将.ahk文件拖放到本脚本上进行格式化!
}
三、使用&扩展建议
  • 快速使用:把上面的代码保存成AHKFormatter.ahk,直接把需要格式化的.ahk文件拖到这个脚本图标上,就能自动完成格式化
  • 自定义缩进:修改indentSize的值,或者把StrRepeat(" ", indentSize)改成StrRepeat("t", indentLevel)`来使用制表符缩进
  • 编辑器集成:如果用VS Code,可以把这个脚本配置成外部工具,设置快捷键直接调用(在VS Code的「设置-外部工具」里添加,命令填AutoHotkey.exe "你的脚本路径\AHKFormatter.ahk" "%file%")
  • 功能扩展:可以添加多行注释/* ... */的识别、对齐赋值语句等功能,根据自己的需求调整就行

内容的提问来源于stack exchange,提问作者Stenemo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:28:03