Note:
- There are related existing posts, but this one makes a concrete proposal that complements the feature-request post that asks for proper PowerShell syntax-highlighting support via highlight.js, Enable automatic and on-demand syntax highlighting for PowerShell (updated for highlight.js)
Currently, the tags powershell and powershell-core are associated with SE's default highlighting behavior and with none at all, respectively. This currently often results in completely broken highlighting, as the language used for highlighting is then inferred from the other tags that a given post is tagged with, and if there is only one other tag for which a highlighting language is configured, that language is used for all code blocks; for instance, a post tagged with both xml and powershell will currently cause any PowerShell code to be uselessly and distractingly formatted as XML.
That problem will situationally go away once PowerShell syntax highlighting is fully supported, as requested in the linked post, but for the reasons discussed there, such requests are considered both low-priority and high-impact, so their implementation may be far off or, God forbid, may never happen at all.
As Andrew T. notes in a comment, this will not necessarily provide the proper highlighting automatically, given that if a question post has multiple tags that have highlighting languages assigned, it is automatic detection that kicks in, per code block,[1] which may or may not identify the code correctly. This is a general problem on SE, however; at a minimum, proper support will simplify providing manual highlighting hints, based on the powershell
tag, such as ```powershell
and <!-- language-all: powershell -->
Thus, this request is for a pragmatic stopgap that can be implemented right now and would significantly improve the current experience.
Make
lang-bash
the default code language for powershell and powershell-core FOR NOW, as long as proper PowerShell support isn't yet implemented:- Clearly, Bash is different from PowerShell, but the syntax is, at least in parts, similar enough to make for a passable highlighting experience that is superior to having none (see below).
- (If someone can come up with a better fit, all the better;
lang-php
appears to work similarly well / poorly.) - See the bottom section for examples and limitations of rendering PowerShell code with
lang-bash
.
The alternative - undesirable to my mind, but still an improvement over the current situation - is to disable highlighting altogether, i.e. to associate the tags with
lang-none
- More generally, it would make sense for all tags relating to languages for which no highlighter is currently available to default to
lang-none
, as suggested in Stop guessing/auto-detecting a language when you KNOW it will be incorrect
- More generally, it would make sense for all tags relating to languages for which no highlighter is currently available to default to
Workarounds for now:
To get a (somewhat) predictable, (mostly) useful highlighting PowerShell experience for now, individual code blocks - or whole posts, via a HTML comment - must be explicitly marked as using a specific highlighter, and there are two basic options:
Option A: Use
```lang-powershell
or<!-- language-all: lang-powershell -->
, even though thelang-powershell
highlight.js identifier isn't yet officially supported.The upside is that posts tagged this way could benefit from proper highlighting if and when it becomes available in the future, because
lang-powershell
should be a supported identifier then (see the list of supported languages in the highlight.js docs and their identifiers and how the map onto thelang-
-prefixed identifiers used on SE sites (section "Language codes currently available on Stack Exchange"), which are a subset of the languages that highlight.js supports.- That said, it seems that it takes at least a dummy edit to old posts in order to re-render them from the Markdown source based on the then-recognized languages.
For now, this currently unknown ID triggers automatic language detection, which is notably based on the specific code[2] (as opposed to the current behavior of letting other tags pick the language):
- Typically, PowerShell code is automatically detected as either
language-bash
orlanguage-php
, which, as stated, makes for a passable experience now.
- Typically, PowerShell code is automatically detected as either
The downside is that the automatic detection may sometimes pick an unhelpful language. In that case you can use Option B.
Option B: Tell a white lie and use
sh
(which maps ontolang-bash
) instead -```sh
or<!-- language-all: sh -->
The upside is that you get
lang-bash
highlighting predictably, resulting in passable highlighting.The downside is that you lock in that so-so highlighting, without automatically benefitting from proper highlighting if and when it becomes available in the future. (You'd have to go back and edit old posts manually). Also, it may be bit confusing to see a reference to a different language in the source code - fortunately, however, that is invisible to the readers of a post.
Examples of highlighting PowerShell code with sh
== lang-bash
:
- What works (well enough - note that there's generally little coloring, but at least there's no distracting incorrect coloring):
# This is a single-line comment; see below for block comments, which don't work.
# A (multi-line) pipeline; see below for line-continuation.
# Note: Very little coloring here, but at least there's no *incorrect*
# coloring.
Get-ChildItem -LiteralPath E:\ -Recurse -Directory |
Where-Object { $_.FullName.Length -ge 95 -and $_.BaseName.Length -ge 44 } |
Sort-Object -Descending { $_.FullName.Length } |
Rename-Item -NewName { $_.BaseName.Substring(0, 10) + $_.Extension } -WhatIf
# Variable assignments, string literals.
# See below re strings ending in \"
$foo = 'bar none' # single-quoted
$bar = "Honey,`nI'm $HOME" # double-quoted
# double-quoted with escaped " - "" works; see below for `"
$baz = "There was 3"" of snow."
# *Simple* here-strings.
@'
This is a line.
Another line.
'@
@"
This is a line.
Another line.
"@
# Here-strings that have **embedded strings using the same quoting*,
# render *somewhat* broken, but at least subsequent statements
# aren't affected:
@'
This is an 'embedded single-quoted string'.
Another line.
'@
@"
This is an "embedded double-quoted string".
$HOME is where the heart is.
2 + 2 = $(2 + 2)
Another line.
"@
# Language statements, such as `foreach`
foreach ($i in 0..19 + 19..0) {
' ' * (19-$i) + 'o ' * $i
}
# ... or `switch` ("break" is a Bash keyword, so it's highlighted)
switch -Wildcard -File $someFile {
'#*' { $_ }
default { break }
}
# Line continuations (which are best avoided).
Get-ChildItem `
-LiteralPath "C:\temp" `
-Filter *.txt
# .NET method calls:
# in-line
[int]::Parse(' 42', [cultureinfo]::CurrentCulture)
# multi-line
[int]::Parse(
' 42',
[cultureinfo]::CurrentCulture
)
- What DOESN'T work (shows workarounds, where possible):
<#
a block
comment, notably one containing what are normally
syntax elements, such as a "quoted string"
Fortunately, block comments are rare in PowerShell code snippets on SO.
#>
# A double-quoted string ending \" is interpreted as
# an escaped ", so the string's end isn't recognized.
# Note how "Get-Date" on the next line is colored as if it were
# still part of the string.
# WORKAROUNDS:
# * If feasible, use '...\', i.e. *single*-quoting instead.
# * A \ at the end of a file path is often not necessary and can be omitted.
# * Place a dummy comment with a single " at the end of the line,
# to at least avoid impacting subsequent lines; you can precede
# this dummy comment - #" - with enough whitespace so that it
# is out of view by default (would only become visible with horizontal
# scrolling.
Get-ChildItem "C:\temp\" -Filter *.txt
Get-Date
# Similarly, an unbalanced escaped `" inside "..." causes
# the true end of the string NOT to be recognized, as evidenced by
# "of snow" not rendering as part of the string and "Get-Date"
# on the next line being considered part of a *new* string that
# the " after "of snow" is considered to have started.
# WORKAROUND:
# Use "" instead of `" to escape embedded " chars.
$baz = "There was 3`" of snow."
Get-Date
[1] That is, all code blocks then use SE's default
highlighting, reflected in the HTML with an outer <pre class="default s-code-block">
element; see the next footnote for how to inspect this, and this post for an example, which has competing java and javascript tags.
[2] You can determine what specific language was auto-detected for a given block by using ```lang-powershell
and then inspecting the resulting HTML: lang-powershell
is retained as the outer class
value, but the first child element reveals what actual highlighting language is being used, such as PHP in this example:
<pre class="lang-powershell s-code-block">
<code class="hljs language-php">...
lang-bash
does that for PowerShell, while often - but definitely not always - doing the right(-enough) thing in general. To me, that's indubitably preferable to having no highlighting at all.