Source of: geshi/geshi/posh.php | remove line numbers | download


Source Display
1
<?php 
2
/************************************************************************************* 
3
 * posh.php 
4
 * --------------------------------- 
5
 * Author: Joel Bennett (Jaykul@HuddledMasses.org) 
6
 * Copyright: (c) 2007-2010 Joel Bennett (http://HuddledMasses.org/) 
7
 * Release Version: 1.1.0 
8
 * Date Started:  2007-06-08 
9
 * Last Modified: 2010-04-16 
10
 * 
11
 * PowerShell language file for GeSHi. 
12
 * 
13
 * The lists of Nouns, Verbs, and Parameters are based on my personal install  
14
 * with PowerShell Community Extensions installed.  The really bad news is the  
15
 * fact that aliases are left out almost completely, along with anything from  
16
 * .Net or COM objects ... 
17
 * 
18
 
19
## You need to define this function before using any of the pattern generating scripts below.... 
20
function Join-String {  
21
  param    ( [string]$separator="', '", [string]$append, [string]$prepend, [string]$prefix="'", [string]$postfix="'") 
22
  begin    { [string[]]$items = @($prepend.split($separator)) } 
23
  process  { $items += $_ } 
24
  end      { $ofs = $separator; $items += @($append.split($separator)); return "$prefix$($items -ne '')$postfix" } 
25
26
  
27
 * CHANGES 
28
 * ------- 
29
 * 2007-06-08 (0.1.0) 
30
 *  -  First Release 
31
 * 2007-06-09 (1.0.0) 
32
 *  -  Changed to use regular expressions for: 
33
 *     verbs, nouns, and -parameters (was already using them for $variables) 
34
 * 2007-06-10 (1.0.1) 
35
 *  -  Ditched the specific list of parameters in favor of just assuming that 
36
 *     anything that starts with a "-" is a parameter.  Otherwise it won't  
37
 *     highlight anything that you shorten. 
38
 *  -  Improved the lists by *adding* the "deffinitive" list of verbs from the  
39
 *     MS CLI spec to my personal verb list.  I didn't remove anything because 
40
 *     ultimately I don't care if it's an official verb if it's a command on my 
41
 *     computer. You should still consider adding your personal verbs too! 
42
 *  -  I improved the 4th Keyword list by exporting my personal list of aliases 
43
 *     and functions ... (and showing the command, so you can generate your own) 
44
 *     and removing the variables entirely (they're already highlighted anyway). 
45
 * 2008-12-27 (1.1.0) 
46
 *  -  Updated for CTP3 with powershell scripts 
47
 * 
48
 * 2010-04-16 (1.2.0) 
49
 *  -  Updated for RTM (not really needed, but why not) 
50
 * 
51
 * TODO (last updated 2010-04-16) 
52
 * ------------------------- 
53
 *  -  I would like to create a script which can dump this whole file out based  
54
 *     on an individual user's personal particular set of snapins, cmdlets and  
55
 *     functions.  After all, for YOUR personal site, the cmdlets and functions  
56
 *     which you have available are the only ones that actually matter :D 
57
 *     HOWEVER: I don't think it's that important, because   
58
 * 
59
 ************************************************************************************* 
60
 * 
61
 *     This file is part of GeSHi. 
62
 * 
63
 *   GeSHi is free software; you can redistribute it and/or modify 
64
 *   it under the terms of the GNU General Public License as published by 
65
 *   the Free Software Foundation; either version 2 of the License, or 
66
 *   (at your option) any later version. 
67
 * 
68
 *   GeSHi is distributed in the hope that it will be useful, 
69
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of 
70
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
71
 *   GNU General Public License for more details. 
72
 * 
73
 *   You should have received a copy of the GNU General Public License 
74
 *   along with GeSHi; if not, write to the Free Software 
75
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
76
 * 
77
 ************************************************************************************/ 
78
 
79
$language_data = array ( 
80
  'LANG_NAME' => 'Posh'
81
  'COMMENT_SINGLE' => array(=> '#'), 
82
  'COMMENT_MULTI' => array('<#'=>'#>'), 
83
  'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE
84
  'QUOTEMARKS' => array('"'"'"), 
85
  'HARDQUOTE' => array('@"$','^"@'),          // An optional 2-element array defining the beginning and end of a hard-quoted string 
86
  'HARDESCAPE' => array(),  // Things that must still be escaped inside a hard-quoted string 
87
                // If HARDQUOTE is defined, HARDESCAPE must be defined 
88
                // This will not work unless the first character of each element is either in the 
89
                // QUOTEMARKS array or is the ESCAPE_CHAR 
90
  'ESCAPE_CHAR' => '`'
91
  'KEYWORDS' => array( 
92
      => array(  
93
# PoSH keywords/reserved words 
94
# [type]::gettype("System.Management.Automation.KeywordTokenReader").InvokeMember("_keywordTokens", "NonPublic,Static,GetField", $null, $_, @() ).GetEnumerator()|%{$_.Name.Trim("-")}|?{$_ -match "^[A-z]"}|Sort -Desc|Join-String "', '" -Prefix "'" -Postfix "'" | clip 
95
'while''var''using''until''try''trap''throw''switch''return''process''param''in''if''function''from''foreach''for''finally''filter''exit''end''elseif''else''dynamicparam''do''define''data''continue''class''catch''break''begin' 
96
      ), 
97
      => array( 
98
# Operators 
99
# [type]::gettype("System.Management.Automation.OperatorTokenReader").InvokeMember("_expressionOperatorTokens", "NonPublic,Static,GetField", $null, $_, @() ).GetEnumerator()|%{$_.Name.Trim("-")}|?{$_ -match "^[A-z]"}|Sort -Desc|Join-String "', '" -Prefix "'" -Postfix "'" | clip 
100
'xor''split''replace''or''notmatch''notlike''notcontains''not''ne''match''lt''like''le''join''isplit''isnot''is''ireplace''inotmatch''inotlike''inotcontains''ine''imatch''ilt''ilike''ile''igt''ige''ieq''icontains''gt''ge''f''eq''csplit''creplace''contains''cnotmatch''cnotlike''cnotcontains''cne''cmatch''clt''clike''cle''cgt''cge''ceq''ccontains''bxor''bor''bnot''band''as''and' 
101
      ), 
102
# built in language type shorcuts, plus a couple of .Net base types... 
103
# [type]::gettype("System.Management.Automation.TypeAccelerators")::get.GetEnumerator()|%{$_.Key}|Sort -Desc|Join-String "', '" -Prefix "'" -Postfix "'" | clip 
104
      => array( 
105
'xml''wmisearcher''wmiclass''wmi''type''switch''string''single''scriptblock''runspacefactory''runspace''regex''ref''psprimitivedictionary''psobject''psmoduleinfo''pscustomobject''powershell''long''ipaddress''int''hashtable''float''double''decimal''char''byte''bool''array''adsisearcher''adsi' 
106
        ), 
107
      => array( 
108
# DEFAULT (NoProfile) list of aliases and functions (filtered to remove verb-noun functions which will already be highlighted, and to remove drive letter functions) 
109
# Combined list generated with: 
110
# gcm -type "Alias,Function,Filter" | Select -Expand Name | ?{$_ -match "[A-z]" -and $_ -notmatch "[A-z]-|:"}|Sort -Unique -Desc | %{[regex]::escape($_) -replace '.ps1$',''} |Join-String "', '" -Prefix "'" -Postfix "'" | clip 
111
'write''wjb''where''type''tee''TabExpansion''swmi''sv''start''spsv''spps''spjb''sp''sort''sleep''sl''si''set''select''sc''sbp''sasv''saps''sal''sajb''rwmi''rvpa''rv''rsnp''rsn''rp''rnp''rni''rmo''rmdir''rm''rjb''ri''ren''rdr''rd''rcjb''rbp''r''pwd''pushd''ps''prompt''popd''oh''ogv''nv''nsn''nmo''ni''ndr''nal''mv''mp''move''mount''more''mkdir''mi''measure''md''man''ls''lp''kill''iwmi''ise''ipsn''ipmo''ipcsv''ipal''ImportSystemModules''ii''ihy''iex''icm''history''help''h''gwmi''gv''gu''gsv''gsnp''gsn''group''gps''gp''gmo''gm''gl''gjb''gi''ghy''gdr''gcs''gcm''gci''gc''gbp''gal''fw''ft''foreach''fl''fc''exsn''etsn''erase''epsn''epcsv''epal''echo''ebp''dir''diff''del''dbp''cvpa''cpp''cpi''cp''copy''compare''clv''cls''clp''cli''clhy''clear''clc''chdir''cd\\''cd\.\.''cd''cat''asnp''ac' 
112
      ), 
113
   ), 
114
   'SYMBOLS' => array( 
115
    '('')''['']''{''}'"-""+""="'!''%''&''*''|''/''<''>'
116
   ), 
117
   'CASE_SENSITIVE' => array( 
118
      GESHI_COMMENTS => true
119
      => false
120
      => false
121
      => false
122
      => false
123
      => false
124
      => false
125
   ), 
126
   'STYLES' => array( 
127
      'KEYWORDS' => array( 
128
         => 'color: #666699; font-weight: bold;'
129
         => 'color: #333399; font-weight: bold; font-style: italic;'
130
         => 'color: #003366; font-weight: bold;'
131
         => 'color: #660033;'
132
      //~ 5 => 'color: #006600; font-style: italic;', 
133
      //~ 6 => 'color: #000000; font-style: italic;', 
134
      ), 
135
      'COMMENTS' => array( 
136
         => 'color: #666666; font-style: italic;'
137
         'MULTI' => 'color: #666666; font-style: italic;' 
138
      ), 
139
      'ESCAPE_CHAR' => array( 
140
         => 'color: #000099; font-weight: bold;' 
141
      ), 
142
      'BRACKETS' => array( 
143
         => 'color: #333;' 
144
      ), 
145
      'STRINGS' => array( 
146
         => 'color: #009900;' 
147
      ), 
148
      'NUMBERS' => array( 
149
         => 'color: #cc66cc;' 
150
      ), 
151
      'METHODS' => array( 
152
         => 'color: #003366;'
153
         => 'color: #003366;'
154
//       3 => 'color: #666;' 
155
      ), 
156
      'SYMBOLS' => array( 
157
         => 'color: #66cc66;' 
158
      ), 
159
      'REGEXPS' => array( 
160
         => 'color: #0066cc; font-style: italic;',    # verb-noun 
161
         => 'font-style: normal;',                    # noun 
162
         => 'color: #000066;',                        # parameters 
163
         => 'color: #660033; font-weight: bold;',     # variables 
164
         => 'color: #003366; font-weight: bold;',     # types 
165
      ), 
166
      'SCRIPT' => array( 
167
      ) 
168
   ), 
169
   'URLS' => array( 
170
   ), 
171
   'OOLANG' => true
172
   'OBJECT_SPLITTERS' => array( 
173
      => '.'
174
      => '::'
175
   ), 
176
   'REGEXPS' => array( 
177
# Verbs. This is the OFFICIAL list. Full SEARCH pattern GENERATED with this: 
178
# get-verb | %{$_.verb} | sort -unique -descending | Join-String -prefix "((?:" -Separator "|" -postfix ")-[a-zA-Z_][a-zA-Z0-9_]*)"|clip 
179
# NOTE: THIS HIGHLIGHTS THE WHOLE COMMAND 
180
      => array ( 
181
         GESHI_SEARCH => '((?:Write|Watch|Wait|Use|Update|Unregister|Unpublish|Unprotect|Unlock|Uninstall|Undo|Unblock|Trace|Test|Sync|Switch|Suspend|Submit|Stop|Step|Start|Split|Skip|Show|Set|Send|Select|Search|Save|Revoke|Resume|Restore|Restart|Resolve|Reset|Request|Repair|Rename|Remove|Register|Redo|Receive|Read|Push|Publish|Protect|Pop|Ping|Out|Open|New|Move|Mount|Merge|Measure|Lock|Limit|Join|Invoke|Install|Initialize|Import|Hide|Group|Grant|Get|Format|Find|Export|Expand|Exit|Enter|Enable|Edit|Dismount|Disconnect|Disable|Deny|Debug|Copy|ConvertTo|ConvertFrom|Convert|Connect|Confirm|Compress|Complete|Compare|Close|Clear|Checkpoint|Block|Backup|Assert|Approve|Add)-[a-zA-Z_][a-zA-Z0-9_]*)'
182
         GESHI_REPLACE => '\\1'
183
         GESHI_MODIFIERS => 'i'
184
         GESHI_BEFORE => ''
185
         GESHI_AFTER => '' 
186
      ), 
187
# Nouns come after a Verb and a dash. This is the OFFICIAL list. Full SEARCH pattern GENERATED with this: 
188
# get-verb | %{$_.verb} | sort -unique -descending | Join-String -Separator "|" -prefix "((?:" -postfix ")-)([a-zA-Z_][a-zA-Z0-9_]*)"|clip 
189
# HYPOTHETICALLY, if you wanted a list of the actual nouns on your system: 
190
# get-command | foreach-object{$_.noun} | sort-object -unique -descending | Join-String -Separator "|" -prefix "((?:" -postfix "))"|clip 
191
# NOTE: THIS HIGHLIGHTS JUST THE NOUN 
192
      => array ( 
193
         GESHI_SEARCH => '((?:Write|Watch|Wait|Use|Update|Unregister|Unpublish|Unprotect|Unlock|Uninstall|Undo|Unblock|Trace|Test|Sync|Switch|Suspend|Submit|Stop|Step|Start|Split|Skip|Show|Set|Send|Select|Search|Save|Revoke|Resume|Restore|Restart|Resolve|Reset|Request|Repair|Rename|Remove|Register|Redo|Receive|Read|Push|Publish|Protect|Pop|Ping|Out|Open|New|Move|Mount|Merge|Measure|Lock|Limit|Join|Invoke|Install|Initialize|Import|Hide|Group|Grant|Get|Format|Find|Export|Expand|Exit|Enter|Enable|Edit|Dismount|Disconnect|Disable|Deny|Debug|Copy|ConvertTo|ConvertFrom|Convert|Connect|Confirm|Compress|Complete|Compare|Close|Clear|Checkpoint|Block|Backup|Assert|Approve|Add)-)([a-zA-Z_][a-zA-Z0-9_]*)'
194
         GESHI_REPLACE => '\\2'
195
         GESHI_MODIFIERS => 'i'
196
         GESHI_BEFORE => '\\1'
197
         GESHI_AFTER => '' 
198
      ),       
199
# Parameters come after a " -" ... and although I can generate a list using: 
200
# "(-(?:"+(get-command | foreach-object{$_.parametersets} | foreach-object {$_.parameters} | foreach-object {$_.name} | sort-object -unique -descending | Join-String -Separator "|")+"))" | Set-Clipboard 
201
############### (?:Year|XsltPath|XPath|Write|Wrap|WorkingDirectory|Word|WindowStyle|Width|WhatIf|Warning|WaitTimeout|Wait|Volume|View|Version|Verify|Verbose|Verb|Variable|ValueOnly|Value|Validate|Utc|UseTimeFromFile|UserName|URL|Update|Unique|UFormat|TypeName|TTL|TrustLevel|Trusted|Truncate|Trace|TotalCount|To|Title|TimestampServer|TimeStamp|Timeout|Time|TID|Text|Temp|TargetObject|Target|Syntax|SyncWindow|Sum|Subject|Strings|StringEncoding|String|Strict|Stream|Step|Status|Statistic|Static|State|StartupType|Start|StackName|Stack|Speed|SourceId|SortBy|SmtpHost|Size|SingleLine|SimpleMatch|SID|ShowError|Shortname|SetModifiedTime|SetCreatedTime|SetAccessedTime|Server|Separator|Select|SecureString|SecureKey|SecondValue|SecondsRemaining|Seconds|Second|ScriptBlock|Scope|SchemaPath|SaveCred|Rtf|Root|Role|Retry|Resolve|ReplyTo|Repair|RemoveOriginal|RemoveListener|RemoveFileListener|RemoveEmptyStrings|Registered|RegexSeparator|Regex|ReferenceObject|Recurse|RecommendedAction|Reason|ReadOnly|ReadCount|Raw|Quiet|Query|Quality|Qualifier|PSSnapin|PSProvider|PSHost|PSDrive|PropertyType|Property|Prompt|Process|Privileges|Privilege|Priority|PrinterName|PrincipalName|PrependPath|PortNumber|PortName|PercentComplete|Percent|Pattern|PathType|Path|Password|PassThru|ParentID|Parent|Parameter|Paging|Owner|Overwrite|OutVariable|OutputPath|Output|OutBuffer|Option|Operation|OnType|OmitXmlDeclaration|Offset|Off|Object|NoWindow|Noun|NoTypeInformation|NoTrimEnd|Notify|NoShellExecute|NoQualifier|NoProfile|NoNewLine|NoLineBreak|NoHeader|NoElement|NoClobber|NoAscii|NoAddress|NewName|NewLine|Newest|Namespace|Name|MultiLine|Most|Month|Modified|Minutes|Minute|Minimum|Min|Milliseconds|Migrate|Message|MemberType|Maximum|Max|MacName|LogName|Log|Location|LocalizedHelpPath|LoadUserProfile|LiteralPath|LiteralName|ListenerOption|List|LineCount|Line|Level|Leaf|LastWord|Last|Label|KeyLength|KeyContainerName|KeyAlgorithm|Key|KeepAspectRatio|JobName|ItemType|IsValid|IsAbsolute|IpAddress|Interval|InterfaceName|Interactive|Insert|InputObject|Input|IndentString|Incremental|IncludeEqual|IncludeEmptyDirectories|IncludeChain|Include|Import|Image|IgnoreWhiteSpace|Ignore|Identity|Id|HtmlBody|Html|Hours|Hour|HostName|HideTableHeaders|Height|Head|Handle|GroupBy|Group|GlobalCatalog|Functionality|Full|From|FragmentOnly|Format|ForegroundColor|Force|Follow|FlattenPaths|First|FilterScript|Filter|Files|FilePath|FileName|Fast|Expression|ExpandProperty|Expand|ExecutionPolicy|ExcludeProperty|ExcludeDifferent|Exclude|Exception|Examples|Exact|EventName|ErrorVariable|ErrorRecord|ErrorLimit|ErrorLevel|ErrorId|ErrorAction|Erase|End|Encrypt|Encoding|EnableScript|Elapsed|DriveName|Drain|DomainName|Domain|DistinguishedName|DisplayName|DisplayHint|DisplayError|DirectoryName|DifferenceObject|Detailed|Destination|Description|Descending|Depth|DependsOn|Delimiter|Delete|Default|Debugger|Debug|Days|Day|Date|CurrentOperation|Culture|Csv|CSPType|CSPName|CryptoRng|Credential|Created|Create|Count|Continuous|Container|ConformanceLevel|Confirm|ComputerName|Compress|Component|Completed|Compatible|ComObject|CommandType|Command|Columns|Column|ClusterName|ClassName|Class|ChildPath|Character|Char|CertUsage|CertSubjectName|CertStoreLocation|CertSerialNumber|CertRequestFileName|CertIssuerName|Certificate|CertFile|Cc|CategoryTargetType|CategoryTargetName|CategoryReason|CategoryActivity|Category|CaseSensitive|Cache|BufferSize|Boost|Body|BlockCount|Bitmap|BinaryPathName|Binary|Begin|Before|Bcc|Base64Text|BackgroundColor|Average|AutoSize|Audit|Audio|AttributesOnNewLine|AttributeName|AttachmentPath|AttachmentLiteralPath|Asynchronous|AsString|AssemblyName|AsSecureString|AsPlainText|Ascending|As|Arguments|ArgumentList|ApplicationName|AppendPath|Append|Anonymous|Allocation|AllAddresses|All|Algorithm|After|Adjust|Activity|AclObject|ACL|Accessed) 
202
# Since you can abbreviate a parameter to it's shortest representation, it seems like the best thing is to just match any word starting with - 
203
# This *MIGHT* affect your math (if you don't leave a space after the -) but I think it'll be better than the alternatives 
204
      => array ( 
205
         GESHI_SEARCH => ' (-[a-zA-Z_][a-zA-Z0-9_]*)'
206
         GESHI_REPLACE => '\\1'
207
         GESHI_MODIFIERS => 'i'
208
         GESHI_BEFORE => ' '
209
         GESHI_AFTER => '' 
210
      ), 
211
# Variables always start with $ and they can be pretty much whatever ... 
212
      => array ( 
213
         GESHI_SEARCH => '(\\$[a-zA-Z_][a-zA-Z0-9_]*)'
214
         GESHI_REPLACE => '\\1'
215
         GESHI_MODIFIERS => ''
216
         GESHI_BEFORE => ''
217
         GESHI_AFTER => '' 
218
      ), 
219
      => array ( 
220
         GESHI_SEARCH => '(\[[a-z][a-z0-9_\.\]\[]+\])'
221
         GESHI_REPLACE => '\\1'
222
         GESHI_MODIFIERS => 'i'
223
         GESHI_BEFORE => ''
224
         GESHI_AFTER => '' 
225
      ), 
226
   ), 
227
   'STRICT_MODE_APPLIES' => GESHI_NEVER
228
   'SCRIPT_DELIMITERS' => array( 
229
   ), 
230
   'HIGHLIGHT_STRICT_BLOCK' => array( 
231
   ) 
232
); 
233
 
234
?>