Skip to content

Commit

Permalink
Merge pull request highlightjs#2 from g8tguy/patch-1
Browse files Browse the repository at this point in the history
Enhanced powershell highlighting.
  • Loading branch information
G8t Guy authored Dec 14, 2016
2 parents 44b2e46 + cafe561 commit 74ede52
Show file tree
Hide file tree
Showing 3 changed files with 181 additions and 29 deletions.
1 change: 1 addition & 0 deletions AUTHORS.en.txt
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,4 @@ Contributors:
- Kenton Hamaluik <[email protected]>
- Marvin Saignat <[email protected]>
- Michael Rodler <[email protected]>
- G8t Guy <[email protected]>
1 change: 1 addition & 0 deletions AUTHORS.ru.txt
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,4 @@ URL: https://highlightjs.org/
- Кентон Хамалуик <[email protected]>
- Марвин Сайнат <[email protected]>
- Михаель Родлер <[email protected]>
- Грейт Гай <[email protected]>
208 changes: 179 additions & 29 deletions src/languages/powershell.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,59 @@
/*
Language: PowerShell
Author: David Mohundro <[email protected]>
Contributors: Nicholas Blumhardt <[email protected]>, Victor Zhou <[email protected]>, Nicolas Le Gall <[email protected]>
*/
Language: PowerShell
Author: David Mohundro <[email protected]>
Contributors: Nicholas Blumhardt <[email protected]>, Victor Zhou <[email protected]>, Nicolas Le Gall <[email protected]>, G8t Guy <[email protected]>
*/

module.exports = function (hljs) {

// https://msdn.microsoft.com/en-us/library/ms714428(v=vs.85).aspx
var VALID_VERBS =
'Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|' +
'Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|' +
'Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|' +
'Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|' +
'ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|' +
'Limit|Merge|New|Out|Publish|Restore|Save|Sync|Unpublish|Update|' +
'Approve|Assert|Complete|Confirm|Deny|Disable|Enable|Install|Invoke|Register|' +
'Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|' +
'Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|' +
'Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|' +
'Unprotect|Use|ForEach|Sort|Tee|Where'

var COMPARISON_OPERATORS =
'-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|' +
'-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|' +
'-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|' +
'-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|' +
'-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|' +
'-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|' +
'-split|-wildcard|-xor'

var KEYWORDS = {
keyword: 'if else foreach return do while until elseif begin for trap data dynamicparam ' +
'end break throw param continue finally in switch exit filter try process catch ' +
'hidden static parameter validate[A-Z]+'
}

function(hljs) {
var BACKTICK_ESCAPE = {
begin: '`[\\s\\S]',
relevance: 0
};
}

var VAR = {
className: 'variable',
variants: [
{begin: /\$[\w\d][\w\d_:]*/}
{ begin: /\$\B/ },
{ className: 'keyword', begin: /\$this/ },
{ begin: /\$[\w\d][\w\d_:]*/ }
]
};
}

var LITERAL = {
className: 'literal',
begin: /\$(null|true|false)\b/
};
}

var QUOTE_STRING = {
className: 'string',
variants: [
Expand All @@ -33,24 +68,26 @@ function(hljs) {
begin: /\$[A-z]/, end: /[^A-z]/
}
]
};
}

var APOS_STRING = {
className: 'string',
variants: [
{ begin: /'/, end: /'/ },
{ begin: /@'/, end: /^'@/ }
]
};
}

var PS_HELPTAGS = {
className: 'doctag',
variants: [
/* no paramater help tags */
/* no paramater help tags */
{ begin: /\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/ },
/* one parameter help tags */
{ begin: /\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/ }
]
};
}

var PS_COMMENT = hljs.inherit(
hljs.COMMENT(null, null),
{
Expand All @@ -62,25 +99,138 @@ function(hljs) {
],
contains: [PS_HELPTAGS]
}
);
)

return {
aliases: ['ps'],
lexemes: /-?[A-z\.\-]+/,
case_insensitive: true,
keywords: {
keyword: 'if else foreach return function do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch',
built_in: 'Add-Computer Add-Content Add-History Add-JobTrigger Add-Member Add-PSSnapin Add-Type Checkpoint-Computer Clear-Content Clear-EventLog Clear-History Clear-Host Clear-Item Clear-ItemProperty Clear-Variable Compare-Object Complete-Transaction Connect-PSSession Connect-WSMan Convert-Path ConvertFrom-Csv ConvertFrom-Json ConvertFrom-SecureString ConvertFrom-StringData ConvertTo-Csv ConvertTo-Html ConvertTo-Json ConvertTo-SecureString ConvertTo-Xml Copy-Item Copy-ItemProperty Debug-Process Disable-ComputerRestore Disable-JobTrigger Disable-PSBreakpoint Disable-PSRemoting Disable-PSSessionConfiguration Disable-WSManCredSSP Disconnect-PSSession Disconnect-WSMan Disable-ScheduledJob Enable-ComputerRestore Enable-JobTrigger Enable-PSBreakpoint Enable-PSRemoting Enable-PSSessionConfiguration Enable-ScheduledJob Enable-WSManCredSSP Enter-PSSession Exit-PSSession Export-Alias Export-Clixml Export-Console Export-Counter Export-Csv Export-FormatData Export-ModuleMember Export-PSSession ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-ComputerRestorePoint Get-Content Get-ControlPanelItem Get-Counter Get-Credential Get-Culture Get-Date Get-Event Get-EventLog Get-EventSubscriber Get-ExecutionPolicy Get-FormatData Get-Host Get-HotFix Get-Help Get-History Get-IseSnippet Get-Item Get-ItemProperty Get-Job Get-JobTrigger Get-Location Get-Member Get-Module Get-PfxCertificate Get-Process Get-PSBreakpoint Get-PSCallStack Get-PSDrive Get-PSProvider Get-PSSession Get-PSSessionConfiguration Get-PSSnapin Get-Random Get-ScheduledJob Get-ScheduledJobOption Get-Service Get-TraceSource Get-Transaction Get-TypeData Get-UICulture Get-Unique Get-Variable Get-Verb Get-WinEvent Get-WmiObject Get-WSManCredSSP Get-WSManInstance Group-Object Import-Alias Import-Clixml Import-Counter Import-Csv Import-IseSnippet Import-LocalizedData Import-PSSession Import-Module Invoke-AsWorkflow Invoke-Command Invoke-Expression Invoke-History Invoke-Item Invoke-RestMethod Invoke-WebRequest Invoke-WmiMethod Invoke-WSManAction Join-Path Limit-EventLog Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Event New-EventLog New-IseSnippet New-Item New-ItemProperty New-JobTrigger New-Object New-Module New-ModuleManifest New-PSDrive New-PSSession New-PSSessionConfigurationFile New-PSSessionOption New-PSTransportOption New-PSWorkflowExecutionOption New-PSWorkflowSession New-ScheduledJobOption New-Service New-TimeSpan New-Variable New-WebServiceProxy New-WinEvent New-WSManInstance New-WSManSessionOption Out-Default Out-File Out-GridView Out-Host Out-Null Out-Printer Out-String Pop-Location Push-Location Read-Host Receive-Job Register-EngineEvent Register-ObjectEvent Register-PSSessionConfiguration Register-ScheduledJob Register-WmiEvent Remove-Computer Remove-Event Remove-EventLog Remove-Item Remove-ItemProperty Remove-Job Remove-JobTrigger Remove-Module Remove-PSBreakpoint Remove-PSDrive Remove-PSSession Remove-PSSnapin Remove-TypeData Remove-Variable Remove-WmiObject Remove-WSManInstance Rename-Computer Rename-Item Rename-ItemProperty Reset-ComputerMachinePassword Resolve-Path Restart-Computer Restart-Service Restore-Computer Resume-Job Resume-Service Save-Help Select-Object Select-String Select-Xml Send-MailMessage Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-JobTrigger Set-Location Set-PSBreakpoint Set-PSDebug Set-PSSessionConfiguration Set-ScheduledJob Set-ScheduledJobOption Set-Service Set-StrictMode Set-TraceSource Set-Variable Set-WmiInstance Set-WSManInstance Set-WSManQuickConfig Show-Command Show-ControlPanelItem Show-EventLog Sort-Object Split-Path Start-Job Start-Process Start-Service Start-Sleep Start-Transaction Start-Transcript Stop-Computer Stop-Job Stop-Process Stop-Service Stop-Transcript Suspend-Job Suspend-Service Tee-Object Test-ComputerSecureChannel Test-Connection Test-ModuleManifest Test-Path Test-PSSessionConfigurationFile Trace-Command Unblock-File Undo-Transaction Unregister-Event Unregister-PSSessionConfiguration Unregister-ScheduledJob Update-FormatData Update-Help Update-List Update-TypeData Use-Transaction Wait-Event Wait-Job Wait-Process Where-Object Write-Debug Write-Error Write-EventLog Write-Host Write-Output Write-Progress Write-Verbose Write-Warning Add-MDTPersistentDrive Disable-MDTMonitorService Enable-MDTMonitorService Get-MDTDeploymentShareStatistics Get-MDTMonitorData Get-MDTOperatingSystemCatalog Get-MDTPersistentDrive Import-MDTApplication Import-MDTDriver Import-MDTOperatingSystem Import-MDTPackage Import-MDTTaskSequence New-MDTDatabase Remove-MDTMonitorData Remove-MDTPersistentDrive Restore-MDTPersistentDrive Set-MDTMonitorData Test-MDTDeploymentShare Test-MDTMonitorData Update-MDTDatabaseSchema Update-MDTDeploymentShare Update-MDTLinkedDS Update-MDTMedia Update-MDTMedia Add-VamtProductKey Export-VamtData Find-VamtManagedMachine Get-VamtConfirmationId Get-VamtProduct Get-VamtProductKey Import-VamtData Initialize-VamtData Install-VamtConfirmationId Install-VamtProductActivation Install-VamtProductKey Update-VamtProduct',
nomarkup: '-ne -eq -lt -gt -ge -le -not -like -notlike -match -notmatch -contains -notcontains -in -notin -replace'
},
var CMDLETS = {
className: 'built_in',
variants: [
{ begin: '('.concat(VALID_VERBS, ')+(-)[\\w\\d]+') },
// Invalid cmdlets!
{ className: 'subst', begin: /[\w\d]+(-)[\w\d]+/ }
]
}

var PS_CLASS = {
className: 'class',
beginKeywords: 'class enum', end: /[{]/, excludeEnd: true,
contains: [hljs.TITLE_MODE]
}

var PS_FUNCTION = {
className: 'keyword',
begin: /function\s+/, end: /([^A-Z0-9-])/,
excludeEnd: true,
contains: [
CMDLETS,
// Invalid function names!
{ className: 'subst', begin: /[\w\d]+/ }
]
}

// Using statment, plus type, plus assembly name.
var PS_USING = {
className: 'keyword',
begin: /using\s/, end: /$/,
contains: [
BACKTICK_ESCAPE,
hljs.NUMBER_MODE,
QUOTE_STRING,
APOS_STRING,
LITERAL,
VAR,
PS_COMMENT
{ className: 'type', begin: /(assembly|command|module|namespace|type)/ },
{ className: 'meta', begin: /\S+/ }
]
};
}

// Comperison operators & function named parameters.
var PS_ARGUMENTS = {
variants: [
// PS literals are pretty verbose so it's a good idea to accent them a bit.
{ className: 'subst', begin: '('.concat(COMPARISON_OPERATORS, ')\\b') },
{ className: 'literal', begin: /(-)[\w\d]+/ }
]
}

var STATIC_MEMBER = {
className: 'selector-tag',
begin: /::\w+\b/, end: /$/,
returnBegin: true,
contains: [
{ className: 'attribute', begin: /\w+/, endsParent: true }
]
}

var HASH_SIGNS = {
className: 'selector-tag',
begin: /\@\B/

}


var PS_NEW_OBJECT_TYPE = {
className: 'built_in',
begin: /New-Object\s+\w/, end: /$/,
returnBegin: true,
contains: [
{ begin: /$/, endsParent: true },
{ className: 'meta', begin: /\s([\w\.])+/, endsParent: true }
]
}

// It's a very general rule so I'll narrow it a bit with some strict boundaries
// to avoid any possible false-positive collisions!
var PS_METHODS = {
className: 'name',
begin: /[\w]+[ ]??\(/, end: /$/,
returnBegin: true,
contains: [
{
className: 'keyword', begin: '('.concat(
KEYWORDS.keyword.toString().replace(/\s/g, '|'
), ')\\b'),
endsParent: true
},
{
className: 'built_in', begin: /[\w]+\b/,
endsParent: true
}
]
}

var GENTLEMANS_SET = [
STATIC_MEMBER,
PS_METHODS,
PS_COMMENT,
BACKTICK_ESCAPE,
hljs.NUMBER_MODE,
QUOTE_STRING,
APOS_STRING,
PS_NEW_OBJECT_TYPE,
CMDLETS,
VAR,
LITERAL,
HASH_SIGNS
]

var PS_TYPE = {
className: 'no-markup',
begin: /\[/, end: /\]/,
excludeBegin: true,
excludeEnd: true,
contains: GENTLEMANS_SET.concat(
'self',
{ className: 'meta', begin: /[\.\w\d]+/ }
)
}

return {
aliases: ['ps'],
lexemes: /-?[A-z\.\-]+/,
case_insensitive: true,
keywords: KEYWORDS,
contains: GENTLEMANS_SET.concat(
PS_CLASS,
PS_FUNCTION,
PS_USING,
PS_ARGUMENTS,
PS_TYPE
)
}
}

0 comments on commit 74ede52

Please sign in to comment.