Vscode-powershell: Provide a built-in PowerShell code formatter

Created on 5 May 2016  路  20Comments  路  Source: PowerShell/vscode-powershell

Are there options for code formatting? If not, can this be put on the road map?

Issue-Enhancement

Most helpful comment

Since this is a commonly requested feature, let's discuss what features that a PowerShell code formatter should have in VS Code. I'd love to see before and after examples of script code which show how you'd like your code to be formatted. @kapilmb and I will be using your ideas and examples to come up with an initial code formatting implementation for a future extension update!

It doesn't matter if people don't agree on formatting styles; we're planning on making formatting rules configurable so that each user can get the code style that they want to see.

For those of you who are already aware of the PowerShell Best Practices and Style Guide, we are paying close attention to those rules as well :)

All 20 comments

Not yet, but after the 0.6.0 release this week I'm sure we'll see some code formatters show up thanks to the new extensibility model. We could provide a standard formatter in the future but I don't know if or when that might happen.

Any update on this one?

Any update on this? This is indeed core feature that is expected

I would be interested in helping out with this, I think this would be a great addition. 馃憤

Since this is a commonly requested feature, let's discuss what features that a PowerShell code formatter should have in VS Code. I'd love to see before and after examples of script code which show how you'd like your code to be formatted. @kapilmb and I will be using your ideas and examples to come up with an initial code formatting implementation for a future extension update!

It doesn't matter if people don't agree on formatting styles; we're planning on making formatting rules configurable so that each user can get the code style that they want to see.

For those of you who are already aware of the PowerShell Best Practices and Style Guide, we are paying close attention to those rules as well :)

I get a lot of scripts which before I can even look at them, need to fix indentation style for.
image
Number of spaces should be consistent and tabs or spaces should be used (I'm spaces but preferably configurable).
image
The reason this happens I guess is because of the author just copy pasting stuff in :-)

Also indent levels should be corrected:
image
image

This is basically my number 1 expectation of the formatter. The JSON formatter does a good job for me almost every day when I get ARM templates send in for review / bug fixing, Having a similar formatting fixer for PS code would be awesome!

Key Items

  1. Indentation Fixes such as BGelens excellent description above.
  2. Brace Alignment - Due to style differences, have a toggleable option to do:
function foo {
}

vs.

function foo 
{
}

(I think the first option should be default)

And something similar for Pipelines, e.g.

Get-ChildItem | Out-Gridview -PassThru | foreach {
    echo $_.fullname
}

versus:

Get-ChildItem | 
    Out-Gridview -PassThru | 
    foreach {
        echo $_.fullname
    }
  1. Alias/Parameter/Attribute/etc. Expansion. A lot of this already exists but having a "one click fix" would be nice. Basically allow me to write using a lot of shorthand, and then one-click clean it up into fully readable code.

_Example:_
gci * -dir | % {echo $_.fullname} | ogv -out sin

Becomes:

Get-ChildItem -Filter * -Directory | 
    ForEach-Object {
        Write-Output $PSItem.FullName
    } | 
    Out-GridView -OutputMode Single
}
  1. CamelCase fixes for statements and parameters based on their defintion
    _Example:_ fix get-childIteM to Get-ChildItem

Nice to Haves:

  1. Comment ending braces. For instance:
function Test-Something {
  if ($true) {
    echo "something"
  } #if
} #function Test-Something

There may be a lot of exceptions and preferences with what these comments should include so it's dangerous ground for a first release.

I'd rather have alias expansion be a separate operation. I have certain aliases I have whitelisted with PSSA and I wouldn't want the formatter to ignore that whitelist. I would also consider staying away from formatting pipelines to start with. Folks just have too many ways and I'm not sure there's much consensus.

Space between keywords and curlies/parens
I would like to see the formatter stick a space (or not based on setting) between keywords like do, for, foreach, if, switch, while, param and the opening ( or {. I'd also like to enforce that if there is text on the line before a { there is a space before the {.

@rkeithhill Can you explain more about the PSSA whitelist? Why wouldn't you want these cleaned or fully expanded? In either case could again easily be a true/false toggleable preference for the formatter. Just curious.

We use the PSSA whitelist, because we find it acceptable to use cd/pushd/popd in our scripts. I also would not expect a "formatter" to expand aliases.

@rkeithhill OK, so since it is a style preference I'd recommend it be available as an option as such. Just another toggleable field to put in your settings.json, something like:

"powershell.codeformatter.expandAliases": false,
"powershell.codeformatter.expandCommands": true,
"powershell.codeformatter.expandParameters": true

And if you really wanted to get fancy have a whitelist preference for each that you could just reference your existing PSSA whitelist.

Whether it's default or not I'd leave to @daviwil to decide, using the Style and Formatting guide as a baseline.

So to be a little more transparent about what we're doing, we are going to try to implement a set of rules in Script Analyzer which identify and apply code style fixes. Since PSSA can now do alias expansion with whitelisted aliases, everyone will get the behavior that they want but it just won't be considered a "formatting rule" :)

@daviwil I think that's the best way to go, as if its in PSSA it can be applied more generically than just in VSCode (you could use it in ISE for example). So what would this discussion for the VSCode portion specifically be about? How the UI would interface with it? I would assume any details in the actual formatting would be more appropriate to the PSSA github.

EDIT: For instance, I'd like the code formatter to hook into onSave via a preference variable, and then have a ctrl-shift-P option to invoke the code formatter. If I have text selected it only formats that code. If I have nothing selected, it formats the whole file I'm currently working on. That way I can do it both on-the-fly, or write shorthand and have it clean it up prior to a commit after I hit "save". What it does is purely to call this particular subset of PSScriptAnalyzer, and all the logic and preferences be there (maybe some of the PSScriptAnalyzer settings passed to settings.json variables such as discussed above)

Yep, or on the command line!

Whoops, missed the rest of the text, thanks e-mail preview. We were just getting the discussion started here so that we don't distract people with the Script Analyzer aspect. When we start the effort for this soon we'll be tracking it at the PSScriptAnalyzer repo.

As far as the UI is concerned, we'll be coming up with a way to configure PSSA more easily in the VS Code experience. Right now you can use the PSSA settings file to configure rules but we need a better experience than that.

@daviwil OK sounds good. My original post is the "before/after" you were asking for :).

https://github.com/PowerShell/vscode-powershell/issues/167#issuecomment-265205548

Yep, indeed it is. Thanks everyone for the great feedback so far! Seems like the largest benefit would just be straightening up the indentation and curly brace alignment. Regarding things like where curly braces go, those details will absolutely be configurable. We'll ship with some default rules that are configured to behave like the recommendations in the PowerShell community's style guide but you'll be able to change them to meet your own tastes.

@daviwil Only other thing I can think if is optionally a preview feature, that runs the code and then pops up a diff just like with how Git Compares work in VSCode so you can review before accepting. Can't imagine I'd personally use this often but others might find it helpful.

Hmmm that's an interesting suggestion, we could definitely give it a shot!

This was added in 0.9.0!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

TheDanishDynamo picture TheDanishDynamo  路  3Comments

rkeithhill picture rkeithhill  路  3Comments

keposet picture keposet  路  3Comments

timoline picture timoline  路  3Comments

bgelens picture bgelens  路  3Comments