how to freely format comments in cc-mode - emacs

I'm quite new to cc-mode and I'd like to configure it to allow me to freely format and use tabs in multiline comments. This is important to me because I want to use cog.py in my source file and need to be able to format the python source in the comment correctly. I'd be ok with comments not beeing autoindented at all, however I'd like to keep auto indenting the rest of the source code.
Example:
...
/*
[[[cog
import cog
for x in ['a','b','c']:
>cog.outl(x)
]]]
*/
...
In the line marked with > I'd like to press TAB to indent the line. cc-mode simply does nothing at all if i do so. I could use spaces there (which is inconvenient) but every (semi-)automatic re-indentation of this block would cause the spaces to vanish and therefore the python code to be incorrectly indented (which is what happens if i happen to press tab somewhere on this line after indenting it with spaces).
I tried to start emacs without my .init to be sure this is default behavior and not modified by my configuration so far. I've done google searches and read the documentation of the cc-mode variables / functions I stumbled upon (cc-mode online docs) while searching for a solution (i.e. c-indent-comments-syntactically-p, c-indent-command, c-tab-always-indent,...) but none of these seemed to solve my question.
EDIT1:
Thanks to abo-abo's idea of a "multi-major-mode" setup i've stumbled upon mmm-mode and have set up automatic switching to python mode for a cog section, which fixes most of my problems.
The only remaining problem is reindenting the whole file or a region containing a cog section. Can I somehow tell cc-mode to not change anything in comments while reindenting the file? mmm-mode + that would be a perfect solution for me.

You can use M-i to force a tab indent on the lines that you want, so you can use it to indent your comments.
You can also change your comments to use // instead. Just select your python code snippet, and do M-x comment-region:
// def foo(x):
// print 'hi'
Then the autoindent won't mess up your indentation.

Related

Emacs highlighting: how to deal with highlighting messed up by unusual usage of special characters?

Problem:
In Emacs configuration modes (e.g. conf-xdefaults-mode or conf-space-mode), some special characters are used in unusual ways, for instance when they define keybindings. This messes up the highlighting for the rest of the buffer.
Example:
The ranger rc.conf file uses conf-space-mode which greatly helps its readability. But lines such as:
map # console shell -p%space
map "<any> tag_toggle tag=%any
mess up the highlighting since # usually defines a comment and is followed by font-lock-comment-face until the end of the line and " defines the beginning of a string and is followed by font-lock-string-face until it encounters a closing quote.
Escaping those characters is not an option because it would prevent them from defining the keybindings.
Possible solution:
The best solution I can think of is to fiddle with font lock settings for those configuration modes to remove the highlighting after those special characters. But I will then loose the proper highlighting after those characters when it is suitable.
A compromise could be to keep highlighting after # since this only messes up one line and there are a lot of comments in those configuration files, while removing the highlighting after single and double quotes since those mess up the entire rest of the buffer and strings are not so common in configuration files.
Question:
What is the proper way to deal with these situations?
Is there a way to reset the highlighting at a point in the buffer? or to insert a character which would affect the highlighting (to fix it) without affecting the code? or is there a way to "escape" some characters for the highlighting only without affecting the code?
The easy way
It's probably easiest to just live with it but keep things constrained. Here, I took ranger's default rc.conf and re-arranged some of the font-lock errors.
Let's ignore the blue "map" for now. We have two visible font-lock errors. The map #... is font-locking as a comment, and the map "... font-locking as a string to the end of the buffer. The first error is self-constrained. Comments end at the end of the line. The second error we constrain by adding a comment. (I don't know if ranger would accept comments in the middle of the line, so I'm only using beginning-of-line comments here.)
The second error is now constrained to one line, but a couple more errors have popped up. Quickly adjusting these we get.
This is something that I could live with, as I'm not in conf files all day long (as opposed to say, source code.) It would be even neater if our new "comments" could be included on the same line.
The hard way
You'll want to use Emacs font-lock-add-keywords. Let's get back to that blue map in the first image. It's rendering blue because conf-space-mode thinks that a string, followed by any amount of whitespace, followed by an opening brace should be rendered in font-lock-type-face (the actually regexp that triggers this is ^[_space__tab_]*\\(.+?\\)[_space__tab_\n]*{[^{}]*?$ where _space_ and _tab_ are actual space and tab characters.)
We can override this in a simple fashion by evaluating
(font-lock-remove-keywords
'conf-space-mode
'(("^\\<\\(map\\)\\>" 1 font-lock-variable-name-face)))
and reloading the buffer with C-x C-v RET. Now, every time that the word "map" appears at the beginning of a line it's rendered as font-lock-variable-name-face (yellow in our example.)
You can make this change permanent by adding a hook to your init file.
(add-hook 'conf-space-mode-hook (lambda ()
(font-lock-remove-keywords
nil
'(("^\\<\\(map\\)\\>" 1 font-lock-variable-name-face)))))
This method doesn't appear to work for your comment (#) and string (' ") delimiters as they're defined in the syntax table. Modifying the syntax table to provide special cases is probably more effort than it's worth.

Shortcut for "code block" macro in Confluence editor

We use confluence for documentaion but i find very time consuming to select the code macro; it's a 5 step process. Even typing the macro by hand is not efficient.
In the Stack Overflow editor all we have to do is select the text and press a button or hit ctrlK, and the text is formatted as code.
Is there a way to do this in Confluence?
even typing by hand is also not efficient
I use the code macro extensively and always use the autocomplete feature by typing { and choosing 'Code Macro' from the list (It's enough to type co for the code macro).
This is a very efficient.
Of course a keyboard shortcut would be faster, but there is no shortcut for the code macro. (AFAIK there is no keyboard shortcut for a specific macro at all)
I use Ctrl-Shift-D then wrap the text in {code}.
This also fixes the problem with formatting being stripped from pasted text.
In Confluence 5.x if you edit a page, you can type {cod<enter} and it puts a Code Block box on the page, but when code is pasted into this box it can strip out end of line characters.
Open the Insert Markup window using Ctrl-Shift-D
Paste in your code as plain text This way the formatting is not stripped out.
Add {code} tags.
You can also type three back ticks ``` to create a code block as you would in vanilla Markdown. This creates an empty code block very quickly. I never have with problems with formatting when pasting code in this way.
The one irritating feature of this method is that you can't specify the language as you do in Markdown, you have to select the language from a list.

Eclipse: Automatic line wrapping to specified width

I'd like for my lines, especially within comments, to be automatically managed so they don't get too long.
I remember once I had a configuration for vim which automatically moved the word I was typing to the next line once I reached 72 characters. It wasn't smart enough to rearrange the paragraph if I edit it, but it was a start.
Is there something that can manage these for me? I have a tendency to write really long comments in my code, and it helps to make them look neat by having consistent width, but it's always a pain to do this because oftentimes editing a sentence requires editing the entire rest of the paragraph.
I have just recently discovered the Ctrl+Shift+F feature. It is amazing and superior to Ctrl+I which is what I was using up till now, but I noticed that it does not do anything to clean up my comments.
Update: The answers are correct when working with Java in Eclipse. It seems like I have to wait for the CDT to incorporate this feature.
In "Windows -> Preferences", go to "Java -> Code style -> Formatter" to customize the formatter (called when you click Ctrl+Shift+F). In the tab "comment", you can set the maximum line width for comments (it can be different then the line width for code).
Tip: in the preferences, "Java -> Editor -> Save actions", you can make Eclipse to automatically format your file when you save it, so your code is always correctly indented !
The automatic formatting of Eclipse great no question.
If your comments are reformatted depends on what comment type and how you already have inserted line breaks.
Writing for example one very long line comment starting with // will be broken down by the formatter into multiple lines.
However you later edit the formatted lines - e.g. delete parts of it the formatter will leave them as they are. Only over-long lines will be changed.
Just in difference to block comments like this: /* comment */
Those comments will always be re-formatted in case the line is too short or too long.
If you want to format your header comment, you have to check Enable header comment formatting - that was the trick for me.
Obviously, to use this, you must create new formatter profile.

Problem writing a snippet containing Emacs Lisp code

I've been trying to make use of a cool feature of YASnippet: write snippets containing embedded Emacs Lisp code. There is a snippet for rst-mode that surrounds the entered text with "=" that is as long as the text such as in
====
Text
====
Based on this snippet, I decided to slightly modify it (with Elisp) so that it comments out these three lines depending on the major mode you are in (I thought that such a snippet would be useful to organize the source code). So I wrote this:
${1:`(insert comment-start)`} ${2:$(make-string (string-width text) ?\-)}
$1 ${2:Text}
$1 ${2:$(make-string (string-width text) ?\-)}
$0
This code works relatively well except for one problem: the indentation of these three lines gets mixed up, depending on the major mode I'm in (e.g., in emacs-lisp-mode, the second and the third lines move more to the right than the first line).
I think the source of the problem might have something to do with what comes after the string ${1: on the first line. If I add a character, I have no problem (i.e., all three lines are correctly aligned at the end of the snippet expansion). If I add a single space after this string, the misalignment problem still continues though.
So my question is: do you know of any way of rewriting this snippet so that this misalignment does not arise? Do you know what's the source of this behaviour?
Cheers,
From Writing snippets:
yas/indent-line
The variable yas/indent-line controls the indenting. It is bound to 'auto by default, which causes your snippet to be indented according to the mode of the buffer it was inserted in.
Another variable yas/also-auto-indent-first-line, when non-nil does exactly that :-).
To use the hard-coded indentation in your snippet template, set this variable to fixed.
To control indentation on a per-snippet basis, see also the directive # expand-env: in Writing Snippets.
For backward compatibility with earlier versions of YASnippet, you can also place a $> in your snippet, an (indent-according-to-mode) will be executed there to indent the line. This only takes effect when yas/indent-line is set to something other than 'auto.
for (${int i = 0}; ${i < 10}; ${++i})
{$>
$0$>
}$>

what's the syntax for telling VI to read/write a source file with soft-tabs and a specified indentation?

Someplace I saw a snippet of code which told vi to use soft tabs and set the size of a tab. If you put this snippet at the bottom of a source file, then vi would magically use those settings for that file.
What is the syntax and rules for including that snippet in a source file? Can emacs be made to use these settings as well?
You can put this in a comment in your source file:
ex: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:
The comment syntax depends on the type of the source file.
For C/C++/Java, this would be:
// ex: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:
For JSP, this would be:
<%-- ex: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab: --%>
This works if it is placed at the beginning of the source file, but I'm not sure that this'll work if placed at the end of it too.
This will not work for emacs. There might be a different way of achieving the same for emacs.
Check out :h modeline.
Example:
/* vim: ai set sw=4 ts=4 */
See :h modelines for how many lines into a file Vim will check for modeline info. The default is to check the first 5 lines.
As far as I know, vi didn't have this capability. You're likely thinking of the modeline feature of Vim. There is similar functionality in emacs, where you can put local variables in the file.
Note that, at least in Vim, modelines have had a history of vulnerabilities. This is primarily due to problematic options being specifically blacklisted instead of only allowing a certain subset of variables to be set in modelines. I'd suggest using a plugin like securemodelines.
Put this in your C++ source file:
// vim: set ft=cpp
The modeline feature looks for the string "vim:" and then executes what follows. Note: this could open up potential exploits if you don't trust the files you are opening, so think twice before enabling this feature.
Okay, first of all, in real vi you do this in the .exrc file.
Second, use
set autoindent tabstop=8 shiftwidth=4
because otherwise vi will insert tabs it thinks are only 4 characters wide. The resulting text file will not look like it makes sense in any other editor.