Emacs indentation of the for each statement in C++ - c++

I'm trying to get emacs to correctly format the "for each" construct in c++.
I want the braces to be lined up with the f in for in both of the following examples:
for each(Type a in b)
{ //^c^s shows substatement-open
//... do stuff
}
for( ; ; )
{ //^c^s shows substatement-open
//... do stuff
}
In both cases, using [Ctrl-c Ctrl-s] (or [Ctrl-c Ctrl-o]) shows that both opening { characters are of type substatement-open and when viewing the c-offsets-alist I see that substatement-open is equal to 0.
How can I make emacs indent the for each() command similar to how it indents the for(;;) command?

Presumably emacs is not recognising "for each" as c++ syntax (I don't either. Is this a microsoft extension? A preprocessor hack? New for the upcoming standard?). So there is no wonder that it is not formatting it "right".
You could hack the mode, or ask the maintainer of the same (I wouldn't expect a possitive response, though, unless this is going to be proper c++ Very Soon Now).
From the comments The answers to my parenthetical questions are:
The precise form the OP asks about is a Microsoft managed-c++ extension.
There is BOOST_FOREACH available now
The C++0x stand will include a container-ranged loop with a syntax like for( <type> <loopcounter> : <container> )
and from slink's answer it appears that the mode maintainer is supporting the Microsoft syntax in the latest versions...

For me--under Emacs 23.0.91--the c++-mode indents the for each block as it was a normal for loop.

Related

Format for curly braces in VS Code Snipets for C/C++

I installed the C/C++ Snippets extension in VS Code, and it creates a snippet like this:
for ( )
{
// your code
}
but I want the open brace on the keyword line:
for ( ) {
I found this topic for C/C++ formation in VS Code: "Format Curly Braces on Same Line in C++ VS Code" but it didn't solve the problem (so, the snippet extension doesn't follow the C formatting "rules" in VS Code, I guess).
I can't find any setting in the VS Code settings JSON file for this extension.
Anyone have an idea?
(In the ideal world, the curly brace for functions would remain on the next line and only braces associated with keywords would be on the same line.)
Thank you,
-Vin
I did some intense digging and found the name of the file that holds the snippits, then looked in all the "usual suspect" places and found it:
C:\Users\.vscode\extensions\hars.cppsnippets-0.0.14\snippets\
in this directory, there are two files: c.json, cpp.json
In each there are json entries for each snippit. I edited a couple in the c.json to test and they now format as I want. Thanks Ali! your suggestions got me thinking!

What's this curly brace comma syntax in Visual Studio?

What is this weird syntax you can use the the watch window (or even to set breakpoints) and where can I find it documented:
{,,test2.exe}<variable name>
When starting the program, the first will translate to my entry point and will break on execution start.
Intuitively I can see what this means, but where is it documented and what are the leading commas for (what stuff can you put in there)?
Why does using the syntax in the watch window help?
As the VS2015 documentation states, that is called a Context Operator, valid only for C++ native applications.
You could put function and source file before the first and the second comma.
For VS2010 and previous versions the documentation is slightly different and more verbose.

Opening curly brace fails to indent consistently

I'm transitioning to Visual Studio 2010 from version 2008 and have noticed several differences between the editor. Most I have fixed or found work-arounds for. One feature that I cannot get to work like it did in 2008 is when I type an open curly brace "{" on a non-empty line in a CPP file. Typically, after starting a for, if, while, or similar statement, I'll automatically type the {} on separate lines below the statement so that the curly braces are nicely lined up (it's an OCD thing). VS 2010 does what I want in this situation.
if (varIsTrue)
{
varIsTrue = false; // typed after the initial {} pair.
// do something really innovative here...
}
It's when I forget that initial "{" that the editor no longer wants to help.
if (varIsTrue)
varIsTrue = false;
Oops. Forgot the curly brace (or I simply need to create a code block for additional code.)
Typing a "{" gives
if (varIsTrue)
{varIsTrue = false;
instead of
if (varIsTrue)
{varIsTrue = false;
so that hitting ENTER will properly indent "varIsTrue = false;"
Visual Studio 2008 handled this correctly, but 2010 does not. I've yet to find a way fix this in the editor options, and I assume that an editor extension would be the only other option.
So basically, if there is a way to fix this in the editor, how can I do it? If not, does an extension exist that would allow me to fix the problem?
Interestingly, this problem does not exhibit itself in a C# file, so I am hoping there is a way to fix it for CPP files.
I appreciate any help regarding this.

Visual Studio Code doesn't format

I want to format my code by pressing Ctrl+K and Ctrl+D.
But after that, the code is still the same. For example:
void func1()
{
}
void func2() {
}
These functions still look the same after formating.
What am I doing wrong?
The C++ text formatting engine is fairly limited when compared to C# or VB.Net. It is pretty much limited to fixing indentation and correcting tabs vs. spaces. It makes no attempt to clean up which line braces appear on. Hence you're doing nothing wrong here, this is just a limitation of the C++ formatting engine
EDIT
As #dalle pointed out Visual Studio 2013 does indeed support limited brace formatting in C++. By default though the formatting is turned off. You need to explicitly enable it for format document to begin formatting your braces.
Tools -> Options
Text Editor -> C/C++ -> Formatting -> New Lines
Select "Move to a new line" under "Position of open braces for functions"
Once this is done format document will begin to correctly position the braces

Replace C style comments by C++ style comments

How can I automatically replace all C style comments (/* comment */) by C++ style comments (// comment)?
This has to be done automatically in several files. Any solution is okay, as long as it works.
This tool does the job:
https://github.com/cenit/jburkardt/tree/master/recomment
RECOMMENT is a C++ program which
converts C style comments to C++ style
comments.
It also handles all the non-trivial cases mentioned by other people:
This code incorporates suggestions and
coding provided on 28 April 2005 by
Steven Martin of JDS Uniphase,
Melbourne Florida. These suggestions
allow the program to ignore the
internal contents of strings, (which
might otherwise seem to begin or end
comments), to handle lines of code
with trailing comments, and to handle
comments with trailing bits of code.
This is not a trivial problem.
int * /* foo
/* this is not the beginning of a comment.
int * */ var = NULL;
What do you want to replace that with? Any real substitution requires sometimes splitting lines.
int * // foo
// this is not the beginning of a comment.
// int *
var = NULL;
How do you intend to handle situations like this:
void CreateExportableDataTable(/*[out, retval]*/ IDispatch **ppVal)
{
//blah
}
Note the comment inside the parens... this is a common way of documenting things in generated code, or mentioning default parameter values in the implementation of a class, etc. I'm usually not a fan of such uses of comments, but they are common and need to be considered. I don't think you can convert them to C++ style comments without doing some heavy thinking.
I'm with the people who commented in your question. Why do it? Just leave it.
it wastes time, adds useless commits to version control, risk of screwing up
EDIT:
Adding details from the comments from the OP
The fundamental reason of preferring C++-style comment is that you can comment out a block of code which may have comments in it. If that comment is in C-style, this block-comment-out of code is not straight forward. – unknown (yahoo)
that might be a fair/ok thing to want to do, but I have two comments about that:
I know of no one who would advocate changing all existing code - that is a preference for new code. (IMO)
If you feel the need to "comment out code" (another iffy practice) then you can do it as needed - not before
It also appears that you want to use the c-style comments to block out a section of code? Or are you going to use the // to block out many lines?
One alternative is a preprocessor #ifdef for that situation. I cringe at that but it is just as bad as commenting out lines/blocks. Neither should be left in the production code.
I recently converted all C-style comments to C++-style for all files in our repository. Since I could not find a tool that would do it automatically, I wrote my own: c-comments-to-cpp
It is not fool-proof, but way better than anything else I've tried (including RECOMMENT). Among other things, it supports converting Doxygen style comments, for instance:
/**
* #brief My foo struct.
*/
struct foo {
int bar; /*!< This is a member.
It also has a meaning. */
};
Gets converted to:
/// #brief My foo struct.
struct foo {
int bar; ///< This is a member.
///< It also has a meaning.
};
Here's a Python script that will (mostly) do the job. It handles most edge cases, but it does not handle comment characters inside of strings, although that should be easy to fix.
#!/usr/bin/python
import sys
out = ''
in_comment = False
file = open(sys.argv[1], 'r+')
for line in file:
if in_comment:
end = line.find('*/')
if end != -1:
out += '//' + line[:end] + '\n'
out += ' ' * (end + 2) + line[end+2:]
in_comment = False
else:
out += '//' + line
else:
start = line.find('/*')
cpp_start = line.find('//')
if start != -1 and (cpp_start == -1 or cpp_start > start):
out += line[:start] + '//' + line[start+2:]
in_comment = True
else:
out += line
file.seek(0)
file.write(out)
Why don't you write a C app to parse it's own source files? You could find the /* comments */ sections with a relatively easy Regex query. You could then replace the new line characters with new line character + "//".
Anyway, just a thought. Good luck with that.
If you write an application/script to process the C source files, here are some things to be careful of:
comment characters within strings
comment characters in the middle of a line (you might not want to split the code line)
You might be better off trying to find an application that understands how to actually parse the code as code.
There are a few suggestions that you might like to try out:
a)Write your own code (C/ Python/ any language you like) to replace the comments. Something along the lines of what regex said or this naive solution 'might' work:
[Barring cases like the one rmeador, Darron posted]
for line in file:
if line[0] == "\*":
buf = '//' + all charachters in the line except '\*'
flag = True
if flag = True:
if line ends with '*/':
strip off '*/'
flag = False
add '//' + line to buf
b)Find a tool to do it. (I'll look up some and post, if I find them.)
c)Almost all modern IDE's (if you are using one) or text editors have an auto comment feature. You can then manually open up each file, select comment lines, decide how to handle the situation and comment C++ style using an accelerator (say Ctrl + M). Then, you can simply 'Find and Replace' all "/*" and "*/", again using your judgment. I have Gedit configured to do this using the "Code Comment' plugin. I don't remember the way I did it in Vim off hand. I am sure this one can be found easily.
If there are just "several files" is it really necessary to write a program? Opening it up in a text editor might do the trick quicker in practice, unless there's a whole load of comments. emacs has a comment-region command that (unsurprisingly) comments a region, so it'd just be a case of ditching the offending '/*' and '*/'.
Very old question, I know, but I just achieved this using "pure emacs". In short, the solution looks as follows:
Run M-x query-replace-regexp. When prompted, enter
/\*\(\(.\|^J\)*?\)*\*/
as the regex to search for. The ^J is a newline, which you can enter by pressing ^Q (Ctrl+Q in most keyboards), and then pressing the enter key. Then enter
//\,(replace-regexp-in-string "[\n]\\([ ]*?\\) \\([^ ]\\)" "\n\\1// \\2" \1))
as the replacement expression.
Essentially, the idea is that you use two nested regex searches. The main one simply finds C-style comments (the *? eager repetition comes very handy for this). Then, an elisp expression is used to perform a second replacement inside the comment text only. In this case, I'm looking for newlines followed by space, and replacing the last three space characters by //, which is nice for preserving the comment formatting (works only as long as all comments are indented, though).
Changes to the secondary regex will make this approach work in other cases, for example
//\,(replace-regexp-in-string "[\n]" " " \1))
will just put the whole contents of the original comment into a single C++-style comment.
from PHP team convention... some reasonning has to exist if the question was asked. Just answer if you know.
Never use C++ style comments (i.e. // comment). Always use C-style
comments instead. PHP is written in C, and is aimed at compiling
under any ANSI-C compliant compiler. Even though many compilers
accept C++-style comments in C code, you have to ensure that your
code would compile with other compilers as well.
The only exception to this rule is code that is Win32-specific,
because the Win32 port is MS-Visual C++ specific, and this compiler
is known to accept C++-style comments in C code.