Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

AHK Syntax Highlighting using Javascript/CSS


  • Please log in to reply
22 replies to this topic
supergrass
  • Members
  • 51 posts
  • Last active: Mar 26 2015 12:13 AM
  • Joined: 21 Feb 2007
I have been looking for ahk syntax highlighting for any website (no server side required).

I came across this website: Alex Gorbatchev Syntax Highlighter. The code is formatted using separate "brush" files. There are many languages already covered.

The system relies on javascript definition files which defines css styles and regex terms. For some reason it does not seem to work on autohotkey.net.

Posted Image

I have created a proof of concept here using the testsuite.ahk file that comes with Finc's SciTE editor.

You can see I have not got far with the highlighting. Maybe someone with some css/javascript experience can take this further?

[Edit] I have updated the test page with the new brush. Thanks! :D

FYI Here is a version with some enhancements such as showing/hiding line numbers. I think the forum pages on Gorbatchev show some other tricks.

Here is another javascript site which claims to auto-recognize languages!

majkinetor
  • Moderators
  • 4512 posts
  • Last active: May 20 2019 07:41 AM
  • Joined: 24 May 2006
Thanks.
Posted Image

n-l-i-d
  • Guests
  • Last active:
  • Joined: --
This is as far as I got with the shBrushAhk.js. Labels doesn't seem to work.

SyntaxHighlighter.brushes.Ahk = function()
{
var commands = 'AutoTrim BlockInput Break Click ClipWait Continue Control ControlClick ControlFocus ControlGet' +
' ControlGetFocus ControlGetPos ControlGetText ControlMove ControlSend ControlSendRaw ControlSetText CoordMode Critical DetectHiddenText' +
' DetectHiddenWindows Drive DriveGet DriveSpaceFree Edit Else EnvAdd EnvDiv EnvGet EnvMult' +
' EnvSet EnvSub EnvUpdate Exit ExitApp FileAppend FileCopy FileCopyDir FileCreateDir FileCreateShortcut' +
' FileDelete FileGetAttrib FileGetShortcut FileGetSize FileGetTime FileGetVersion FileInstall FileMove FileMoveDir FileRead' +
' FileReadLine FileRecycle FileRecycleEmpty FileRemoveDir FileSelectFile FileSelectFolder FileSetAttrib FileSetTime FormatTime GetKeyState' +
' Gosub Goto GroupActivate GroupAdd GroupClose GroupDeactivate Gui GuiControl GuiControlGet Hotkey' +
' If IfEqual IfExist IfGreater IfGreaterOrEqual IfInString IfLess IfLessOrEqual IfMsgBox IfNotEqual' +
' IfNotExist IfNotInString IfWinActive IfWinExist IfWinNotActive IfWinNotExist ImageSearch IniDelete IniRead IniWrite' +
' Input InputBox KeyHistory KeyWait ListHotkeys ListLines ListVars Loop Menu MouseClick' +
' MouseClickDrag MouseGetPos MouseMove MsgBox OnExit OutputDebug Pause PixelGetColor PixelSearch PostMessage' +
' Process Progress Random RegDelete RegRead RegWrite Reload Repeat Return Run' +
' RunAs RunWait Send SendEvent SendInput SendMessage SendMode SendPlay SendRaw SetBatchLines' +
' SetCapslockState SetControlDelay SetDefaultMouseSpeed SetEnv SetFormat SetKeyDelay SetMouseDelay SetNumlockState SetScrollLockState SetStoreCapslockMode' +
' SetTimer SetTitleMatchMode SetWinDelay SetWorkingDir Shutdown Sleep Sort SoundBeep SoundGet SoundGetWaveVolume' +
' SoundPlay SoundSet SoundSetWaveVolume SplashImage SplashTextOff SplashTextOn SplitPath StatusBarGetText StatusBarWait StringCaseSense' +
' StringGetPos StringLeft StringLen StringLower StringMid StringReplace StringRight StringSplit StringTrimLeft StringTrimRight' +
' StringUpper Suspend SysGet Thread ToolTip Transform TrayTip URLDownloadToFile While WinActivate' +
' WinActivateBottom WinClose WinGet WinGetActiveStats WinGetActiveTitle WinGetClass WinGetPos WinGetText WinGetTitle WinHide' +
' WinKill WinMaximize WinMenuSelectItem WinMinimize WinMinimizeAll WinMinimizeAllUndo WinMove WinRestore WinSet WinSetTitle' +
' WinShow WinWait WinWaitActive WinWaitClose WinWaitNotActive';

var keys = 'Shift LShift RShift Alt' +
' LAlt RAlt Control LControl RControl Ctrl LCtrl RCtrl LWin RWin' +
' AppsKey AltDown AltUp ShiftDown ShiftUp CtrlDown CtrlUp LWinDown LWinUp RWinDown' +
' RWinUp LButton RButton MButton WheelUp WheelDown WheelLeft WheelRight XButton1 XButton2' +
' Joy1 Joy2 Joy3 Joy4 Joy5 Joy6 Joy7 Joy8 Joy9 Joy10' +
' Joy11 Joy12 Joy13 Joy14 Joy15 Joy16 Joy17 Joy18 Joy19 Joy20' +
' Joy21 Joy22 Joy23 Joy24 Joy25 Joy26 Joy27 Joy28 Joy29 Joy30' +
' Joy31 Joy32 JoyX JoyY JoyZ JoyR JoyU JoyV JoyPOV JoyName' +
' JoyButtons JoyAxes JoyInfo Space Tab Enter Escape Esc BackSpace BS' +
' Delete Del Insert Ins PGUP PGDN Home End Up Down' +
' Left Right PrintScreen CtrlBreak Pause ScrollLock CapsLock NumLock Numpad0 Numpad1' +
' Numpad2 Numpad3 Numpad4 Numpad5 Numpad6 Numpad7 Numpad8 Numpad9 NumpadMult NumpadAdd' +
' NumpadSub NumpadDiv NumpadDot NumpadDel NumpadIns NumpadClear NumpadUp NumpadDown NumpadLeft NumpadRight' +
' NumpadHome NumpadEnd NumpadPgup NumpadPgdn NumpadEnter F1 F2 F3 F4 F5' +
' F6 F7 F8 F9 F10 F11 F12 F13 F14 F15' +
' F16 F17 F18 F19 F20 F21 F22 F23 F24 Browser_Back' +
' Browser_Forward Browser_Refresh Browser_Stop Browser_Search Browser_Favorites Browser_Home Volume_Mute Volume_Down Volume_Up Media_Next' +
' Media_Prev Media_Stop Media_Play_Pause Launch_Mail Launch_Media Launch_App1 Launch_App2';

var funcs = 'Abs ACos Asc ASin ATan Ceil Chr Cos DllCall Exp' +
' FileExist Floor GetKeyState IL_Add IL_Create IL_Destroy InStr IsFunc IsLabel Ln' +
' Log LV_Add LV_Delete LV_DeleteCol LV_GetCount LV_GetNext LV_GetText LV_Insert LV_InsertCol LV_Modify' +
' LV_ModifyCol LV_SetImageList Mod NumGet NumPut OnMessage RegExMatch RegExReplace RegisterCallback Round' +
' SB_SetIcon SB_SetParts SB_SetText Sin Sqrt StrLen SubStr Tan TV_Add TV_Delete' +
' TV_GetChild TV_GetCount TV_GetNext TV_Get TV_GetParent TV_GetPrev TV_GetSelection TV_GetText TV_Modify VarSetCapacity' +
' WinActive WinExist';

var keywords = 'Pixel Mouse Screen Relative RGB LTrim RTrim Join Low BelowNormal' +
' Normal AboveNormal High Realtime ahk_id ahk_pid ahk_class ahk_group Between Contains' +
' In Is Integer Float IntegerFast FloatFast Number Digit Xdigit Alpha' +
' Upper Lower Alnum Time Date Not Or And AlwaysOnTop Topmost' +
' Top Bottom Transparent TransColor Redraw Region ID IDLast ProcessName MinMax' +
' ControlList Count List Capacity StatusCD Eject Lock Unlock Label FileSystem' +
' Label SetLabel Serial Type Status static global local ByRef Seconds' +
' Minutes Hours Days Read Parse Logoff Close Error Single Tray' +
' Add Rename Check UnCheck ToggleCheck Enable Disable ToggleEnable Default NoDefault' +
' Standard NoStandard Color Delete DeleteAll Icon NoIcon Tip Click Show' +
' MainWindow NoMainWindow UseErrorLevel Text Picture Pic GroupBox Button Checkbox Radio' +
' DropDownList DDL ComboBox ListBox ListView DateTime MonthCal Slider StatusBar Tab' +
' Tab2 TreeView UpDown IconSmall Tile Report SortDesc NoSort NoSortHdr Grid' +
' Hdr AutoSize Range xm ym ys xs xp yp Font' +
' Resize Owner Submit NoHide Minimize Maximize Restore NoActivate NA Cancel' +
' Destroy Center Margin MaxSize MinSize OwnDialogs GuiEscape GuiClose GuiSize GuiContextMenu' +
' GuiDropFiles TabStop Section AltSubmit Wrap HScroll VScroll Border Top Bottom' +
' Buttons Expand First ImageList Lines WantCtrlA WantF2 Vis VisFirst Number' +
' Uppercase Lowercase Limit Password Multi WantReturn Group Background bold italic' +
' strike underline norm BackgroundTrans Theme Caption Delimiter MinimizeBox MaximizeBox SysMenu' +
' ToolWindow Flash Style ExStyle Check3 Checked CheckedGray ReadOnly Password Hidden' +
' Left Right Center NoTab Section Move Focus Hide Choose ChooseString' +
' Text Pos Enabled Disabled Visible LastFound LastFoundExist AltTab ShiftAltTab AltTabMenu' +
' AltTabAndMenu AltTabMenuDismiss NoTimers Interrupt Priority WaitClose Wait Exist Close Blind' +
' Unicode Asc Chr Deref Mod Pow Exp Sqrt' +
' Log Ln Round Ceil Floor Abs Sin Cos Tan ASin' +
' ACos ATan BitNot BitAnd BitOr BitXOr BitShiftLeft BitShiftRight Yes No' +
' Ok Cancel Abort Retry Ignore TryAgain On Off All HKEY_LOCAL_MACHINE' +
' HKEY_USERS HKEY_CURRENT_USER HKEY_CLASSES_ROOT HKEY_CURRENT_CONFIG HKLM HKU HKCU HKCR HKCC REG_SZ' +
' REG_EXPAND_SZ REG_MULTI_SZ REG_DWORD REG_BINARY';

var variables = 'A_AhkPath A_AhkVersion A_AppData A_AppDataCommon A_AutoTrim A_BatchLines A_CaretX A_CaretY A_ComputerName ' +
'A_ControlDelay A_Cursor A_DD A_DDD A_DDDD A_DefaultMouseSpeed A_Desktop A_DesktopCommon A_DetectHiddenText A_DetectHiddenWindows ' +
'A_EndChar A_EventInfo A_ExitReason A_FormatFloat A_FormatInteger A_Gui A_GuiEvent A_GuiControl A_GuiControlEvent A_GuiHeight ' +
'A_GuiWidth A_GuiX A_GuiY A_Hour A_IconFile A_IconHidden A_IconNumber A_IconTip A_Index A_IPAddress1 ' +
'A_IPAddress2 A_IPAddress3 A_IPAddress4 A_ISAdmin A_IsCompiled A_IsSuspended A_KeyDelay A_Language A_LastError A_LineFile ' +
'A_LineNumber A_LoopField A_LoopFileAttrib A_LoopFileDir A_LoopFileExt A_LoopFileFullPath A_LoopFileLongPath A_LoopFileName A_LoopFileShortName A_LoopFileShortPath ' +
'A_LoopFileSize A_LoopFileSizeKB A_LoopFileSizeMB A_LoopFileTimeAccessed A_LoopFileTimeCreated A_LoopFileTimeModified A_LoopReadLine A_LoopRegKey A_LoopRegName A_LoopRegSubkey ' +
'A_LoopRegTimeModified A_LoopRegType A_MDAY A_Min A_MM A_MMM A_MMMM A_Mon A_MouseDelay A_MSec ' +
'A_MyDocuments A_Now A_NowUTC A_NumBatchLines A_OSType A_OSVersion A_PriorHotkey A_ProgramFiles A_Programs A_ProgramsCommon ' +
'A_ScreenHeight A_ScreenWidth A_ScriptDir A_ScriptFullPath A_ScriptName A_Sec A_Space A_StartMenu A_StartMenuCommon A_Startup ' +
'A_StartupCommon A_StringCaseSense A_Tab A_Temp A_ThisHotkey A_ThisMenu A_ThisMenuItem A_ThisMenuItemPos A_TickCount A_TimeIdle ' +
'A_TimeIdlePhysical A_TimeSincePriorHotkey A_TimeSinceThisHotkey A_TitleMatchMode A_TitleMatchModeSpeed A_UserName A_WDay A_WinDelay A_WinDir A_WorkingDir ' +
'A_YDay A_YEAR A_YWeek A_YYYY Clipboard ClipboardAll ComSpec ErrorLevel ProgramFiles True False';

var directives = 'AllowSameLineComments ClipboardTimeout CommentFlag ErrorStdOut EscapeChar HotkeyInterval HotkeyModifierTimeout Hotstring IfWinActive IfWinExist' +
' IfWinNotActive IfWinNotExist Include IncludeAgain InstallKeybdHook InstallMouseHook KeyHistory LTrim MaxHotkeysPerInterval MaxMem' +
' MaxThreads MaxThreadsBuffer MaxThreadsPerHotkey NoEnv NoTrayIcon Persistent SingleInstance UseHook WinActivateForce';

var hotkey = '::';

// css color keywords:
// comments string keyword preprocessor variable value functions constants script color1-3

this.regexList = [
{ regex: /;.*$/gm, css: 'comments' }, // one line comments
{ regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
{ regex: /\%\w+\%/g, css: 'variable' }, // variables
{ regex: new RegExp(this.getKeywords(variables), 'gmi'), css: 'variable' }, // ahk variables
{ regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions bold' }, // functions
{ regex: new RegExp(this.getKeywords(keys), 'gmi'), css: 'value' }, // values
{ regex: new RegExp(this.getKeywords(commands), 'gmi'), css: 'constants bold' }, // constants
{ regex: new RegExp(this.getKeywords(directives), 'gmi'), css: 'bold' }, // directives
{ regex: new RegExp(this.getKeywords(hotkey), 'gmi'), css: 'functions bold' }, // hotkeys/hotstrings
{ regex: /^\w+\:/g, css: 'bold' }, // labels, doesn't seem to work
{ regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword bold' } // keywords
];

};

SyntaxHighlighter.brushes.Ahk.prototype = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Ahk.aliases = ['ahk', 'autohotkey'];


HTH

Lexikos
  • Administrators
  • 9844 posts
  • AutoHotkey Foundation
  • Last active:
  • Joined: 17 Oct 2006
Very nice!

Labels doesn't seem to work.

Your regexp is missing the 'm' modifier, so '^' only matches at the beginning of the code, not at the beginning of each line. Also, labels can be preceded by whitespace, and can contain pretty much anything except for commas and whitespace. I'd use something like this, which also highlights hotkey labels:
/^\s*\S+\:(?!=)/gm
Edit: Added (?!=) to exclude assignment ':='. At first I thought to use (?!\S), but that would exclude labels of some one-line hotkeys.

Btw, GreaseMonkey ftw.

A v i
  • Members
  • 1323 posts
  • Last active: Nov 14 2015 06:56 PM
  • Joined: 30 Jan 2013

Amazing !

I didn't undersatnd a word eariler but looking at the Test page's source , I got the highlighter working. 

Thanks for creating the brush. 


Now a CS Undergrad. | My WebsiteAutohotkey Scripts | Softwares

Telegram me : @aviaryan


jNizM
  • Members
  • 928 posts
  • Last active: Jan 12 2018 09:23 AM
  • Joined: 01 Aug 2012
HIGHLIGHT.JS
--> Demo
--> GitHub

hope someone can make a language.js for autohotkey
[AHK] 1.1.27.04 x64 Unicode | [WIN] 10 Pro (Version 1709)
My GitHub Profile | Donations are appreciated if I could help you

A v i
  • Members
  • 1323 posts
  • Last active: Nov 14 2015 06:56 PM
  • Joined: 30 Jan 2013

HIGHLIGHT.JS
--> Demo
--> GitHub

hope someone can make a language.js for autohotkey

Why do you recommend Highlight.js when everything is available for Syntax Highlighter .

Take a look at a sample page here . 


Now a CS Undergrad. | My WebsiteAutohotkey Scripts | Softwares

Telegram me : @aviaryan


guest3456
  • Members
  • 1704 posts
  • Last active: Nov 19 2015 11:58 AM
  • Joined: 10 Mar 2011
because highlight.js can do Zenburn

A v i
  • Members
  • 1323 posts
  • Last active: Nov 14 2015 06:56 PM
  • Joined: 30 Jan 2013

because highlight.js can do Zenburn

Good enough reason.

Syntax Highlighter too has a theme like that. Take a look at Fade to Gray or Midnight or make your own Zenburn.

By the way, I will try to duplicate Zenburn . 

 

Anybody has better themes for Syntax Highlighter ??


Now a CS Undergrad. | My WebsiteAutohotkey Scripts | Softwares

Telegram me : @aviaryan


LARK2355
  • Members
  • 9 posts
  • Last active: Sep 28 2013 06:59 AM
  • Joined: 02 Feb 2012

Hi

Here is an alternative way off doing it going from ahk to css directly

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
; #SingleInstance [force|ignore|off]
header1 =<html><head><title>View AHK using Cascading Style Sheets </title><style type="text/css">`n
divno=1
Loop, read, %A_ScriptDir%\AHK_CSS.txt
{
Loop, parse, A_LoopReadLine, 〠
{
field%a_index%:=A_loopfield
}
; 0= open and close div 1= open only on this word 2= close only on this word 3= open and close but only if after  `n(new line)
if (field3=0 or field3=1 or field3=3)
{
; only write if a new div
header2 = %header2%DIV%divno% %field2%`n
}
if (field3=0 or field3=2 or field3=3)
{
; only increment if end of div
divno+=1
}
}
header3 =</style></head><body>
foot =</body></html>
usep1 =%1%
if (usep1="")
{
usep1=%A_ScriptDir%\AHK_CSS.tmp
}
FileRead, AHK_CSS,  %usep1%
if errorlevel
{
msgbox file %usep1% not found
}
gosub process
AHK_CSS =%header1% %header2%%header3%%AHK_CSS%%foot%
FileDelete,%A_ScriptDir%\AHK_CSS.html 
FileAppend, %AHK_CSS%, %A_ScriptDir%\AHK_CSS.html 
runwait "%A_ScriptDir%\AHK_CSS.html" 
return
process:
; process ahk scipt here in field AHK_CSS
Transform,AHK_CSS, HTML, %AHK_CSS% ,1
loop 3
{
; double space should not be allowed in html unless specified
StringReplace,  AHK_CSS, AHK_CSS,%A_space%%A_space%,%A_space%,1 
; clear  manual formatting to allow this formatting to work better
StringReplace,  AHK_CSS, AHK_CSS,%A_tab%%A_tab%,%A_tab%,1 
}
divno=1
Loop, read, %A_ScriptDir%\AHK_CSS.txt
{
Loop, parse, A_LoopReadLine, 〠
{
field%a_index%:=A_loopfield
}
if field3=0
{
StringReplace,  AHK_CSS,AHK_CSS,%field1%,<DIV%divno%>%field1%</DIV%divno%>,1 
}	
if field3=3
{
StringReplace, AHK_CSS, AHK_CSS,`n%field1%,`n<DIV%divno%>%field1%</DIV%divno%>,1 
StringReplace,  AHK_CSS, AHK_CSS,`n%a_tab%%field1%,`n<DIV%divno%>%field1%</DIV%divno%>,1 
StringReplace,  AHK_CSS,AHK_CSS,`n%a_space%%field1%,`n<DIV%divno%>%field1%</DIV%divno%>,1 
}	
if field3=1
{
StringReplace,  AHK_CSS, AHK_CSS ,`n%field1%,`n<DIV%divno%>%field1%,1 
StringReplace,  AHK_CSS, AHK_CSS ,`n%a_tab%%field1%,`n<DIV%divno%>%field1%,1 
StringReplace,  AHK_CSS, AHK_CSS ,`n%a_space%%field1%,`n<DIV%divno%>%field1%,1 
}	
if field3=2
{
StringReplace,  AHK_CSS, AHK_CSS ,`n%field1%,%field1%</DIV%divno%>`n,1 
StringReplace,  AHK_CSS, AHK_CSS ,%a_tab%%field1%,%field1%</DIV%divno%>`n,1 
StringReplace,  AHK_CSS, AHK_CSS ,`n%a_space%%field1%,%field1%</DIV%divno%>`n,1 
}	
if (field3=0 or field3=2 or field3=3)
{
divno+=1
}
}
return
guiclose:
exitapp

and this file AHK_CSS.txt holds the keywords , the CSS format command and the rule type

GuiControl〠{color:#aacc22;}〠3
Gui〠{color:#33cc33;}〠3
A_〠{font-size:150%; color:#666600;}〠0
:〠{font-size:150%; color:#e83399;}〠0
=〠{color:#e33399;}〠0
Gosub〠{color:#ff9900;}〠0
Return〠{position:relative;left:30%; color:#ff9900; font-weight:bold;}〠3
Run〠{font-size:150%; color:#bf0000;}〠3
If〠{color:#ff33cc;}〠3
Else〠{color:#ff33cc;}〠3
Loop〠{font-size:150%; color:#cc0066;}〠3
Font〠{color:#cc00ff;}〠3
Send〠{font-size:150%; color:#cc0000;}〠3
Menu〠{color:#9966ff;}〠3
File〠{color:#33cccc;}〠3
;〠{font-size:150%; color:#cc00cc;}〠3
,〠{font-size:150%; color:#0400ff;}〠0
{〠{color:#993399; position:relative;left:20px;}〠1
}〠〠2
(〠{color:red;}〠0
)〠{color:red;}〠0
[〠{color:blue;}〠0
]〠{color:blue;}〠0
---------〠-------

I would not recommend it to do every keyword as it would be to slow but its good just to tidy up and it does indent loop brackets and you have full control

I also am sure it could be made faster by all you clever guys

hope it helps

ps Unicode version



A v i
  • Members
  • 1323 posts
  • Last active: Nov 14 2015 06:56 PM
  • Joined: 30 Jan 2013

Updated AutoHotkey brush with Zenburn theme @ https://github.com/a...ter-ahk-zenburn

Test Page @ https://rawgithub.co...ge/bigTest.html

preview.png


Now a CS Undergrad. | My WebsiteAutohotkey Scripts | Softwares

Telegram me : @aviaryan


guest3456
  • Members
  • 1704 posts
  • Last active: Nov 19 2015 11:58 AM
  • Joined: 10 Mar 2011
^^ that is a pretty nice color scheme... comment is pretty hard to read but other than that i really like it

A v i
  • Members
  • 1323 posts
  • Last active: Nov 14 2015 06:56 PM
  • Joined: 30 Jan 2013
Thank you sir,

Now a CS Undergrad. | My WebsiteAutohotkey Scripts | Softwares

Telegram me : @aviaryan


A v i
  • Members
  • 1323 posts
  • Last active: Nov 14 2015 06:56 PM
  • Joined: 30 Jan 2013

Added the above Zenburn theme (with enhancements) and Autohotkey Syntax Highlighter brush in a forkable repo at  --  https://github.com/a...ter-ahk-zenburn


Now a CS Undergrad. | My WebsiteAutohotkey Scripts | Softwares

Telegram me : @aviaryan


fathom
  • Members
  • 13 posts
  • Last active: Apr 02 2015 04:58 PM
  • Joined: 27 Aug 2012

Nice Avi!

 

I've created a Monokai theme based upon your Zenburn.  https://github.com/d...lighter-monokai

 

 

screenshot.png