1"""
2 pygments.lexers.automation
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Lexers for automation scripting languages.
6
7 :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
8 :license: BSD, see LICENSE for details.
9"""
10
11from pygments.lexer import RegexLexer, include, bygroups, combined
12from pygments.token import Text, Comment, Operator, Name, String, \
13 Number, Punctuation, Generic
14
15__all__ = ['AutohotkeyLexer', 'AutoItLexer']
16
17
18class AutohotkeyLexer(RegexLexer):
19 """
20 For autohotkey source code.
21 """
22 name = 'autohotkey'
23 url = 'http://www.autohotkey.com/'
24 aliases = ['autohotkey', 'ahk']
25 filenames = ['*.ahk', '*.ahkl']
26 mimetypes = ['text/x-autohotkey']
27 version_added = '1.4'
28
29 tokens = {
30 'root': [
31 (r'^(\s*)(/\*)', bygroups(Text, Comment.Multiline), 'incomment'),
32 (r'^(\s*)(\()', bygroups(Text, Generic), 'incontinuation'),
33 (r'\s+;.*?$', Comment.Single),
34 (r'^;.*?$', Comment.Single),
35 (r'[]{}(),;[]', Punctuation),
36 (r'(in|is|and|or|not)\b', Operator.Word),
37 (r'\%[a-zA-Z_#@$][\w#@$]*\%', Name.Variable),
38 (r'!=|==|:=|\.=|<<|>>|[-~+/*%=<>&^|?:!.]', Operator),
39 include('commands'),
40 include('labels'),
41 include('builtInFunctions'),
42 include('builtInVariables'),
43 (r'"', String, combined('stringescape', 'dqs')),
44 include('numbers'),
45 (r'[a-zA-Z_#@$][\w#@$]*', Name),
46 (r'\\|\'', Text),
47 (r'\`([,%`abfnrtv\-+;])', String.Escape),
48 include('garbage'),
49 ],
50 'incomment': [
51 (r'^\s*\*/', Comment.Multiline, '#pop'),
52 (r'[^*]+', Comment.Multiline),
53 (r'\*', Comment.Multiline)
54 ],
55 'incontinuation': [
56 (r'^\s*\)', Generic, '#pop'),
57 (r'[^)]', Generic),
58 (r'[)]', Generic),
59 ],
60 'commands': [
61 (r'(?i)^(\s*)(global|local|static|'
62 r'#AllowSameLineComments|#ClipboardTimeout|#CommentFlag|'
63 r'#ErrorStdOut|#EscapeChar|#HotkeyInterval|#HotkeyModifierTimeout|'
64 r'#Hotstring|#IfWinActive|#IfWinExist|#IfWinNotActive|'
65 r'#IfWinNotExist|#IncludeAgain|#Include|#InstallKeybdHook|'
66 r'#InstallMouseHook|#KeyHistory|#LTrim|#MaxHotkeysPerInterval|'
67 r'#MaxMem|#MaxThreads|#MaxThreadsBuffer|#MaxThreadsPerHotkey|'
68 r'#NoEnv|#NoTrayIcon|#Persistent|#SingleInstance|#UseHook|'
69 r'#WinActivateForce|AutoTrim|BlockInput|Break|Click|ClipWait|'
70 r'Continue|Control|ControlClick|ControlFocus|ControlGetFocus|'
71 r'ControlGetPos|ControlGetText|ControlGet|ControlMove|ControlSend|'
72 r'ControlSendRaw|ControlSetText|CoordMode|Critical|'
73 r'DetectHiddenText|DetectHiddenWindows|Drive|DriveGet|'
74 r'DriveSpaceFree|Edit|Else|EnvAdd|EnvDiv|EnvGet|EnvMult|EnvSet|'
75 r'EnvSub|EnvUpdate|Exit|ExitApp|FileAppend|'
76 r'FileCopy|FileCopyDir|FileCreateDir|FileCreateShortcut|'
77 r'FileDelete|FileGetAttrib|FileGetShortcut|FileGetSize|'
78 r'FileGetTime|FileGetVersion|FileInstall|FileMove|FileMoveDir|'
79 r'FileRead|FileReadLine|FileRecycle|FileRecycleEmpty|'
80 r'FileRemoveDir|FileSelectFile|FileSelectFolder|FileSetAttrib|'
81 r'FileSetTime|FormatTime|GetKeyState|Gosub|Goto|GroupActivate|'
82 r'GroupAdd|GroupClose|GroupDeactivate|Gui|GuiControl|'
83 r'GuiControlGet|Hotkey|IfEqual|IfExist|IfGreaterOrEqual|IfGreater|'
84 r'IfInString|IfLess|IfLessOrEqual|IfMsgBox|IfNotEqual|IfNotExist|'
85 r'IfNotInString|IfWinActive|IfWinExist|IfWinNotActive|'
86 r'IfWinNotExist|If |ImageSearch|IniDelete|IniRead|IniWrite|'
87 r'InputBox|Input|KeyHistory|KeyWait|ListHotkeys|ListLines|'
88 r'ListVars|Loop|Menu|MouseClickDrag|MouseClick|MouseGetPos|'
89 r'MouseMove|MsgBox|OnExit|OutputDebug|Pause|PixelGetColor|'
90 r'PixelSearch|PostMessage|Process|Progress|Random|RegDelete|'
91 r'RegRead|RegWrite|Reload|Repeat|Return|RunAs|RunWait|Run|'
92 r'SendEvent|SendInput|SendMessage|SendMode|SendPlay|SendRaw|Send|'
93 r'SetBatchLines|SetCapslockState|SetControlDelay|'
94 r'SetDefaultMouseSpeed|SetEnv|SetFormat|SetKeyDelay|'
95 r'SetMouseDelay|SetNumlockState|SetScrollLockState|'
96 r'SetStoreCapslockMode|SetTimer|SetTitleMatchMode|'
97 r'SetWinDelay|SetWorkingDir|Shutdown|Sleep|Sort|SoundBeep|'
98 r'SoundGet|SoundGetWaveVolume|SoundPlay|SoundSet|'
99 r'SoundSetWaveVolume|SplashImage|SplashTextOff|SplashTextOn|'
100 r'SplitPath|StatusBarGetText|StatusBarWait|StringCaseSense|'
101 r'StringGetPos|StringLeft|StringLen|StringLower|StringMid|'
102 r'StringReplace|StringRight|StringSplit|StringTrimLeft|'
103 r'StringTrimRight|StringUpper|Suspend|SysGet|Thread|ToolTip|'
104 r'Transform|TrayTip|URLDownloadToFile|While|WinActivate|'
105 r'WinActivateBottom|WinClose|WinGetActiveStats|WinGetActiveTitle|'
106 r'WinGetClass|WinGetPos|WinGetText|WinGetTitle|WinGet|WinHide|'
107 r'WinKill|WinMaximize|WinMenuSelectItem|WinMinimizeAllUndo|'
108 r'WinMinimizeAll|WinMinimize|WinMove|WinRestore|WinSetTitle|'
109 r'WinSet|WinShow|WinWaitActive|WinWaitClose|WinWaitNotActive|'
110 r'WinWait)\b', bygroups(Text, Name.Builtin)),
111 ],
112 'builtInFunctions': [
113 (r'(?i)(Abs|ACos|Asc|ASin|ATan|Ceil|Chr|Cos|DllCall|Exp|FileExist|'
114 r'Floor|GetKeyState|IL_Add|IL_Create|IL_Destroy|InStr|IsFunc|'
115 r'IsLabel|Ln|Log|LV_Add|LV_Delete|LV_DeleteCol|LV_GetCount|'
116 r'LV_GetNext|LV_GetText|LV_Insert|LV_InsertCol|LV_Modify|'
117 r'LV_ModifyCol|LV_SetImageList|Mod|NumGet|NumPut|OnMessage|'
118 r'RegExMatch|RegExReplace|RegisterCallback|Round|SB_SetIcon|'
119 r'SB_SetParts|SB_SetText|Sin|Sqrt|StrLen|SubStr|Tan|TV_Add|'
120 r'TV_Delete|TV_GetChild|TV_GetCount|TV_GetNext|TV_Get|'
121 r'TV_GetParent|TV_GetPrev|TV_GetSelection|TV_GetText|TV_Modify|'
122 r'VarSetCapacity|WinActive|WinExist|Object|ComObjActive|'
123 r'ComObjArray|ComObjEnwrap|ComObjUnwrap|ComObjParameter|'
124 r'ComObjType|ComObjConnect|ComObjCreate|ComObjGet|ComObjError|'
125 r'ComObjValue|Insert|MinIndex|MaxIndex|Remove|SetCapacity|'
126 r'GetCapacity|GetAddress|_NewEnum|FileOpen|Read|Write|ReadLine|'
127 r'WriteLine|ReadNumType|WriteNumType|RawRead|RawWrite|Seek|Tell|'
128 r'Close|Next|IsObject|StrPut|StrGet|Trim|LTrim|RTrim)\b',
129 Name.Function),
130 ],
131 'builtInVariables': [
132 (r'(?i)(A_AhkPath|A_AhkVersion|A_AppData|A_AppDataCommon|'
133 r'A_AutoTrim|A_BatchLines|A_CaretX|A_CaretY|A_ComputerName|'
134 r'A_ControlDelay|A_Cursor|A_DDDD|A_DDD|A_DD|A_DefaultMouseSpeed|'
135 r'A_Desktop|A_DesktopCommon|A_DetectHiddenText|'
136 r'A_DetectHiddenWindows|A_EndChar|A_EventInfo|A_ExitReason|'
137 r'A_FormatFloat|A_FormatInteger|A_Gui|A_GuiEvent|A_GuiControl|'
138 r'A_GuiControlEvent|A_GuiHeight|A_GuiWidth|A_GuiX|A_GuiY|A_Hour|'
139 r'A_IconFile|A_IconHidden|A_IconNumber|A_IconTip|A_Index|'
140 r'A_IPAddress1|A_IPAddress2|A_IPAddress3|A_IPAddress4|A_ISAdmin|'
141 r'A_IsCompiled|A_IsCritical|A_IsPaused|A_IsSuspended|A_KeyDelay|'
142 r'A_Language|A_LastError|A_LineFile|A_LineNumber|A_LoopField|'
143 r'A_LoopFileAttrib|A_LoopFileDir|A_LoopFileExt|A_LoopFileFullPath|'
144 r'A_LoopFileLongPath|A_LoopFileName|A_LoopFileShortName|'
145 r'A_LoopFileShortPath|A_LoopFileSize|A_LoopFileSizeKB|'
146 r'A_LoopFileSizeMB|A_LoopFileTimeAccessed|A_LoopFileTimeCreated|'
147 r'A_LoopFileTimeModified|A_LoopReadLine|A_LoopRegKey|'
148 r'A_LoopRegName|A_LoopRegSubkey|A_LoopRegTimeModified|'
149 r'A_LoopRegType|A_MDAY|A_Min|A_MM|A_MMM|A_MMMM|A_Mon|A_MouseDelay|'
150 r'A_MSec|A_MyDocuments|A_Now|A_NowUTC|A_NumBatchLines|A_OSType|'
151 r'A_OSVersion|A_PriorHotkey|A_ProgramFiles|A_Programs|'
152 r'A_ProgramsCommon|A_ScreenHeight|A_ScreenWidth|A_ScriptDir|'
153 r'A_ScriptFullPath|A_ScriptName|A_Sec|A_Space|A_StartMenu|'
154 r'A_StartMenuCommon|A_Startup|A_StartupCommon|A_StringCaseSense|'
155 r'A_Tab|A_Temp|A_ThisFunc|A_ThisHotkey|A_ThisLabel|A_ThisMenu|'
156 r'A_ThisMenuItem|A_ThisMenuItemPos|A_TickCount|A_TimeIdle|'
157 r'A_TimeIdlePhysical|A_TimeSincePriorHotkey|A_TimeSinceThisHotkey|'
158 r'A_TitleMatchMode|A_TitleMatchModeSpeed|A_UserName|A_WDay|'
159 r'A_WinDelay|A_WinDir|A_WorkingDir|A_YDay|A_YEAR|A_YWeek|A_YYYY|'
160 r'Clipboard|ClipboardAll|ComSpec|ErrorLevel|ProgramFiles|True|'
161 r'False|A_IsUnicode|A_FileEncoding|A_OSVersion|A_PtrSize)\b',
162 Name.Variable),
163 ],
164 'labels': [
165 # hotkeys and labels
166 # technically, hotkey names are limited to named keys and buttons
167 (r'(^\s*)([^:\s("]+?:{1,2})', bygroups(Text, Name.Label)),
168 (r'(^\s*)(::[^:\s]+?::)', bygroups(Text, Name.Label)),
169 ],
170 'numbers': [
171 (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float),
172 (r'\d+[eE][+-]?[0-9]+', Number.Float),
173 (r'0\d+', Number.Oct),
174 (r'0[xX][a-fA-F0-9]+', Number.Hex),
175 (r'\d+L', Number.Integer.Long),
176 (r'\d+', Number.Integer)
177 ],
178 'stringescape': [
179 (r'\"\"|\`([,%`abfnrtv])', String.Escape),
180 ],
181 'strings': [
182 (r'[^"\n]+', String),
183 ],
184 'dqs': [
185 (r'"', String, '#pop'),
186 include('strings')
187 ],
188 'garbage': [
189 (r'[^\S\n]', Text),
190 # (r'.', Text), # no cheating
191 ],
192 }
193
194
195class AutoItLexer(RegexLexer):
196 """
197 For AutoIt files.
198
199 AutoIt is a freeware BASIC-like scripting language
200 designed for automating the Windows GUI and general scripting
201 """
202 name = 'AutoIt'
203 url = 'http://www.autoitscript.com/site/autoit/'
204 aliases = ['autoit']
205 filenames = ['*.au3']
206 mimetypes = ['text/x-autoit']
207 version_added = '1.6'
208
209 # Keywords, functions, macros from au3.keywords.properties
210 # which can be found in AutoIt installed directory, e.g.
211 # c:\Program Files (x86)\AutoIt3\SciTE\au3.keywords.properties
212
213 keywords = """\
214 #include-once #include #endregion #forcedef #forceref #region
215 and byref case continueloop dim do else elseif endfunc endif
216 endselect exit exitloop for func global
217 if local next not or return select step
218 then to until wend while exit""".split()
219
220 functions = """\
221 abs acos adlibregister adlibunregister asc ascw asin assign atan
222 autoitsetoption autoitwingettitle autoitwinsettitle beep binary binarylen
223 binarymid binarytostring bitand bitnot bitor bitrotate bitshift bitxor
224 blockinput break call cdtray ceiling chr chrw clipget clipput consoleread
225 consolewrite consolewriteerror controlclick controlcommand controldisable
226 controlenable controlfocus controlgetfocus controlgethandle controlgetpos
227 controlgettext controlhide controllistview controlmove controlsend
228 controlsettext controlshow controltreeview cos dec dircopy dircreate
229 dirgetsize dirmove dirremove dllcall dllcalladdress dllcallbackfree
230 dllcallbackgetptr dllcallbackregister dllclose dllopen dllstructcreate
231 dllstructgetdata dllstructgetptr dllstructgetsize dllstructsetdata
232 drivegetdrive drivegetfilesystem drivegetlabel drivegetserial drivegettype
233 drivemapadd drivemapdel drivemapget drivesetlabel drivespacefree
234 drivespacetotal drivestatus envget envset envupdate eval execute exp
235 filechangedir fileclose filecopy filecreatentfslink filecreateshortcut
236 filedelete fileexists filefindfirstfile filefindnextfile fileflush
237 filegetattrib filegetencoding filegetlongname filegetpos filegetshortcut
238 filegetshortname filegetsize filegettime filegetversion fileinstall filemove
239 fileopen fileopendialog fileread filereadline filerecycle filerecycleempty
240 filesavedialog fileselectfolder filesetattrib filesetpos filesettime
241 filewrite filewriteline floor ftpsetproxy guicreate guictrlcreateavi
242 guictrlcreatebutton guictrlcreatecheckbox guictrlcreatecombo
243 guictrlcreatecontextmenu guictrlcreatedate guictrlcreatedummy
244 guictrlcreateedit guictrlcreategraphic guictrlcreategroup guictrlcreateicon
245 guictrlcreateinput guictrlcreatelabel guictrlcreatelist
246 guictrlcreatelistview guictrlcreatelistviewitem guictrlcreatemenu
247 guictrlcreatemenuitem guictrlcreatemonthcal guictrlcreateobj
248 guictrlcreatepic guictrlcreateprogress guictrlcreateradio
249 guictrlcreateslider guictrlcreatetab guictrlcreatetabitem
250 guictrlcreatetreeview guictrlcreatetreeviewitem guictrlcreateupdown
251 guictrldelete guictrlgethandle guictrlgetstate guictrlread guictrlrecvmsg
252 guictrlregisterlistviewsort guictrlsendmsg guictrlsendtodummy
253 guictrlsetbkcolor guictrlsetcolor guictrlsetcursor guictrlsetdata
254 guictrlsetdefbkcolor guictrlsetdefcolor guictrlsetfont guictrlsetgraphic
255 guictrlsetimage guictrlsetlimit guictrlsetonevent guictrlsetpos
256 guictrlsetresizing guictrlsetstate guictrlsetstyle guictrlsettip guidelete
257 guigetcursorinfo guigetmsg guigetstyle guiregistermsg guisetaccelerators
258 guisetbkcolor guisetcoord guisetcursor guisetfont guisethelp guiseticon
259 guisetonevent guisetstate guisetstyle guistartgroup guiswitch hex hotkeyset
260 httpsetproxy httpsetuseragent hwnd inetclose inetget inetgetinfo inetgetsize
261 inetread inidelete iniread inireadsection inireadsectionnames
262 inirenamesection iniwrite iniwritesection inputbox int isadmin isarray
263 isbinary isbool isdeclared isdllstruct isfloat ishwnd isint iskeyword
264 isnumber isobj isptr isstring log memgetstats mod mouseclick mouseclickdrag
265 mousedown mousegetcursor mousegetpos mousemove mouseup mousewheel msgbox
266 number objcreate objcreateinterface objevent objevent objget objname
267 onautoitexitregister onautoitexitunregister opt ping pixelchecksum
268 pixelgetcolor pixelsearch pluginclose pluginopen processclose processexists
269 processgetstats processlist processsetpriority processwait processwaitclose
270 progressoff progresson progressset ptr random regdelete regenumkey
271 regenumval regread regwrite round run runas runaswait runwait send
272 sendkeepactive seterror setextended shellexecute shellexecutewait shutdown
273 sin sleep soundplay soundsetwavevolume splashimageon splashoff splashtexton
274 sqrt srandom statusbargettext stderrread stdinwrite stdioclose stdoutread
275 string stringaddcr stringcompare stringformat stringfromasciiarray
276 stringinstr stringisalnum stringisalpha stringisascii stringisdigit
277 stringisfloat stringisint stringislower stringisspace stringisupper
278 stringisxdigit stringleft stringlen stringlower stringmid stringregexp
279 stringregexpreplace stringreplace stringright stringsplit stringstripcr
280 stringstripws stringtoasciiarray stringtobinary stringtrimleft
281 stringtrimright stringupper tan tcpaccept tcpclosesocket tcpconnect
282 tcplisten tcpnametoip tcprecv tcpsend tcpshutdown tcpstartup timerdiff
283 timerinit tooltip traycreateitem traycreatemenu traygetmsg trayitemdelete
284 trayitemgethandle trayitemgetstate trayitemgettext trayitemsetonevent
285 trayitemsetstate trayitemsettext traysetclick trayseticon traysetonevent
286 traysetpauseicon traysetstate traysettooltip traytip ubound udpbind
287 udpclosesocket udpopen udprecv udpsend udpshutdown udpstartup vargettype
288 winactivate winactive winclose winexists winflash wingetcaretpos
289 wingetclasslist wingetclientsize wingethandle wingetpos wingetprocess
290 wingetstate wingettext wingettitle winkill winlist winmenuselectitem
291 winminimizeall winminimizeallundo winmove winsetontop winsetstate
292 winsettitle winsettrans winwait winwaitactive winwaitclose
293 winwaitnotactive""".split()
294
295 macros = """\
296 @appdatacommondir @appdatadir @autoitexe @autoitpid @autoitversion
297 @autoitx64 @com_eventobj @commonfilesdir @compiled @computername @comspec
298 @cpuarch @cr @crlf @desktopcommondir @desktopdepth @desktopdir
299 @desktopheight @desktoprefresh @desktopwidth @documentscommondir @error
300 @exitcode @exitmethod @extended @favoritescommondir @favoritesdir
301 @gui_ctrlhandle @gui_ctrlid @gui_dragfile @gui_dragid @gui_dropid
302 @gui_winhandle @homedrive @homepath @homeshare @hotkeypressed @hour
303 @ipaddress1 @ipaddress2 @ipaddress3 @ipaddress4 @kblayout @lf
304 @logondnsdomain @logondomain @logonserver @mday @min @mon @msec @muilang
305 @mydocumentsdir @numparams @osarch @osbuild @oslang @osservicepack @ostype
306 @osversion @programfilesdir @programscommondir @programsdir @scriptdir
307 @scriptfullpath @scriptlinenumber @scriptname @sec @startmenucommondir
308 @startmenudir @startupcommondir @startupdir @sw_disable @sw_enable @sw_hide
309 @sw_lock @sw_maximize @sw_minimize @sw_restore @sw_show @sw_showdefault
310 @sw_showmaximized @sw_showminimized @sw_showminnoactive @sw_showna
311 @sw_shownoactivate @sw_shownormal @sw_unlock @systemdir @tab @tempdir
312 @tray_id @trayiconflashing @trayiconvisible @username @userprofiledir @wday
313 @windowsdir @workingdir @yday @year""".split()
314
315 tokens = {
316 'root': [
317 (r';.*\n', Comment.Single),
318 (r'(#comments-start|#cs)(.|\n)*?(#comments-end|#ce)',
319 Comment.Multiline),
320 (r'[\[\]{}(),;]', Punctuation),
321 (r'(and|or|not)\b', Operator.Word),
322 (r'[$|@][a-zA-Z_]\w*', Name.Variable),
323 (r'!=|==|:=|\.=|<<|>>|[-~+/*%=<>&^|?:!.]', Operator),
324 include('commands'),
325 include('labels'),
326 include('builtInFunctions'),
327 include('builtInMarcros'),
328 (r'"', String, combined('stringescape', 'dqs')),
329 (r"'", String, 'sqs'),
330 include('numbers'),
331 (r'[a-zA-Z_#@$][\w#@$]*', Name),
332 (r'\\|\'', Text),
333 (r'\`([,%`abfnrtv\-+;])', String.Escape),
334 (r'_\n', Text), # Line continuation
335 include('garbage'),
336 ],
337 'commands': [
338 (r'(?i)(\s*)({})\b'.format('|'.join(keywords)),
339 bygroups(Text, Name.Builtin)),
340 ],
341 'builtInFunctions': [
342 (r'(?i)({})\b'.format('|'.join(functions)),
343 Name.Function),
344 ],
345 'builtInMarcros': [
346 (r'(?i)({})\b'.format('|'.join(macros)),
347 Name.Variable.Global),
348 ],
349 'labels': [
350 # sendkeys
351 (r'(^\s*)(\{\S+?\})', bygroups(Text, Name.Label)),
352 ],
353 'numbers': [
354 (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float),
355 (r'\d+[eE][+-]?[0-9]+', Number.Float),
356 (r'0\d+', Number.Oct),
357 (r'0[xX][a-fA-F0-9]+', Number.Hex),
358 (r'\d+L', Number.Integer.Long),
359 (r'\d+', Number.Integer)
360 ],
361 'stringescape': [
362 (r'\"\"|\`([,%`abfnrtv])', String.Escape),
363 ],
364 'strings': [
365 (r'[^"\n]+', String),
366 ],
367 'dqs': [
368 (r'"', String, '#pop'),
369 include('strings')
370 ],
371 'sqs': [
372 (r'\'\'|\`([,%`abfnrtv])', String.Escape),
373 (r"'", String, '#pop'),
374 (r"[^'\n]+", String)
375 ],
376 'garbage': [
377 (r'[^\S\n]', Text),
378 ],
379 }