Update MBWindow.ahk

Update MBWindow.ahk

#IfWinActive ahk_exe MapInfoPro.exe ;THIS WILL NEED EXTENSION THROUGH "isMapBasicWindow()"
mbWin_enterBehaviour = 1

$Enter::    ;$ so Enter can be re-used
    If Not isMapBasicWindow() {
        send, {Enter}
        return
    }

    If (mbWin_enterBehaviour > 1) {
    	send, ^a
    )

    ;Get the MapBasic source from the MapBasic Window
    old_clipboard := ClipboardAll
	Clipboard=
	send, ^c
	clipwait,0.1
	MBSource := clipboard
	clipboard := old_clipboard

	If (needsCompiling(MBSource)) {
	    Compile(MBSource)
	} else {
	    send,{Enter}
	}

return

isMapBasicWindow(){
    ;TO DO: This should have more (fast) checks.
    MapInfo := ComObjGet("MapInfo.Application.x64")
    return MapInfo.Eval("ActiveWindow()") = 1002
}

needsCompiling(src){
	;Separated RegEx - This may require simplifying...:
	i := 0
	i := i + regexmatch(src,"i)\bAlter\b\s+\b(Control|MapInfoDialog)\b")			;matches {Alter Control,Alter MapInfoDialog}
	i := i + regexmatch(src,"i)\bCall\b")						        ;matches Call
	i := i + regexmatch(src,"i)\bDeclare\b\s+\b(Function|Sub)\b")				;matches {Declare Function, Declare Sub}
	i := i + regexmatch(src,"i)\bDefine\b")						        ;matches Define
	i := i + regexmatch(src,"i)\bDialog\b")						        ;matches {Dialog, Dialog Preserve, Dialog Remove}
	i := i + regexmatch(src,"i)\bDim\s+\w+\s*(,\s*\w+\s*)+\s+as\b")				;matches Dim {2 variable declarations} as
	i := i + regexmatch(src,"i)\bDo\s+Case\s+(.|\s)*?\bEnd\s+Case\b")			;matches Do Case … End Case,
	i := i + regexmatch(src,"i)\bDo\b\s+(.|\s)*?\bLoop\b")				    	;matches Do … Loop
	i := i + regexmatch(src,"i)\bEnd\s+Program\b")					        ;matches End Program
	i := i + regexmatch(src,"i)\bExit\s+(Do|For|Function|Sub)\b")				;matches {Exit Do, Exit For, Exit Function, Exit Sub}
	i := i + regexmatch(src,"i)\bFor\b(.|\s)*?\bNext\b")				    	;matches For … Next,
	i := i + regexmatch(src,"i)\bFunction\b(.|\s)*\bEnd\s+Function\b")			;matches Function … End Function
	i := i + regexmatch(src,"i)\bGoTo\b")			            			;matches GoTo
	i := i + regexmatch(src,"i)\bSub\b(.|\s)*\bEnd\s+Sub\b")				;matches Sub … End Sub
	i := i + regexmatch(src,"i)\bIf\b(.|\s)*?\bThen\b(.|\s)*?\bEnd\s+If\b")			;matches If .*? then … End If
	i := i + regexmatch(src,"i)\bInclude\b\s+\b"".*""\b")				    	;matches Include “…”
	i := i + regexmatch(src,"i)\bOnError\s+GoTo\b")					        ;matches OnError GoTo
	i := i + regexmatch(src,"i)\bOpen\s+File\b")					    	;matches Open File
	i := i + regexmatch(src,"i)\bProgressBar\b")    					;matches ProgressBar
	i := i + regexmatch(src,"i)\bResume\b")			    				;matches Resume
	i := i + regexmatch(src,"i)\bSet\s+Handler\b")		    				;matches Set Handler
	i := i + regexmatch(src,"i)\bType\b(.|\s)*?\bEnd\s+Type\b") 				;matches Type … End Type
	i := i + regexmatch(src,"i)\bWhile\b(.|\s)*?\bWend\b")		    			;matches While … Wend
	return i > 0
}

#IfWinActive ahk_exe MapInfoPro.exe ;THIS WILL NEED EXTENSION THROUGH "isMapBasicWindow()"
mbWin_enterBehaviour = 1

$Enter::    ;$ so Enter can be re-used
    If Not isMapBasicWindow() {
        send, {Enter}
        return
    }

    If (mbWin_enterBehaviour > 1) {
    	send, ^a
    )

    ;Get the MapBasic source from the MapBasic Window
    old_clipboard := ClipboardAll
	Clipboard=
	send, ^c
	clipwait,0.1
	MBSource := clipboard
	clipboard := old_clipboard

	If (needsCompiling(MBSource)) {
	    Compile(MBSource)
	} else {
	    send,{Enter}
	}

return

isMapBasicWindow(){
    ;TO DO: This should have more (fast) checks.
    MapInfo = ComObjGet("MapInfo.Application.x64")
    return MapInfo.Eval("ActiveWindow()") = 1002
}

needsCompiling(src){
	;Separated RegEx - This may require simplifying...:
	i := 0
	i := i + regexmatch(src,"i)\bAlter\b\s+\b(Control|MapInfoDialog)\b")			;matches {Alter Control,Alter MapInfoDialog}
	i := i + regexmatch(src,"i)\bCall\b")						        ;matches Call
	i := i + regexmatch(src,"i)\bDeclare\b\s+\b(Function|Sub)\b")				;matches {Declare Function, Declare Sub}
	i := i + regexmatch(src,"i)\bDefine\b")						        ;matches Define
	i := i + regexmatch(src,"i)\bDialog\b")						        ;matches {Dialog, Dialog Preserve, Dialog Remove}
	i := i + regexmatch(src,"i)\bDim\s+\w+\s*(,\s*\w+\s*)+\s+as\b")				;matches Dim {2 variable declarations} as
	i := i + regexmatch(src,"i)\bDo\s+Case\s+(.|\s)*?\bEnd\s+Case\b")			;matches Do Case … End Case,
	i := i + regexmatch(src,"i)\bDo\b\s+(.|\s)*?\bLoop\b")				    	;matches Do … Loop
	i := i + regexmatch(src,"i)\bEnd\s+Program\b")					        ;matches End Program
	i := i + regexmatch(src,"i)\bExit\s+(Do|For|Function|Sub)\b")				;matches {Exit Do, Exit For, Exit Function, Exit Sub}
	i := i + regexmatch(src,"i)\bFor\b(.|\s)*?\bNext\b")				    	;matches For … Next,
	i := i + regexmatch(src,"i)\bFunction\b(.|\s)*\bEnd\s+Function\b")			;matches Function … End Function
	i := i + regexmatch(src,"i)\bGoTo\b")			            			;matches GoTo
	i := i + regexmatch(src,"i)\bSub\b(.|\s)*\bEnd\s+Sub\b")				;matches Sub … End Sub
	i := i + regexmatch(src,"i)\bIf\b(.|\s)*?\bThen\b(.|\s)*?\bEnd\s+If\b")			;matches If .*? then … End If
	i := i + regexmatch(src,"i)\bInclude\b\s+\b"".*""\b")				    	;matches Include “…”
	i := i + regexmatch(src,"i)\bOnError\s+GoTo\b")					        ;matches OnError GoTo
	i := i + regexmatch(src,"i)\bOpen\s+File\b")					    	;matches Open File
	i := i + regexmatch(src,"i)\bProgressBar\b")    					;matches ProgressBar
	i := i + regexmatch(src,"i)\bResume\b")			    				;matches Resume
	i := i + regexmatch(src,"i)\bSet\s+Handler\b")		    				;matches Set Handler
	i := i + regexmatch(src,"i)\bType\b(.|\s)*?\bEnd\s+Type\b") 				;matches Type … End Type
	i := i + regexmatch(src,"i)\bWhile\b(.|\s)*?\bWend\b")		    			;matches While … Wend
	return i > 0
}


removed ctrl:capsLock mapping

removed ctrl:capsLock mapping

new keyboard has hardware mapping for this

;Replaces the default Win+E shortcut with XYplorer
#e::
run C:\Program Files (x86)\XYplorer\XYplorer.exe
return

;Ctrl + Alt + R -- reloads current script
^!r::Reload

;Alt + Win + E -- Opens this file
!#e::
EnvGet, HOME, HOMEPATH
run "gvim" "%HOME%\.dotfiles\autohotkey-scripts\my_keyboard_shortcuts.ahk"
Return

OpenWithVim() ;opens current file in vim if using XYPlorer, else opens vim
{
	EnvGet, DROPBOX, DB_HOME
	oldClipboard = %clipboard%
	IfWinActive, ahk_class ThunderRT6FormDC
	{
		SendInput ^p
		Sleep, 100
		Run, "runemacs" "%clipboard%"
		clipboard = %oldClipboard%
	}
	Else
	{
		Run, "runemacs", C:\users\nate
	}
}

Pause::
OpenWithVim()
Return

Insert::
OpenWithVim()
Return

;Replaces the default Win+E shortcut with XYplorer
#e::
run C:\Program Files (x86)\XYplorer\XYplorer.exe
return

;Ctrl + Alt + R -- reloads current script
^!r::Reload

;Alt + Win + E -- Opens this file
!#e::
EnvGet, HOME, HOMEPATH
run "gvim" "%HOME%\.dotfiles\autohotkey-scripts\my_keyboard_shortcuts.ahk"
Return

;shortcuts for Vim

Capslock::Ctrl

OpenWithVim() ;opens current file in vim if using XYPlorer, else opens vim
{
	EnvGet, DROPBOX, DB_HOME
	oldClipboard = %clipboard%
	IfWinActive, ahk_class ThunderRT6FormDC
	{
		SendInput ^p
		Sleep, 100
		Run, "runemacs" "%clipboard%"
		clipboard = %oldClipboard%
	}
	Else
	{
		Run, "runemacs", C:\users\nate
	}
}

Pause::
OpenWithVim()
Return

Insert::
OpenWithVim()
Return


Adds ahk function to be run when the script is quit

; Uncomment if you don't want this script appearing in your system tray
; #NoTrayIcon
#SingleInstance Force
#Persistent
MsgNum := DllCall("RegisterWindowMessage", Str, "VIRTUALDESKTOPGRIDSWITCHER_COMMAND")

exeName := "VirtualDesktopGridSwitcher.exe"

; Launch VirtualDesktopGridManager if it's not already running.
DetectHiddenWindows, On
If !WinExist("ahk_exe " . exeName) {
    Run "../VirtualDesktopGridSwitcher.exe"
}

OnExit, % OnExitFn

; All commands
GO_UP := 1
GO_LEFT := 2
GO_RIGHT := 3
GO_DOWN := 4
MOVE_UP := 5
MOVE_LEFT := 6
MOVE_RIGHT := 7
MOVE_DOWN := 8
TOGGLE_STICKY := 10
DEBUG_SHOW_CURRENT_WINDOW_HWND := 11
SET_HWND_MESSAGE_TARGET := 12
SWITCHED_DESKTOP := 13
QUIT := 14

OnMessage(MsgNum, "ReceiveMessage")
myHwnd := HexToDec(A_ScriptHwnd)
SendCommand(SET_HWND_MESSAGE_TARGET, myHwnd)

desktopName := Object()
desktopName[0] := "Main"
desktopName[1] := "Work"
desktopName[2] := ""
desktopName[3] := "Chat"
desktopName[4] := ""
desktopName[5] := ""
desktopName[6] := ""
desktopName[7] := "BF"
desktopName[8] := "Music"
return

; Return an HWND that will receive our commands.
GetTargetHwnd() {
    global exeName
    DetectHiddenWindows, On
    WinGet, a, List, ahk_exe %exeName%
    Loop, %a% {
        id := a%A_Index%
        WinGetClass, cls, ahk_id %id%
        ; Skip the "GDI+" window
        If(RegExMatch(cls, "^GDI") = 0) {
            return id
        }
    }
}

; Send a command to VirtualDesktopGridSwitcher
SendCommand(cmd, value) {
    ; All variables are global unless declared to be local
    global
    local id
    id := GetTargetHwnd()
    PostMessage, %MsgNum%, %cmd%, %value%, , ahk_id %id%
}

; Called when VirtualDesktopGridSwitcher sends us a message
ReceiveMessage(cmd, value, msg, hwnd) {
    ; All variables are global unless declared to be local
    global
	local num
	if (cmd = SWITCHED_DESKTOP) {
	    num := value + 1
	    ShowOverlay("Desktop " + num, desktopName[value])
	} else {
	    MsgBox, %cmd%, %value%
	}
}

HexToDec(hex) {
	result := hex + 0
	; result .= ""
	return result
}

ShowOverlay(title, message) {
    SysGet, primary, MonitorPrimary
    SysGet, monitor, Monitor, %primary%
	width := 200
	height := 50
	padding := 100
	x := monitorLeft + ((monitorRight - monitorLeft) / 2) - (width / 2)
	y := monitorBottom - height - padding
    SplashImage, Icons/1.ico, BX%x%Y%y%W%width%H%height%, %message%, %title%, ,
}

HideOverlay() {
    SplashImage, Off
}

ShouldHideOverlay() {
	if(GetKeyState("Ctrl", "P") = 0 && GetKeyState("LWin", "P") = 0) {
	    return 1
	} else {
	    return 0
	}
}

CheckHideOverlay() {
    if(ShouldHideOverlay() = 1) {
	    HideOverlay()
	}
ToggleAlwaysOnTop(hwnd := "") {
    if(hwnd == "") {
        hwnd := WinExist("A")
    }
    WinSet, AlwaysOnTop, Toggle, ahk_id %hwnd%
    ;WinGet, ExStyle, ExStyle, ahk_id %hwnd%
    ;if(ExStyle & 0x8) {
    ;    message := "Always on Top Enabled"
    ;} else {
    ;    message := "Always on Top Disabled"
    ;}
    ;TrayTip, , %message%, 1, 0x10
}

OnExitFn() {
    ; TODO kill the .exe
}

}

;;;;;;;
; Hotkeys.  Customize these to your liking.

^#Left::SendCommand(GO_LEFT, 0)
^#Right::SendCommand(GO_RIGHT, 0)
^#Down::SendCommand(GO_DOWN, 0)
^#Up::SendCommand(GO_UP, 0)
#!Left::SendCommand(MOVE_LEFT, 0)
#!Right::SendCommand(MOVE_RIGHT, 0)
#!Down::SendCommand(MOVE_DOWN, 0)
#!Up::SendCommand(MOVE_UP, 0)
^#S::SendCommand(TOGGLE_STICKY, 0)
^#D::SendCommand(DEBUG_SHOW_CURRENT_WINDOW_HWND, 0)
^#A::ToggleAlwaysOnTop()
^#F::
    MouseGetPos,,,id
    MsgBox, %id%
return
~*Ctrl Up::CheckHideOverlay()
~*LWin Up::CheckHideOverlay()

; Uncomment if you don't want this script appearing in your system tray
; #NoTrayIcon
#SingleInstance Force
#Persistent
MsgNum := DllCall("RegisterWindowMessage", Str, "VIRTUALDESKTOPGRIDSWITCHER_COMMAND")

exeName := "VirtualDesktopGridSwitcher.exe"

; Launch VirtualDesktopGridManager if it's not already running.
DetectHiddenWindows, On
If !WinExist("ahk_exe " . exeName) {
    Run "../VirtualDesktopGridSwitcher.exe"
}

; All commands
GO_UP := 1
GO_LEFT := 2
GO_RIGHT := 3
GO_DOWN := 4
MOVE_UP := 5
MOVE_LEFT := 6
MOVE_RIGHT := 7
MOVE_DOWN := 8
TOGGLE_STICKY := 10
DEBUG_SHOW_CURRENT_WINDOW_HWND := 11
SET_HWND_MESSAGE_TARGET := 12
SWITCHED_DESKTOP := 13
QUIT := 14

OnMessage(MsgNum, "ReceiveMessage")
myHwnd := HexToDec(A_ScriptHwnd)
SendCommand(SET_HWND_MESSAGE_TARGET, myHwnd)

desktopName := Object()
desktopName[0] := "Main"
desktopName[1] := "Work"
desktopName[2] := ""
desktopName[3] := "Chat"
desktopName[4] := ""
desktopName[5] := ""
desktopName[6] := ""
desktopName[7] := "BF"
desktopName[8] := "Music"
return

; Return an HWND that will receive our commands.
GetTargetHwnd() {
    global exeName
    DetectHiddenWindows, On
    WinGet, a, List, ahk_exe %exeName%
    Loop, %a% {
        id := a%A_Index%
        WinGetClass, cls, ahk_id %id%
        ; Skip the "GDI+" window
        If(RegExMatch(cls, "^GDI") = 0) {
            return id
        }
    }
}

; Send a command to VirtualDesktopGridSwitcher
SendCommand(cmd, value) {
    ; All variables are global unless declared to be local
    global
    local id
    id := GetTargetHwnd()
    PostMessage, %MsgNum%, %cmd%, %value%, , ahk_id %id%
}

; Called when VirtualDesktopGridSwitcher sends us a message
ReceiveMessage(cmd, value, msg, hwnd) {
    ; All variables are global unless declared to be local
    global
	local num
	if (cmd = SWITCHED_DESKTOP) {
	    num := value + 1
	    ShowOverlay("Desktop " + num, desktopName[value])
	} else {
	    MsgBox, %cmd%, %value%
	}
}

HexToDec(hex) {
	result := hex + 0
	; result .= ""
	return result
}

ShowOverlay(title, message) {
    SysGet, primary, MonitorPrimary
    SysGet, monitor, Monitor, %primary%
	width := 200
	height := 50
	padding := 100
	x := monitorLeft + ((monitorRight - monitorLeft) / 2) - (width / 2)
	y := monitorBottom - height - padding
    SplashImage, Icons/1.ico, BX%x%Y%y%W%width%H%height%, %message%, %title%, ,
}

HideOverlay() {
    SplashImage, Off
}

ShouldHideOverlay() {
	if(GetKeyState("Ctrl", "P") = 0 && GetKeyState("LWin", "P") = 0) {
	    return 1
	} else {
	    return 0
	}
}

CheckHideOverlay() {
    if(ShouldHideOverlay() = 1) {
	    HideOverlay()
	}
ToggleAlwaysOnTop(hwnd := "") {
    if(hwnd == "") {
        hwnd := WinExist("A")
    }
    WinSet, AlwaysOnTop, Toggle, ahk_id %hwnd%
    ;WinGet, ExStyle, ExStyle, ahk_id %hwnd%
    ;if(ExStyle & 0x8) {
    ;    message := "Always on Top Enabled"
    ;} else {
    ;    message := "Always on Top Disabled"
    ;}
    ;TrayTip, , %message%, 1, 0x10
}

}

;;;;;;;
; Hotkeys.  Customize these to your liking.

^#Left::SendCommand(GO_LEFT, 0)
^#Right::SendCommand(GO_RIGHT, 0)
^#Down::SendCommand(GO_DOWN, 0)
^#Up::SendCommand(GO_UP, 0)
#!Left::SendCommand(MOVE_LEFT, 0)
#!Right::SendCommand(MOVE_RIGHT, 0)
#!Down::SendCommand(MOVE_DOWN, 0)
#!Up::SendCommand(MOVE_UP, 0)
^#S::SendCommand(TOGGLE_STICKY, 0)
^#D::SendCommand(DEBUG_SHOW_CURRENT_WINDOW_HWND, 0)
^#A::ToggleAlwaysOnTop()
^#F::
    MouseGetPos,,,id
    MsgBox, %id%
return
~*Ctrl Up::CheckHideOverlay()
~*LWin Up::CheckHideOverlay()


KeyHelp close after 5s

KeyHelp close after 5s

global Arg

Functions:
    @("Help", "帮助信息")
    @("KeyHelp", "置顶的按键帮助信息")
    @("AhkRun", "使用 Ahk 的 Run() 运行 `; command", true)
    @("CmdRun", "使用 cmd 运行 : command", true)
    @("CmdRunOnly", "只使用 cmd 运行，忽略 mintty")
    @("WinRRun", "使用 win + r 运行", true)
    @("Dictionary", "有道词典在线翻译", true)
    @("RunAndDisplay", "使用 cmd 运行，并显示结果", true)
    @("ReloadFiles", "重新加载需要搜索的文件")
    @("Clip", "显示剪切板内容")
    @("Calc", "计算器")
    @("SearchOnBaidu", "使用 Baidu（百度）搜索剪切板或输入内容", true)
    @("SearchOnGoogle", "使用 Google（谷歌）搜索剪切板或输入内容", true)
    @("SearchOnBing", "使用 Bing（必应）搜索剪切板或输入内容", true)
    @("SearchOnTaobao", "使用 Taobao（淘宝）搜索剪切板或输入内容")
    @("SearchOnJingdong", "使用 JD（京东）搜索剪切板或输入内容")
    @("EditConfig", "编辑配置文件")
    @("ClearClipboardFormat", "清除剪切板中文字的格式")
    @("RunClipboard", "使用 ahk 的 Run 运行剪切板内容")
    @("EmptyRecycle", "清空回收站")
    @("Logoff", "注销 登出")
    @("RestartMachine", "重启")
    @("ShutdownMachine", "关机")
    @("SuspendMachine", "挂起 睡眠 待机")
    @("HibernateMachine", "休眠")
    @("TurnMonitorOff", "关闭显示器")
    @("T2S", "将剪切板或输入内容中的繁体转成简体")
    @("S2T", "将剪切板或输入内容中的简体转成繁体")
    @("ShowIp", "显示 IP")
    @("Calendar", "用浏览器打开万年历")
    @("CleanupRank", "清理命令权重中的无效命令")
    @("ArgTest", "参数测试：ArgTest arg1,arg2,...")

    if (IsLabel("ReservedFunctions"))
    {
        GoSub, ReservedFunctions
    }
return

Help:
    DisplayResult(KeyHelpText() . GetAllFunctions())
return

KeyHelp:
    ToolTip, % KeyHelpText()
    SetTimer, RemoveToolTip, 5000
return

CmdRun:
    RunWithCmd(Arg)
return

CmdRunOnly:
    RunWithCmd(Arg, true)
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 . " 个参数：" . 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 == "" ? clipboard : Arg

    url := "http://fanyi.youdao.com/openapi.do?keyfrom=YouDaoCV&key=659600698&"
            . "type=data&doctype=json&version=1.2&q=" UrlEncode(word)

    jsonText := StrReplace(UrlDownloadToString(url), "-phonetic", "_phonetic")

    if (jsonText == "no query")
    {
        DisplayResult("未查到结果")
        return
    }

    parsed := JSON.Load(jsonText)
	result := parsed.query

	if (parsed.basic.uk_phonetic != "" && parsed.basic.us_phonetic != "")
	{
		result .= " UK: [" parsed.basic.uk_phonetic "], US: [" parsed.basic.us_phonetic "]`n"
	}
	else if (parsed.basic.phonetic != "")
	{
		result .= " [" parsed.basic.phonetic "]`n"
	}
    else
    {
        result .= "`n"
    }

	if (parsed.basic.explains.Length() > 0)
	{
		result .= "`n"
		for index, explain in parsed.basic.explains
		{
			result .= "    * " explain "`n"
		}
	}

	if (parsed.web.Length() > 0)
	{
		result .= "`n----`n"

		for i, element in parsed.web
		{
			result .= "`n    * " element.key
			for j, value in element.value
			{
				if (j == 1)
				{
					result .= "`n       "
				}
				else
				{
					result .= "`; "
				}

				result .= value
			}
		}
	}

    DisplayResult(result)
    clipboard := result
return

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

T2S:
    text := Arg == "" ? clipboard : Arg
    clipboard := ""
    clipboard := Kanji_t2s(text)
    ClipWait
    DisplayResult(clipboard)
return

S2T:
    text := Arg == "" ? clipboard : Arg
    clipboard := ""
    clipboard := Kanji_s2t(text)
    ClipWait
    DisplayResult(clipboard)
return

ClearClipboardFormat:
    clipboard := clipboard
return

SearchOnBaidu:
    word := Arg == "" ? clipboard : Arg

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

SearchOnGoogle:
    word := UrlEncode(Arg == "" ? clipboard : Arg)

    Run, https://www.google.com.hk/#newwindow=1&safe=strict&q=%word%
return

SearchOnBing:
    word := Arg == "" ? clipboard : Arg

    Run, http://cn.bing.com/search?q=%word%
return

SearchOnTaobao:
    word := Arg == "" ? clipboard : Arg

    Run, https://s.taobao.com/search?q=%word%
return

SearchOnJingdong:
    word := Arg == "" ? clipboard : Arg

    Run, http://search.jd.com/Search?keyword=%word%&enc=utf-8
return

RunClipboard:
    Run, %clipboard%
return

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

RunAndDisplay:
    DisplayResult(RunAndGetOutput(Arg))
return

WinRRun:
    Send, #r
    Sleep, 100
    Send, %Arg%
    Send, {enter}
return

Logoff:
    Shutdown, 0
return

ShutdownMachine:
    Shutdown, 1
return

RestartMachine:
    Shutdown, 2
return

HibernateMachine:
    ; 参数 #1: 使用 1 代替 0 来进行休眠而不是挂起。
	; 参数 #2: 使用 1 代替 0 来立即挂起而不询问每个应用程序以获得许可。
	; 参数 #3: 使用 1 而不是 0 来禁止所有的唤醒事件。
    DllCall("PowrProf\SetSuspendState", "int", 1, "int", 0, "int", 0)
return

SuspendMachine:
    DllCall("PowrProf\SetSuspendState", "int", 0, "int", 0, "int", 0)
return

TurnMonitorOff:
	; 关闭显示器:
	SendMessage, 0x112, 0xF170, 2,, Program Manager
	; 0x112 is WM_SYSCOMMAND, 0xF170 is SC_MONITORPOWER.
	; 对上面命令的注释: 使用 -1 代替 2 来打开显示器.
	; 使用 1 代替 2 来激活显示器的节能模式.
return

EmptyRecycle:
    FileRecycleEmpty,
return

global Arg

Functions:
    @("Help", "帮助信息")
    @("KeyHelp", "置顶的按键帮助信息")
    @("AhkRun", "使用 Ahk 的 Run() 运行 `; command", true)
    @("CmdRun", "使用 cmd 运行 : command", true)
    @("CmdRunOnly", "只使用 cmd 运行，忽略 mintty")
    @("WinRRun", "使用 win + r 运行", true)
    @("Dictionary", "有道词典在线翻译", true)
    @("RunAndDisplay", "使用 cmd 运行，并显示结果", true)
    @("ReloadFiles", "重新加载需要搜索的文件")
    @("Clip", "显示剪切板内容")
    @("Calc", "计算器")
    @("SearchOnBaidu", "使用 Baidu（百度）搜索剪切板或输入内容", true)
    @("SearchOnGoogle", "使用 Google（谷歌）搜索剪切板或输入内容", true)
    @("SearchOnBing", "使用 Bing（必应）搜索剪切板或输入内容", true)
    @("SearchOnTaobao", "使用 Taobao（淘宝）搜索剪切板或输入内容")
    @("SearchOnJingdong", "使用 JD（京东）搜索剪切板或输入内容")
    @("EditConfig", "编辑配置文件")
    @("ClearClipboardFormat", "清除剪切板中文字的格式")
    @("RunClipboard", "使用 ahk 的 Run 运行剪切板内容")
    @("EmptyRecycle", "清空回收站")
    @("Logoff", "注销 登出")
    @("RestartMachine", "重启")
    @("ShutdownMachine", "关机")
    @("SuspendMachine", "挂起 睡眠 待机")
    @("HibernateMachine", "休眠")
    @("TurnMonitorOff", "关闭显示器")
    @("T2S", "将剪切板或输入内容中的繁体转成简体")
    @("S2T", "将剪切板或输入内容中的简体转成繁体")
    @("ShowIp", "显示 IP")
    @("Calendar", "用浏览器打开万年历")
    @("CleanupRank", "清理命令权重中的无效命令")
    @("ArgTest", "参数测试：ArgTest arg1,arg2,...")

    if (IsLabel("ReservedFunctions"))
    {
        GoSub, ReservedFunctions
    }
return

Help:
    DisplayResult(KeyHelpText() . GetAllFunctions())
return

KeyHelp:
    ToolTip, % KeyHelpText()
return

CmdRun:
    RunWithCmd(Arg)
return

CmdRunOnly:
    RunWithCmd(Arg, true)
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 . " 个参数：" . 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 == "" ? clipboard : Arg

    url := "http://fanyi.youdao.com/openapi.do?keyfrom=YouDaoCV&key=659600698&"
            . "type=data&doctype=json&version=1.2&q=" UrlEncode(word)

    jsonText := StrReplace(UrlDownloadToString(url), "-phonetic", "_phonetic")

    if (jsonText == "no query")
    {
        DisplayResult("未查到结果")
        return
    }

    parsed := JSON.Load(jsonText)
	result := parsed.query

	if (parsed.basic.uk_phonetic != "" && parsed.basic.us_phonetic != "")
	{
		result .= " UK: [" parsed.basic.uk_phonetic "], US: [" parsed.basic.us_phonetic "]`n"
	}
	else if (parsed.basic.phonetic != "")
	{
		result .= " [" parsed.basic.phonetic "]`n"
	}
    else
    {
        result .= "`n"
    }

	if (parsed.basic.explains.Length() > 0)
	{
		result .= "`n"
		for index, explain in parsed.basic.explains
		{
			result .= "    * " explain "`n"
		}
	}

	if (parsed.web.Length() > 0)
	{
		result .= "`n----`n"

		for i, element in parsed.web
		{
			result .= "`n    * " element.key
			for j, value in element.value
			{
				if (j == 1)
				{
					result .= "`n       "
				}
				else
				{
					result .= "`; "
				}

				result .= value
			}
		}
	}

    DisplayResult(result)
    clipboard := result
return

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

T2S:
    text := Arg == "" ? clipboard : Arg
    clipboard := ""
    clipboard := Kanji_t2s(text)
    ClipWait
    DisplayResult(clipboard)
return

S2T:
    text := Arg == "" ? clipboard : Arg
    clipboard := ""
    clipboard := Kanji_s2t(text)
    ClipWait
    DisplayResult(clipboard)
return

ClearClipboardFormat:
    clipboard := clipboard
return

SearchOnBaidu:
    word := Arg == "" ? clipboard : Arg

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

SearchOnGoogle:
    word := UrlEncode(Arg == "" ? clipboard : Arg)

    Run, https://www.google.com.hk/#newwindow=1&safe=strict&q=%word%
return

SearchOnBing:
    word := Arg == "" ? clipboard : Arg

    Run, http://cn.bing.com/search?q=%word%
return

SearchOnTaobao:
    word := Arg == "" ? clipboard : Arg

    Run, https://s.taobao.com/search?q=%word%
return

SearchOnJingdong:
    word := Arg == "" ? clipboard : Arg

    Run, http://search.jd.com/Search?keyword=%word%&enc=utf-8
return

RunClipboard:
    Run, %clipboard%
return

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

RunAndDisplay:
    DisplayResult(RunAndGetOutput(Arg))
return

WinRRun:
    Send, #r
    Sleep, 100
    Send, %Arg%
    Send, {enter}
return

Logoff:
    Shutdown, 0
return

ShutdownMachine:
    Shutdown, 1
return

RestartMachine:
    Shutdown, 2
return

HibernateMachine:
    ; 参数 #1: 使用 1 代替 0 来进行休眠而不是挂起。
	; 参数 #2: 使用 1 代替 0 来立即挂起而不询问每个应用程序以获得许可。
	; 参数 #3: 使用 1 而不是 0 来禁止所有的唤醒事件。
    DllCall("PowrProf\SetSuspendState", "int", 1, "int", 0, "int", 0)
return

SuspendMachine:
    DllCall("PowrProf\SetSuspendState", "int", 0, "int", 0, "int", 0)
return

TurnMonitorOff:
	; 关闭显示器:
	SendMessage, 0x112, 0xF170, 2,, Program Manager
	; 0x112 is WM_SYSCOMMAND, 0xF170 is SC_MONITORPOWER.
	; 对上面命令的注释: 使用 -1 代替 2 来打开显示器.
	; 使用 1 代替 2 来激活显示器的节能模式.
return

EmptyRecycle:
    FileRecycleEmpty,
return


Update to my interpreter. Fixed some stuff and added "Round" and "Join"

#SingleInstance
SetBatchLines, -1
DllCall("AllocConsole")

FilePath = %1% ; Pull from command line parameter

if !FilePath
	FileSelectFile, FilePath,,, Select a noops source file, Noops Source (*.noops)

FileRead, Script, %FilePath%
MyNoops := new noops(Script)
MyNoops.Execute()
MsgBox

class noops
{
	static Params := {Var: -3
	, Print: -1, Add: 2, Sub: 2
	, While: -1, Div: 2, Mul: 2
	, Less: 2, Char: 1, Asc: 1
	, Not: 1, Round: 1, Join: -1}

	__New(Script)
	{
		this.Variables := []
		this.Script := Script
	}

	Execute()
	{
		this.Lines := StrSplit(this.Script, "`n", "`r")
		while this.Lines.MaxIndex()
		{
			this.Line := this.Lines.Remove(1)
			this.Process(StrSplit(this.Line, " "))
		}
	}

	Process(Words, Num=0)
	{
		Out := []
		if Num < 0
			Num := ~0
		while Words.MaxIndex()
		{
			Word := Words.Remove(1)

			if this.Params.HasKey(Word)
			{
				ParamCount := this.Params[Word]
				Params := this.Process(Words, ParamCount)
				Result := this["_" Word].(this, Params*)
				Out.Insert(Result)
			}
			else
				Out.Insert(Word)

			if (Out.MaxIndex() >= Num)
				break
		}
		return Out
	}

	Resolve(Word, Separator=" ")
	{
		if IsObject(Word)
		{
			for each, Word in Word
				Out .= Separator this.Resolve(Word)
			return SubStr(Out, StrLen(Separator)+1)
		}
		return this.Variables.HasKey(Word) ? this.Variables[Word] : Word
	}

	_Var(varname, isornot, value*)
	{
		Value := this.Resolve(Value)
		if (this.Resolve(isornot) = "is")
			this.Variables[varname] := Value
	}

	_Print(Text*)
	{
		FileOpen("$CONOUT", "w").Write(this.Resolve(Text))
	}

	_Add(Addend1, Addend2)
	{
		return this.Resolve(Addend1)+this.Resolve(Addend2)
	}

	_Sub(Minuend, Subtrahend)
	{
		return this.Resolve(Minuend) - this.Resolve(Subtrahend)
	}

	_Mul(Multiplier1, Multiplier2)
	{
		return this.Resolve(Multiplier1) * this.Resolve(Multiplier2)
	}

	_Div(Dividend, Divisor)
	{
		return this.Resolve(Dividend) / this.Resolve(Divisor)
	}

	_Less(Left, Right)
	{
		return this.Resolve(Left) < this.Resolve(Right)
	}

	_ID(Variable)
	{
		this.Variables[Variable] -= 1
	}

	_While(Statement)
	{
		Expression := StrSplit(this.Line, " ")
		Expression.Remove(1) ; the word "While"

		Level := IndentLevel(this.Lines[1])
		while IndentLevel(this.Lines[1]) >= Level
			SubScript .= SubStr(this.Lines.Remove(1), Level) "`n"

		SubScript := new noops(SubScript)
		SubScript.Variables := this.Variables

		while this.Resolve(this.Process(Expression.Clone()))
			SubScript.Execute()
	}

	_Char(Asc)
	{
		return Chr(this.Resolve(Asc))
	}

	_Asc(Char)
	{
		return Asc(this.Resolve(Char))
	}

	_Not(Value)
	{
		return !this.Resolve(Value)
	}

	_Round(Value)
	{
		return Round(this.Resolve(Value))
	}

	_Join(Values*)
	{
		return this.Resolve(Values, "")
	}
}

IndentLevel(String)
{
	return RegExMatch(String, "^ *\K[^ ]")
}

#SingleInstance

FileName = %1% ; Pull from command line parameter

if !FileName
	FileSelectFile, FileName,,, Select a noops source file, Noops Source (*.noops)

FileRead, Script, %1%
MyNoops := new noops(Script)
MyNoops.Execute()
MsgBox

class noops
{
	static Params := {Var: -3
	, Print: -1, Add: 2, Sub: 2
	, While: -1, Div: 2, Mul: 2
	, Less: 2, Char: 1, Asc: 1
	, Not: 1}

	__New(Script)
	{
		this.Variables := []
		this.Script := Script
	}

	Execute()
	{
		this.Lines := StrSplit(this.Script, "`n", "`r")
		while this.Lines.MaxIndex()
		{
			this.Line := this.Lines.Remove(1)
			this.Process(StrSplit(this.Line, " "))
		}
	}

	Process(Words, Num=0)
	{
		Out := []
		if Num < 0
			Num := ~0
		while Words.MaxIndex()
		{
			Word := Words.Remove(1)

			if this.Params.HasKey(Word)
			{
				ParamCount := this.Params[Word]
				Params := this.Process(Words, ParamCount)
				Result := this["_" Word].(this, Params*)
				Out.Insert(Result)
			}
			else
				Out.Insert(Word)

			if (Out.MaxIndex() >= Num)
				break
		}
		return Out
	}

	Resolve(Word)
	{
		if IsObject(Word)
		{
			for each, Word in Word
				Out .= " " this.Resolve(Word)
			return SubStr(Out, 2)
		}
		return this.Variables.HasKey(Word) ? this.Variables[Word] : Word
	}

	_Var(varname, isornot, value*)
	{
		Value := this.Resolve(Value)
		if (this.Resolve(isornot) = "is")
			this.Variables[varname] := Value
	}

	_Print(Text*)
	{
		Print(this.Resolve(Text), "")
		;MsgBox, % this.Resolve(Text)
	}

	_Add(Addend1, Addend2)
	{
		return this.Resolve(Addend1)+this.Resolve(Addend2)
	}

	_Sub(Minuend, Subtrahend)
	{
		return this.Resolve(Minuend) - this.Resolve(Subtrahend)
	}

	_Mul(Multiplier1, Multiplier2)
	{
		return this.Resolve(Multiplier1) * this.Resolve(Multiplier2)
	}

	_Div(Dividend, Divisor)
	{
		return this.Resolve(Dividend) / this.Resolve(Divisor)
	}

	_Less(Left, Right)
	{
		return this.Resolve(Left) < this.Resolve(Right)
	}

	_ID(Variable)
	{
		this.Variables[Variable] -= 1
	}

	_While(Statement)
	{
		Expression := StrSplit(this.Line, " ")
		Expression.Remove(1) ; the word "While"

		Level := IndentLevel(this.Lines[1])
		while IndentLevel(this.Lines[1]) >= Level
			SubScript .= SubStr(this.Lines.Remove(1), Level) "`n"

		SubScript := new noops(SubScript)
		SubScript.Variables := this.Variables

		while this.Resolve(this.Process(Expression.Clone()))
			SubScript.Execute()
	}

	_Char(Asc)
	{
		return Chr(this.Resolve(Asc))
	}

	_Asc(Char)
	{
		return Asc(this.Resolve(Char))
	}

	_Not(Value)
	{
		return !this.Resolve(Value)
	}
}

IndentLevel(String)
{
	return RegExMatch(String, "^ *\K[^ ]")
}

Join(Array, String=" ")
{
	for Key, Value in Array
		Out .= String Value
	Return SubStr(Out, StrLen(String)+1)
}


Fix Kanji.ahk

Fix Kanji.ahk

Kanji_s2t(text){
    Return Kanji(text, 1)
}

Kanji_t2s(text){
    Return Kanji(text)
}

; https://autohotkey.com/boards/viewtopic.php?t=9133
Kanji(s,r:=""){ ;  r= 1-简繁 ""-繁简
    static f:=__Kanji()
    n:=r?f.1:f.2
    Loop,Parse,s
        b.=n[A_Loopfield]?n[A_Loopfield]:A_Loopfield
    Return b
}

__Kanji(){
    FileRead,s,% A_ScriptDir "\lib\Kanji\Kanji.txt"
    f:=[], h:=[],s:=Trim(s)
    Loop,Parse,s,% A_Space
        f[a:=SubStr(A_Loopfield,1,1)]:=b:=SubStr(A_Loopfield,2),h[b]:=a
    Return [f,h]
}

Kanji_s2t(text){
    Return Kanji(text, 1)
}

Kanji_t2s(text){
    Return Kanji(text)
}

; https://autohotkey.com/boards/viewtopic.php?t=9133
Kanji(s,r:=""){ ;  r= 1-简繁 ""-繁简
    static f:=__Kanji()
    n:=r?f.1:f.2
    Loop,Parse,s
        b.=n[A_Loopfield]?n[A_Loopfield]:A_Loopfield
    Return b
}

__Kanji(){
    FileRead,s,% A_ScriptDir "\Kanji\Kanji.txt"
    f:=[], h:=[],s:=Trim(s)
    Loop,Parse,s,% A_Space
        f[a:=SubStr(A_Loopfield,1,1)]:=b:=SubStr(A_Loopfield,2),h[b]:=a
    Return [f,h]
}


Change QR window size

Change QR window size

global Arg

; 这里可能会调用一些不包含在源码包里的第三方库
ReservedFunctions:
    if (!FileExist(A_ScriptDir "\Lib\Reserved"))
    {
        return
    }

    @("GenerateQR", "生成二维码")
return

; GenerateQR begin

GenerateQR:
    word := Arg == "" ? clipboard : Arg
    QRfile := GenerateQR(word)

    GdipToken := Gdip_Startup()

    bitmap := Gdip_CreateBitmapFromFile(QRfile)
    imageWidth := Gdip_GetImageWidth(bitmap)
    Gdip_DisposeImage(bitmap)
    Gdip_Shutdown(GdipToken)

    Gui, QR:Destroy
    Gui, QR:Add, Picture, x50 y50 w%imageWidth% h-1 gQRSaveAs, % file := QRfile
    Gui, QR:Show, % "w" imageWidth + 100 " h" imageWidth + 100
return

QRSaveAs:
    Fileselectfile, selectedFile, s16, 二维码.png, 另存为, PNG图片(*.png)
    if (selectedFile == "")
    {
        return
    }

    if (!RegExMatch(selectedFile,"i)\.png"))
    {
        selectedFile .= ".png"
    }

    FileMove, %file%, %selectedFile%, 1
    GUI, QR:Destroy
return

QrGuiEscape:
QrGuiClose:
    FileDelete, %file%
    GUI, QR:Destroy
return

GenerateQR(string, file = "")
{
    if (file == "")
    {
        file := A_Temp "\RunZ.QR.png"
    }

    DllCall(A_ScriptDir "\Lib\Reserved\quricol32.dll\GeneratePNG"
        , "str", file, "str", string, "int", 4, "int", 2, "int", 0)
    return file
}

; GenerateQR end

global Arg

; 这里可能会调用一些不包含在源码包里的第三方库
ReservedFunctions:
    if (!FileExist(A_ScriptDir "\Lib\Reserved"))
    {
        return
    }

    @("GenerateQR", "生成二维码")
return

; GenerateQR begin

GenerateQR:
    word := Arg == "" ? clipboard : Arg
    QRfile := GenerateQR(word)

    GdipToken := Gdip_Startup()

    bitmap := Gdip_CreateBitmapFromFile(QRfile)
    imageWidth := Gdip_GetImageWidth(bitmap)
    Gdip_DisposeImage(bitmap)
    Gdip_Shutdown(GdipToken)

    Gui, QR:Destroy
    Gui, QR:Add, Picture, w%imageWidth% h-1 gQRSaveAs, % file := QRfile
    Gui, QR:Show, % "w" imageWidth + 20
return

QRSaveAs:
    Fileselectfile, selectedFile, s16, 二维码.png, 另存为, PNG图片(*.png)
    if (selectedFile == "")
    {
        return
    }

    if (!RegExMatch(selectedFile,"i)\.png"))
    {
        selectedFile .= ".png"
    }

    FileMove, %file%, %selectedFile%, 1
    GUI, QR:Destroy
return

QrGuiEscape:
QrGuiClose:
    FileDelete, %file%
    GUI, QR:Destroy
return

GenerateQR(string, file = "")
{
    if (file == "")
    {
        file := A_Temp "\RunZ.QR.png"
    }

    DllCall(A_ScriptDir "\Lib\Reserved\quricol32.dll\GeneratePNG"
        , "str", file, "str", string, "int", 4, "int", 2, "int", 0)
    return file
}

; GenerateQR end