Let Emacs highlight syntax keyword pair - c++

I am learning how to use Emacs to write code (c++). I was wondering, if there a package (I am using Emacs 24.3) that can highlight syntax elements which are pair or belong to the same group? For example, I would like three elements if, elseif, else to be highlighted at the same time when the cursor is on any of them, so that I can see clearly which three blocks of code belong to the same condition sentence. I think it is useful especially when there is nesting if sentences. Another scenario would be (I am not sure if it is the same feature as previous one), when the cursor is on a return key word, all return keywords will be highlighted at the same time. That way I can check all the exiting cases in a function.
BTW this feature might be less useful in c++ than in some other languages such as shell scripting or VB.NET, where there is no curly bracket. But it is still a good helper in reading the code.

I don't think there's such a thing already for C++. For languages whose major modes uses SMIE for navigation and indentation (e.g. ruby-mode), you can enable show-paren-mode which will highlight the matching opening/closing keyword. If you're on the "if" it won't highlight the else/elseif, tho.
And I don't know any package which higlights all the "return"s in a function, although this should be fairly easy to write based on beginning-of-defun and end-of-defun.

Related

clojure terminating parenthesis syntax

Is there any reason why the expression
(foo5 (foo4 (foo3 (foo2 (foo1 arg)))))
cannot be replaced with
(foo5 (foo4 (foo3 (foo2 (foo1 arg)-)
or the like, and then expanded back?
I know lack of reader macros means that you cannot change syntax, but can this expansion possibly be hard coded into the java?
I do this when I hand write code.
Yes, you could do this, even without reader macros (in fact, you can change Clojures syntax with a bit of hacking).
But, the question is, what would it gain you? Would it always expand to top-level? But then cutting and pasting code would fail, if you moved it to or from top level. And, of course, all the various tools that operate of clojure syntax would need to understand it.
Ultimately if you really dislike all the close parens why not use
(-> arg foo1 foo2 foo3 foo4)
instead?
Yes, this could be done, but I'm not sure it is the right solution and there are a number of negatives which will likely outweigh the benefits.
Suggestions like this are often the result of poor coding tools and a 'traditional' conceptual model for writing code. Selecting the right tools and looking at your code from a slightly different perspective will usually eliminate the cause which lead to this type of suggestion.
Most of the non-functional, non-lispy style languages are based around a token and line model of code. You tend to think of the code in terms of lines of tokens and you tend to edit the code on this basis. There is typically less nesting of expressions and lines are usually terminated with some marker, such as a semi-colan. Likewise, tools such as your editor, have features which have evolved to support token and line based editing. They are good at it.
The lisp style languages are less focused on lines of tokens. The emphasis here is on list forms. lines of tokens are replaced with nested lists of symbols - the line is less relevant and you typically have a lot more nesting of forms. This change means your standard line oriented tools, like your editor, are less suitable. The typical mental model of the code as lines of tokens is also less useful.
With languages like Clojure, your better off thinking in terms of list forms and not lines of code. Once you make this transition, you then start looking for tools which also model the code along these lines. For example, you either look for editors specifically designed to work with lists of data rather than lines of data or you look for editors which have extensions which will allow you to work with lists.
Once your editor understands that lists are the fundamental grouping unit, not lines, things like parenthesis become largely irrelevant from a code writing/editing perspective. You don't worry about closing parenthesis, counting parenthesis nesting levels etc. This all gets managed by the editor automatically. You don't move by lines, you move by lists, you don't kill/delete a line, you kill a list, you don't cut and copy a block of lines, you cut and copy a list of lists etc.
The good news is that in many respects, the structure of these list based code representations are actually easier to manipulate than most of the line based languages. This is primarily because there is less ambiguity or complexity. There are fewer exceptions to the rules and the rules are inherently simple. As a consequence, many editors designed for programmers will have support for this style of coding as well as advanced features which are difficult to implement in less structured code.
My suspicion is that your suggestion to have an additional bit of syntactic sugar to avoid having to type multiple closing parenthesis is actually a symptom of not having the right tools to write your code. Once you do, you will almost never need to enter a closing parenthesis or count opening parens to ensure you get the nesting right. This will be handled by the editor. Your biggest challenge will be in shifting your mental model to think in terms of lists and lists of lists. The parens will become largely invisible and you will jump around in your code according to list units rather than line units. The change is not easy and it can take some time to re-train your brain and fingers, but once you do, you will likely be surprised at how quickly you begin to edit and manipulate your code.
If your an emacs user, I highly recommend extensions such as paredit and lispy. If your using some other editor, look for paredit type extensions. However, as these are extensions, you must also spend some time training yourself to use whatever the key bindings are that the extension uses - there is no point having an extension with great code navigaiton based on lists if you still just arrow around with the arrow keys (unless it is emacs and you have re-bound those arrow keys to use the paredit navigation bindings).

notepad++ keyword only if at beginning of line

Is there a way to create a rule for a Keyword in your User Define Language that states that in order for this to be a keyword, it must be at the beginning of the line ... or at least be the first word on the line?
Note: I'm the guy who answered the question on SuperUser. The same answer:
I am afraid this is not possible. You can consult UDL2 documentation to learn about User Defined Language capabilities. It is intentionally restricted in order to be easy enough giving a compromise between usability for ordinary users and efficiency.
Solution: The only thing I can advise to you beyond UDL2 is to create your own build of Notepad++. If you get the source, you can see that all built-in language highlighters are implemented procedurally using .lex files. You can create yours and there you have unlimited highlighting possibilities. Then you need to add color definitions to existing XML files, menu item and necessary bindings and you should be done. Hint: built-in Batch language is already highlighting first word on the line so maybe it is a good point to start from.
Workaround: if highlighting of first word on line is sufficient to you, just switch langugage to Batch. :)
Another solution: In these cases, user RProgram always suggests people to switch from Notepad++ to SynWrite editor. Its user-defined languages have much wider capabilities. Maybe this will be the fastest way how you can get to desired result without going too deep.
Actually the built-in 'INI File' language option already highlights the first words ('Keys') up to the '=' sign (besides coloring 'section' names) but that's all. It may be useful for some uses but is certainly limited in applicability.

Automatic refactoring

Please suggest a tool that could automate replacing like:
Mutex staticMutex = Mutex(m_StaticMutex.Handle());
staticMutex.Wait();
to
boost::unique_lock<boost::mutex> lock(m_StaticMutex);
As you see, the arguments must be taken into account. Is there a way simpler than regular expressions?
If you can do this with a modest amount of manual work (even including "search and replace") then this answer isn't relevant.
If the code varies too much (indentation, comments, different variable names) and there's a lot of these, you might need a Program Transformation tool. Such tools tend to operate on program representations such as abstract syntax trees, and consequently are not bother by layout or whitespace or even numbers that are spelled differently because of radix, but actually have the same value.
Our DMS Software Reengineering Toolkit is one of these, and has a C++ Front End.
You'd need to give it a rewrite rule something like the following:
domain Cpp; -- tell DMS to use the C++ front end for parsing and prettyprinting
rule replace_mutex(i:IDENTIFIER):statements -> statements
"Mutex \i = Mutex(m_StaticMutex.Handle());
\i.Wait();" =>
"boost::unique_lock<boost::mutex> lock(m_StaticMutex);";
The use of the metavariable \i in both places will ensure that the rule only fires if the name is exactly the same in both places.
It isn't clear to me precisely what you are trying to accomplish; it sort of looks like you want to replace each private mutex with one global one, but I'm not a boost expert. If you tried to do that, I'd expect your program to behave differently.
If those lines appear frequently in your code, similar formatted, just with different variable names, but not "too" frequently (<200~300 times), I would suggest you use an editor with record-replay capabilities (for example Visual Studio under Windows). Record the steps to replace the 2 lines by the new one (but keep the variable name). Then repeat "search for Mutex" - "replay macro" as often as you need it.
Of course, this specific case should be also solvable for all occurences at once by any text editor with good "Find-and-Replace in Files" capabilities.

Is there a style checker for c++?

I have worked with java for a while now, and I found checkstyle to be very useful. I am starting to work with c++ and I was wondering if there is a style checker with similar functionality. I am mainly looking for the ability to write customized checks.
What about Vera++ ?
Vera++ is a programmable tool for verification, analysis and transformation of C++ source code.
Vera++ is mainly an engine that parses C++ source files and presents the result of this parsing to scripts in the form of various collections - the scripts are actually performing the requested tasks.
Click here to see a more complete demo of what it can do.
crc.hpp:157: keyword 'explicit' not followed by a single space
crc.hpp:588: closing curly bracket not in the same line or column
dynamic_property_map.hpp:82: keyword 'if' not followed by a single space
functional.hpp:106: line is longer than 100 characters
multi_index_container.hpp:472: comma should be followed by whitespace
version.hpp:37: too many consecutive empty lines
weak_ptr.hpp:108: keyword 'catch' not followed by a single space
...
I have had good feedback about Artistic Style which allows to apply a uniform style on code without too much hassle.
It's free and there are plenty of "classic" styles already defined. It might not work with C++0x new constructs though.
I am also expecting a Clang library, though I haven't found any to date. Normally, given Clang's structure it should be relatively easy, but then it's always easier to say than to code and I guess nobody took the time yet.
KWStyle seems to be a lightweight fit

What are alternatives to regexes for syntax highlighting?

While editing this and that in Vim, I often find that its syntax highlighting (for some filetypes) has some defects. I can't remember any examples at the moment, but someone surely will. Usually, it consists of strings badly highlighted in some cases, some things with arithmetic and boolean operators and a few other small things as well.
Now, vim uses regexes for that kinda stuff (its own flavour).
However, I've started to come across editors which, at first glance, have syntax highlighting better taken care of. I've always thought that regexes are the way to go for that kind of stuff.
So I'm wondering, do those editors just have better written regexes, or do they take care of that in some other way ? What ? How is syntax highlighting taken care of when you want it to be "stable" ?
And in your opinion what is the editor that has taken care it the best (in your editor of choice), and how did he do it (language-wise) ?
Edit-1: For example, editors like Emacs, Notepad2, Notepad++, Visual Studio - do you perchance know what mechanism they use for syn. high. ?
The thought that immediately comes to mind for what you'd want to use instead of regexes for syntax highlighting is parsing. Regexes have a lot of advantages, but as we see with vim's highlighting, there are limits. (If you look for threads about using regexes to analyze XML, you'll find extensive material on why regexes can't do what parsers do.)
Since what we want from syntax highlighting is for it to follow the syntactic structure of the language, which regexes can only approximate, you need to perform some level of real parsing to go beyond what regexes can do. A simple recursive descent lexer will probably do great for most languages, I'm thinking.
Some programming languages have a formal definition/specification written in Backus-Naur Form. All*) programming languages can be described in it. All you then need, is some kind of parser for the notation.
*) not verified
For instance, C's BNF definition is "only five pages long".
If you want accurate highlighting one needs real programming not regular expressions. RegExs are rarely the answer fir anything but trivial tasks. To do highlighting in a better way you need to write a simple parser. Parses basically have separate components that each can do something like identify and consume a quoted string or number literal. If said component when looking at it's given cursor can't consume what's underneath it does nothing. From that you can easily parse or highlight fairly simply and easily.
Given something like
static int field = 123;
• The first macher would skip the whitespace before "static". The keyword, literal etc matchers would do nothing because handling whitespace is not their thing.
• The keyword matched when positioned over "static" would consume that. Because "s" is not a digit the literal matched does nothing. The whitespace skipper does nothing as well because "s" is not a whitespace character.
Naturally your loop continues to advance the cursor over the input string until the end is reached. The ordering of your matchers is of course important.
This approach is both flexible in that it handles syntactically incorrect fragments and is also easy to extend and reuse individual matchers to support highlighting of other languages...
I suggest the use of REs for syntax highlighting. If it's not working properly, then your RE isn't powerful or complicated enough :-) This is one of those areas where REs shine.
But given that you couldn't supply any examples of failure (so we can tell you what the problem is) or the names of the editors that do it better (so we can tell you how they do it), there's not a lot more we'll be able to give you in an answer.
I've never had any trouble with Vim with the mainstream languages and I've never had a need to use weird esoteric languages, so it suits my purposes fine.