15

Note:

Currently, the tags and 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 and 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 and 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


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 the lang-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 the lang--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 or language-php, which, as stated, makes for a passable experience now.
    • 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 onto lang-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 and 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">...

7
  • Re: XML + Powershell, I can understand adding highlighting to Powershell tags, with a caveat that Makyen has explained: if there are 2 or more tags with different language highlighting, then all will default to "default highlighting" instead, and each code block needs to be given highlighting hint.
    – Andrew T.
    Commented Oct 23, 2022 at 20:14
  • Thanks, @AndrewT., I've updated the post to clarify; please check that I got this right; I'm assuming you're saying that if at least two tags that have mapped highlighting languages are present, automatic detection kicks on for each block. Correct?
    – mklement0
    Commented Oct 23, 2022 at 20:43
  • 1
    Yeah, that's what I observed from this question with both 'java' and 'javascript' tags where no code blocks on the answers are highlighted with either 'java' or 'javascript'.
    – Andrew T.
    Commented Oct 23, 2022 at 20:54
  • There isn't any point in using syntax highlighting for any of these at the moment. For all practical purposes, syntax highlighting for the shell scripting languages is completely broken (e.g., what seems to be random highlight of variables names that happen to be some keyword in another context. Or weird highlighting of any kind of command line invocations (most scripts have them), with different options on the same level highlighted differently). With the current syntax highlighter, the syntax highlight for them ought to be turned off completely. And yes, this is configurable. Commented Oct 23, 2022 at 23:03
  • 3
    @PeterMortensen, syntax highlighting isn't about perfection, it's about whether it de facto helps the human observer visualize parse the code. It comes down to whether the highlighting is more helpful than not. Notably, it's very important to highlight comments as such, and something like 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.
    – mklement0
    Commented Oct 23, 2022 at 23:11
  • 1
    On the subject of load and priorities: Powershell-tagged questions are now more common than bash-tagged questions. insights.stackoverflow.com/…
    – Pxtl
    Commented Aug 9, 2023 at 17:20
  • 1
    Good to know, @Pxtl, thanks - and good to know about insights.stackoverflow.com/trends in general.
    – mklement0
    Commented Aug 9, 2023 at 17:27

0

You must log in to answer this question.