Hacker News new | past | comments | ask | show | jobs | submit login
EditorConfig: Consistent coding styles across various editors and IDEs (editorconfig.org)
393 points by homarp 49 days ago | hide | past | web | favorite | 216 comments



These days I vastly prefer autoformatters, only run at precommit stage myself. Instead of having to adapt to different styles everytime and getting distracted by stylistic changes mid-coding (eg. on save), I can just rely that the styles are eventually consistent and code ahead. It takes some time getting used to, but it’s super refreshing.


Personally, I rely a lot on autoformatters ran on save. It frees my mind completely from thinking about formatting, I can write ugly one-liners that get immediately beautified and I have an almost-immediate feedback for syntax errors (it doesn't autoformat => I made a syntax error somewhere)


This was something I wasn't really expecting when I started working on prettier. It was a strong selling point when people adopted it within Facebook.

I still can't believe that it only took a year between the first commit of prettier and 100% of Facebook massive codebase to be completely formatted using prettier.

Prettier is also growing extremely quickly in open source. It's now at 3.7 million downloads a week, compared to 6 million for React.


Even if there were no other advantages to Prettier, I would use it for this. It seems barbaric to write in languages now that don’t have something similar happening on save.


I didn't get to say this before I quit working at FB, but thank you for building prettier! It really made writing and reviewing JS much less painful.


Agreed, I now feel like I'm editing the AST instead of editing text, it's quite magical.


That latter point is how I do a lot of my syntax-related bug finding with Emacs: press C-x h Tab, look for where the indentation starts to look unexpectedly wonky, fix the issue that caused it, repeat.


Same here. This is so powerful. I absolutely love python, but this is one thing it doesn't allow. On the other when working in say Rust, I can express my thought in a line or 2 straight from brain to keyboard without having to care about any formatting, hit autoformatter and also typically get an immediate feedback about basic syntax.

When writing in a language that can be auto formatted, it is a huge cognitive overload removed from my shoulders, like having a copilot.


Have you tried any Python autoformatters? `autopep8`, `yapf`, and `Black` come to mind.


My team just converted to `black`. I find it shockingly bad. I does format code legally according to its rules, but the result is often absolute trash from a human readability standpoint.


I’m fascinated by this response: Black has been the first Python autoformatter I have had that problem with and felt comfortable enabling as a pre-commit / CI check.

Do you have any examples of things which were so bad? The team has been pretty response for the handful of things which I reported.


I think it's really a people problem:

Black will mindlessly split long lines into shorter, and my coworkers will just leave them as is. The results are eye bleedingly awful.

I hope most black proponents expect people to look at the generated code and change things until it looks decent?

Of course this problem is inherent in a tool that is autoformatting rather than warning, and seems to me to indicate a mentality that code is meant to be read by computers, not humans.


I think some of this is just that you have strong personal opinions which are somewhat out of the norm. I have Black split long lines but the results are never what I’d call awful and I’d increasingly class that as a code-smell indicator since the cases where I haven’t been happy with the results were generally unnecessarily complex lines which could be split to be more readable.

I would also flip your last sentence completely: computers don’t have problems reading code of any style. Auto-formatting is so humans don’t burn time adjusting to different styles or, worse, failing to parse them the same way as a compiler.


You seem to be sitting on two chairs here.

The split of the long lines aren't bad, but they are also bad because the long lines are inherently too complex.

Of course some times our broken up lines are too complex, and should ideally be restructured, but...

1. The mechanical way Black does it is rarely the best way to decomplexify things.

2. Often the long line wasn't complex at all. It just contained a simple but long string. Line length is a weak measure of code complexity, but as a dumb script, it's all Black can use.

That said, my main beef is really with the 88 char line length. If it was 120 or 140, I wouldn't like Black either, but I'd only be kinda annoyed. Coupled with 4 char indentations, 88 s an absurdly small space to fit code in, when we have the biggest screens in history. It's an incomprehensible madness to me.

Not sure what your final section says. I hope it's not that humans should learn to read code just like computers do?

To me, one of the most important quotes about our job is this:

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”


FWIW, Black now allows line-length customization via the `--line-length` argument.


Yeah, we actually looked at that today, and I'm impressed by how it repairs what it tore apart in "88" mode.

We might change things up and I might be OK with my 'black life after all.


Yes. They can format correct python to pep8, but can't guess which if an else correspond to if I write it all on one or two lines.


This experience must have been with a formatter different than Black. That one has no problems with any valid syntax.


I think the point is that the valid python syntax is potentially a limitation on any autoformatting tool. Like, suppose you were writing in C. You might well write this:

    if(x);else if(y){if(z);else;}
and clang-format would turn it into this:

    if(x) {
    } else if(y) {
        if(z) {
        } else {
        }
    }
But the equivalent in Python has to be correctly indented to be interpreted properly, because you need to distinguish these two cases:

    if x: pass                 if x: pass
    elif y:                    elif y:
        if x: pass                 if x: pass
    else: pass                     else: pass
(This is the classic shift/reduce problem: https://www.gnu.org/software/bison/manual/html_node/Shift_00...)

This is sort-of not unreasonable, because of course code has to be syntactically correct for the autoformatter to do its thing, and if you're working in Python, these are the syntax rules. So, what can you do?

But suppose you'd come to find it valuable to be able to stuff all your code on one line and have the autoformatter sort it out: you might then find the Python syntax a backwards step by comparison, rather than an improvement. I think this is the claim that's being made, and no more.


It even has a name, the Dangling Else, and dates back to Algol:

https://en.wikipedia.org/wiki/Dangling_else


This is what I meant, yes, although I could never have explained it half as well as you did!


One solution is to make the formatter interactive and prompt for which interpretation is desired.

A CL restart-style editor integration for this could be interesting.


Ok, help me understand this. I’m on #TeamTab which puts me at odds with most coding standards. I usually work solo, so I don’t care, but every time I do let someone else edit a file, the commit shows every line has changed because their editor converts my indents.

Are you saying there’s a tool that will let me work with (superior) tabs but have standards compliant commits?

I’ve tried doing this in my .gitconfig with limited success. It didn’t work consistently.


The thing with ideal auto-formatters is that there is no discussion about tabs vs spaces anymore!

In a perfect world each language has exactly one (non-configurable) formatter and this solves all the formatting discussions.

For JS I use prettier and altough I am not 100% happy with some of the formatting choices I _love_ it because I can focus on code and not have flamewars about tabs vs spaces with my co-workers. prettier ends all style discussions. And code reviews are much nicer because people concentrate on checking the code, not the formatting.


I think the perfect world would have any number of formatters, but with ubiquitous tooling that allows each person to see code in their preferred format.


This sounds horrible for collaboration and pair programming tho.


The real-world choice is not (tabs) || (spaces), it's (tabs && spaces) || (spaces). Which is why spaces is the objectively superior choice.


In any project I've worked on that has used tabs for indentation, I've found no need to combine tabs and spaces. I've never been anywhere that enforces neurotic alignment standards, and if such guidelines aren't part of your workflow, I don't know why anyone would consciously inflict spaces upon themselves or their team. Some editors handle them like shit, and formatting fuckups always find their way in unless you're using an autoformatter.

The only arguments I hear for spaces are alignment (I don't have time to give a shit about such minor aesthetic preferences) and forcing other people to see code a certain way (I really don't understand why I would want to force my editing preferences on others). I don't think either one of them justifies the annoyance of spaces.


Huh? You say "[I wouldn't] force my editing preferences on others", yet you want to insist on inserting invisible whitespace characters into shared source code. That seems inconsistent to me.


That's a disingenuous misinterpretation of the comment. There's a clear difference between "I'd like code to be indented", which is widely agreed upon to be a good idea, and "you need to see my code indented with four characters because I hardcoded this into my source code", which is personal preference.


They are invisible whitespace characters that are handled reliably and flexibly in every editor that I've ever used them in. The same cannot be said for spaces. If a codebase is using two space indenting, I get to look at the resulting puke (this is subjective, of course) on my screen. I might be able to do some hackjob fix to change how they're displayed, but why should I have to? There's a character that satisfies both me and the animal that wanted to indent their code with 2 spaces.


You’re jumping to conclusions. Projects use both tabs and spaces because they have different purposes: tabs are for indentation, and spaces are for alignment. When you use spaces exclusively, you’re conflating the two and requiring tooling to be more complex to handle figuring out what you meant semantically from a lossy format. (Also, many people use who use tabs will do so exclusively and give up alignment, for simplicity’s sake.)


I'm not jumping to anything. Rather, I'm sharing my observations. I've been in the field for 20 years, and I stand by my point, which is that spaces will always find their way into a project. Projects that use tabs inevitably end up containing spaces too; not because of an intended specialized use case, but because of human nature.


Human nature being that people who prefer spaces will end up inserting them where they don't belong, and then have the gall to blame tabs for being confusing because they messed up the indentation :/


That's not true if your code style doesn't allow visually lining things up. Then tabs will only ever act as standard indentation, and so tabs vs spaces doesn't actually matter aside from enforcing line length.


Tabs allow each developer to choose his level of indentation. I think personal choice and flexibility to always be the objectively superior choice.


It depends on the exact formatting used. Many popular schemes only require tabs at the beginning of the line, and are not dependent on tab size.


Using hanging indents for line continuations solves this issue by making the choice of using tabs or spaces a non-issue.


This should help. Stick and en editorconfig file in the root of your project and tell it to use tabs and if all developers are using a supported editor then their (superior) spaces would be converted to the (inferior) tabs lol


on the other hand, i appreciate being able to comment out lines by typing `//` and not having my indentation f'd up. i also like to be able to un-indent stuff using backspace rather than shift-tab. also, using tabs at 4-spaces allows me to more easily detect misalignment since deleting one 4-space tab is obvious, while deleting a single space is not. while i know EOL line comments are not everyone's cup of tea, good luck getting good alignment (or changing alignment) on those with spaces.

i say tabs are superior. the real solution is probably variable width tabstops: http://nickgravgaard.com/elastic-tabstops/


> also, using tabs at 4-spaces allows me to more easily detect misalignment since

If you use an autoformatter there is no need to manually check for misalignement!

Just type in some code, press a key and everything is aligned, problem solved!


Yes. With this sort of tool, all this potential drudge work simply vanishes! I suppose if you don't use these tools, it might not be obvious just how amazingly super convenient it all becomes.

Indentation all fucked up? No problem, press the auto format key, and the computer will unfuck it for you.

Need to indent or unindent a block of code? No problem, press the auto format key. You don't even have to think about whether it needs more indentation, or less. The computer will do that for you.

Do you type all your code on one line without putting any spaces in? Well, don't tell anybody, just press the auto format key, and they will never find out. (I know I just told you not to tell anybody, but: I do this all the time. And it's great.)

In fact, you don't need to really think about any of this whatsoever even at this level of detail, because you can just develop the habit of pressing the reformat key every now and again. Or get the editor to do it every time you save, and then you don't even have to remember to do that.

But, however you do it, this sort of tool reduces to pretty much zero the amount of energy you have to expend on caring about how the code looks.


My experience with spaces is usually editors treating 4 spaces as a tab when backspacing. The rare need for a real single unit backspace has to be made up for with 3 additional spaces.


The trouble is most editors do this half-assed, for example you can select half of a "tab" if you use spaces, which makes no sense and lets you screw up the indentation easier.

The only editor that really does properly support "just set this option and then it's like you are using tabs" is Atom. But I don't really want to use Atom.


For an open source project, I'd recommend using an autoformatter, documenting it in the contributing guide, and enforcing it in CI so that anyone submitting a PR can clearly see if they submit something that breaks the formatting rules. I am much happier contributing to projects like these rather than trying to figure out all of the nuances of the author's preferred formatting style. Working with autoformatters for the last year or two has made me care much less about things like tabs vs spaces, I just care that the tooling is set up so that I don't need to think about it.

As a concrete example (for JS projects), you could configure Prettier to use tabs for indentation:

https://prettier.io/docs/en/options.html#tabs

Then you could use eslint-plugin-prettier, which fails lint if the code isn't Prettier-formatted and makes ESLint autofix also run Prettier:

https://github.com/prettier/eslint-plugin-prettier

Then set up lint to run in CI alongside tests.


Tabs are an editor feature, and their use in your editor is somewhat unrelated to the way your editor serializes them onto disk.

There are configurations for your editor that will allow this, independent of the EditorConfig project.


It may be an editor feature, but it's a UX anti-feature.

If you are in a system small enough that you only ever have to look at code in a code editor, then this anti-feature won't be a real problem.

If you work in a sufficiently complex environment that displays code across a variety of platforms, tabs will only make working with the code more difficult.


Not really. Most interfaces let you select the tab size or use some sensible default (e.g. 4). If you are using tabs properly it doesn't matter what display size they have.

One odd exception is GitHub which inexplicably uses size-8 tabs by default which is way too big. I can only assume that somebody there is a space zealot and wants to screw up the UX for enlightened tab users.


Take a look at a picture of a mechanical typewriter:

http://blog.gngcreative.com/wp-content/uploads/2015/02/mi0fg...

Those metal things you can see there, those are tabstops. They are called tabstops because when you press the tab key, the carriage mechanically stops at the tabstop.

Tabstops were placed every 8 characters. A tabstop is simply a way to "type" 8 spaces with one keypress.

Github is not the only page that uses 8 spaces for a tab, and it's definitely not inexplicable. The Unix/Linux terminal uses 8 spaces by default if you insert a tab. Vim uses 8 spaces by default if you insert a tab. Python considers a tab to be equivalent to 8 spaces. I'm sure there are a lot of other systems that default to this value.

If you want to control how an indentation looks, use spaces. If you want tabs because the size is configurable and can be adjusted to one's preferences, you can't at the same time complain about "unreasonable configurations" that others use :)


> Tabstops were placed every 8 characters. A tabstop is simply a way to "type" 8 spaces with one keypress.

tabstops were _not_ restricted to 8 characters. In many systems different tabstops were different widths from their predecessor. E.g. your first tabstop might be 20 characters in but all the ones after it would be 8 past their predecessor. Alternately you could vary all of them but that'd look pretty weird.


Thanks, TIL. But 8 was common, right? At least from online sources I was under the impression that typewriter tabstops were the reason for the 8 character default.


Ok but I don't know if you noticed but we don't use typewriters anymore.


I was only answering to the assertion that tab-width of 8 is "inexplicable".


Yes really.

When I have to work on N platforms that are constantly shifting, I don't want to spend the overhead and mental effort to reconfigure the ones that can be reconfigured, and eat nameless dread on the ones that can't.

When you view code across dozens of platforms, across dozens of machines, your perspective on "high maintenance config" everywhere changes a bit.

If you can't be effective with default configs, you lose efficiency to config maintenance.

Really, the last thing I want to deal with while I'm triaging some critical issue is dependency management for N code viewers.


The `.editorconfig` file in question actually also instructs GitHub to display source code in your repository with a given amount of spaces-per-tab. Just place the file in the root of your repository:

  root = true
  [*]
  indent_style = tab
  indent_size = 2
That being said, GitHub's default setting can only be seen as a spaces mongering ploy to subvert the true usage of tabs.


8 is the standard tab width. That's probably why GitHub chose it. (Why 8? I've no idea. Somebody will be along with an explanation soon enough, I am sure, and you can decide whether you believe it or not. But, whatever, it has been 8 for a very long time.)


To change it from 8, you need the `tab-size` CSS property. This has long been supported by all except IE/Edge.

This can be very neat for responsive design: use tabs for your indentation, and then on large screens use `tab-size: 4` because you’ve got space to spare and four is generally superior to two, and on narrow screens use `tab-size: 2` because you don’t have as much width to play with.


I don’t think it’s GitHub that chose this; the standard size for a tab in most browsers seems to be eight characters.


That's a good point. I checked and it does actually just seem to pass the tab characters through, letting the browser do its thing.


If you're using a typewriter and constructing tables (hence "tab"), 8 is a good balance between column width and number of columns.


This isn't true, because lining things up visually works differently with tabs than with spaces. (Although, personally, this is why I never visually align code like that, but that's the standard style in many organizations/languages.)


I will never understand why people get so religious about tabs vs spaces, but this is a hill I’m willing to die on: please don’t line things up visually in your source code, beyond standard indentation.


> but this is a hill I’m willing to die on: please don’t line things up visually in your source code, beyond standard indentation.

what's the argument against this? There are many arguments for how it can improve readability and speed up understanding of what you're looking at when you're not familiar with it.


There are some popular coding standards that essentially require it, unfortunately.

My opinion on this is that it's a bad idea in the age where we (finally) have near universal acceptance of source control, because they bloat commits with irrelevant changes in surrounding lines to preserve alignment when identifiers change. Black got it exactly right - optimize for readability and change locality.


why are you against it?


It’s brittle and fiddly, and it’s basically the only way to make it impossible to use proportional fonts, which are much more important for readability.

If you feel like it’s useful, you should probably be using an editor with real elastic tabstops instead.


"It’s brittle and fiddly"

You picked the wrong vocation my friend. It's "brittle and fiddly" all the way down.


the fact that most editors use mono-space fonts by default and hardly anyone is clamoring for the ability to use proprotional fonts seems to argue against them being particularly important to readability, at least as far as the community seems to be concerned.

re "you should probably be using an editor with real elastic tabstops" ... i don't get what you're trying to say. What does real or fake elastic tabstops have to do with the choice to align code beyond just indentation?


Manual alignment is often used as a poor man’s elastic tabstops.

I think there’s a chicken-and-egg situation with monospaced type and programming. Programming was a thing before digital proportional typefaces were a thing, so some people came to rely on the fixed spacing to treat their source code as a 2d grid rather than a 1d buffer. This in turn made it more difficult to switch over to proportional typefaces despite their advantages, and at some point code == monospaced was just taken for granted. Another issue that comes from mistaking your code for a 2d mosaic is the dogma of dictating a maximum number of characters per line, instead of the more reasonable approach of using whatever expresses the structure of the program most clearly, and relying on line wrapping to make sure it’s all visible.

FWIW I use proportional fonts, and 95% of the time it’s completely unproblematic. Fortunately I rarely work with code that uses manual alignment. It’s usually the occasional ASCII diagram that forces me to temporarily switch over to fixed pitch.


See `go fmt` for Go and Black for Python for examples to try out.


gofmt uses tabs too ;-)


Do git commit hooks work for you? You and your collaborators can do whatever. The hook ensures things are converted to either tabs or spaces prior to commit. You can also set up a CI job to auto-reject any PRs that aren't tab/space compliant.

This is all pretty pretty straightforward to configure on a per-repo basis too, so you can hop around multiple projects with different standards and not have to think too much about this.


> Are you saying there’s a tool that will let me work with (superior) tabs but have standards compliant commits?

Yes. It's an autoformatter and it will make you never care again about tabs and spaces and other unimportant issues us devs love to bicker about. Focus on the higher level stuff instead :)


I use both: an increasing percentage of formatters and linters support .editorconfig so you can set the common basics there and not need to duplicate configuration for every tool you use on a project.

I’m in very strong agreement on using formatters, too, but I have mine run on-save. It’s slightly disconcerting at first but extremely relieving when you realize how long it’s been since you’ve talked about code style.


I agree, I love on-save formatting. Now I can just type code I know is syntactically correct, hit save, and let the formatter worry about the formatting.


I first encountered this when I began working in golang because it was batteries included with go fmt.

I know this makes me late to the party, so can anyone comment on similarly dominant/official tools in their language of professional experience?

A web search can find tools, but it’s hard to know when one is likely to be “blessed” by potential future project teams.


C, C++, Objective-C: clang-format

Java: Probably google-java-format

HTML, CSS, JavaScript, TypeScript, Markdown, YAML: Prettier

Python: autopep8, yapf, and black are all widely used and I don't think any of them is dominant. I personally favor black, as it's the only one of the three that strives to leave as few degrees of freedom as possible (i.e., the same source code is always formatted the same way).

Rust: rustfmt


Black seems to be the most popular these days. It's certainly the one you hear the most about and it's getting support by default in vscode and pycharm.


Since we're on the subject: I was just looking into https://standardjs.com and wondering about how others are using these kinds of tools. It seems you've made extensive use of formatters: what made you decide on the ones you listed? I like linters a lot myself, but I'm not using formatters because it is difficult to work on code after a tool has reorganized it without my understanding of what it did. However, I rarely have time to go back through and do the cleanup myself. Does using these tools save you from the "I'll go back and clean this up later." mentality?


clang-format works with Java. It’s not as great at Eclipse’s formatter, but it is quite good and I’ve never had significant issues with it.


Black is written by python core devs AFAIK (pip install black).


I love it so much because you cannot configure it much, so it defines a clear standard that everybody can depend on



For Javascript, ESLint and Prettier are the most used (can be used together)

Flake8 + Black for Python do a good job


On my case,

C++, .NET languages, TypeScript, JavaScript: Default Visual Studio/VSC configuration

Java: Eclipse/Netbeans/InteliJ configured for Sun's conventions


I use go fmt and editor config together. Gotta tame the white space locally. All them tabs give me whiplash.


Bah I read a lot about the niceties of using autoformaters then I had to use clang-format for C++ at work and when I discovered that the format is totally borked when you use macros in lambdas, well..

I prefer manual formatting, yes each coder does it differently but who cares? The result is still readable which is NOT the case when an automatic formatting tool goes nuts..


I agree that autoformatters are the only way to go. It is nice if your editor kind of gets it close, though, so it's less jarring when things move around after save.


This is why I love gofmt. Because I don't care about formats and finally there's a tool to remove the tabs vs spaces debate and allow people to focus on issues of substance.


You might still want this for your editor to properly have indenting information as you are coding though no?


Also a good policy for naive diff algorithms that don't know whether minor changes are semantic or not (e.g. whitespace in Python vs. PHP)


So, do you format back again to your style before editing?

You can't preview a file without modifying the file.


My frustration with editorconfig files is that they don't have nearly enough breadth of config options to create close-to-identical setups for everyone on the team. The options are shallow compared to all the ways a modern formatter (like WebStorm's) can differ between users.

It seems like CLI tools built for a specific language are the best solution as of now.


At my job we use tabs, but elsewhere I've always used spaces. Rather than installing yet another plug-in, I use a Vim autocmd that checks to see whether I'm in a company repo, and if I am, it applies some overrides.

Links:

- Autocmd that runs on relevant filetypes: https://github.com/wincent/wincent/blob/db33e22c1/roles/dotf...

- Function that detects a work repo: https://github.com/wincent/wincent/blob/db33e22c1/roles/dotf...

- Function that finds nearest Git directory: https://github.com/wincent/wincent/blob/db33e22c1/roles/dotf...

- Function that applies overrides: https://github.com/wincent/wincent/blob/db33e22c1/roles/dotf...

(Disclaimer: like most things in my dotfiles repo, overengineering level 99.)


Am I the only who thinks that vimscript is truly awful and much inferior to Elisp?


As much as I like Elisp - does this matter in this context?


I guess not. Just a thought I suppose.


Having written quite a bit of vimscript, I can confirm for you its true awfulness.


What makes you say this? I don't necessarily _love_ Vimscript but it's a fairly straightforward imperative language. I also never understood why so many people rave about Elisp.


I mean, Elisp isn’t the greatest as languages go, but it’s really nice actually (compared to all the other languages that you use to script editors). The joke that everyone makes about emacs is “it’s an operating system with an editor on top” is actually 100% true. Emacs is built on top of Elisp, which is a testement to it’s power.

From your comment, it sounds like you’ve never used emacs/elisp. Why don’t you give it a try? With evil-mode, you don’t even have to give up your vim keybindings! Emacs is the most configurable and powerful editor in existence, and that’s not an opinion, it’s a fact.

PS: I actually use Intellij for my day to day scala work, but emacs is still the best (given enough time to configure/program the way you want).


I actually did try Emacs for a while for exactly the reasons you point out. I heard how great it was and wanted to see for myself what all the fuss was about. I used it exclusively for a few months and gained some familiarity with Elisp, but eventually ended up going back to Vim (for a variety of reasons that I'll not get into here). In my experience Vimscript is "easier" in the sense of going from an idea of something I want to do to actually implementing it.

Even after using Emacs + Elisp for all that time, I never experienced that transcendental moment that so many fans of Lisp dialects seem to share.


Git has a mechanism for getting the root repo directory - `git rev-parse --show-toplevel`


True. I guess I wanted to avoid shelling out, but it probably wouldn't hurt.



EditorConfig should be called CodeConformity.

The project doesn’t actually aim to provide consistent editor config. They only want to control code formatting.

The maintainers refuse to implement certain configs on principle, such as soft wrap.


I added an .editorconfig to every project at work. As lead it's my perogative to enforce standards. Personally I'm not super picky. If it's not mangled I have no opinion on formatting or editor choice of any dev on the team, except: tab inserts spaces, no auto-formatting an entire file allowed, and the editor must be editorconfig compatible.


Nah formatters are a must. If a standard isnt automatically enforced, its not enforced period.

Mix format

Go fmt

Prettier

Etc


Linters in CI enforce standards. I’ll admit it’s not as nice an experience as automatic formatting on every dev machine. But it’s how things have been done for a long time, including recently, in JavaScript, before prettier took off.


What's wrong with using a linter to format a file automatically?


It kills the history in the version control system.


This is true only if the formatter is introduced mid-project. Additionally, for git, it only messes up git-blame, you can still traverse the history and see changes prior to an autoformatting change.


It doesn't work for GUIs (e.g. github), but on the command line you can do `git blame -w` to ignore whitespace.


Github supports a ?w=1 param to do the same.

It disables the commenting interface on PRs however :(


I’m mixed on this if you use tools like GitHub or gitlab where it’s fairly easy to navigate the history so my rule is picking a quiet time to autoformat (i.e. coordinating open branches) and then marking the commit clearly as having no other impact so people can avoid reviewing it line by line.


I hate to respond with just 'this' but this is the correct response.

The problems we've had are all because we can't get consensus to auto-format, but then someone gets frustrated because they can't understand the code they're reading after someone committed mortal indentation sins, so then they auto-format and bam, history is worthless again.


EditorConfig is fantastic. I've used it for years now across client projects, internal work, and even in educational content that I've authored.

It honestly doesn't do a lot, but what it does do is standardize on things that are easily agreed upon like line endings and tab style / width. It leaves language specific options to purpose built linters.


But if the language-based linter is also an automatic formatter, what's the benefit of editorconfig?

All mainstream languages have good formatters these days that go much deeper and understand the language.


I use editorconfig for a lot of miscellaneous file types that I don't have an autoformatter for: markdown, jsonl, ...


Isn’t the advantage that EditorConfig allows you to choose a style over the style enforced by the language? For new languages and markup files this isn’t a problem because they may have developed a style guide in conjunction with the language but older languages don’t have that benefit.


Possibly, but I don't work with any teams that use any languages that don't have their own formatters, so I don't even know which languages are still missing one.

The languages they're using are C#, TypeScript, JavaScript, Go, Python, and Ruby.


Golang has solves this problem amazingly well. I only focus on writing code. Everything else gofmt takes care of. The best part is that since all Golang code is formatted the same way its quite easy to see if something is messed up simply by the code structure.


Do languages other than C# support formatter/convention configuration via EditorConfig? Or is C# going some other way here?

Ref: https://docs.microsoft.com/en-us/visualstudio/ide/editorconf...


It’s not a language feature but an editor feature. Editors often have built-in syntax-aware linters and refornatters that support additional rules you can put inside editorconfig files.

Visual Studio has built-in support for editorconfig and also supplies C#-specific formatting rules, hence why the web-page you linked-to exists.


I was looking at this just the other day not realizing it was something other than just a Microsoft thing. There didn't seem to be anything to deal with auto wrapping long lines by breaking them in sensible ways which is one of my favorite things about clang-format for C++. ReSharper does it for C# but doesn't do a very good job in my experience and ReSharper has such abysmal performance in Visual Studio that I've had to turn it off despite it having some useful features. The ability to smart wrap lines is something I haven't found a substitute for yet for C#.


I use a 40-inch 4K monitor running at 96dpi so I have evolved past the need to wrap long lines. Lines that are “too long” simply don’t exist!


I use a 43" 4K monitor as my main monitor and a 27" 1440p in portrait as my secondary. I typically have the Unity editor on my main monitor though and C# code on the secondary and in that arrangement with the font at a size I find comfortable I still need to wrap at around 120 columns. The other arrangement I sometimes use is two side by side windows on the 4K monitor and even that still has a width limit.

C# is pretty bad in this regard compared to C++ because the standard formatting rules of indenting namespaces and the fact that there are no free functions wastes a lot of the left hand side most of the time.


Yes. But my question is still unanswered: Do other editors provide something like this for other languages? It seems to me that it's a MS only thing.


I'm not sure this answers your question, but VS Code (MS still) does the same sort of thing for golang via gofmt on save.

I think it's enabled by default now.


I added EditorConfig to a project recently, and was super disappointed with the scarcity of things I could actually configure. I thought there would be many, many config settings. But I was wrong -- there are only eight (https://github.com/editorconfig/editorconfig/wiki/EditorConf...), with one of them listed as " Supported By A Limited Number of Editors", and the editor I was using (Intellij) is listed as supporting it, but does not.

I wanted to configure a lot of things, like "braces at the end of the line, not a new line by itself", or "always use braces, even in a single-statement branch", or even "one space after 'if' before the paren".

None of these are configurable with EditorConfig. It's pretty disappointing.


You probably want a code-formatter (perhaps on a git hook).

Trailing white space, fill-column width, and tabs vs. spaces are really all I’d expect from cross editor config.


IntelliJ supports editorconfig just fine.

I'm not sure why you were disappointed, editorconfig does not advertise the features you mentioned. For more involved autoformatting you need some kind of tool like gofmt or Prettier for JavaScript.


> IntelliJ supports editorconfig just fine.

When I set the line length config setting, and then have intellij autoformat a file, it doesn't break lines at that length.

> I'm not sure why you were disappointed, editorconfig does not advertise the features you mentioned. For more involved autoformatting you need some kind of tool like gofmt or Prettier for JavaScript.

The elevator pitch for EditorConfig, as taken from the first sentence of its website, is "EditorConfig helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs." The things I want I consider coding styles.


IMO there should be two configurations for code style. One for files and one for presentation. That way any coder can view and edit files to their own preferences.


You can already do that today if your editor implements a prettify-symbols-mode https://marketplace.visualstudio.com/items?itemName=siegebel...

You can let editorconfig/linters/formatters to take care of code style, and prettify-symbols-mode of your preferred presentation, which should be stable as well given a stable code style.


It's almost like plain text (with primitive ASCII art arrows and such) isn't a great user interface, even for developers! We should come up with some way of separating the Model and View... :-)


We have not even exhausted the possibilities of augmented text. IntelliJ at least annotates callee argument names and inferred types. For rust people are tinkering on borrowchecker region analysis annotations.

I'm sure there's more that could be done.


JetBrains MPS is such an example: https://www.jetbrains.com/mps/


This already exists when tabs are used for indentation.


Added support for this to git.sr.ht a while ago. It's used to set your preferred tab width and to show a ruler at the max line limit (which default to 8 and 80 columns respectively if you don't have an editorconfig file).


I really love the hand-drawn versions of all the icons for the editors this works with! They add a nice note of playfulness to the whole thing.


This is really old, so I am curious why is it on HN front page? Am I missing something here?


People occasionally repost content on forums. Usually it's because the OP hasn't seen it before and thought it would be good to share. As long as it's not excessive it can show a new bunch of people something they might not have seen before.

e.g. I've been on HN for a few years and have never heard of this.


Cool. I thought there was a new features or release. It’s a great tool. I use it VIM and VSCode


The editor can detect all of these for each file. If the editor doesn't, it probably don't support editorconfig either.


Editorconfig’s main benefit for me is the case when a contributor adds new files.


The settings can be derived from other files in the repo


Do you know of an editor plugin that does this reliably? I’ve tried a few in vim that end up being more trouble than they’re worth.

The hurestics can get tricky, especially when different file types have different kinds of indentation (got Makefiles in your otherwise two-space indented project?) or in projects that include vendored dependencies.


I dont know of such a plugin. But Im working on a editor that doesn't allow you to edit indentation. The trickiest part is for the editor to know which parts of the file it should touch when you for example insert a code block bracket. And should the diff in SCM now include the whole block, or just the lines where you inserted { and }. And also languages like Python where white space matters.


How can you release something like this with no emacs or vim support?


There is both Emacs and Vim support. Scroll down to "Download a Plugin".


Fair enough. I suck.


Call me a despot, but I am of the opinion that everyone should use the same development environment in a given team. That means same editor, same style and same OS. People might complain in the beginning if they have to change from another environment, but that will be short-lived, and the cost will be minimal compared to the otherwise continuing wankery and bickering over each developer’s subjective opinions on code style and editor. Why? The manager says so. It’s so simple at that point.


I couldn't disagree more. With modern tools like gofmt and Prettier for code formatting and Vagrant for dev VMs, it basically doesn't matter what environment anyone works in. Code style should always be enforced in an automated way, and running all your software in a VM means you don't need to install anything locally except for an editor and Git.

Edit: Obviously this doesn't apply if you do platform-specific work (like iOS development) or rely on tools that are only available on a single platform; in that case, you're probably right.


You underestimate the value of uniformity and group pressure. Everyone gets used to the one environment in the end. How did you pick up a programming language and editor in the first place? How did you pick up a new one? It was fine.

If people are using different environments, people are still able to wank and bicker over differences in environment.

By the way, it’s not just about code style and editor. By sharing the same environment, people can share build tools and other tools much more easily.


> You underestimate the value of uniformity and group pressure.

I don't, because I've worked in both kinds of environments and have not seen any benefits to the system you propose. Uniform development machines doesn't automatically mean that you've solved all consistency problems. Also, I'm not sure what you mean by "build tools" specifically, but any software needed for a project to run should ideally live within a Vagrant VM (or Docker or whatever), so it should be self-contained and not require any installation of additional software.

> How did you pick up a programming language and editor in the first place? How did you pick up a new one? It was fine.

IME, it takes several months to really become fluent and productive in a new editor, and potentially longer for a new language (depending on previous experience, etc). So "it's fine" as long as you consider a multi-month learning curve "fine".


> IME, it takes several months to really become fluent and productive in a new editor

I'm interested to know what editors you have switched to/from and why. Example, switched from emacs to vi because manager forced us to, etc.


I've tried many editors for various reasons, although I've never been forced to learn a new one for work. (The time I worked at a place where everyone used the same editor, it happened to be IntelliJ, with which I was already familiar.) The most difficult was when I switched to Vim fulltime to learn it. It took me about a year to really "grok" it and become productive. I've also done the same with Atom and VS Code, but those never felt as productive for me, so I gave up a month or two in. I keep coming back to IntelliJ, which is what I use now, because it fits so well with the way I work and I'm most productive with it.


Docker, Vagrant, build tools are all the same. They should just be uniform. Don't hire someone unexperienced in the uniform language. After that, one-time investment in assimilation to the uniform environment. That versus never-ending loss.


I completely agree with all of that, but I don't see what that has to do with your choice of editor or OS. If you use Vagrant/Docker, all your build tools should live there, so it doesn't matter what OS you use. I don't see what "never-ending loss" you face when people use different OSes or editors; I've never faced that in practice as it literally doesn't matter.


You’ve moved the OS into the docker image, so it’s basically the same OS, therefore I’m satisfied. What runs the docker image is less important, but it would be better to have uniform computers and OS in case one of them breaks. You can replace it much more easily.

What remains is editor/IDE. I’m still of the opinion that everyone should use the same development environment, preferably a full-fledged IDE which enforces code style at write time. This also prevents the bad diff issue, amongst a lot of the more important problems I’ve explained elsewhere.

Of course it’s all a matter of opinion. I base this opinion on how I experienced this environment. Nowhere else I’ve worked managed to get so much done and collaborate so easily.


You grossly underestimate our industry's ability to wank and bicker over everything anyway.

You also overvalue uniformity. Or under value the antifragility of not caring how the code was created. The most fragile systems I have ever had the displeasure of being near, required a very specific build machine because the environment couldn't be replicated. In large, because the original development team did what you propose, and mandated all development happen using the same controlled environment.


Hyper-standardized, pants-shittingly brittle build environments stemming from the mentality that the OP is suggesting is its own special sort of hell. It's "works on my machine" applied to a way bigger surface.

Yes, a team obviously has to agree on obvious things such as language and build system. However, cornering yourself into such a tight environment leaves a lot of opportunities to have the rug get pulled out from under you.

I currently work on a team that writes DAQ software in C++ for Windows. The developer has their choice in everything (editor, VCS front-end, debugging and profiling, etc.) as long as the build system runs, their code meets the team's code standards, and they're productive with it. We've found that we can basically close our eyes, point at a random target system, and odds are that our code base can be trivially ported to that target with minimal effort. That reality is possible because somebody has incidentally tested just about everything. At one point in the past, we had a pretty narrow/rigid build process, and it bit us in the ass and hamstrung more developers than it was worth.


How did it bite you in the ass out of honest interest? I have not done commercial C++, so I would be interested to know.


We were hit with the reality that the software (and/or components of it) may need to be run on Linux, OSX, and other targets at some point in the near future. At the time, everything was done with a single IDE, a single compiler, with specific old versions of libraries, only targeting Windows, and with no expectation that it would ever have to be done any other way, even though we probably should have assumed that the day would come. It was always assumed that it would just work, but life comes at you fast when you actually have to do it. After weaning the project off of environment specific tools, the process has become a lot more like our initial assumption.

C/C++ are unique in that build processes and integrating other people's code in them are inordinately hard problems in and of themselves. Different compilers will behave a little differently, different operating systems will behave a little differently, and some of the niceties that a certain IDE or tool provide you will behave a little differently, depending on the exact circumstances you're dealing with. The safe thing to do is make no environment assumptions, and try to make everything as portable between environments as possible. You need to have your focuses, but it's reassuring to know that you can jump ship if and when you need to.


Thanks for the input. Couldn’t that be solved by automated building and testing over multiple VMs?


Most anything can be solved by automation in software. The trick here is the anti-fragile nature of every new team member being a slight shock to the system.

You still need solid testing for making sure you don't miss regressions. So, we aren't claiming this is a replacement for any solid engineering strategies.


I never understand how people can even argue that uniform style is necessary, you have to dig into 3rd party code with different styles every day anyway.

And imo autoformatters are too inflexible. Most default rules are ok when you don't make any effort about formatting at all but break down when you manually lay out things for improved readibility. E.g. when splitting arguments to one arg per line and parens on separate lines and the autoformatter will just go and squash them all together into single lines up to the line limit, except the lambda in the middle which will be broken out into a separate line. Or other fun things like that.

Formatters which rearrange code by alphabetical sorting or sorting by visibility are even worse. They can introduce so much commit noise just because you change an identifier.


git diff -C can show rearrangements and renames.


it still pollutes the git blame, doesn't help with web views of code repos and causes more merge/rebase conflicts.

the sorting causes more problems than its very questionable worth.


Setting the git diff algorithm to patience or histogram would probably solve a lot of the merge issues. You’re right on the web views. It would be nice if they respected the algorithm setting from the git config.


In my experience the diff algorithms do nothing when one person moves the function and another edits it. The algos just fiddle around the margins of diff hunks.


> If people are using different environments, people are still able to wank and bicker over differences in environment.

How far would you take it? Would you (like Steve Jobs) try to get everyone to dress the same, too?


There’s a reason behind uniform in many institutions.


Interesting use of the passive voice! Yes, there is. Also common in places with uniforms: requirements for haircuts, nails, makeup/perfumes, daily inspections, etc. You didn't answer my question.

As Wikipedia says: "Modern uniforms are most often worn by armed forces and paramilitary organizations such as police, emergency services, security guards, in some workplaces and schools and by inmates in prisons."

One of these things is not like the others. Is running your professional software team like a paramilitary group or prison the only way you can get them to stop "bickering"? For people who are immature enough to bicker about any difference between individuals, when you enforce the standardization of one attribute, they just switch to something else.


Wikipedia does not say that the above is an example of the passive voice. Passive voice requires past participle. "is" above is present continuous anyway.

I don't think that running a software team like a paramilitary group is the only way to stop bickering, but some elements of how paramilitary groups are managed are very attractive in this context, and seem to have worked where I saw them applied.

The employees of a lot of banks happen to wear suits, shirts and trousers, programmers included. I wouldn't discount the benefit of this purely because paramilitary organisations also happen to enforce a uniform.


> Interesting use of the passive voice!

http://www.lel.ed.ac.uk/~gpullum/passive_loathing.pdf esp 3 (25)


Or they just leave.


I would strongly consider leaving if my manager decreed that I mustn’t use vim and must instead use webstorm/atom/whatever (especially if not in vim mode).

I’ve spent a lot of time setting up my dev environment so it works well for me, and I’m more productive and happy in it.

Style/formatting consistency is one thing, but editor uniformity is an unrelated thing. Yes, it makes collaborating easier, but is that worth the cost of people being less happy or less productive?

I don’t dislike other editors, but I like my setup a lot, and there are, imo, pretty huge switching costs involved in switching to/from vim/emacs and a GUI editor.


I have decades of experience with my preferred editor. That has more value than your whitespace preferences, even if they were incompatible (which isn't true).


I have used Emacs for over half my life. I had to use IntelliJ. Coding style was enforced. Same OS. It was fine. Maybe a bit of a struggle in the beginning. It was actually brilliant. I was soon whizzing away having learnt all the new shortcuts.

I would choose the benefit of uniformity over my personal preferences any day. You don’t know until you’ve seen it.


IntelliJ shortcuts are easy to learn because it hardly has any, in comparison. It's decent at Java boilerplate, but have you started writing plugins for editing other files? Because I can't convince myself that's worth the time investment.


If there aren't easily available and widely used tools for a chosen language, then it might not be the right choice.


Or the manager could just get everyone to stop their "continuing wankery and bickering over each developer’s subjective opinions". If you're a professional, you should act like it.

Most of my friends and coworkers use DeWalt, while some use Milwaukee, and there's even a few oddballs who use Makita, but I've never heard any 'bickering' about it.


I don’t agree with the analogy. The interface of a drill is much less complex and is basically the same over all brands. The longevity and power may well differ. Drill bits are standard and work as well in a Makita as in a DeWalt. I don’t think that tradesmen personally identify with their drills. Drills are not political.


Thus, EditorConfig! It's a standard for editor configuration, and is basically the same in all text editors.

Drill bits are standard, but lots of other tool interfaces are not. Batteries are not at all compatible, for example, and not even within the same brand (different voltage, different battery chemistry, ...). When someone's Milwaukee 18V lithium battery dies, and there's only a DeWalt 20V charger, nobody makes snide remarks about brand, any more than if you had the wrong size wrench for the bolt you needed to tighten.

It's true that "drills are not political", so why would you allow developers to claim that text editors are? That is a social problem, so it requires a social solution. You seem to keep implying that software developers uniquely posses an inability to behave reasonably in the presence of alternatives.


Developers are not unique in thinking that they are unique.


I agree with you if that editor is Emacs and the OS is Linux.


Don't you mean that OS is Emacs and the editor is evil... :)


> Linux

Linux is not a OS, it's a kernel. You would also have to force all developers onto the same distribution.


Yes, Gentoo.


is Emacs as OS on top of the Linux kernel a GNU/Linux?


I agree with you, but I am not the manager.


Beat me to it! LOL


This works, for some value of working, in structured corporate teams but good luck forcing open source developers to use a specific editor per project.


Have you actually tried this, and how did it work out on the team?


Yes. I hated it in the beginning, but it was so nice later on to be able to work together, share tools, share build scripts, to know my stuff would work on their stuff and to concentrate on the real issues.


Can you explain the situation and original environment a little more?

Those haven't been problems for the teams I've been on, and we've always been "every man for himself" when it comes to dev environment. As long as code follows the style guide, passes tests and gets through a code review, nobody cares about the dev's environment. Did you try that and it didn't work? What led to management mandating conformity?


I don't know what led to the decision. The CEO had already built a very successful company on the same principles. The company where I worked had these same principles from day one. This also happened to be a start-up and not a megacorp. This was not in an anglophone country, so norms differ. I am from England for the record. Out of all of the companies where I have worked, this has been the most successful, and became successful the quickest. The IDE was IntelliJ-based.

I have never before or since worked at a company that allowed "every man for himself" while managing to enforce the discipline required to maintain a uniform style guide, tests always passing and code review. It was nice to go over to a colleague's computer and see exactly the same code as I see on my own, and in the same environment. Everyone used the same debugger interface and same unit test interface, because everyone used the same IDE. They become more natural to use. People were able to refactor easily and maintain consistent naming standards, which is more difficult in Emacs, and especially in vim.


I'd leave any company where they tried to enforce that. Thankfully I'm at a career point where I get to decide without leaving, but I still regularly tell recruiters I'm not interested on the basis of OS and platform choices. It matters that much to my happiness.

So yes, the objections will be shortlived because anyone good enough to have options that don't like your choices will choose not to work in your team.


I respect your preference. I now prefer the tranquility of assimilation and consistency in my career. I would also tell recruiters that I do not care about OS and platform choices, as long as they are uniform across unique teams.


That's why I love languages with formatting tools like gofmt. There's no arguing about style, you just set it to format your code on each save.


Maybe not force everyone to use the same environment although it have tradeoffs. But absolutely lock down versions of tools used. I've had lost commits because different versions of SCM was used. Or stuff not working in different version of framework.


But why? You can enforce coding styles in a passive way through linters and formateers that work actoss IDEs. And in those rare cases that a junior dev is trying to show their worth by using a poorly configured VIM or Emacs, then there’s pre-commit hooks.


> That means same editor, same style and same OS.

The OS used for development is, in many cases, also the OS used for routine debugging. An OS monoculture on a cross-platform product team means that some product gets a lot more incidental testing than the others.


Multiple build targets enforced uniformly over the whole team.


I'm not talking about build issues, but runtime ones. There's a lot of stuff that comes up during routine debugging of desktop apps, for example.


There should be a process in place for routine testing on each target environment. Testing on BeOS shouldn't just be done because Bob happens to like doing his development on BeOS.


I didn't say that was the only testing, either. However, use during development is also testing, and in practice it can easily add up to more hours of testing than routine testing - and if all of those hours are on the same platform, then you get skewed picture overall. In addition, routine testing is usually much more scripted.

But frankly, your original point doesn't make sense to me, because there's simply no downside, so why argue about upsides? The team can agree on a single code style (or have that mandated from above), but how does that affect editors, and especially OSes? The only meaningful constraint is that one's choices must be able to handle the mandated style.

Same thing for other stuff. For example, it makes sense to mandate a testing framework. But if multiple IDEs support that framework, what's the point of forcing the choice on that?


Good luck making the UI developers use the same tools as the autonomy and perception engineers.


See “team”.


Not everyone works as developer #4932 on some fungible homogenous team.


That's it, isn't it? I cannot think of any other profession where such a large majority of people defend so strongly their right to work on their own terms inside an organisation. When was the last time you heard about a solicitor or someone from HR complaining that he won't use Excel or Word because org-mode or Corel Wordperfect is better for his needs, and he can just email the .org files around anyway. People can open them with wordpad.exe or TextEdit if they like.

I wonder whether this is actually a sort of class issue. The dissonance between being part of god's chosen tribe and the realisation of being decidedly middle class all the while. It manifests itself by turning people into Emacs emos. It's not a phase, I am unique, and I'll run away from home if you tell me otherwise.


I hate to say it but after reading all of your comments this on in particular think I'm sold on the idea and I was really against it when I read your first comment. I don't know if will catch on but I would definitely give it a chance.


Interesting thoughts. I haven't given it that much thought. All I know is that the tools that are great for C++ development aren't equally as great for web application development. But we are all certainly on the same team, collaborating on a daily basis.

It felt absurd that if we aren't all doing the same job then surely we're not on the same team


You're right on that. I never viewed backend and frontend as the same team. Obviously they should be using the appropriate tools for their job.


> Why? The manager says so.

That attitude is the quickest way to lose my respect.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: