added additional dialouge

added additional dialouge


DC 插件：完善功能

DC 插件：完善功能

/*
    此插件仅供自用，依赖对 DC 代码的修改以及专门的配置

    ---

    DC 的优势

    开源，免费，跨平台，可以自由改代码定制功能，很好编译
    可以改代码让所有目录中的父目录（..）消失（已完成）
    可以把按键绑定到工具栏的子菜单上，然后再通过按键触发功能
    内建 lua 解释器，方便写一些高级功能（感觉功能有限，用处不大）
    主界面和配置界面更漂亮、好用

    ---

    TODO

    整理快捷键列表到配置文件

    迁移 TC 的主菜单命令

    CreateShortcut 导出为命令

    作为 OpenDialog
*/

DoubleCommander:
    global DC := "ahk_class DClass"
    global DC_Dir := "c:\mine\app\doublecmd"
    DC_Name := "DoubleCommander"

    vim.SetWin(DC_Name, "DClass", "doublecmd.exe")
    vim.Mode("normal", DC_Name)

    vim.BeforeActionDo("DC_ForceInsertMode", DC_Name)
return

DC_ForceInsertMode() {
    ControlGetFocus, ctrl
    if (InStr(ctrl, "Edit") == 1) {
        return true
    }

    WinGet, MenuID, ID, AHK_CLASS #32768
    if (MenuID != "") {
        return true
    }

    return false
}

DC_Run(cmd) {
    ControlSetText, Edit1, % cmd, % DC
    ControlSend, Edit1, {enter}, % DC
}

; 返回值 [1]: left/right [2]: 左侧面板所占比例 0-100
DC_GetPanelInfo() {
    ClipSaved := ClipboardAll
    Clipboard := ""
    DC_run("cm_CopyPanelInfoToClip")
    ClipWait, 2

    PanelInfo := StrSplit(Clipboard, " ")
    Clipboard := ClipSaved

    return PanelInfo
}

DC_ExecuteToolbarItem(Id) {
    DC_Run("cm_ExecuteToolbarItem ToolItemID=" . Id)
}

DC_ColumnsView(columnset) {
    if (columnset == "") {
        DC_Run("cm_ColumnsView")
    } else {
        DC_Run("cm_ColumnsView columnset=" columnset)
    }
}

<DC_ContextMenu>:
    Send, {appskey}
return

<DC_Rename>:
    Send, {f2}{right}
return

<DC_RenameFull>:
    Send, {f2}^a
return

<DC_Test>:
    ; DC_ExecuteToolbarItem("{700FF494-B939-48A3-B248-8823EB366AEA}")
    DC_Run("cm_About")
return

<DC_Restart>:
    WinClose, % DC
    WinWaitClose, % DC, , 2

    Run, % DC_Dir . "\doublecmd.exe"

    WinWaitActive, % DC

    if (!WinExist(DC)) {
        MsgBox, 重启失败 %ErrorMessage%
    }
return

<DC_Show_50_50>:
    DC_Run("cm_PanelsSplitterPerPos splitpct=50")
return

<DC_Show_100_0>:
    DC_Run("cm_PanelsSplitterPerPos splitpct=100")
return

<DC_Show_0_100>:
    DC_Run("cm_PanelsSplitterPerPos splitpct=0")
return

<DC_HorizontalFilePanels>:
    DC_Run("cm_HorizontalFilePanels mode=legacy")
return

<DC_Toggle_50_100>:
    PanelInfo := DC_GetPanelInfo()

    if (abs(50 - PanelInfo[2]) < 10) {
        if (PanelInfo[1] == "left") {
            DC_Run("cm_PanelsSplitterPerPos splitpct=100")
        } else {
            DC_Run("cm_PanelsSplitterPerPos splitpct=0")
        }
    } else {
        DC_Run("cm_PanelsSplitterPerPos splitpct=50")
    }
return

<DC_MakeDir>:
    DC_Run("cm_MakeDir")
return

<DC_PreviousParallelDir>:
    SleepTime := 10

    ClipSaved := ClipboardAll
    Clipboard := ""
    DC_Run("cm_CopyCurrentPathToClip")
    ClipWait, 2

    OldPwd := Clipboard

    if (InStr(OldPwd, "\") == 1) {
        ; 网络文件系统比较慢
        SleepTime := 50
    }

    if (StrLen(OldPwd) == 3) {
        ; 在根分区 TODO
        ; Gosub, <cm_GotoPreviousDrive>

        Clipboard := ClipSaved
        ClipSaved := ""

        return
    }

    DC_Run("cm_ChangeDirToParent")
    Sleep, % SleepTime

    Send, {up}
    Sleep, % SleepTime

    Send, {right}

    Clipboard := ClipSaved
    ClipSaved := ""
return

<DC_NextParallelDir>:
    SleepTime := 10

    ClipSaved := ClipboardAll
    Clipboard := ""
    DC_Run("cm_CopyCurrentPathToClip")
    ClipWait, 2

    OldPwd := Clipboard

    if (InStr(OldPwd, "\") == 1) {
        ; 网络文件系统比较慢
        SleepTime := 50
    }

    if (StrLen(OldPwd) == 3) {
        ; 在根分区 TODO
        ; Gosub, <cm_GotoPreviousDrive>

        Clipboard := ClipSaved
        ClipSaved := ""

        return
    }

    DC_Run("cm_ChangeDirToParent")
    Sleep, % SleepTime

    Send, {down}
    Sleep, % SleepTime

    Send, {right}
    Sleep, % SleepTime

    Clipboard := ""
    DC_Run("cm_CopyCurrentPathToClip")
    ClipWait, 2

    if (InStr(OldPwd, Clipboard) == 1) {
        ; 下一个是文件
        DC_Run("cm_ViewHistoryPrev")
    }

    Clipboard := ClipSaved
    ClipSaved := ""
return

<DC_DownSelect>:
    Send +{Down}
return

<DC_UpSelect>:
    Send +{Up}
return

<DC_CreateNewFile>:
    ControlGetFocus, TLB, % DC
    ControlGetPos, xn, yn, , , % TLB, % DC

    Menu, NewFileMenu, Add
    Menu, NewFileMenu, DeleteAll
/*
   TODO
    Menu, NewFileMenu, Add , S >> 快捷方式, <cm_CreateShortcut>
    Menu, NewFileMenu, Icon, S >> 快捷方式, %A_WinDir%\system32\Shell32.dll, 264
    Menu, NewFileMenu, Add
*/

    Loop, % DC_Dir . "\ShellNew\*.*" {
        ft := SubStr(A_LoopFileName, 1, 1) . " >> " . A_LoopFileName
        Menu, NewFileMenu, Add, % ft, DC_NewFileMenuAction
        Menu, NewFileMenu, Icon, % ft, %A_WinDir%\system32\Shell32.dll
    }

    Menu, NewFileMenu, Show, % xn, % yn + 2
return

DC_NewFileMenuAction:
    Filename := RegExReplace(A_ThisMenuItem, ".\s>>\s")
    FilePath := DC_Dir . "\ShellNew\" . Filename

    Gui, Destroy
    Gui, Add, Text, x12 y20 w50 h20 +Center, 模板源
    Gui, Add, Edit, x72 y20 w300 h20 Disabled, % FilePath
    Gui, Add, Text, x12 y50 w50 h20 +Center, 新建文件
    Gui, Add, Edit, x72 y50 w300 h20, % Filename
    Gui, Add, Button, x162 y80 w90 h30 gDC_NewFileOk default, 确认(&S)
    Gui, Add, Button, x282 y80 w90 h30 gDC_NewFileClose , 取消(&C)
    Gui, Show, w400 h120, 新建文件
return

DC_NewFileClose:
    Gui, Destroy
return

DC_NewFileOK:
    GuiControlGet, SrcFilePath, , Edit1
    GuiControlGet, NewFilename, , Edit2

    ClipSaved := ClipboardAll
    Clipboard :=
    DC_Run("cm_CopyCurrentPathToClip")
    ClipWait, 2
    DstPath := Clipboard
    Clipboard := ClipSaved
    ClipSaved := ""

    if (InStr(DstPath, "`r")) {
        DstPath := SubStr(DstPath, 1, InStr(DstPath, "`r") - 1)
    } else if (DstPath == "") {
        return
    }

    NewFilePath := DstPath . NewFilename
    if (FileExist(NewFilePath)) {
        MsgBox, 4, 新建文件, 新建文件已存在，是否覆盖？
        IfMsgBox No
            return
    }

    FileCopy, % SrcFilePath, % NewFilePath, 1

    ; TODO
    ; 好像无法实现定位到新创建的文件

    Gui, Destroy
return

<DC_Toggle>:
    if (WinExist(DC)) {
        WinGet, Ac, MinMax, % DC
        if (Ac == -1) {
            WinActivate, % DC
        } else {
            if (!WinActive(DC)) {
                WinActivate, % DC
            } else {
                WinMinimize, % DC
            }
        }
    } else {
        Run, % DC_Dir . "\doublecmd.exe"
        WinWait, % DC

        if (!WinActive(DC)) {
            WinActivate, % DC
        }
    }
return

<DC_SortByName>:
    DC_Run("cm_SortByName")
return

<DC_SortByExt>:
    DC_Run("cm_SortByExt")
return

<DC_SortBySize>:
    DC_Run("cm_SortBySize")
return

<DC_SortByDate>:
    DC_Run("cm_SortByDate")
return

<DC_SortByAttr>:
    DC_Run("cm_SortByAttr")
return

<DC_ReverseOrder>:
    DC_Run("cm_ReverseOrder")
return

<DC_FocusSwap>:
    DC_Run("cm_FocusSwap")
    ; side=left/right
return

<DC_CopyCurrentPathToClip>:
    DC_Run("cm_CopyCurrentPathToClip")
return

<DC_OpenExplorer>:
    DC_Run(".")
return

<DC_MarkFile>:
    DC_Run("cm_EditComment")
    ; 不要在已有备注的文件使用
    Send, ^+{end}🖥{f2}
return

<DC_UnMarkFile>:
    DC_Run("cm_EditComment")
    ; 删除 DC_MarkFile 的文件标记，也可用于清空文件备注
    Send, ^+{end}{del}{f2}
return

<DC_ShowMainMenu>:
    DC_Run("cm_ShowMainMenu")
return

<DC_ShowButtonMenu>:
    DC_Run("cm_ShowButtonMenu")
return

<DC_OperationsViewer>:
    DC_Run("cm_OperationsViewer")
return

<DC_TreeView>:
    DC_Run("cm_TreeView")
return

<DC_FocusTreeView>:
    DC_Run("cm_FocusTreeView")
return

<DC_BriefView>:
    DC_Run("cm_BriefView")
return

<DC_ColumnsView1>:
    DC_ColumnsView("mine")
return

<DC_ColumnsView2>:
    DC_ColumnsView("test")
return

<DC_ThumbnailsView>:
    DC_Run("cm_ThumbnailsView")
    Gosub, <DC_ThumbnailsSwitchKey>
return

<DC_ThumbnailsSwitchKey>:
    InThumbsView := !InThumbsView

    if (InThumbsView) {
        vim.Map("l", "<right>", DC_Name)
    } else {
        vim.Map("l", "<enter>", DC_Name)
    }
return

<DC_ToggleShowInfo>:
    vim.GetWin(DC_Name).SetInfo(!vim.GetWin(DC_Name).info)
return

<DC_CopyFileContent>:
    Clipboard := ""
    DC_Run("cm_CopyFullNamesToClip")
    ClipWait, 2

    Fileread, Contents, % Clipboard
    Clipboard := Contents
return

<DC_CopyFilenamesOnly>:
    Clipboard := ""
    DC_Run("cm_CopyFullNamesToClip")
    ClipWait, 2

    SplitPath, Clipboard, OutFileName, , , OutFilenameNoExt

	if (InStr(FileExist(Clipboard), "D")) {
        Clipboard := OutFileName
    } else if (InStr(Clipboard, ".")) {
        Clipboard := OutFilenameNoExt
    }
return

/*
    此插件仅供自用，依赖对 DC 代码的修改以及专门的配置

    ---

    DC 的优势

    开源，免费，跨平台，可以自由改代码定制功能，很好编译
    可以改代码让所有目录中的父目录（..）消失（已完成）
    可以把按键绑定到工具栏的子菜单上，然后再通过按键触发功能
    内建 lua 解释器，方便写一些高级功能（感觉功能有限，用处不大）
    主界面和配置界面更漂亮、好用

    ---

    TODO

    列表视图和缩略图试图返回上一级目录失效

    ff/fa 按键

    迁移 TC 的主菜单命令

    CreateShortcut 导出为命令

    缩略图模式自动修改按键绑定

    整理快捷键列表到配置文件

    切换到上/下一个同级目录（进行中）

    作为 OpenDialog
*/

DoubleCommander:
    global DC := "ahk_class DClass"
    global DC_Dir := "c:\mine\app\doublecmd"
    DC_Name := "DoubleCommander"

    vim.SetWin(DC_Name, "DClass", "doublecmd.exe")
    vim.Mode("normal", DC_Name)

    vim.Map("h", "<left>", DC_Name)
    vim.Map("j", "<down>", DC_Name)
    vim.Map("k", "<up>", DC_Name)
    vim.Map("l", "<enter>", DC_Name)
    vim.Map("gg", "<home>", DC_Name)
    vim.Map("G", "<end>", DC_Name)
    vim.Map("o", "<DC_ContextMenu>", DC_Name)
    vim.Map("<la-r>", "<DC_Rename>", DC_Name)
    vim.Map("<f1>", "<DC_Test>", DC_Name)
    vim.Map("<f2>", "<DC_RenameFull>", DC_Name)
    vim.Map("<f5>", "<DC_Restart>", DC_Name)
    vim.Map("<c-f>", "<pgdn>", DC_Name)
    vim.Map("<c-b>", "<pgup>", DC_Name)
    vim.Map("zz", "<DC_Toggle_50_100>", DC_Name)
    vim.Map("zi", "<DC_Show_100_0>", DC_Name)
    vim.Map("zo", "<DC_Show_0_100>", DC_Name)
    vim.Map("zv", "<DC_HorizontalFilePanels>", DC_Name)
    vim.Map("<S-K>", "<DC_PreviousParallelDir>", DC_Name)
    vim.Map("<S-J>", "<DC_NextParallelDir>", DC_Name)
    vim.Map("<c-k>", "<DC_UpSelect>", DC_Name)
    vim.Map("<c-j>", "<DC_DownSelect>", DC_Name)
    vim.Map("i", "<DC_CreateNewFile>", DC_Name)
    vim.Map("sn", "<DC_SortByName>", DC_Name)
    vim.Map("se", "<DC_SortByExt>", DC_Name)
    vim.Map("ss", "<DC_SortBySize>", DC_Name)
    vim.Map("sd", "<DC_SortByDate>", DC_Name)
    vim.Map("sa", "<DC_SortByAttr>", DC_Name)
    vim.Map("sr", "<DC_ReverseOrder>", DC_Name)
    vim.Map("s1", "<DC_SortByName>", DC_Name)
    vim.Map("s2", "<DC_SortByExt>", DC_Name)
    vim.Map("s3", "<DC_SortBySize>", DC_Name)
    vim.Map("s4", "<DC_SortByDate>", DC_Name)
    vim.Map(".", "<DC_OpenExplorer>", DC_Name)
    vim.Map("""", "<DC_MarkFile>", DC_Name)
    vim.Map("_", "<DC_UnMarkFile>", DC_Name)
    vim.Map("Vm", "<DC_ShowMainMenu>", DC_Name)
    vim.Map("Vb", "<DC_ShowButtonMenu>", DC_Name)
    vim.Map("Vv", "<DC_OperationsViewer>", DC_Name)
    vim.Map("Va", "<DC_BriefView>", DC_Name)
    vim.Map("V1", "<DC_ColumnsView1>", DC_Name)
    vim.Map("V2", "<DC_ColumnsView2>", DC_Name)

    vim.BeforeActionDo("DC_ForceInsertMode", DC_Name)
return

DC_ForceInsertMode() {
    ControlGetFocus, ctrl
    if (InStr(ctrl, "Edit") == 1) {
        return true
    }

    WinGet, MenuID, ID, AHK_CLASS #32768
    if (MenuID != "") {
        return true
    }

    return false
}

DC_Run(cmd) {
    ControlSetText, Edit1, % cmd, % DC
    ControlSend, Edit1, {enter}, % DC
}

; 返回值 [1]: left/right [2]: 左侧面板所占比例 0-100
DC_GetPanelInfo() {
    ClipSaved := ClipboardAll
    Clipboard := ""
    DC_run("cm_CopyPanelInfoToClip")
    ClipWait, 2

    PanelInfo := StrSplit(Clipboard, " ")
    Clipboard := ClipSaved

    return PanelInfo
}

DC_ExecuteToolbarItem(Id) {
    DC_Run("cm_ExecuteToolbarItem ToolItemID=" . Id)
}

DC_ColumnsView(columnset) {
    if (columnset == "") {
        DC_Run("cm_ColumnsView")
    } else {
        DC_Run("cm_ColumnsView columnset=" columnset)
    }
}

<DC_ContextMenu>:
    Send, {appskey}
return

<DC_Rename>:
    Send, {f2}{right}
return

<DC_RenameFull>:
    Send, {f2}^a
return

<DC_Test>:
    ; DC_ExecuteToolbarItem("{700FF494-B939-48A3-B248-8823EB366AEA}")
    DC_Run("cm_About")
return

<DC_Restart>:
    WinClose, % DC
    WinWaitClose, % DC, , 2

    Run, % DC_Dir . "\doublecmd.exe"

    WinWaitActive, % DC

    if (!WinExist(DC)) {
        MsgBox, 重启失败 %ErrorMessage%
    }
return

<DC_Show_50_50>:
    DC_Run("cm_PanelsSplitterPerPos splitpct=50")
return

<DC_Show_100_0>:
    DC_Run("cm_PanelsSplitterPerPos splitpct=100")
return

<DC_Show_0_100>:
    DC_Run("cm_PanelsSplitterPerPos splitpct=0")
return

<DC_HorizontalFilePanels>:
    DC_Run("cm_HorizontalFilePanels mode=legacy")
return

<DC_Toggle_50_100>:
    PanelInfo := DC_GetPanelInfo()

    if (abs(50 - PanelInfo[2]) < 10) {
        if (PanelInfo[1] == "left") {
            DC_Run("cm_PanelsSplitterPerPos splitpct=100")
        } else {
            DC_Run("cm_PanelsSplitterPerPos splitpct=0")
        }
    } else {
        DC_Run("cm_PanelsSplitterPerPos splitpct=50")
    }
return

<DC_MakeDir>:
    DC_Run("cm_MakeDir")
return

<DC_PreviousParallelDir>:
; TODO
/*
    ClipSaved := ClipboardAll
    Clipboard := ""
    DC_Run("cm_CopyCurrentPathToClip")
    ClipWait

    OldPwd := Clipboard

    if (StrLen(OldPwd) == 3) {
        ; 在根分区
        ; Gosub, <cm_GotoPreviousDrive>

        Clipboard := ClipSaved
        ClipSaved := ""

        return
    }
    ; DC_Run("cm_ChangeDirToParent")
*/

    Send, {left}
    Sleep, 10
    Send, {up}
    Sleep, 10
    Send, {right}

/*
    if (InStr(OldPwd, "wfx") == 1) {
        ; 网络文件系统比较慢，等待下
        Sleep, 50
    }

    Clipboard := ClipSaved
    ClipSaved := ""
*/
return

<DC_NextParallelDir>:
; TODO
    Send, {left}
    Sleep, 10
    Send, {down}
    Sleep, 10
    Send, {right}
return

<DC_DownSelect>:
    Send +{Down}
return

<DC_UpSelect>:
    Send +{Up}
return

<DC_CreateNewFile>:
    ControlGetFocus, TLB, % DC
    ControlGetPos, xn, yn, , , % TLB, % DC

    Menu, NewFileMenu, Add
    Menu, NewFileMenu, DeleteAll
/*
   TODO
    Menu, NewFileMenu, Add , S >> 快捷方式, <cm_CreateShortcut>
    Menu, NewFileMenu, Icon, S >> 快捷方式, %A_WinDir%\system32\Shell32.dll, 264
    Menu, NewFileMenu, Add
*/

    Loop, % DC_Dir . "\ShellNew\*.*" {
        ft := SubStr(A_LoopFileName, 1, 1) . " >> " . A_LoopFileName
        Menu, NewFileMenu, Add, % ft, DC_NewFileMenuAction
        Menu, NewFileMenu, Icon, % ft, %A_WinDir%\system32\Shell32.dll
    }

    Menu, NewFileMenu, Show, % xn, % yn + 2
return

DC_NewFileMenuAction:
    Filename := RegExReplace(A_ThisMenuItem, ".\s>>\s")
    FilePath := DC_Dir . "\ShellNew\" . Filename

    Gui, Destroy
    Gui, Add, Text, x12 y20 w50 h20 +Center, 模板源
    Gui, Add, Edit, x72 y20 w300 h20 Disabled, % FilePath
    Gui, Add, Text, x12 y50 w50 h20 +Center, 新建文件
    Gui, Add, Edit, x72 y50 w300 h20, % Filename
    Gui, Add, Button, x162 y80 w90 h30 gDC_NewFileOk default, 确认(&S)
    Gui, Add, Button, x282 y80 w90 h30 gDC_NewFileClose , 取消(&C)
    Gui, Show, w400 h120, 新建文件
return

DC_NewFileClose:
    Gui, Destroy
return

DC_NewFileOK:
    GuiControlGet, SrcFilePath, , Edit1
    GuiControlGet, NewFilename, , Edit2

    ClipSaved := ClipboardAll
    Clipboard :=
    DC_Run("cm_CopyCurrentPathToClip")
    ClipWait, 2
    DstPath := Clipboard
    Clipboard := ClipSaved
    ClipSaved := ""

    if (InStr(DstPath, "`r")) {
        DstPath := SubStr(DstPath, 1, InStr(DstPath, "`r") - 1)
    } else if (DstPath == "") {
        return
    }

    NewFilePath := DstPath . NewFilename
    if (FileExist(NewFilePath)) {
        MsgBox, 4, 新建文件, 新建文件已存在，是否覆盖？
        IfMsgBox No
            return
    }

    FileCopy, % SrcFilePath, % NewFilePath, 1

    ; TODO
    ; 好像无法实现定位到新创建的文件

    Gui, Destroy
return

<DC_Toggle>:
    if (WinExist(DC)) {
        WinGet, Ac, MinMax, % DC
        if (Ac == -1) {
            WinActivate, % DC
        } else {
            if (!WinActive(DC)) {
                WinActivate, % DC
            } else {
                WinMinimize, % DC
            }
        }
    } else {
        Run, % DC_Dir . "\doublecmd.exe"
        WinWait, % DC

        if (!WinActive(DC)) {
            WinActivate, % DC
        }
    }
return

<DC_SortByName>:
    DC_Run("cm_SortByName")
return

<DC_SortByExt>:
    DC_Run("cm_SortByExt")
return

<DC_SortBySize>:
    DC_Run("cm_SortBySize")
return

<DC_SortByDate>:
    DC_Run("cm_SortByDate")
return

<DC_SortByAttr>:
    DC_Run("cm_SortByAttr")
return

<DC_ReverseOrder>:
    DC_Run("cm_ReverseOrder")
return

<DC_FocusSwap>:
    DC_Run("cm_FocusSwap")
    ; side=left/right
return

<DC_CopyCurrentPathToClip>:
    DC_Run("cm_CopyCurrentPathToClip")
return

<DC_OpenExplorer>:
    DC_Run(".")
return

<DC_MarkFile>:
    DC_Run("cm_EditComment")
    ; 不要在已有备注的文件使用
    Send, ^+{end}🖥{f2}
return

<DC_UnMarkFile>:
    DC_Run("cm_EditComment")
    ; 删除 DC_MarkFile 的文件标记，也可用于清空文件备注
    Send, ^+{end}{del}{f2}
return

<DC_ShowMainMenu>:
    DC_Run("cm_ShowMainMenu")
return

<DC_ShowButtonMenu>:
    DC_Run("cm_ShowButtonMenu")
return

<DC_OperationsViewer>:
    DC_Run("cm_OperationsViewer")
return

<DC_TreeView>:
    DC_Run("cm_TreeView")
return

<DC_FocusTreeView>:
    DC_Run("cm_FocusTreeView")
return

<DC_BriefView>:
    DC_Run("cm_BriefView")
return

<DC_ColumnsView1>:
    DC_ColumnsView("mine")
return

<DC_ColumnsView2>:
    DC_ColumnsView("test")
return


[word] Cycle through markup

[word] Cycle through markup

; Autohotkey configuration file
; AHK Version v.1.1.32.00
; Franklin Chou (franklin.chou@nelsonmullins.com)
; 22 Mar. 2020
; Tested to work on Lenovo X1 Yoga, Gen. 4

#SingleInstance Force
#Persistent

GLOBAL_DEBUG_MODE := 0
Return

CapsLock::Ctrl
LCtrl::Return
;LCtrl::CapsLock

; DEBUG TOOLS -----------------------------------------------------------------

#c::
  If(GLOBAL_DEBUG_MODE > 0) {
    ; WinGetTitle, title, A
    WinGetClass, title, A
    MsgBox %title%
  }
Return

f12::
  If(GLOBAL_DEBUG_MODE > 0) {
    Reload
  }
Return

#'::
  If(GLOBAL_DEBUG_MODE > 0) {
    WinGet windows, List
    Loop %windows% {
      id := windows%A_Index%
      WinGetTitle wt, ahk_id %id%
      r .= wt . "`n"
    }
    MsgBox %r%
  }
Return

; TIMEKEEPER ------------------------------------------------------------------

; Shift focus to the timekeeper app
#!e::
  timekeeper_app := WinExist("ahk_class WindowsForms10.Window.8.app.0.262fb3d")
  ;MsgBox %timekeeper_app%
  If(timekeeper_app > 0) {
    WinActivate, ahk_id %timekeeper_app%
  } Else {
    Run, DTE.exe, C:\Program Files (x86)\DTEAxiom
  }
Return

; Start the timer on the selected item in the daily view
#IfWinActive ahk_class WindowsForms10.Window.8.app.0.262fb3d
  >+s::
    WinGetActiveTitle, active_title
    match_result := RegExMatch(active_title, "^Entries for")
    ; each item in the dropdown is approximately 25 pixels
    ; so item 4 (Start Timer) is 100 pixels down from the context menu
    drop_down := 100
    If(match_result > 0) {
      WinMove, 100, 100
      MouseMove, 100, 280
      Send {RButton}
      Sleep, 10 ; need to sleep to allow submenu time to come up
      MouseMove, 170, 300 + drop_down
      Send {LButton}
    }
Return

; WORD/OUTLOOK ----------------------------------------------------------------
#If WinActive("ahk_class OpusApp") || WinActive("ahk_class rctrl_renwnd32")
  PrintScreen::AppsKey
Return

; WORD ONLY -------------------------------------------------------------------
#If WinActive("ahk_class OpusApp")
  >+M::  ; Cycle through types of markup
    Send !r
    Sleep, 10
    Send td
    Send {Down}
    Send {Enter}
Return


RunZ: fix ;cmd and :cmd

RunZ: fix ;cmd and :cmd

#NoEnv
#SingleInstance, Force
#NoTrayIcon

FileEncoding, utf-8
SendMode Input

; 自动生成的命令文件
global g_CommandsFile := A_ScriptDir . "\Commands.txt"
global g_ConfFile := A_ScriptDir . "\RunZ.ini"
; 配置文件
global g_Conf := class_EasyINI(g_ConfFile)

; 从配置文件读取
global g_SearchFileDir = g_Conf.config.SearchFileDir
global g_SearchFileType = g_Conf.config.SearchFileType

; 所有命令
global g_Commands
; 当搜索无结果时使用的命令
global g_FallbackCommands
; 编辑框当前内容
global g_CurrentInput
; 当前匹配到的第一条命令
global g_CurrentCommand
; 当前匹配到的所有命令
global g_CurrentCommandList
; 是否启用 TCMatch
global g_EnableTCMatch = TCMatchOn(g_Conf.config.TCMatchPath)
; 列表排序的第一个字符
global g_FirstChar := Asc("a")
; 当前输入命令的参数，数组，为了方便没有添加 g_ 前缀
global Arg

if (FileExist(g_CommandsFile))
{
    LoadCommands()
}
else
{
    GoSub, ReloadCommand
}

Gui, Main:Font, s12
Gui, Main:Add, Edit, gProcessInputCommand vSearchArea w600 h25,
Gui, Main:Add, Edit, w600 h250 ReadOnly vDisplayArea, % SearchCommand("", true)
if (g_Conf.config.ShowCurrentCommand)
{
    Gui, Main:Add, Edit, w600 h25 ReadOnly,
}
Gui, Main:Show, , RunZ
;WinSet, Style, -0xC00000, A

Hotkey, IfWinActive, RunZ
HotKey, enter, RunCurrentCommand
HotKey, ^j, ClearInput
HotKey, f1, Help
HotKey, f2, EditConfig

bindKeys := "abcdefghijklmno"
Loop, Parse, bindKeys
{
    ; lalt
    HotKey, <!%A_LoopField%, RunSelectedCommand1
    HotKey, ~%A_LoopField%, RunSelectedCommand2
    HotKey, ~+%A_LoopField%, AddCustomCommand
}

if (g_Conf.config.SaveInputText && g_Conf.auto.InputText != "")
{
    Send, % g_Conf.auto.InputText
}

return

Esc::
    if (g_Conf.config.SaveInputText)
    {
        g_Conf.DeleteKey("auto", "InputText")
        g_Conf.AddKey("auto", "InputText", g_CurrentInput)
        g_Conf.Save()
    }
    ExitApp
return

GenerateCommandList()
{
    FileDelete, %g_CommandsFile%

    for dirIndex, dir in StrSplit(g_SearchFileDir, " | ")
    {
        if (InStr(dir, "A_") == 1)
        {
            searchPath := %dir%
        }
        else
        {
            searchPath := dir
        }

        for extIndex, ext in StrSplit(g_SearchFileType, " | ")
        {
            Loop, Files, %searchPath%\%ext%, R
            {
                if (g_Conf.config.SearchFileExclude != ""
                        && RegexMatch(A_LoopFileLongPath, g_Conf.config.SearchFileExclude))
                {
                    continue
                }
                FileAppend, file | %A_LoopFileLongPath%`n, %g_CommandsFile%,
            }
        }
    }
}

ProcessInputCommand:
    GuiControlGet, g_CurrentInput, , SearchArea
    SearchCommand(g_CurrentInput)
return

SearchCommand(command = "", firstRun = false)
{
    result := ""
    commandPrefix := SubStr(command, 1, 1)

    if (commandPrefix ==  ";" || commandPrefix == ":")
    {
        if (commandPrefix == ";")
        {
            g_CurrentCommand := g_FallbackCommands[1]
        }
        else if (commandPrefix == ":")
        {
            g_CurrentCommand := g_FallbackCommands[2]
        }

        g_CurrentCommandList.Insert(g_CurrentCommand)
        result .= "a | " . g_CurrentCommand
        Arg := SubStr(g_CurrentInput, 2)
        DisplayResult(result)
        return result
    }
    ; 用空格来判断参数
    else if (InStr(command, " ") && g_CurrentCommand != "")
    {
        Arg := SubStr(command, InStr(command, " ") + 1)
        return
    }

    g_CurrentCommandList := Object()

    order := g_FirstChar

    for index, element in g_Commands
    {
        currentCommand := StrSplit(element, " | ")[2]

        if (InStr(element, "file | ", true, 1))
        {
            ; 只搜不带扩展名的文件名
            SplitPath, currentCommand, , , , currentCommand
            elementToShow := SubStr("file | " . currentCommand, 1, 68)
        }
        else
        {
            elementToShow := SubStr(element, 1, 68)
        }

        if (MatchCommand(currentCommand, command))
        {
            g_CurrentCommandList.Insert(element)

            if (order == g_FirstChar)
            {
                g_CurrentCommand := element
            }
            else
            {
                result .= "`n"
            }

            result .= Chr(order++) . " | " . elementToShow

            if (order - g_FirstChar >= 15)
            {
                break
            }

            ; 第一次运行只加载 function 类型
            if (firstRun && (order - g_FirstChar >= 11))
            {
                result .= "`n`n现有 " g_Commands.Length() " 条命令。"
                result .= "`n`n键入内容 搜索，回车 执行第一条，Alt + 字母 执行，F1 帮助，Esc 退出。"

                break
            }
        }
    }

    if (result == "")
    {
        g_CurrentCommand := g_FallbackCommands[1]
        g_CurrentCommandList := g_FallbackCommands
        Arg := g_CurrentInput

        for index, element in g_FallbackCommands
        {
            if (index != 1)
            {
                result .= "`n"
            }

            result .= Chr(g_FirstChar - 1 + index++) . " | " . element
        }
    }

    DisplayResult(result)
    return result
}

DisplayResult(result)
{
    DisplayText(result)

    if (g_CurrentCommandList.Length() == 1 && g_Conf.config.RunIfOnlyOne)
    {
        GoSub, RunCurrentCommand
    }

    if (g_Conf.config.ShowCurrentCommand)
    {
        ControlSetText, Edit3, %g_CurrentCommand%
    }
}

ClearInput:
    ControlSetText, Edit1,
return

RunCurrentCommand:
    RunCommand(g_CurrentCommand)
return

MatchCommand(Haystack, Needle)
{
    if (g_EnableTCMatch)
    {
        return TCMatch(Haystack, Needle)
    }

    return InStr(Haystack, Needle)
}

RunCommand(command)
{
    command := StrSplit(command, "（")[1]

    if (RegexMatch(command, "^(file|url)"))
    {
        cmd := StrSplit(command, " | ")[2]
        Run, %cmd%
    }
    else if (InStr(command, "function | ", true, 1))
    {
        cmd := StrSplit(command, " | ")[2]
        if (IsLabel(cmd))
        {
            GoSub, %cmd%
        }
    }
}

RunSelectedCommand1:
    index := Asc(SubStr(A_ThisHotkey, 3, 1)) - Asc("a") + 1

    RunCommand(g_CurrentCommandList[index])
return

RunSelectedCommand2:
    ControlGetFocus, ctrl,
    if (ctrl == "Edit1")
    {
        return
    }

    index := Asc(SubStr(A_ThisHotkey, 2, 1)) - Asc("a") + 1

    RunCommand(g_CurrentCommandList[index])
return

AddCustomCommand:
    ControlGetFocus, ctrl,
    if (ctrl == "Edit1")
    {
        return
    }

    index := Asc(SubStr(A_ThisHotkey, 3, 1)) - Asc("a") + 1

    if (g_CurrentCommandList[index] != "")
    {
        g_Conf.AddKey("command", g_CurrentCommandList[index], g_CurrentInput)

        g_Conf.Save()

        LoadCommands()
    }
return

LoadCommands()
{
    g_Commands := Object()
    g_FallbackCommands := Object()

    for key, value in g_Conf.command
    {
        if (value != "")
        {
            g_Commands.Insert(key . "（" . value "）")
        }
        else
        {
            g_Commands.Insert(key)
        }
    }

    @("AhkRun", "使用 Ahk 的 Run 运行 `; cmd", true)
    @("CmdRun", "使用 cmd 运行 : cmd", true)
    @("ReloadCommand", "重新搜索文件")
    @("Clip", "显示剪切板内容")
    @("EditConfig", "编辑配置文件")
    @("Help", "帮助信息")
    @("ArgTest", "参数测试：ArgTest arg1,arg2,...")

    GoSub, UserCmd

    Loop, Read, %g_CommandsFile%
    {
        g_Commands.Insert(A_LoopReadLine)
    }
}

DisplayText(text)
{
    textToDisplay := StrReplace(text, "`n", "`r`n")
    ControlSetText, Edit2, %textToDisplay%
}

ArgTest:
    Args := StrSplit(Arg, ",")
    result := "共有 " . Args.Length() . " 个参数。`n`n"

    for index, argument in Args
    {
        result .= "第 " . index - 1 " 个参数：" . argument . "`n"
    }

    DisplayText(result)
return

ReloadCommand:
    GenerateCommandList()

    LoadCommands()
return

Help:
    helpText := "帮助：`n`n"
        . "键入内容 搜索，回车 执行（a），Alt + 字母 执行，F1 帮助，Esc 退出`n"
        . "Tab + 字母 也可执行字母对应功能`n"
        . "Tab + 大写字母 可将字母对应功能加入到配置文件，以便优先显示`n"
        . "Ctrl + j 清除编辑框内容`n"
        . "F2 编辑配置文件`n`n"
        . "可直接输入网址，如 www.baidu.com`n"
        . "分号开头则使用 ahk 的 Run 运行命令，如 `;ping www.baidu.com`n"
        . "冒号开头则在 cmd 运行命令，如 :ping www.baidu.com`n"
        . "当搜索无结果时，回车 也等同 run 输入内容`n"
        . "当输入内容包含空格时，列表锁定，逗号作为命令参数的分隔符`n"

    DisplayText(helpText)
return

EditConfig:
    Run, % g_ConfFile
return

Clip:
    DisplayText("剪切板内容长度 " . StrLen(clipboard) . " ：`n`n" . clipboard)
return

CmdRun:
    RunWithCmd(Arg)
return

AhkRun:
    Run, %Arg%
return

; AddAction(label, info, fallback)
@(label, info, fallback = false)
{
    g_Commands.Insert("function | " . label . "（" . info . "）")
    if (fallback)
    {
        g_FallbackCommands.Insert("function | " . label . "（" . info . "）")
    }
}

RunAndGetOutput(command)
{
    tempFileName := "RunZ.stdout.log"
    fullCommand = bash -c "%command% &> %tempFileName%"

    if (!FileExist("c:\msys64\usr\bin\bash.exe"))
    {
        fullCommand = %ComSpec% /C "%command% > %tempFileName%"
    }

    RunWait, %fullCommand%, %A_Temp%, Hide
    FileRead, result, %A_Temp%\%tempFileName%
    FileDelete, %A_Temp%\%tempFileName%
    return result
}

RunWithCmd(command)
{
    if (FileExist("c:\msys64\usr\bin\mintty.exe"))
    {
        Run, % "mintty -e sh -c '" command "; read'"
    }
    else
    {
        Run, % ComSpec " /C " command
    }
}

#include %A_ScriptDir%\..\lib\class_EasyIni.ahk
#include %A_ScriptDir%\lib\Kanji\Kanji.ahk
#include %A_ScriptDir%\lib\TCMatch.ahk
#include %A_ScriptDir%\lib\Eval.ahk
#include %A_ScriptDir%\Commands.ahk

#NoEnv
#SingleInstance, Force
#NoTrayIcon

FileEncoding, utf-8
SendMode Input

; 自动生成的命令文件
global g_CommandsFile := A_ScriptDir . "\Commands.txt"
global g_ConfFile := A_ScriptDir . "\RunZ.ini"
; 配置文件
global g_Conf := class_EasyINI(g_ConfFile)

; 从配置文件读取
global g_SearchFileDir = g_Conf.config.SearchFileDir
global g_SearchFileType = g_Conf.config.SearchFileType

; 所有命令
global g_Commands
; 当搜索无结果时使用的命令
global g_FallbackCommands
; 编辑框当前内容
global g_CurrentInput
; 当前匹配到的第一条命令
global g_CurrentCommand
; 当前匹配到的所有命令
global g_CurrentCommandList
; 是否启用 TCMatch
global g_EnableTCMatch = TCMatchOn(g_Conf.config.TCMatchPath)
; 列表排序的第一个字符
global g_FirstChar := Asc("a")
; 当前输入命令的参数，数组，为了方便没有添加 g_ 前缀
global Arg

if (FileExist(g_CommandsFile))
{
    LoadCommands()
}
else
{
    GoSub, ReloadCommand
}

Gui, Main:Font, s12
Gui, Main:Add, Edit, gProcessInputCommand vSearchArea w600 h25,
Gui, Main:Add, Edit, w600 h250 ReadOnly vDisplayArea, % SearchCommand("", true)
if (g_Conf.config.ShowCurrentCommand)
{
    Gui, Main:Add, Edit, w600 h25 ReadOnly,
}
Gui, Main:Show, , RunZ
;WinSet, Style, -0xC00000, A

Hotkey, IfWinActive, RunZ
HotKey, enter, RunCurrentCommand
HotKey, ^j, ClearInput
HotKey, f1, Help
HotKey, f2, EditConfig

bindKeys := "abcdefghijklmno"
Loop, Parse, bindKeys
{
    ; lalt
    HotKey, <!%A_LoopField%, RunSelectedCommand1
    HotKey, ~%A_LoopField%, RunSelectedCommand2
    HotKey, ~+%A_LoopField%, AddCustomCommand
}

if (g_Conf.config.SaveInputText && g_Conf.auto.InputText != "")
{
    Send, % g_Conf.auto.InputText
}

return

Esc::
    if (g_Conf.config.SaveInputText)
    {
        g_Conf.DeleteKey("auto", "InputText")
        g_Conf.AddKey("auto", "InputText", g_CurrentInput)
        g_Conf.Save()
    }
    ExitApp
return

GenerateCommandList()
{
    FileDelete, %g_CommandsFile%

    for dirIndex, dir in StrSplit(g_SearchFileDir, " | ")
    {
        if (InStr(dir, "A_") == 1)
        {
            searchPath := %dir%
        }
        else
        {
            searchPath := dir
        }

        for extIndex, ext in StrSplit(g_SearchFileType, " | ")
        {
            Loop, Files, %searchPath%\%ext%, R
            {
                if (g_Conf.config.SearchFileExclude != ""
                        && RegexMatch(A_LoopFileLongPath, g_Conf.config.SearchFileExclude))
                {
                    continue
                }
                FileAppend, file | %A_LoopFileLongPath%`n, %g_CommandsFile%,
            }
        }
    }
}

ProcessInputCommand:
    GuiControlGet, g_CurrentInput, , SearchArea
    SearchCommand(g_CurrentInput)
return

SearchCommand(command = "", firstRun = false)
{
    ; 用空格来判断参数
    if (InStr(command, " ") && g_CurrentCommand != "")
    {
        Arg := SubStr(command, InStr(command, " ") + 1)
        return
    }

    result := ""
    order := g_FirstChar

    g_CurrentCommandList := Object()

    for index, element in g_Commands
    {
        currentCommand := StrSplit(element, " | ")[2]

        if (InStr(element, "file | ", true, 1))
        {
            ; 只搜不带扩展名的文件名
            SplitPath, currentCommand, , , , currentCommand
            elementToShow := SubStr("file | " . currentCommand, 1, 68)
        }
        else
        {
            elementToShow := SubStr(element, 1, 68)
        }

        if (MatchCommand(currentCommand, command))
        {
            g_CurrentCommandList.Insert(element)

            if (order == g_FirstChar)
            {
                g_CurrentCommand := element
            }
            else
            {
                result .= "`n"
            }

            result .= Chr(order++) . " | " . elementToShow

            if (order - g_FirstChar >= 15)
            {
                break
            }

            ; 第一次运行只加载 function 类型
            if (firstRun && (order - g_FirstChar >= 11))
            {
                result .= "`n`n现有 " g_Commands.Length() " 条命令。"
                result .= "`n`n键入内容 搜索，回车 执行第一条，Alt + 字母 执行，F1 帮助，Esc 退出。"

                break
            }
        }
    }

    if (result == "")
    {
        if (SubStr(command, 1, 1) == ";")
        {
            g_CurrentCommand := g_FallbackCommands[1]
            g_CurrentCommandList.Insert(g_CurrentCommand)
            result .= "a | " . g_CurrentCommand
            Arg := SubStr(g_CurrentInput, 2)
        }
        else if (SubStr(command, 1, 1) == ":")
        {
            g_CurrentCommand := g_FallbackCommands[2]
            g_CurrentCommandList.Insert(g_CurrentCommand)
            result .= "a | " . g_CurrentCommand
            Arg := SubStr(g_CurrentInput, 2)
        }
        else
        {
            g_CurrentCommand := g_FallbackCommands[1]
            g_CurrentCommandList := g_FallbackCommands
            Arg := g_CurrentInput

            for index, element in g_FallbackCommands
            {
                if (index != 1)
                {
                    result .= "`n"
                }

                result .= Chr(g_FirstChar - 1 + index++) . " | " . element
            }
        }
    }

    DisplayText(result)

    if (order - g_FirstChar == 1 && g_Conf.config.RunIfOnlyOne)
    {
        GoSub, RunCurrentCommand
    }

    if (g_Conf.config.ShowCurrentCommand)
    {
        ControlSetText, Edit3, %g_CurrentCommand%
    }

    return result
}

ClearInput:
    ControlSetText, Edit1,
return

RunCurrentCommand:
    RunCommand(g_CurrentCommand)
return

MatchCommand(Haystack, Needle)
{
    if (g_EnableTCMatch)
    {
        return TCMatch(Haystack, Needle)
    }

    return InStr(Haystack, Needle)
}

RunCommand(command)
{
    command := StrSplit(command, "（")[1]

    if (RegexMatch(command, "^(file|url)"))
    {
        cmd := StrSplit(command, " | ")[2]
        Run, %cmd%
    }
    else if (InStr(command, "function | ", true, 1))
    {
        cmd := StrSplit(command, " | ")[2]
        if (IsLabel(cmd))
        {
            GoSub, %cmd%
        }
    }
}

RunSelectedCommand1:
    index := Asc(SubStr(A_ThisHotkey, 3, 1)) - Asc("a") + 1

    RunCommand(g_CurrentCommandList[index])
return

RunSelectedCommand2:
    ControlGetFocus, ctrl,
    if (ctrl == "Edit1")
    {
        return
    }

    index := Asc(SubStr(A_ThisHotkey, 2, 1)) - Asc("a") + 1

    RunCommand(g_CurrentCommandList[index])
return

AddCustomCommand:
    ControlGetFocus, ctrl,
    if (ctrl == "Edit1")
    {
        return
    }

    index := Asc(SubStr(A_ThisHotkey, 3, 1)) - Asc("a") + 1

    if (g_CurrentCommandList[index] != "")
    {
        g_Conf.AddKey("command", g_CurrentCommandList[index], g_CurrentInput)

        g_Conf.Save()

        LoadCommands()
    }
return

LoadCommands()
{
    g_Commands := Object()
    g_FallbackCommands := Object()

    for key, value in g_Conf.command
    {
        if (value != "")
        {
            g_Commands.Insert(key . "（" . value "）")
        }
        else
        {
            g_Commands.Insert(key)
        }
    }

    @("AhkRun", "使用 Ahk 的 Run 运行 `; cmd", true)
    @("CmdRun", "使用 cmd 运行 : cmd", true)
    @("ReloadCommand", "重新搜索文件")
    @("Clip", "显示剪切板内容")
    @("EditConfig", "编辑配置文件")
    @("Help", "帮助信息")
    @("ArgTest", "参数测试：ArgTest arg1,arg2,...")

    GoSub, UserCmd

    Loop, Read, %g_CommandsFile%
    {
        g_Commands.Insert(A_LoopReadLine)
    }
}

DisplayText(text)
{
    textToDisplay := StrReplace(text, "`n", "`r`n")
    ControlSetText, Edit2, %textToDisplay%
}

ArgTest:
    Args := StrSplit(Arg, ",")
    result := "共有 " . Args.Length() . " 个参数。`n`n"

    for index, argument in Args
    {
        result .= "第 " . index - 1 " 个参数：" . argument . "`n"
    }

    DisplayText(result)
return

ReloadCommand:
    GenerateCommandList()

    LoadCommands()
return

Help:
    helpText := "帮助：`n`n"
        . "键入内容 搜索，回车 执行（a），Alt + 字母 执行，F1 帮助，Esc 退出`n"
        . "Tab + 字母 也可执行字母对应功能`n"
        . "Tab + 大写字母 可将字母对应功能加入到配置文件，以便优先显示`n"
        . "Ctrl + j 清除编辑框内容`n"
        . "F2 编辑配置文件`n`n"
        . "可直接输入网址，如 www.baidu.com`n"
        . "分号开头则使用 ahk 的 Run 运行命令，如 `;ping www.baidu.com`n"
        . "冒号开头则在 cmd 运行命令，如 :ping www.baidu.com`n"
        . "当搜索无结果时，回车 也等同 run 输入内容`n"
        . "当输入内容包含空格时，列表锁定，逗号作为命令参数的分隔符`n"

    DisplayText(helpText)
return

EditConfig:
    Run, % g_ConfFile
return

Clip:
    DisplayText("剪切板内容长度 " . StrLen(clipboard) . " ：`n`n" . clipboard)
return

CmdRun:
    RunWithCmd(Arg)
return

AhkRun:
    Run, %Arg%
return

; AddAction(label, info, fallback)
@(label, info, fallback = false)
{
    g_Commands.Insert("function | " . label . "（" . info . "）")
    if (fallback)
    {
        g_FallbackCommands.Insert("function | " . label . "（" . info . "）")
    }
}

RunAndGetOutput(command)
{
    tempFileName := "RunZ.stdout.log"
    fullCommand = bash -c "%command% &> %tempFileName%"

    if (!FileExist("c:\msys64\usr\bin\bash.exe"))
    {
        fullCommand = %ComSpec% /C "%command% > %tempFileName%"
    }

    RunWait, %fullCommand%, %A_Temp%, Hide
    FileRead, result, %A_Temp%\%tempFileName%
    FileDelete, %A_Temp%\%tempFileName%
    return result
}

RunWithCmd(command)
{
    if (FileExist("c:\msys64\usr\bin\mintty.exe"))
    {
        Run, % "mintty -e sh -c '" command "; read'"
    }
    else
    {
        Run, % ComSpec " /C " command
    }
}

#include %A_ScriptDir%\..\lib\class_EasyIni.ahk
#include %A_ScriptDir%\lib\Kanji\Kanji.ahk
#include %A_ScriptDir%\lib\TCMatch.ahk
#include %A_ScriptDir%\lib\Eval.ahk
#include %A_ScriptDir%\Commands.ahk


get all windows matching a process by id

; Autohotkey configuration file
; AHK Version v.1.1.32.00
; Franklin Chou (franklin.chou@nelsonmullins.com)
; 22 Mar. 2020
; Tested to work on Lenovo X1 Yoga, Gen. 4

#SingleInstance Force
#Persistent

GLOBAL_DEBUG_MODE := 1
Return

CapsLock::Ctrl
LCtrl::Return
;LCtrl::CapsLock

; DEBUG TOOLS -----------------------------------------------------------------

#c::
  If(GLOBAL_DEBUG_MODE > 0) {
    ; WinGetTitle, title, A
    WinGetClass, title, A
    MsgBox %title%
  }
Return

f12::
  If(GLOBAL_DEBUG_MODE > 0) {
    Reload
  }
Return

; SYSTEM ----------------------------------------------------------------------

; Current window
; Current windows in list
; Current list position

; Access different windows of the same group
!`::
  WinGet, process_name, ProcessName, A ; get the active window's process name
  matches := GetWindowsOfProcess(process_name)
  MsgBox % matches.Length()
Return

; Get the window ids of all the processes under that process name
GetWindowsOfProcess(process_name) {
  ids := Array()
  WinGet, window_ids, List ; get the IDs for all the windows running
  Loop %window_ids% {
    id := window_ids%A_Index%
    WinGet, a_process_name, ProcessName, ahk_id %id%
    If (a_process_name = process_name) {
      ; MsgBox %a_process_name%
      ; MsgBox %id%
      ids.Push(id)
    }
  }
  Return, ids
}

; TIMEKEEPER ------------------------------------------------------------------

; Shift focus to the timekeeper app
#!e::
  timekeeper_app := WinExist("ahk_class WindowsForms10.Window.8.app.0.262fb3d")
  ;MsgBox %timekeeper_app%
  If(timekeeper_app > 0) {
    WinActivate, ahk_id %timekeeper_app%
  } Else {
    Run, DTE.exe, C:\Program Files (x86)\DTEAxiom
  }
Return

; Start the timer on the selected item in the daily view
#IfWinActive ahk_class WindowsForms10.Window.8.app.0.262fb3d
  >+s::
    WinGetActiveTitle, active_title
    match_result := RegExMatch(active_title, "^Entries for")
    ; each item in the dropdown is approximately 25 pixels
    ; so item 4 (Start Timer) is 100 pixels down from the context menu
    drop_down := 100
    If(match_result > 0) {
      WinMove, 100, 100
      MouseMove, 100, 280
      Send {RButton}
      Sleep, 10 ; need to sleep to allow submenu time to come up
      MouseMove, 170, 300 + drop_down
      Send {LButton}
    }
Return

; MSOFFICE --------------------------------------------------------------------

; Let the print screen key open the application options key (for spell check)
; Word and Outlook
#If WinActive("ahk_class OpusApp") || WinActive("ahk_class rctrl_renwnd32")
  PrintScreen::AppsKey
Return

; This ridiculous keymapping is care of Lenovo
; which maps F12 to some bloatware keyboard manager utility
#If WinActive("ahk_class OpusApp") || WinActive("ahk_class XLMAIN")
  F12::
    Send {F12}
Return

; WORD ONLY -------------------------------------------------------------------

; Cycle through types of markup
#If WinActive("ahk_class OpusApp")
  >+m::
    Send !r
    Sleep, 10
    Send td
    Send {Down}
    Send {Enter}
Return

; Autohotkey configuration file
; AHK Version v.1.1.32.00
; Franklin Chou (franklin.chou@nelsonmullins.com)
; 22 Mar. 2020
; Tested to work on Lenovo X1 Yoga, Gen. 4

#SingleInstance Force
#Persistent

GLOBAL_DEBUG_MODE := 1
Return

CapsLock::Ctrl
LCtrl::Return
;LCtrl::CapsLock

; DEBUG TOOLS -----------------------------------------------------------------

#c::
  If(GLOBAL_DEBUG_MODE > 0) {
    ; WinGetTitle, title, A
    WinGetClass, title, A
    MsgBox %title%
  }
Return

f12::
  If(GLOBAL_DEBUG_MODE > 0) {
    Reload
  }
Return

; SYSTEM ----------------------------------------------------------------------

; Current window
; Current windows in list
; Current list position

; Access different windows of the same group
!`::

  map := {}

  WinGet, window_id_list, List ; get the IDs for all the windows running
  Loop %window_id_list% {
    id := window_id_list%A_Index%
    WinGetTitle, window_title, ahk_id %id%
    WinGet, process_name, ProcessName, ahk_id %id%
    If (window_title) {
      ; attrs = [window_title, proces_name]
      map[id] := process_name
    }
    attrs := ""
  }
  id := ""
  window_title := ""

  For k, v in map {
    ; MsgBox "%k% -> %v%"
  }
  ; result := ""

  ; WinActivate, ahk_id 70380

Return

; switch to the next window in the group
SwitchWindow(current_window, windows_list, list_index) {
  Return
}

; TIMEKEEPER ------------------------------------------------------------------

; Shift focus to the timekeeper app
#!e::
  timekeeper_app := WinExist("ahk_class WindowsForms10.Window.8.app.0.262fb3d")
  ;MsgBox %timekeeper_app%
  If(timekeeper_app > 0) {
    WinActivate, ahk_id %timekeeper_app%
  } Else {
    Run, DTE.exe, C:\Program Files (x86)\DTEAxiom
  }
Return

; Start the timer on the selected item in the daily view
#IfWinActive ahk_class WindowsForms10.Window.8.app.0.262fb3d
  >+s::
    WinGetActiveTitle, active_title
    match_result := RegExMatch(active_title, "^Entries for")
    ; each item in the dropdown is approximately 25 pixels
    ; so item 4 (Start Timer) is 100 pixels down from the context menu
    drop_down := 100
    If(match_result > 0) {
      WinMove, 100, 100
      MouseMove, 100, 280
      Send {RButton}
      Sleep, 10 ; need to sleep to allow submenu time to come up
      MouseMove, 170, 300 + drop_down
      Send {LButton}
    }
Return

; MSOFFICE --------------------------------------------------------------------

; Let the print screen key open the application options key (for spell check)
; Word and Outlook
#If WinActive("ahk_class OpusApp") || WinActive("ahk_class rctrl_renwnd32")
  PrintScreen::AppsKey
Return

; This ridiculous keymapping is care of Lenovo
; which maps F12 to some bloatware keyboard manager utility
#If WinActive("ahk_class OpusApp") || WinActive("ahk_class XLMAIN")
  F12::
    Send {F12}
Return

; WORD ONLY -------------------------------------------------------------------

; Cycle through types of markup
#If WinActive("ahk_class OpusApp")
  >+m::
    Send !r
    Sleep, 10
    Send td
    Send {Down}
    Send {Enter}
Return


Add shortcuts to send capital accented letters


/*
  @Author : johngrib82@gmail.com
  @Created : 2015. NOV. 19
*/

/*
  Capslock is mode changer in this program
  NORMAL   - Mode like VIM. (Arrow keys and Mouse controls)
  INSERT   - Normal key input mode.
  CAPSLOCK - Normal Capslock mode.
*/
CapsLock::
+Capslock::
  CMD.clear("num")
  if( GetKeyState("Capslock", "T") ){
    SetCapsLockState, Off
  } else {
    SetCapsLockState, On
  }
  if(GetKeyState("shift", "P")){
    CMD.changeMode("caps")
  } else {
    CMD.changeMode("auto")
  }
  Send, {LShift up}
return

/*
  double click 'ESC' key to NORMAL mode
*/
#If GetKeyState("capslock","T") = 0
  $Esc::
      if (A_PriorHotKey = "$Esc" and A_TimeSincePriorHotKey < 500) {
      SetCapsLockState, On
      CMD.changeMode("auto")
    } else {
      #IfWinActive, ahk_class SWT_Window0
        if(IME_CHECK("A"))
          Send, {VK15}    ; input Korean/English switch key
      #If
      SendInput {Esc}
    }
  return
#if

/*
  colon to input command mode
*/
#If GetKeyState("capslock","T")
  $+SC027::  ;  : (colon) command

    SetCapsLockState, Off
    CMD.changeMode("auto")

    Gui +LastFound +OwnDialogs +AlwaysOnTop

    title := "input_command"
    contents := ""
    InputBox, input_sentence, %title%, %contents%, ,300, 110
    AUTO_TEMP := ""
    AUTO_CNT  := 1

    input_sentence := Trim(input_sentence)

    args := StrSplit(input_sentence, " ")
    args[0] := input_sentence

    if(args.Length() < 1){
      return
    }
    func_name := "command_" . args[1]

    if( IsFunc( func_name ) ) {
      %func_name%(args)
    }
    SetCapsLockState, On
    CMD.clear("auto")
  return
#If

/*
  tab to auto complete in inputbox (input_command)
*/
#IfWinActive input_command
  $Tab::
  ControlGetText, txt, Edit1, input_command

  if(AUTO_TEMP = ""){
    AUTO_TEMP := Trim(txt)
    AUTO_CNT  := 1
    AUTO_ARR  := Object()
    reg := "^" . AUTO_TEMP

    arr := CFG.get_sect("INPUT_COMMAND")
    cnt := 0
    Loop % arr.MaxIndex()
    {
      th := arr[a_index]
      if(RegExMatch(th, reg)){
        cnt := cnt + 1
        AUTO_ARR.Insert(th)
      }
    }

    if(cnt > 0){
      result := AUTO_ARR[AUTO_CNT]
      ControlSetText, Edit1, %result%, input_command
      AUTO_CNT := AUTO_CNT + 1
      return
    }
  } else if( A_PriorKey = "Tab" ) {
    reg := "^" . AUTO_TEMP

    if(AUTO_ARR.MaxIndex() < AUTO_CNT){
      AUTO_CNT := 1
    }
    result := AUTO_ARR[AUTO_CNT]
    ControlSetText, Edit1, %result%, input_command
    AUTO_CNT := AUTO_CNT + 1
    return
  } else if( A_PriorKey <> "Tab" ) {
    AUTO_TEMP := ""
    return
  }
  return
#IfWinActive

/*
  number commands : numbers works like VIM
*/
$0::
$1::
$2::
$3::
$4::
$5::
$6::
$7::
$8::
$9::
  StringTrimLeft, num, A_ThisHotkey, StrLen(A_ThisHotkey) - 1

  clear_str := { "m": "func_win_memorize", "'" :  "func_win_mem_activate" }
  if(clear_str.HasKey(CMD.get_cmd())) {
    function := clear_str[CMD.get_cmd()]
    %function%(num)
    CMD.clear("auto")
    return
  }

  CMD.append_num(num)

  if ( CMD.get_num() = "0" ) {
    key_0(CMD.get_num())
    CMD.clear("num")
    return
  }
    show_mode(CMD.get_num())
return

; shift + 4 : END key
$+4:: key_4(CMD.get_num())

$*i::
$*o::
  func_i_o()
return

/*
  commands (joinable with number)
*/
$*g::
$*t::
$*r::
$*b::
$*f::
$*q::
$*e::
$w::
$a::
$s::
$d::
$z::
$x::
$+x::
$c::
$m::
$SC028::  ;  '
  ; get hot_key
  hot_key := A_ThisHotkey

  if(A_ThisHotkey = "$SC028"){
    hot_key := "'"
  } else if(RegExMatch(A_ThisHotkey, "^\W")){
    StringTrimLeft, hot_key, A_ThisHotkey, StrLen(A_ThisHotkey) - 1
  }

  ; join previous command with current command
  CMD.append_cmd(hot_key)
  func_name := "key_" . CMD.get_cmd()
  clear_command := 0

  ; if command and function name matched, call function
  ; commands length should shorter than 3
  if( IsFunc( func_name) ) {
    clear_command := %func_name%(CMD.get_num())
    clear_command = 1
  } else if( 1 < StrLen(CMD.get_cmd())){
    clear_command = 1
  }

  if(clear_command = 1){
    CMD.clear("auto")
    return
  }

  show_mode(CMD.get_num_cmd())
return

/*
  mouse pointer accelator
  n + w a s d
  m + w a s d
  , + w a s d
*/
$SC01A::return  ;  [
$SC01B::return  ;  ]
$SC02B::return  ;  \

/*
  help
*/
$+VKBF::Run, ".\manual.html"

/*
  h j k l moves
  h : left
  j : down
  k : up
  l : right
*/
#If GetKeyState("capslock","T") and StrLen(CMD.get_num()) < 1
    *h:: Left
    *j:: Down
    *k:: Up
    *l:: Right
#If
#If GetKeyState("capslock","T") and StrLen(CMD.get_num()) > 0
    *h:: func_hjkl_move("Left", CMD.get_num())
    *j:: func_hjkl_move("Down", CMD.get_num())
    *k:: func_hjkl_move("Up", CMD.get_num())
    *l:: func_hjkl_move("Right", CMD.get_num())
#If

/*
  @Author : johngrib82@gmail.com
  @Created : 2015. NOV. 19
*/

/*
  Capslock is mode changer in this program
  NORMAL   - Mode like VIM. (Arrow keys and Mouse controls)
  INSERT   - Normal key input mode.
  CAPSLOCK - Normal Capslock mode.
*/
CapsLock::
+Capslock::
  CMD.clear("num")
  if( GetKeyState("Capslock", "T") ){
    SetCapsLockState, Off
  } else {
    SetCapsLockState, On
  }
  if(GetKeyState("shift", "P")){
    CMD.changeMode("caps")
  } else {
    CMD.changeMode("auto")
  }
  Send, {LShift up}
return

/*
  double click 'ESC' key to NORMAL mode
*/
#If GetKeyState("capslock","T") = 0
  $Esc::
      if (A_PriorHotKey = "$Esc" and A_TimeSincePriorHotKey < 500) {
      SetCapsLockState, On
      CMD.changeMode("auto")
    } else {
      #IfWinActive, ahk_class SWT_Window0
        if(IME_CHECK("A"))
          Send, {VK15}    ; input Korean/English switch key
      #If
      SendInput {Esc}
    }
  return
#if

/*
  colon to input command mode
*/
#If GetKeyState("capslock","T")
  $+SC027::  ;  : (colon) command

    SetCapsLockState, Off
    CMD.changeMode("auto")

    Gui +LastFound +OwnDialogs +AlwaysOnTop

    title := "input_command"
    contents := ""
    InputBox, input_sentence, %title%, %contents%, ,300, 110
    AUTO_TEMP := ""
    AUTO_CNT  := 1

    input_sentence := Trim(input_sentence)

    args := StrSplit(input_sentence, " ")
    args[0] := input_sentence

    if(args.Length() < 1){
      return
    }
    func_name := "command_" . args[1]

    if( IsFunc( func_name ) ) {
      %func_name%(args)
    }
    SetCapsLockState, On
    CMD.clear("auto")
  return
#If

#IfWinActive input_command
  $Tab::

  ControlGetText, txt, Edit1, input_command

  ;MsgBox %AUTO_TEMP%

  if(AUTO_TEMP = ""){
    AUTO_TEMP := Trim(txt)
    AUTO_CNT  := 1
    AUTO_ARR  := Object()
    reg := "^" . AUTO_TEMP

    arr := CFG.get_sect("INPUT_COMMAND")
    cnt := 0
    Loop % arr.MaxIndex()
    {
      th := arr[a_index]
      if(RegExMatch(th, reg)){
        cnt := cnt + 1
        AUTO_ARR.Insert(th)
      }
    }

    if(cnt > 0){
      result := AUTO_ARR[1]
      ControlSetText, Edit1, %result%, input_command
      return
    }
    /*
    for i, v in AUTO_ARR
    {
      MsgBox % i . " : " . v
    }
    */
  } else if( A_PriorKey = "Tab" ) {

  } else if( A_PriorKey <> "Tab" ) {

  }

    ;MsgBox % AUTO_TEMP
    /*
    ControlSetText, Edit1, test_msg, input_command
   */
  return
#IfWinActive

/*
  number commands : numbers works like VIM
*/
$0::
$1::
$2::
$3::
$4::
$5::
$6::
$7::
$8::
$9::
  StringTrimLeft, num, A_ThisHotkey, StrLen(A_ThisHotkey) - 1

  clear_str := { "m": "func_win_memorize", "'" :  "func_win_mem_activate" }
  if(clear_str.HasKey(CMD.get_cmd())) {
    function := clear_str[CMD.get_cmd()]
    %function%(num)
    CMD.clear("auto")
    return
  }

  CMD.append_num(num)

  if ( CMD.get_num() = "0" ) {
    key_0(CMD.get_num())
    CMD.clear("num")
    return
  }
    show_mode(CMD.get_num())
return

; shift + 4 : END key
$+4:: key_4(CMD.get_num())

$*i::
$*o::
  func_i_o()
return

/*
  commands (joinable with number)
*/
$*g::
$*t::
$*r::
$*b::
$*f::
$*q::
$*e::
$w::
$a::
$s::
$d::
$z::
$x::
$+x::
$c::
$m::
$SC028::  ;  '
  ; get hot_key
  hot_key := A_ThisHotkey

  if(A_ThisHotkey = "$SC028"){
    hot_key := "'"
  } else if(RegExMatch(A_ThisHotkey, "^\W")){
    StringTrimLeft, hot_key, A_ThisHotkey, StrLen(A_ThisHotkey) - 1
  }

  ; join previous command with current command
  CMD.append_cmd(hot_key)
  func_name := "key_" . CMD.get_cmd()
  clear_command := 0

  ; if command and function name matched, call function
  ; commands length should shorter than 3
  if( IsFunc( func_name) ) {
    clear_command := %func_name%(CMD.get_num())
    clear_command = 1
  } else if( 1 < StrLen(CMD.get_cmd())){
    clear_command = 1
  }

  if(clear_command = 1){
    CMD.clear("auto")
    return
  }

  show_mode(CMD.get_num_cmd())
return

/*
  mouse pointer accelator
  n + w a s d
  m + w a s d
  , + w a s d
*/
$SC01A::return  ;  [
$SC01B::return  ;  ]
$SC02B::return  ;  \

/*
  help
*/
$+VKBF::Run, ".\manual.html"

/*
  h j k l moves
  h : left
  j : down
  k : up
  l : right
*/
#If GetKeyState("capslock","T") and StrLen(CMD.get_num()) < 1
    *h:: Left
    *j:: Down
    *k:: Up
    *l:: Right
#If
#If GetKeyState("capslock","T") and StrLen(CMD.get_num()) > 0
    *h:: func_hjkl_move("Left", CMD.get_num())
    *j:: func_hjkl_move("Down", CMD.get_num())
    *k:: func_hjkl_move("Up", CMD.get_num())
    *l:: func_hjkl_move("Right", CMD.get_num())
#If


Nicer code

Nicer code

;Control key Ctrl- ^
;Alt key Alt- !
;Shift key Shift- +
;Windows key Win- #

#Persistent
;#NoTrayIcon
#SingleInstance Force
DetectHiddenWindows, On
DetectHiddenText, On
SetTitleMatchMode, RegEx ;match titles and classes using regular expressions
SetTitleMatchMode Slow ;match titles and classes using regular expressions
CoordMode, Mouse, Screen
CoordMode, ToolTip, Screen
OldTicks = 0

;check for cygwin path
CygPath = C:\Program Files (x86)\cygwin
IfNotExist %CygPath%
	CygPath = C:\Cygwin

BrowserPath = C:\Program Files (x86)\Mozilla Firefox\firefox.exe
IfNotExist %BrowserPath%
	BrowserPath = "C:\Users\vleeshue\AppData\Local\Google\Chrome\Application\chrome.exe"

WTWPath = C:\Program Files\WTW\WTW.exe
IfNotExist %WTWPath%
	WTWPath = C:\Program Files\K2T\WTW\WTW.exe

GroupAdd, adobe, ahk_class OWL.DocumentWindow
GroupAdd, adobe, ahk_class illustrator
GroupAdd, adobe, ahk_class PSViewC
GroupAdd, adobe, ahk_class Photoshop
GroupAdd, adobe, Photoshop

return

;replace stuff in clipboard when it changes
OnClipboardChange:
{
	if (A_EventInfo == 1) and (SubStr(clipboard, 1, 7) == "http://")
	{
		StringReplace, clipboard, clipboard, `%5b, [, All
		StringReplace, clipboard, clipboard, `%5d, ], All
	}
	return
}

;declare some fun functions...

;activate/run a program
FRun(window, path, folder)
{
	if (!window or !WinExist(window))
	{
		Run, %path%, %folder%
	}
	else
	{
		WinShow
		WinActivate
	}
	return
}

;create random file name
RandomFileName()
{
	FormatTime, fileName,, yyyyMMdd_HHmmss_
	characters := "abcdefghijklmnopqrstuvwxyz"
	Loop 3
	{
		Random, rand, 1, strlen(characters)
		fileName := fileName . substr(characters, rand, 1)
	}
	return fileName
}

;calling upload script
UploadFiles()
{
	ToolTip, Uploading files..., -1920+50, 50
	RunWait, %CygPath%\bin\mintty.exe "/bin/bash -l -c send_to_pinkyard.py|clip", %CygPath%
	ToolTip
	return
}

;calling screen script
MakeScreen(arguments)
{
	baseFileName := "Z:\hub\pinkyard\queued\" . RandomFileName()
	PNGFileName := "Z:\tmp.png"
	JPGFileName := "Z:\tmp.jpg"
	RunWait, % "C:\program files (x86)\scrsh.exe --path " . PNGFileName . " " . arguments, "Z:\", Hide
	if %ErrorLevel% = 0
	{
		RunWait, % "Z:\src\optipng\support\optipng.exe -o1 " . PNGFileName, "Z:\", Hide
		RunWait, % CygPath . "bin\convert.exe " . PNGFileName . " -quality 80 " . JPGFileName, "Z:\", Hide
		FileGetSize, JPGFileSize, % JPGFileName
		FileGetSize, PNGFileSize, % PNGFileName
		if % PNGFileSize > JPGFileSize
		{
			path1 := JPGFileName
			path2 := baseFileName . ".jpg"
		}
		else
		{
			path1 := PNGFileName
			path2 := baseFileName . ".png"
		}
		FileCopy, % path1, % path2
		FileDelete, % JPGFileName
		FileDelete, % PNGFileName
		SoundPlay, Z:\clutter\sounds\ping.wav
	}
	return path
}

#If FileExist(CygPath)
	;cygwin - activate/run
	+^![::
	{
		Run, %CygPath%\bin\mintty.exe --size "120`,40" --position "1050`,45" --class "mintty_thetty" --exec /bin/bash --login -i, %CygPath%
		return
	}
	^![::
	{
		if (!WinExist("ahk_class mintty_thetty"))
		{
			Run, %CygPath%\bin\mintty.exe --size "120`,40" --position "1050`,45" --class "mintty_thetty" --exec /bin/bash --login -i -c 'while /bin/true`; do /bin/bash`; cygstart "%A_AhkPath%" "Z:\src\hide.ahk"`; clear; done', %CygPath%
			WinWait ahk_class mintty_thetty
		}
		else
		{
			WinShow
			WinActivate
		}
		WinSet, Style, -0x004b0000
		return
	}
	;ssh to burza - activate/run
	+^!]::Run, %CygPath%\bin\mintty.exe --size "200`,70" --position "100`,45" --class mintty_ssh --exec /bin/ssh -p 65000 rr-@sakuya.pl, %CygPath%/bin
	^!]::
	{
		if (!WinExist("ahk_class mintty_ssh"))
		{
			Run, %CygPath%\bin\mintty.exe --size "200`,70" --position "100`,45" --class mintty_ssh --exec /bin/ssh -p 65000 rr-@sakuya.pl, %CygPath%/bin
			WinWait ahk_class mintty_ssh
		}
		else
		{
			WinShow
			WinActivate
		}
		return
	}
	;text editor - activate/run + fix screen position
	+^!N::
	{
		IfWinExist, ahk_class Vim
		{
			WinShow
			WinActivate
		}
		else
		{
			Run, %CygPath%\bin\mintty.exe --size "240`,90" --position "100`,45" --class "Vim" --exec "/bin/vim" --cmd 'cd /cygdrive/z', %CygPath%/bin
			WinWait, ahk_class Vim
		}
		WinMove, , , 100, 100, 1600, 900
		return
	}
	+PrintScreen::MakeScreen("-g")
	!PrintScreen::MakeScreen("-r active-window --shift -8,-8,+16,+16 --force-gui")
	!#PrintScreen::MakeScreen("-r active-monitor")
	#PrintScreen::MakeScreen("-r all-monitors")
	+^!U::UploadFiles() ;upload files

;explorer - activate/run
#E::FRun("ahk_class CabinetWClass", "Z:\", "Z:\")

;foobar - activate/run
#If FileExist("C:\program files (x86)\foobar2000\foobar2000.exe")
	Launch_Media::FRun("ahk_class {97E27FAA-C0B3-4b8e-A693-ED7881E99FC1}", "C:\program files (x86)\foobar2000\foobar2000.exe", "C:\Program Files (x86)\foobar2000")

;wtw
#If FileExist(WTWPath)
	;wtw - activate/run
	+^!M::
		if (!WinExist("^WTW"))
		{
			Run, %WTWPath% -x
		}
		else
		{
			WinShow
			WinActivate
		}
		return

;cdisplayex - activate/run
#If FileExist("C:\Program Files (x86)\CDisplayEx\cdisplayex.exe")
	^!/::FRun("CDisplayEx", "C:\Program Files (x86)\CDisplayEx\cdisplayex.exe", "Z:\")

;browser
#If FileExist(BrowserPath)
	;web browser - activate/run
	^!;::
		if WinExist("Mozilla Firefox")
		{
			WinShow
			WinActivate
			Send, !d
		}
		else if WinExist("ahk_class Chrome_WidgetWin_1")
		{
			WinActivate
			ControlFocus, Chrome_OmniboxView1
			SendInput, {Home}+{End}
		}
		else
		{
			IfExist %BrowserPath%
				Run, %BrowserPath%
		}
		return

;windows powershell / cmd functionalities
#IfWinActive ahk_class ConsoleWindowClass
	^V::SendInput {Raw}%clipboard% ;paste on ctrl+v
	^!PgUp::Send ! el{PgUp}{Enter} ;scroll on ctrl+page up
	^!PgDn::Send ! el{PgDn}{Enter} ;scroll on ctrl+page down
#IfWinActive

;acdsee functionalities
#IfWinActive ahk_class ACDBrowser
	WheelDown::Send, ^{Down}^{Space}
	WheelUp::Send, ^{Up}^{Space}
#IfWinActive
#IfWinActive ACDSee
	WheelDown::
		if (A_TickCount - OldTicks >= 80)
		{
			Send, {WheelDown}
			OldTicks := A_TickCount
		}
		return
	]:: ;send to document folder
	RButton & ~LButton::
		FormatTime, Folder,, 'Z:\'
		Send {LAlt down}c
		Send {LAlt up}
		SendInput %Folder%
		Send {Return}
		return
	[:: ;send to upload folder
	~LButton & RButton::
		Send {LAlt down}c
		Send {LAlt up}
		SendInput Z:\hub\pinkyard\queued
		Send {Return}
		Sleep 100
		return
	XButton1::
		WinGet, Transparency, Transparent, A
		if ! Transparency
			WinSet, Transparent, 255, A
		else if Transparency = 255
			WinSet, Transparent, 0, A
		return
	XButton2:: ;start slideshow
		Send {Pause}
		return
#IfWinActive

;other functionalities

;autohotkey - reload this script
!F12::Reload

;maximize active window
!M::
	ActiveHwnd := WinExist("A")
	PostMessage 0x112, 0xf030 ;WM_SYSCOMMAND, SC_MAXIMIZE
	return

;restore active window
!R::
	ActiveHwnd := WinExist("A")
	PostMessage 0x112, 0xf120 ;WM_SYSCOMMAND, SC_RESTORE
	return

;minimize active window
!W::
	if WinActive("WTW$")
	{
		WinHide
	}
	else
	{
		ActiveHwnd := WinExist("A")
		PostMessage 0x112, 0xF020 ;WM_SYSCOMMAND, SC_MINIMIZE
	}
	return

;always on top
!A::WinSet, AlwaysOnTop, Toggle, A

;transparency
#1::WinSet, Transparent, 0, A
#2::WinSet, Transparent, 64, A
#3::WinSet, Transparent, 255, A
#WheelUp::
	WinGet, Transparency, Transparent, A
	if ! Transparency
		Transparency = 255
	Transparency := Transparency + 16
	if Transparency <= 10
	{
		WinSet, Transparent, 10, A
	}
	else if Transparency >= 255
	{
		WinSet, Transparent, 255, A
		WinSet, Transparent, OFF, A
	}
	else
	{
		WinSet, Transparent, %Transparency%, A
	}
	return
#WheelDown::
	WinGet, Transparency, Transparent, A
	if ! Transparency
		Transparency = 255
	Transparency := Transparency - 16
	if Transparency <= 10
	{
		WinSet, Transparent, 10, A
	}
	else if Transparency >= 255
	{
		WinSet, Transparent, 255, A
		WinSet, Transparent, OFF, A
	}
	else
	{
		WinSet, Transparent, %Transparency%, A
	}
	return

;explorer
#IfWinActive ahk_class CabinetWClass
	;new folder
	^n::
		Send {AppsKey}wf
		return
#IfWinActive

;adobe products
#IfWinActive ahk_group adobe
	~LAlt::return
	LAlt UP::Send {Escape}
#IfWinActive

;Control key Ctrl- ^
;Alt key Alt- !
;Shift key Shift- +
;Windows key Win- #

#Persistent
;#NoTrayIcon
#SingleInstance Force
DetectHiddenWindows, On
DetectHiddenText, On
SetTitleMatchMode, RegEx ;match titles and classes using regular expressions
SetTitleMatchMode Slow ;match titles and classes using regular expressions
CoordMode, Mouse, Screen
CoordMode, ToolTip, Screen
OldTicks = 0

;check for cygwin path
CygPath = C:\Program Files (x86)\cygwin
IfNotExist %CygPath%
	CygPath = C:\Cygwin

BrowserPath = C:\Program Files (x86)\Mozilla Firefox\firefox.exe
IfNotExist %BrowserPath%
	BrowserPath = "C:\Users\vleeshue\AppData\Local\Google\Chrome\Application\chrome.exe"

WTWPath = C:\Program Files\WTW\WTW.exe
IfNotExist %WTWPath%
	WTWPath = C:\Program Files\K2T\WTW\WTW.exe

GroupAdd, adobe, ahk_class OWL.DocumentWindow
GroupAdd, adobe, ahk_class illustrator
GroupAdd, adobe, ahk_class PSViewC
GroupAdd, adobe, ahk_class Photoshop
GroupAdd, adobe, Photoshop

return

;replace stuff in clipboard when it changes
OnClipboardChange:
{
	if (A_EventInfo == 1) and (SubStr(clipboard, 1, 7) == "http://")
	{
		StringReplace, clipboard, clipboard, `%5b, [, All
		StringReplace, clipboard, clipboard, `%5d, ], All
	}
	return
}

;declare some fun functions...

;activate/run a program
FRun(window, path, folder)
{
	if (!window or !WinExist(window))
	{
		Run, %path%, %folder%
	}
	else
	{
		WinShow
		WinActivate
	}
	return
}

;create random file name
RandomFileName()
{
	FormatTime, fileName,, yyyyMMdd_HHmmss_
	characters := "abcdefghijklmnopqrstuvwxyz"
	Loop 3
	{
		Random, rand, 1, strlen(characters)
		fileName := fileName . substr(characters, rand, 1)
	}
	return fileName
}

;calling upload script
UploadFiles()
{
	ToolTip, Uploading files..., -1920+50, 50
	RunWait, %CygPath%\bin\mintty.exe "/bin/bash -l -c send_to_pinkyard.py|clip", %CygPath%
	ToolTip
	return
}

;calling screen script
MakeScreen(arguments)
{
	baseFileName := "Z:\hub\pinkyard\queued\" . RandomFileName()
	PNGFileName := "Z:\tmp.png"
	JPGFileName := "Z:\tmp.jpg"
	RunWait, % "C:\program files (x86)\scrsh.exe --path " . PNGFileName . " " . arguments, "Z:\", Hide
	if %ErrorLevel% = 0
	{
		RunWait, % "Z:\src\optipng\support\optipng.exe -o1 " . PNGFileName, "Z:\", Hide
		RunWait, % CygPath . "bin\convert.exe " . PNGFileName . " -quality 80 " . JPGFileName, "Z:\", Hide
		FileGetSize, JPGFileSize, % JPGFileName
		FileGetSize, PNGFileSize, % PNGFileName
		if % PNGFileSize > JPGFileSize
		{
			path1 := JPGFileName
			path2 := baseFileName . ".jpg"
		}
		else
		{
			path1 := PNGFileName
			path2 := baseFileName . ".png"
		}
		FileCopy, % path1, % path2
		FileDelete, % JPGFileName
		FileDelete, % PNGFileName
		SoundPlay, Z:\clutter\sounds\ping.wav
	}
	return path
}

#If FileExist(CygPath)
	;cygwin - activate/run
	+^![::
		Run, %CygPath%\bin\mintty.exe --size "120`,40" --position "1050`,45" --class "mintty_thetty" --exec /bin/bash --login -i, %CygPath%
		return
	 ^![::
	 {
		if (!WinExist("ahk_class mintty_thetty"))
		{
			Run, %CygPath%\bin\mintty.exe --size "120`,40" --position "1050`,45" --class "mintty_thetty" --exec /bin/bash --login -i -c 'while /bin/true; do /bin/bash; cygstart "%A_AhkPath%" "Z:\src\hide.ahk"; clear; done', %CygPath%
			WinWait ahk_class mintty_thetty
		}
		else
		{
			WinShow
			WinActivate
		}
		WinSet, Style, -0x004b0000
		return
	}
	;ssh to burza - activate/run
	+^!]::Run, %CygPath%\bin\mintty.exe --size "200`,70" --position "100`,45" --class mintty_ssh --exec /bin/ssh -p 65000 rr-@sakuya.pl, %CygPath%/bin
	^!]::
	{
		if (!WinExist("ahk_class mintty_ssh"))
		{
			Run, %CygPath%\bin\mintty.exe --size "200`,70" --position "100`,45" --class mintty_ssh --exec /bin/ssh -p 65000 rr-@sakuya.pl, %CygPath%/bin
			WinWait ahk_class mintty_ssh
		}
		else
		{
			WinShow
			WinActivate
		}
		return
	}
	;text editor - activate/run + fix screen position
	+^!N::
	{
		IfWinExist, ahk_class Vim
		{
			WinShow
			WinActivate
		}
		else
		{
			Run, %CygPath%\bin\mintty.exe --size "240`,90" --position "100`,45" --class "Vim" --exec "/bin/vim" --cmd 'cd /cygdrive/z', %CygPath%/bin
			WinWait, ahk_class Vim
		}
		WinMove, , , 100, 100, 1600, 900
		return
	}
	+PrintScreen::MakeScreen("-g")
	!PrintScreen::MakeScreen("-r active-window --shift -8,-8,+16,+16 --force-gui")
	!#PrintScreen::MakeScreen("-r active-monitor")
	#PrintScreen::MakeScreen("-r all-monitors")
	+^!U::UploadFiles() ;upload files

;explorer - activate/run
#E::FRun("ahk_class CabinetWClass", "Z:\", "Z:\")

;foobar - activate/run
#If FileExist("C:\program files (x86)\foobar2000\foobar2000.exe")
	Launch_Media::FRun("ahk_class {97E27FAA-C0B3-4b8e-A693-ED7881E99FC1}", "C:\program files (x86)\foobar2000\foobar2000.exe", "C:\Program Files (x86)\foobar2000")

;wtw
#If FileExist(WTWPath)
	;wtw - activate/run
	+^!M::
		if (!WinExist("^WTW"))
		{
			Run, %WTWPath% -x
		}
		else
		{
			WinShow
			WinActivate
		}
		return

;cdisplayex - activate/run
#If FileExist("C:\Program Files (x86)\CDisplayEx\cdisplayex.exe")
	^!/::FRun("CDisplayEx", "C:\Program Files (x86)\CDisplayEx\cdisplayex.exe", "Z:\")

;browser
#If FileExist(BrowserPath)
	;web browser - activate/run
	^!;::
		if WinExist("Mozilla Firefox")
		{
			WinShow
			WinActivate
			Send, !d
		}
		else if WinExist("ahk_class Chrome_WidgetWin_1")
		{
			WinActivate
			ControlFocus, Chrome_OmniboxView1
			SendInput, {Home}+{End}
		}
		else
		{
			IfExist %BrowserPath%
				Run, %BrowserPath%
		}
		return

;windows powershell / cmd functionalities
#IfWinActive ahk_class ConsoleWindowClass
	^V::SendInput {Raw}%clipboard% ;paste on ctrl+v
	^!PgUp::Send ! el{PgUp}{Enter} ;scroll on ctrl+page up
	^!PgDn::Send ! el{PgDn}{Enter} ;scroll on ctrl+page down
#IfWinActive

;acdsee functionalities
#IfWinActive ahk_class ACDBrowser
	WheelDown::Send, ^{Down}^{Space}
	WheelUp::Send, ^{Up}^{Space}
#IfWinActive
#IfWinActive ACDSee
	WheelDown::
		if (A_TickCount - OldTicks >= 80)
		{
			Send, {WheelDown}
			OldTicks := A_TickCount
		}
		return
	]:: ;send to document folder
	RButton & ~LButton::
		FormatTime, Folder,, 'Z:\'
		Send {LAlt down}c
		Send {LAlt up}
		SendInput %Folder%
		Send {Return}
		return
	[:: ;send to upload folder
	~LButton & RButton::
		Send {LAlt down}c
		Send {LAlt up}
		SendInput Z:\hub\pinkyard\queued
		Send {Return}
		Sleep 100
		return
	XButton1::
		WinGet, Transparency, Transparent, A
		if ! Transparency
			WinSet, Transparent, 255, A
		else if Transparency = 255
			WinSet, Transparent, 0, A
		return
	XButton2:: ;start slideshow
		Send {Pause}
		return
#IfWinActive

;other functionalities

;autohotkey - reload this script
!F12::Reload

;maximize active window
!M::
	ActiveHwnd := WinExist("A")
	PostMessage 0x112, 0xf030 ;WM_SYSCOMMAND, SC_MAXIMIZE
	return

;restore active window
!R::
	ActiveHwnd := WinExist("A")
	PostMessage 0x112, 0xf120 ;WM_SYSCOMMAND, SC_RESTORE
	return

;minimize active window
!W::
	if WinActive("WTW$")
	{
		WinHide
	}
	else
	{
		ActiveHwnd := WinExist("A")
		PostMessage 0x112, 0xF020 ;WM_SYSCOMMAND, SC_MINIMIZE
	}
	return

;always on top
!A::WinSet, AlwaysOnTop, Toggle, A

;transparency
#1::WinSet, Transparent, 0, A
#2::WinSet, Transparent, 64, A
#3::WinSet, Transparent, 255, A
#WheelUp::
	WinGet, Transparency, Transparent, A
	if ! Transparency
		Transparency = 255
	Transparency := Transparency + 16
	if Transparency <= 10
	{
		WinSet, Transparent, 10, A
	}
	else if Transparency >= 255
	{
		WinSet, Transparent, 255, A
		WinSet, Transparent, OFF, A
	}
	else
	{
		WinSet, Transparent, %Transparency%, A
	}
	return
#WheelDown::
	WinGet, Transparency, Transparent, A
	if ! Transparency
		Transparency = 255
	Transparency := Transparency - 16
	if Transparency <= 10
	{
		WinSet, Transparent, 10, A
	}
	else if Transparency >= 255
	{
		WinSet, Transparent, 255, A
		WinSet, Transparent, OFF, A
	}
	else
	{
		WinSet, Transparent, %Transparency%, A
	}
	return

;explorer
#IfWinActive ahk_class CabinetWClass
	;new folder
	^n::
		Send {AppsKey}wf
		return
#IfWinActive

;adobe products
#IfWinActive ahk_group adobe
	~LAlt::return
	LAlt UP::Send {Escape}
#IfWinActive


Fix RunZCmdTool.ahk

Fix RunZCmdTool.ahk

#NoEnv
#NoTrayIcon
SendMode Input
SetWorkingDir %A_ScriptDir%

; 如果该文件报错，说明 UserFunctionsAuto.txt 文件里有重复标签，需要手动修改或删除

global g_UserFunctionsAutoFileName := A_ScriptDir "\..\Conf\UserFunctionsAuto.txt"
global g_FileContent

if (!FileExist(g_UserFunctionsAutoFileName))
{
    FileCopy, %g_UserFunctionsAutoFileName%.template, %g_UserFunctionsAutoFileName%
}

FileRead, g_FileContent, %g_UserFunctionsAutoFileName%

allLabels := Object()
index := 1

Loop, %0%
{
    SplitPath, %A_Index%, fileName, fileDir, fileExt, fileNameNoExt

    if (fileNameNoExt == "")
    {
        continue
    }

    labelName := SafeLabel(fileNameNoExt)
    fileDir := SafeFilename(fileDir)
    fileExt := SafeFilename(fileExt)
    fileName := SafeFilename(fileName)

    uniqueLabelName := labelName

    ; 如果和已有标签重名，添加时间
    if (IsLabel(uniqueLabelName) || allLabels.HasKey(uniqueLabelName))
    {
        uniqueLabelName .= "_" A_Now "_" index
        index++
    }

    AddFile(uniqueLabelName, labelName, fileDir . "\" . fileName, fileDir)
    allLabels[uniqueLabelName] := true
}

FileMove, %g_UserFunctionsAutoFileName%, %g_UserFunctionsAutoFileName%.bak, 1
FileAppend, %g_FileContent%, %g_UserFunctionsAutoFileName%, utf-8

; 打开文件来编辑
Run, %g_UserFunctionsAutoFileName%

return

; 添加一个需要运行的文件
AddFile(name, comment, path, dir)
{
    addFunctionsText = @("%name%", "%comment%")
    addLabelsText = %name%:`r`n    `; 用法：  Run, "文件名" "参数..", 工作目录, Max|Min|Hide`r`n
    addLabelsText = %addLabelsText%    Run, "%path%", "%dir%"`r`nreturn`r`n

    g_FileContent := StrReplace(g_FileContent
        , "    `; -*-*-*-*-*-", "    `; -*-*-*-*-*-`r`n    " addFunctionsText)
    g_FileContent := StrReplace(g_FileContent
        , "`r`n`; -*-*-*-*-*-", "`r`n`; -*-*-*-*-*-`r`n" addLabelsText)
}

SafeLabel(label)
{
    StringReplace, label, label, ", _, All
    return RegExReplace(label, "[ `%```t',]", "_")
}

SafeFilename(label)
{
    StringReplace, label, label, ", ``", All
    StringReplace, label, label, ``, ````, All
    StringReplace, label, label, `%, ```%, All
    StringReplace, label, label, `,, ```,, All
    return label
}

; 伪 @ 函数，用于避免运行出错
@(a = "", b = "", c = "", d = "", e = "", f = "")
{
}

; 用于判断是否有重复标签
#include *i %A_ScriptDir%\..\Conf\UserFunctionsAuto.txt

#NoEnv
#NoTrayIcon
SendMode Input
SetWorkingDir %A_ScriptDir%

; 如果该文件报错，说明 UserFunctionsAuto.txt 文件里有重复标签，需要手动修改或删除

global g_UserFunctionsAutoFileName := A_ScriptDir "\..\Conf\UserFunctionsAuto.txt"
global g_FileContent

if (!FileExist(g_UserFunctionsAutoFileName))
{
    FileCopy, %g_UserFunctionsAutoFileName%.template, %g_UserFunctionsAutoFileName%
}

FileRead, g_FileContent, %g_UserFunctionsAutoFileName%

allLabels := Object()
index := 1

Loop, %0%
{
    SplitPath, %A_Index%, fileName, fileDir, fileExt, fileNameNoExt

    if (fileNameNoExt == "")
    {
        continue
    }

    labelName := fileNameNoExt

    ; 如果和已有标签重名，添加时间
    if (IsLabel(labelName) || allLabels.HasKey(labelName))
    {
        labelName .= "_" A_Now "_" index
        index++
    }

    AddFile(labelName, fileNameNoExt, fileDir "\" fileName, fileDir)
    allLabels[labelName] := true
}

FileMove, %g_UserFunctionsAutoFileName%, %g_UserFunctionsAutoFileName%.bak, 1
FileAppend, %g_FileContent%, %g_UserFunctionsAutoFileName%, utf-8

; 打开文件来编辑
Run, %g_UserFunctionsAutoFileName%

return

; 添加一个需要运行的文件
AddFile(name, comment, path, dir)
{
    addFunctionsText = @("%name%", "%comment%")
    addLabelsText = %name%:`r`n    `; 用法：  Run, "文件名" "参数..", 工作目录, Max|Min|Hide`r`n
    addLabelsText = %addLabelsText%    Run, "%path%", "%dir%"`r`nreturn`r`n

    g_FileContent := StrReplace(g_FileContent
        , "    `; -*-*-*-*-*-", "    `; -*-*-*-*-*-`r`n    " addFunctionsText)
    g_FileContent := StrReplace(g_FileContent
        , "`r`n`; -*-*-*-*-*-", "`r`n`; -*-*-*-*-*-`r`n" addLabelsText)
}

; 伪 @ 函数，用于避免运行出错
@(a = "", b = "", c = "", d = "", e = "", f = "")
{
}

; 用于判断是否有重复标签
#include *i %A_ScriptDir%\..\Conf\UserFunctionsAuto.txt


RunZ: copy result of Calc

RunZ: copy result of Calc

global Arg

InternalFunction:
    @("Help", "帮助信息")
    @("AhkRun", "使用 Ahk 的 Run 运行 `; cmd", true)
    @("CmdRun", "使用 cmd 运行 : cmd", true)
    @("ReloadFiles", "重新加载需要搜索的文件")
    @("Clip", "显示剪切板内容")
    @("Calc", "计算器")
    @("SearchInWeb", "在浏览器（百度）搜索剪切板或输入内容")
    @("EditConfig", "编辑配置文件")
    @("ClearClipboardFormat", "清除剪切板中文字的格式")
    @("RunClipboard", "使用 ahk 的 Run 运行剪切板内容")
    @("T2S", "繁体转简体剪切板内容")
    @("ShowIp", "显示 IP")
    @("Calendar", "用浏览器打开万年历")
    @("Dictionary", "词典，依赖 bash 和 ydcv")
    @("ArgTest", "参数测试：ArgTest arg1,arg2,...")
return

Help:
    helpText := ""
        . "键入内容 搜索，回车 执行（a），Alt + 字母 执行，F1 帮助，Esc 退出`n"
        . "Tab + 字母 也可执行字母对应功能`n"
        . "Tab + 大写字母 可将字母对应功能加入到配置文件，以便优先显示`n"
        . "Ctrl + r 重新创建待搜索文件列表`n"
        . "Ctrl + j 清除编辑框内容`n"
        . "Ctrl + d 用 TC 打开第一个文件所在目录`n"
        . "Ctrl + s 显示第一个文件的完整路径`n"
        . "Ctrl + x 删除第一个文件`n"
        . "F2 编辑配置文件`n`n"
        . "可直接输入网址，如 www.baidu.com`n"
        . "分号开头则使用 ahk 的 Run 运行命令，如 `;ping www.bidu.com`n"
        . "冒号开头则在 cmd 运行命令，如 :ping www.baidu.com`n"
        . "当搜索无结果时，回车 也等同 run 输入内容`n"
        . "当输入内容包含空格时，列表锁定，逗号作为命令参数的分隔符"

    DisplayResult(helpText)
return

CmdRun:
    RunWithCmd(Arg)
return

AhkRun:
    Run, %Arg%
return

Clip:
    DisplayResult("剪切板内容长度 " . StrLen(clipboard) . " ：`n`n" . clipboard)
return

EditConfig:
    Run, % g_ConfFile
return

ArgTest:
    Args := StrSplit(Arg, ",")
    result := "共有 " . Args.Length() . " 个参数。`n`n"

    for index, argument in Args
    {
        result .= "第 " . index - 1 " 个参数：" . argument . "`n"
    }

    DisplayResult(result)
return

ShowIp:
    DisplayResult(A_IPAddress1
            . "`r`n" . A_IPAddress2
            . "`r`n" . A_IPAddress3
            . "`r`n" . A_IPAddress4)
return

Dictionary:
    word := Arg
    if (word == "")
    {
        word := clipboard
    }

    DisplayResult(RunAndGetOutput("echo " . word . " | ydcv"))
return

Calendar:
    Run % "http://www.baidu.com/baidu?wd=%CD%F2%C4%EA%C0%FA"
return

T2S:
    Run, notepad
    clipboard := Kanji_t2s(clipboard)
    Send, ^v
return

ClearClipboardFormat:
    clipboard := clipboard
return

SearchInWeb:
    word := clipboard
    if (Arg != "")
    {
        word := Arg
    }

    Run, https://www.baidu.com/s?wd=%word%
return

RunClipboard:
    Run, %clipboard%
return

Calc:
    result := Eval(Arg)
    DisplayResult(result)
    clipboard := result
return

global Arg

InternalFunction:
    @("Help", "帮助信息")
    @("AhkRun", "使用 Ahk 的 Run 运行 `; cmd", true)
    @("CmdRun", "使用 cmd 运行 : cmd", true)
    @("ReloadFiles", "重新加载需要搜索的文件")
    @("Clip", "显示剪切板内容")
    @("Calc", "计算器")
    @("SearchInWeb", "在浏览器（百度）搜索剪切板或输入内容")
    @("EditConfig", "编辑配置文件")
    @("ClearClipboardFormat", "清除剪切板中文字的格式")
    @("RunClipboard", "使用 ahk 的 Run 运行剪切板内容")
    @("T2S", "繁体转简体剪切板内容")
    @("ShowIp", "显示 IP")
    @("Calendar", "用浏览器打开万年历")
    @("Dictionary", "词典，依赖 bash 和 ydcv")
    @("ArgTest", "参数测试：ArgTest arg1,arg2,...")
return

Help:
    helpText := ""
        . "键入内容 搜索，回车 执行（a），Alt + 字母 执行，F1 帮助，Esc 退出`n"
        . "Tab + 字母 也可执行字母对应功能`n"
        . "Tab + 大写字母 可将字母对应功能加入到配置文件，以便优先显示`n"
        . "Ctrl + r 重新创建待搜索文件列表`n"
        . "Ctrl + j 清除编辑框内容`n"
        . "Ctrl + d 用 TC 打开第一个文件所在目录`n"
        . "Ctrl + s 显示第一个文件的完整路径`n"
        . "Ctrl + x 删除第一个文件`n"
        . "F2 编辑配置文件`n`n"
        . "可直接输入网址，如 www.baidu.com`n"
        . "分号开头则使用 ahk 的 Run 运行命令，如 `;ping www.bidu.com`n"
        . "冒号开头则在 cmd 运行命令，如 :ping www.baidu.com`n"
        . "当搜索无结果时，回车 也等同 run 输入内容`n"
        . "当输入内容包含空格时，列表锁定，逗号作为命令参数的分隔符"

    DisplayResult(helpText)
return

CmdRun:
    RunWithCmd(Arg)
return

AhkRun:
    Run, %Arg%
return

Clip:
    DisplayResult("剪切板内容长度 " . StrLen(clipboard) . " ：`n`n" . clipboard)
return

EditConfig:
    Run, % g_ConfFile
return

ArgTest:
    Args := StrSplit(Arg, ",")
    result := "共有 " . Args.Length() . " 个参数。`n`n"

    for index, argument in Args
    {
        result .= "第 " . index - 1 " 个参数：" . argument . "`n"
    }

    DisplayResult(result)
return

ShowIp:
    DisplayResult(A_IPAddress1
            . "`r`n" . A_IPAddress2
            . "`r`n" . A_IPAddress3
            . "`r`n" . A_IPAddress4)
return

Dictionary:
    word := Arg
    if (word == "")
    {
        word := clipboard
    }

    DisplayResult(RunAndGetOutput("echo " . word . " | ydcv"))
return

Calendar:
    Run % "http://www.baidu.com/baidu?wd=%CD%F2%C4%EA%C0%FA"
return

T2S:
    Run, notepad
    clipboard := Kanji_t2s(clipboard)
    Send, ^v
return

ClearClipboardFormat:
    clipboard := clipboard
return

SearchInWeb:
    word := clipboard
    if (Arg != "")
    {
        word := Arg
    }

    Run, https://www.baidu.com/s?wd=%word%
return

RunClipboard:
    Run, %clipboard%
return

Calc:
    DisplayResult(Eval(Arg))
return