Visual Studio Code C++ Formatter: indent with tabs, align with spaces? - formatting

How would I go about configuring a formatter (in my case, the Visual Studio Code C/C++ formatter) to indent with tabs, but align with spaces?
I've looked at this post and this post, but they were asked more than 5 years ago and I'm wondering if anyone has some new information to share.
I don't mind manually typing out the spaces to align, I just don't want the formatter to convert 4 spaces into a tab.
For reference, I would like my code to be formatted like this, where ---> indicates a single tab and . indicates a single space:
if (condition) {
--->aLongFunction(something).// does something
--->a(b).....................// does something else
}
If I save this code, Visual Studio Code will format it as such:
if (condition) {
--->aLongFunction(something).// does something
--->a(b)--->--->--->--->--->.// does something else
}
This is bad because if someone else wants to look at my code and they have their tab-width set to 2, it would look like this:
if (condition) {
->aLongFunction(something).// does something
->a(b)->->->->->.// does something else
}
And now it is no longer aligned, just strangely spaced out!
I think I value alignment more than I value tabs, so if it comes to it, I will simply switch to use spaces over tabs, but it would be nice if the formatter could see what I'm trying to do!

Related

How can I configure different spacing rules inside for loops in IntelliJ Idea's code style settings?

I am currently working on a Java project, and I am finding IntelliJ Idea's code style system to be extreamly frustrating as it refuses to accept the settings that I want to give it. Specifically, I want spaces around various operators unless they're inside a for loop's header. For example, the following code should be output:
for(int x=0;x<10;++x){ // no spaces around operators when they're in a for loop's header
System.out.println(x);
}
int a = 10; //spaces around = when not in a for loop's header
int b = 50;
a = b;
if(a < b){ //an if statement is not a for loop's header
doSomething();
}
In essence, I want IntelliJ to make an exception to normal space rules when in the header of a for loop, removing these spaces. It looks absolutely disgusting to me to have what should be a dense construction filled with superfluous spaces, to the point that it is making me not want to use IntelliJ Idea at all, despite its numerous great features. THis, for example, severely diminishes the utility of its automatic refactoring ability because I need to manually go through and fix its formatting errors after every refactor.
When I look in the code style settings, the "around operators" checkboxes seem to have no mechanism for a different setting inside for loops:
How can I get IntelliJ Idea to format my code correctly?

How can I automatically format C# line indentations like VB.NET

When I write something in VB.NET, the IDE automatically formats my line indents perfectly, I don't have to use the tab key at anytime.
In C#, when I needed to edit a line of code, and I perhaps wrecked up the indentation like this...
void MyVoid()
{
if (1==1)
{
int iThis = 5; //line with ugly indentation
}
}
..., and I have to correct the indentation manually or use Ctrl AKF to fix it.
In VB.NET, the IDE would fix it automatically when I skip to any other line.
How can I make this as easy as it is in VB.NET?
You can use my (commercial) Continuous Formatting extension that formats the code as you type.
Power Commands has an option to automatically format the document when you save. There's also a lighter-weight extension titled Format document on Save that should do the same.

Apache POI: Partial Cell fonts

If I crack open MS Excel (I assume), or LibreOffice Calc (tested), I can type stuff into a cell, and change the font of parts of the text in a cell, such as doing, in one cell, :
This text is bold and this text is italicized
Again, let me reiterate, that this string could exist in the shown format in one cell.
Can this level of customization be achieved with Apache POI? Searching only seems to show how to apply a font to an entire cell.
Thanks
===UPDATE===
As suggested below, I ended up going with the HSSFRichTextString (as I'm working with HSSF). However, after applying fonts (I tried bold and underline), my text would remain unchanged. This is what I attempted. To put things in context, I am working on something sports-related, in which it is common to display a match up in the form "awayteam"#"hometeam", and depending on certain external conditions, I would like to make one or the other bold. My code looks something like this:
String away = "foo";
String home = "bar";
String bolden = "foo"
HSSFRichTextString val = new HSSFRichTextString(away+"#"+home);
if(bolden.equals(home)) {
val.applyFont(val.getString().indexOf("#") + 1, val.length(), Font.U_SINGLE);
} else if(bolden.equals(away)) {
val.applyFont(0, val.getString().indexOf("#"), Font.U_SINGLE);
}
gameHeaderRow.createCell(g + 1).setCellValue(val);
As you can see, this is a snippet of code from a more complicated function than is displayed, but the brunt of this is actual code. As you can see, I'm doing val.applyFont to part of a string, and then setting a cell value with the string. So I'm not entirely sure what I did wrong there. Any advice is appreciated.
Thanks
KFJ
POI does support it, the class you're looking for is RichTextString. If your cell is a text one, you can get a RichTextString for it, then apply fonts to different parts of it to make different parts of the text look different.
You would be drained if working with SXSSFWorkbook, as it does not support such formatting.
Check it here.
http://apache-poi.1045710.n5.nabble.com/RichTextString-isn-t-working-for-SXSSFWorkbook-td5711695.html
val.applyFont(0, val.getString().indexOf("#"), Font.U_SINGLE);
You should not pass Font.U_SINGLE to applyFont,but new a Font, such as new HSSFFont(), then setUnderline(Font.U_SINGLE).
example:
HSSFFont f1 = new HSSFFont();
f1.setUnderline(Font.U_SINGLE);
val.applyFont(0, val.getString().indexOf("#"), f1);

How do I force opening braces to share the previous code line?

Using the Uncrustify tool I would like to apply the 1TBS style, which places braces like this:
if (x < 0) {
printf("Negative");
}
How do I do this? I can't seem to find the right options.
I think you need to set nl_if_brace to ignore/add/remove/force.
Also, check the sp_else_brace and sp_brace_else options. Set it to 1, otherwise your code will end up with code such as:
if (condition){
instead of
if (condition) {
There's a tool called UniversalIndentGui that lets you play with Uncrustify's various tersely-worded settings and see immediate impact on a block of sample code.
Screenshots of UniversalIndentGUI

Proportional font IDE

I would really like to see a proportional font IDE, even if I have to build it myself (perhaps as an extension to Visual Studio). What I basically mean is MS Word style editing of code that sort of looks like the typographical style in The C++ Programming Language book.
I want to set tab stops for my indents and lining up function signatures and rows of assignment statements, which could be specified in points instead of fixed character positions. I would also like bold and italics. Various font sizes and even style sheets would be cool.
Has anyone seen anything like this out there or know the best way to start building one?
I'd still like to see a popular editor or IDE implement elastic tabstops.
Thinking with Style suggests to use your favorite text-manipulation software like Word or Writer. Create your programme code in rich XML and extract the compiler-relevant sections with XSLT. The "Office" software will provide all advanced text-manipulation and formatting features.
i expected you'll get down-modded and picked on for that suggestion, but there's some real sense to the idea.
The main advantage of the traditional 'non-proportional' font requirement in code editors is to ease the burden of performing code formatting.
But with all of the interactive automatic formatting that occurs in modern IDE's, it's really possible that a proportional font could improve the readability of the code (rather than hampering it, as i'm sure many purists would expect).
A character called Roedy Green (famous for his 'how to write unmaintainable code' articles) wrote about a theoretical editor/language, based on Java and called Bali. It didn't include non-proportional fonts exactly, but it did include the idea of having non-uniform font-sizes.
Also, this short Joel Spolsky post posts to a solution, elastic tab stops (as mentioned by another commentor) that would help with the support of non-proportional (and variable sized) fonts.
#Thomas Owens
I don't find code formatted like that easier to read.
That's fine, it is just a personal preference and we can disagree. Format it the way you think is best and I'll respect it. I frequently ask myself 'how should I format this or that thing?' My answer is always to format it to improve readability, which I admit can be subjective.
Regarding your sample, I just like having that nicely aligned column on the right hand side, its sort of a quick "index" into the code on the left. Having said that, I would probably avoid commenting every line like that anyway because the code itself shouldn't need that much explanation. And if it does I tend to write a paragraph above the code.
But consider this example from the original poster. Its easier to spot the comments in the second one in my opinion.
for (size-type i = 0; i<v.size(); i++) { // rehash:
size-type ii = has(v[i].key)%b.size9); // hash
v[i].next = b[ii]; // link
b[ii] = &v[i];
}
for (size-type i = 0; i<v.size(); i++) { // rehash:
size-type ii = has(v[i].key)%b.size9); // hash
v[i].next = b[ii]; // link
b[ii] = &v[i];
}
#Thomas Owens
But do people really line comments up
like that? ... I never try to
line up declarations or comments or
anything, and the only place I've ever
seen that is in textbooks.
Yes people do line up comments and declarations and all sorts of things. Consistently well formatted code is easier to read and code that is easier to read is easier to maintain.
I wonder why nobody actually answers your question, and why the accepted answer doesn't really have anything to do with your question. But anyway...
a proportional font IDE
In Eclipse you can cchoose any font on your system.
set tab stops for my indents
In Eclipse you can configure the automatic indentation, including setting it to "tabs only".
lining up function signatures and rows of assignment statements
In Eclipse, automatic indentation does that.
which could be specified in points instead of fixed character positions.
Sorry, I don't think Eclipse can help you there. But it is open source. ;-)
bold and italics
Eclipse has that.
Various font sizes and even style sheets would be cool
I think Eclipse only uses one font and font-size for each file type (for example Java source file), but you can have different "style sheets" for different file types.
When I last looked at Eclipse (some time ago now!) it allowed you to choose any installed font to work in. Not so sure whether it supported the notion of indenting using tab stops.
It looked cool, but the code was definitely harder to read...
Soeren: That's kind of neat, IMO. But do people really line comments up like that? For my end of line comments, I always use a single space then // or /* or equivalent, depending on language I'm using. I never try to line up declarations or comments or anything, and the only place I've ever seen that is in textbooks.
#Brian Ensink: I don't find code formatted like that easier to read.
int var1 = 1 //Comment
int longerVar = 2 //Comment
int anotherVar = 4 //Command
versus
int var2 = 1 //Comment
int longerVar = 2 //Comment
int anotherVar = 4 //Comment
I find the first lines easier to read than the second lines, personally.
The indentation part of your question is being done today in a real product, though possibly to even a greater level of automation than you imagined, the product I mention is an XSLT IDE, but the same formatting principles would work with most (but not all) conventional code syntaxes.
This really has to be seen in video to get the sense of it all (sorry about the music back-track). There's also a light XML editor spin-off product, XMLQuire, that serves as a technology demonstrator.
The screenshot below shows XML formatted with quite complex formatting rules in this XSLT IDE, where all indentation is performed word-processor style, using the left margin - not space or tab characters.
To emphasise this formatting concept, all characters have been highlighted to show where the left-margin extends to keep indentation. I use the term Virtual Formatting to describe this - it's not like elastic tab stops, because there simply are no tabs, just margin information which is part of the 'paragraph' formatting (RTF codes are used here). The parser reformats continuously, in the same pass as syntax coloring.
A proportional font hasn't been used here, but it could have been quite easily - because the indentation is set in TWIPS. The editing experience is quite compelling because, as you refactor the code (XML in this case), perhaps through drag and drop, or by extending the length of an attribute value, the indentation just re-flows itself to fit - there's no tab-key or 'reformat' button to press.
So, the indentation is there, but the font work is a more complex problem. I've experimented with this, but found that if fonts are re-selected as you type, the horizontal shifting of the code is too distracting - there would need to be a user-initiated 'format fonts' command probably. The product also has Ink/Handwriting technology built-in for annotating code, but I've yet to exploit this in the live release.
Folks are all complaining about comments not lining up.
Seems to me that there's a very simple solution: Define the unit space as the widest character in the font. Now, proportionally space all characters except the space. the space takes up as much room so as to line up the next character where it would be if all preceeding characters on the line were the widest in the font.
ie:
iiii_space_Foo
xxxx_space_Foo
would line up the "Foo", with the space after the "i" being much wider than after the "x".
So call it elastic spaces. rather than tab-stops.
If you're a smart editor, treat comments specially, but that's just gravy
Let me recall arguments about using the 'var' keyword in C#. People hated it, and thought it would make code less clear. For example, you couldn't know the type in something like:
var x = GetResults("Main");
foreach(var y in x)
{
WriteResult(x);
}
Their argument was, that you couln't see if x was an array, an List or any other IEnumerable. Or what the type of y was. In my opinion the unclearity did not arise from using var, but from picking unclear variable names. Why not just type:
var electionResults = GetRegionalElactionResults("Main");
foreach(var result in electionResults)
{
Write(result); // you can see what you're writing!!
}
"But you still cannot see the type of electionResults!" - does it really matter? If you want to change the return type of GetRegionalElectionResults, you can do so. Any IEnumerable will do.
Fast forward to now. People want to align comments en similar code:
int var2 = 1; //The number of days since startup, including the first
int longerVar = 2; //The number of free days per week
int anotherVar = 38; //The number of working hours per week
So without the comment everything is unclear. And if you don't align the values, you cannot seperate them from the variales. But do you? What about this (ignore the bullets please)
int daysSinceStartup = 1; // including first
int freeDaysPerWeek = 2;
int workingHoursPerWeek = 38;
If you need a comment on EVERY LINE, you're doing something wrong. "But you still need to align the VALUES" - do you? what does 38 have to do with 2?
In C# Most code blocks can easily be aligned using only tabs (or acually, multiples of four spaces):
var regionsWithIncrease =
from result in GetRegionalElectionResults()
where result.TotalCount > result > PreviousTotalCount &&
result.PreviousTotalCount > 0 // just new regions
select result.Region;
foreach (var region in regionsWithIncrease)
{
Write(region);
}
You should never use line-to-line comments and you should rarely need to vertically align things. Rarely, not never. So I understand if some of you guys prefer a monospaced font. I prefer the readibility of font Noto Sans or Source Sans Pro. These fonts are available freely from Google, and resemble Calibri, but are designed for programming and thus have all the neccesary characteristics:
Big : ; . , so you can clearly see the difference
Clearly distinct 0Oo and distinct Il|
The major problem with proportional fonts is they destroy the vertical alignment of the code and this is a fairly major loss when it comes to writing code.
The vertical alignment makes it possible to manipulate rectangular blocks of code that span multiple lines by allowing block operations like cut, copy, paste, delete and indent, unindent etc to be easily performed.
As an example consider this snippet of code:
a1 = a111;
B2 = aaaa;
c3 = AAAA;
w4 = wwWW;
W4 = WWWW;
In a mono-spaced font the = and the ; all line up.
Now if this text is loded into Word and display using a proportional font the text effectively turns into this:
NOTE: Extra white space added to show how the = and ; no longer line up:
a1 = a1 1 1;
B2 = aaaa;
c3 = A A A A;
w4 = w w W W;
W4 = W W W W;
With the vertical alignment gone those nice blocks of code effectively disappear.
Also because the cursor is no longer guaranteed to move vertically (i.e. the column number is not always constant from one line to the next) it makes it more difficult to write throw away macro scripts designed to manipulated similar looking lines.