Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support a customisable formatter (custom indent settings, maybe .editorconfig?) #914

Open
Arcrueid opened this issue May 18, 2018 · 125 comments
Open

Comments

@Arcrueid
Copy link

@Arcrueid Arcrueid commented May 18, 2018

by my resolution I need to increase the tabsize from 2 to 4 spaces but it does not work

User settings:
"[dart]":{ "editor.tabSize": 4, "editor.insertSpaces": true, "editor.detectIndentation": false, }

when formatting the document, always use 2 spaces.

@DanTup
Copy link
Member

@DanTup DanTup commented May 18, 2018

I'm afraid this is by design. The formatter that Dart Code uses is the official one (https://github.com/dart-lang/dart_style) and it does not support changing indenting; it always uses 2 spaces.

I'd love to have an alternative formatter, as I'm not a big fan of dart_style's opinions, but it's way down the list of priorities at this time.

I'm gonna keep this issue open and move to the backlog, as I think having a flexible formatter (such as based on editorconfig) is a reasonable request.

@DanTup DanTup added this to the On Deck milestone May 18, 2018
@DanTup DanTup removed this from the On Deck milestone May 18, 2018
@DanTup DanTup added this to the Backlog milestone May 18, 2018
@DanTup DanTup changed the title Format Document Support a customisable formatter (custom indent settings, maybe .editorconfig?) May 18, 2018
@AshSimmonds
Copy link

@AshSimmonds AshSimmonds commented Jun 16, 2018

For anyone OCD'd by this in VSCode and needs 4 or whatever spaces in the mean time, install the Macros extension, and map a key (or remap ctrl-S, whatever) to something like this:

"macros": {
    "saveAndFormatCode": [
        "cursorEnd",
        {
            "command": "type",
            "args": {
                "text": "  "
            }
        },
        "cursorLeftSelect",
        "cursorLeftSelect",
        "editor.action.selectHighlights",
        {
            "command": "type",
            "args": {
                "text": "    "
            }
        },
        "editor.action.trimTrailingWhitespace",
        "workbench.action.files.save",
    ]
}
@DanTup
Copy link
Member

@DanTup DanTup commented Jun 16, 2018

@AshSimmonds How does that work? I presume it's effectively replacing 2-spaces with a tab, but I don't understand how it's working - what is the cursorEnd bit doing?

Also; if you are just replacing two spaces with a tab, this might mess up when stuff is indented with 4 spaces (wrapped lines) (though that might not be a big deal).

@DanTup
Copy link
Member

@DanTup DanTup commented Jun 16, 2018

Oh, I see - it's typing two spaces at the end, selecting them, then selecting all of the highlighted items (eg. the other double-spaces) and replacing them. Neat trick - though may have the issue mentioned above (and may mess with them insides strings, etc.)

@bwilkerson out of curiosity, does the plugin framework allow replacing the formatter in the server?

@AshSimmonds
Copy link

@AshSimmonds AshSimmonds commented Jun 16, 2018

I don't know that it's a great solution, but it works for me, for now.

Basically yeah - it puts the cursor at the end of the line (because often I save just willy nilly) then plugs in two spaces, then selects them, then selects ALL two spaces throughout the file, then replaces them with four spaces, then removes them by trimming - hopefully leaving the user where they were. (often it leaves you in the same place but still multi-selected, boo hoo but whatever)

@AshSimmonds
Copy link

@AshSimmonds AshSimmonds commented Jun 16, 2018

Oh and yeah - this will obviously mess up anything with two+ spaces in a string or whatever in your code - not my problem basically, just make your own sanity checks if you do stuff like that for some reason.

All this does is replaces all double spaces with quadruple spaces, nothing more, nothing less.

@bwilkerson
Copy link

@bwilkerson bwilkerson commented Jun 16, 2018

... does the plugin framework allow replacing the formatter in the server?

No. The plugin framework allows most operations to be extended, but not replaced. Replacement is hard. What if two plugins want to replace the same operation? Which one wins?

Extending is much easier. What if two plugins want to add navigation information? No problem, we just union all of the results.

However, not all operations are amenable to being extended. Formatting seems like one of those.

@DanTup
Copy link
Member

@DanTup DanTup commented Jun 16, 2018

Makes sense, thanks!

@pablote
Copy link

@pablote pablote commented Jul 9, 2018

Seeing how opinionated the dart_style guys are about this, would it make sense to fork dart_style? make a more configurable version of it, and use that instead on dart-code? I don't really think that being able to chose between tabs/spaces and/or the tab size hurts the lang at all.

@DanTup
Copy link
Member

@DanTup DanTup commented Jul 10, 2018

Whether it's worthwhile depends on a few things:

  1. How much work is it to make a flexible/customisable version of dart_style
  2. How much work would it be to replace the built-in formatter (dart_style is included in the server, it's not just as simple as changing a dependency)
  3. How will it effect code generated by the server (the user wouldn't want all quick-fixes etc. to provide space-indented code if they'd used tabs)
  4. What is the demand for this from users

Right now, I don't have a good answer for any of these.

It's something I'd personally like to see - I really dislike the 2-space indenting, and with an ultrawide monitor wrapping at 80 characters just makes me scroll up/down a lot three quarters of my screen is just the background of my editor - but the benefit needs to outweigh the cost and right now I don't know if it does. I am keeping an eye on the 👍's on this issue though, and so far there are only five and one of them is mine!

@pablote
Copy link

@pablote pablote commented Jul 10, 2018

Ok, that makes sense. I've only recently got into Dart, because of Flutter, and I don't personally feel very confident to do these changes myself. I don't like the 2 spaces either, line widths of around 120 make more sense nowadays, and formatting doesn't seem to handle widget hierarchies great:

output2

@DanTup
Copy link
Member

@DanTup DanTup commented Jul 10, 2018

@pablote That formatting looks really bad - I don't think it should do that. Could you paste that code into a new issue for me to look at? Also - did you increase the max length from 80? I found that makes things much worse (it tries to unwrap everything), though I would still expect the trailing commas to keep things on multiple lines.

@pablote
Copy link

@pablote pablote commented Jul 10, 2018

I did, but reverting back to 80 causes the same issue. Creating a new issue thanks.

@tabinnorway
Copy link

@tabinnorway tabinnorway commented Sep 21, 2018

Any idea if this is going to be worked on? I mean, it's not 1989. I have two big-arse monitors, and it's a little weird to have some Dart plugin developer tell me that all my Dart code needs to fit within the leftmost 1/6th of my editor space.

@DanTup
Copy link
Member

@DanTup DanTup commented Sep 22, 2018

it's a little weird to have some Dart plugin developer tell me

It's also a little weird for someone choosing to use a completely free open source plugin that I started in my spare time to suggest that I'm telling him how to write code 😕

As is stated in my comments above, I very much support this idea. I'm not a big fan of the default formatting either (I sometimes work on flutter_tools where I have to disable the formatter and format code manually). I have an Ultawide monitor and also think 80 character is silly (and although this is customisable, it causes other things to unwrap that I don't want).

The blocker for this is demand - see my comments in #914 (comment). If there is not enough demand then the analysis server is certainly not going to support it (and doing this without server support would not be efficient). The best thing you can for now do is put a 👍 on it and encourage others that want it to do the same. Supporting comments are welcome too, but please try to show a little respect for people that have put considerable spare time into delivering the free open source software you've chosen to use.

@AshSimmonds
Copy link

@AshSimmonds AshSimmonds commented Sep 22, 2018

@DanTup
Copy link
Member

@DanTup DanTup commented Sep 22, 2018

Re-indenting is a slightly simpler problem than changing the formatting entirely. Part of the problem I think many would like to see fixed though is the line-wrapping at 80 characters.

If fixing the indenting without changing wrapping etc. is valuable to many, then maybe there's value in doing something like your macro internally immediately after any format and on any new code inserted by code actions.

Put a 👍 on this comment if you think the indenting may be worthwhile on its own.

@AshSimmonds
Copy link

@AshSimmonds AshSimmonds commented Sep 22, 2018

Huh, ok. I've never noticed the line-wrap issue, always thought that was an IDE determined thing. Maybe I'm dumb and thinking of something else?

screenshot_20180922-185621
screenshot_20180922-185541

@DanTup
Copy link
Member

@DanTup DanTup commented Oct 22, 2020

@Junioreddn this is not currently supported by the Dart extension - that's what this issue is about. Right now the only formatting option is using the SDK formatter (dart_style), turning of the formatter (using dart.enableSdkFormatter) or using an alternative VS Code extension for formatting (though I'm not aware of any that exist currently that support Dart).

@Junioreddn
Copy link

@Junioreddn Junioreddn commented Oct 22, 2020

@Junioreddn this is not currently supported by the Dart extension - that's what this issue is about. Right now the only formatting option is using the SDK formatter (dart_style), turning of the formatter (using dart.enableSdkFormatter) or using an alternative VS Code extension for formatting (though I'm not aware of any that exist currently that support Dart).

@DanTup
It is exactly that, I spent all day yesterday editing and inquiring about the dart formatter to be able to put the Allman style in automatic, I even used this formatter:
image

It is from extension that I configured to have the Allman style but when I gave it to (Shift + Alt + F) it threw an error, so I had to put the default formatter of dart, but I still do not get used to this style

@Junioreddn
Copy link

@Junioreddn Junioreddn commented Oct 22, 2020

@DanTup
I really hope they add some option that allows you to configure that style in Dart, I wrote on twitter to Bob Nystrom, to know his opinion about it to see if they can suggest that idea to the developers of Dart style

Regards from Dominican Republic!! 😄

@phanirithvij
Copy link

@phanirithvij phanirithvij commented Nov 2, 2020

@DanTup #914 (comment) you said

The blocker for this is demand - see my comments in #914 (comment). If there is not enough demand then the analysis server is certainly not going to support it...

This is currently the #1 issue in the most upvoted list. Does that unblock it?
Also FYI it is the #3 most upvoted and #2 most commented issue in the dart_style repo.
cc: @munificent

@DanTup
Copy link
Member

@DanTup DanTup commented Nov 3, 2020

@phanirithvij my comment was that this is unlikely to happen if there's not clear demand, rather than it will be done if there is demand (apologies if this wasn't so clear). I think it's fair to say there is demand for this, but it's not a priority for me right now (there's a lot of other things to do and I have finite hours).

I have made some changes to make it easier to disable the SDK formatter in this extension, and I've offered pointers if someone wanted to build this (I think it would make sense in its own extension, even if I built it), though there have been no takers so far.

@JaapWeijland
Copy link

@JaapWeijland JaapWeijland commented Dec 3, 2020

I just wanted to share my 2 cents and say that I also would like to have an option to change to tabs / 4 spaces.

@Tbhesswebber
Copy link

@Tbhesswebber Tbhesswebber commented Dec 6, 2020

I just spent five minutes digging through the source code and discovered that they have an API available to create a new formatter. The formatter accepts arguments for page width and indents.

I know the fundamentals of building an extension, but have never used a language server, which I assume would be needed to build an extension that can actually run Dart code. Can someone point me towards resources that could get me off the ground for building a formatting extension so that we can all have a better time doing Advent of Code in Dart this year? 😂

@DanTup
Copy link
Member

@DanTup DanTup commented Dec 6, 2020

The formatter accepts arguments for page width and indents.

My understanding is that theindent field you're seeing there only sets leading indentation for every line, it does not control the character(s) used for indenting while formatting:

  /// The number of characters of indentation to prefix the output lines with.
  final int indent;

but have never used a language server, which I assume would be needed to build an extension that can actually run Dart code

The way I would go abouting build a separate formatting extension that used dart_style (or a fork of) would be to create a Dart command line app that ran in a "server mode" (similar to how the language server and Flutter tools work) that you can send JSON commands to over stdout to be formatted and returned JSON responses with the formatted code (or a set of edits). Compile that natively and ship it inside a VS Code extension that spawns the program at activation (and closes it at deactivation) and just translates VS Code's format requests over to it. That would avoid needing to have/locate any Dart SDK or worry about SDK versioning.

I expect the performance doing that would be fine, but some possible later improvements could then be to:

  • Send the file contents to the server when a file is first opened/modified and then send the edits - that way the server already knows the contents of all open files and getting a formatted file wouldn't involve sending the whole file contents over
  • Return just the minimal edits for the formatting rather than the entire formatted file (this is something the LSP server does, as replacing an entire file can result in breakpoints moving around for > 100k files in VS Code as it doesn't try to match old/new lines up)
@ivatar39

This comment was marked as off-topic.

@DanTup
Copy link
Member

@DanTup DanTup commented Dec 7, 2020

@ivatar39 this repo/issue is for the VS Code extension, and is unrelated to Android Studio. There are discussions about dartfmt in Android Studio at flutter/flutter-intellij#4617 and https://youtrack.jetbrains.com/issue/WEB-45838.

@JackLilhammers
Copy link

@JackLilhammers JackLilhammers commented Feb 3, 2021

While I argue that every project should be consistent in terms of visual and code style, I also think that the idea that every program written in one language adopts the same style is deeply flawed.

From the official FAQ

1 and 2

  • Consistency is paramount within the single project
  • Different projects developed by different people don't need to look the same
  • Anyone is much more likely to be a user of someone elses's code rather than a contributor.
    Therefore there's little benefit in forcing one true style

3 and 4

  • Sometimes breaking the rules greatly helps readability
  • Beauty is subjective
    Therefore removing all flexibility could actually produce code less readable and uglier for those who develop it in order to make it easier to read for someone who will never even know about the existence of that particular project

Also there are 2 other points not covered by the FAQ

  1. If people can avoid the formatter, and people very well can and do, this whole house of cards collapses onto itself, because the promise of uniformity is already broken
  2. Tabs help visually impaired people
    https://dev.to/alexandersandberg/why-we-should-default-to-tabs-instead-of-spaces-for-an-accessible-first-environment-101f
@GulliverMadrid
Copy link

@GulliverMadrid GulliverMadrid commented Mar 6, 2021

"it's an explicit decision by dart_style not to be configurable"

I hope this decision will be reviewed as it is not very developer-friendly. But in the meantime, perhaps it would be desirable to make the current situation more explicit from the beginning.

@DanTup
Copy link
Member

@DanTup DanTup commented Mar 8, 2021

"it's an explicit decision by dart_style not to be configurable"

I hope this decision will be reviewed as it is not very developer-friendly.

To be clear, the quote there is about the dart_style package. It's a Dart formatter designed to work in a specific way. It's not a goal or an explicit decision for the VS Code extension to not be configurable, but since it uses dart_style indirectly through the analysis server, it inherits that behaviour.

But in the meantime, perhaps it would be desirable to make the current situation more explicit from the beginning.

I've tried to be as explicit as possible about this. The very first reply at the top of this thread is me stating that this is a limitation of using dart_style and that although I'd like to support user preferences, it's definitely not a priority. I have left this issue open because I think it's a fair request (and I that there should be somewhere for people to put 👍 's so there is some visibility of demand) but it's not something I except to be tackled in the near future.

Let's try to avoid spamming everyone subscribed with the same complaints over and over. If you would like to see this issue, please add a 👍 . It's clear that many people would like this and that some find the idea that the formatter is not configurable ridiculous, but it's not particularly productive to keep repeating this - I'd prefer not to lock this issue since I've offered assistance if someone else wanted to create a VS Code formatter for this. Thanks!

@phanirithvij
Copy link

@phanirithvij phanirithvij commented Mar 9, 2021

@DanTup this is the most 👍ed issue in this repo. Did you set some 10000 goal to take a look at this?

@Tbhesswebber
Copy link

@Tbhesswebber Tbhesswebber commented Mar 9, 2021

@phanirithvij and others - I am neither a maintainer of, nor a contributor to, this extension, but there seems to be a major misunderstanding here. I don't mean to speak for @DanTup, but this was a pain point for me as well and, hopefully, my perspective helps to clarify the issue and how we can fix it.

Dart Code extends VS Code with support for the Dart programming language, and provides tools for effectively editing, refactoring, running, and reloading Flutter mobile apps, and AngularDart web apps.
readme.md#introduction

This is an extension to streamline the development and usage of Dart within VSCode. The aim isn't to provide new tooling for the Dart language as a whole, but to improve the development experience in Code to align with what you might see in Android Studio and other IDEs.

As Dan has said in their previous response, the pain point that we are all experiencing isn't one brought on by this extension, but by the tooling provided by the Dart team themselves. With enough 👍 on this issue, maybe we can add fuel to the fire for dart_style to become more accessible with configuration options. If you want your thoughts to be heard by those who can truly make the change, a great place would be within the dart_style package. While we would all hope that the Dart team would listen to the desires of their users, the tool expressly states that it is opinionated and targets the masses, not the needs of an individual, so this kind of change would realistically be a directional change to their roadmap.

In the meantime, someone could create their own formatter and Dan would support integration of that alternative tooling with the extension. I actually volunteered to do that before work got insane and you can see Dan's response showing their dedication to supporting such an effort.

@avkonst
Copy link

@avkonst avkonst commented Mar 9, 2021

Then, it looks like the deal is to fork the dart_style, change these two lines: https://github.com/dart-lang/dart_style/blob/51a93d9fa37d1b0ae034ca2190c2bdc9ce77ec4f/lib/src/whitespace.dart#L10-L13
from 2 to 4 and release a new package. Next notify Dan to add an option to the extension to choose between 2 formatters the current one and the new one. The new one will need to keep merging in all future updates from the current and keep this patch applied. Is this the plan?

@DanTup
Copy link
Member

@DanTup DanTup commented Mar 10, 2021

My suggestions for how I would build it are in #914 (comment), which is to build as its own VS Code extension.

It's not possible to just switch the formatter inside this extension as dart_style is not consumed directly by the VS Code extension. Instead, it the requests go to the language server and it does the formatting (it has a dependency on dart_style). It's unlikely a fork of dart_style would be merged into the SDK. VS Code also has functionality to switch between formatters, but it is done in the basis of one extension == one formatter.

@ngdangtu-vn
Copy link

@ngdangtu-vn ngdangtu-vn commented Mar 13, 2021

I would like syntax style like this:

void main() async
{
   // tab that equivalent to 3 space indents
   Map<String, String> map =
   {
      'This': 'is',
      'a'   : 'very',
      'very': 'long',
      'long': 'map',
   };
}

Do you think it is possible to ask for a customized formatting like this? All the brackets type will have a newline if the content inside is too long. For function and statements (if, for, while, etc.), its brackets always have a newline. Also inside indentation as well, it would be great if I'm allowed to align colons in the sane column.

@munificent
Copy link

@munificent munificent commented Mar 23, 2021

Then, it looks like the deal is to fork the dart_style, change these two lines: https://github.com/dart-lang/dart_style/blob/51a93d9fa37d1b0ae034ca2190c2bdc9ce77ec4f/lib/src/whitespace.dart#L10-L13
from 2 to 4 and release a new package.

That's a start, but you'll probably find it leads to unpleasant formatting that you don't expect in many cases, for example, wrapped expressions in conditions would now confusingly line up with the body:

if (functionNameThatIsVeryLong() ||
    anotherFunctionName) {
    nowThisLinesUpWithTheCondition();
}

You'll likely find a cascade of other formatting changes that you need to make in order to get a holistic set of output that you like. I would suggest making the change, running the tests, and see what breaks. Change the expected output in the tests to be how you like. Then circle back to the formatter and figure out what other changes you need to make to it to get all those tests to pass.

@avkonst
Copy link

@avkonst avkonst commented Mar 23, 2021

@JackLilhammers
Copy link

@JackLilhammers JackLilhammers commented Mar 24, 2021

One could almost borrow your philosophy of the greater good and say that's a small price to pay for actually being able to read the rest of the code...

Or the formatter could do the smart thing and put the operators to the left, where they can be aligned regardless the length of the operands

if (longLongLongLongLongLongLongLongLongLongLong()
    || shorter()
    || notShortButNotLongest()) {
    nowThisVisuallyDiffersFromTheCondition();
}

Of course if that still seems confusing to you, the easiest thing you can do is tweak what you send it. While the formatter tries to make all code look great, there are trade-offs in some of the rules. In those cases, it leans towards making more common idioms look better.

If your code ends up looking bad, your code may be off the beaten path. Usually hoisting an expression up to a local variable or taking a big lambda out and making it a named function is all that's need to get back to a happy place.

@locohost
Copy link

@locohost locohost commented Mar 30, 2021

Using "dart.enableSdkFormatter": false in my settings.json did the trick for me! I now have my tab-4 working perfectly in .dart files in VS Code. Thank you for all the help @DanTup!! :-) NOTE: Using "Format Document" stops working, but at least my manual formatting stays when I save. I'm happy :-)

@GZGavinZhao
Copy link

@GZGavinZhao GZGavinZhao commented Apr 17, 2021

I think it might be a good idea to have a settings json file for us to edit and tweak specific settings.

@gostan99
Copy link

@gostan99 gostan99 commented Jun 11, 2021

I would like syntax style like this:

void main() async
{
   // tab that equivalent to 3 space indents
   Map<String, String> map =
   {
      'This': 'is',
      'a'   : 'very',
      'very': 'long',
      'long': 'map',
   };
}

Do you think it is possible to ask for a customized formatting like this? All the brackets type will have a newline if the content inside is too long. For function and statements (if, for, while, etc.), its brackets always have a newline. Also inside indentation as well, it would be great if I'm allowed to align colons in the sane column.

I like this style too. It is easier to read in my opinion

@jabezborja
Copy link

@jabezborja jabezborja commented Jun 22, 2021

I love the auto-formatting of Dart but I don't like this:

final Widget myWidget =
     await Widget();

Can I disable it? I just don't want that. Can I get it just one line?

@DanTup
Copy link
Member

@DanTup DanTup commented Jun 22, 2021

@jabezborja The formatting rules are from dart_style rather than this extension. However, I can't reproduce what you're seeing, it always goes on a single line. Can you provide a complete code sample that is formatting like this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet