I read in this Swift Style Guide, which is apparently based on Apple's own Swift library style:
'Non-documentation comments always use the double-slash format (//), never the C-style block format (/* ... */).'
Why is it important not to use C-style comments for multiple lines?
There's a few benefits I see in favour of single line comments (//) over multi-line comments (/* */, calling these "C-style" doesn't really make sense, because both styles are valid in C) are easier to toggle.
Single-line comments are easier to insert/remove, because most IDEs have a shortcut for toggling them. In Xcode, it's ⌘ + / by default.
Multi-line comments introduce more opportunities of inconsistency. Which of these should be used?
This approach is compact, but disturbs the horizontal alignment of A
/* A
B
C */
This approach keeps the alignment of elements intact, but wastes vertical space:
/*
A
B
C
*/
This approach keeps alignment of elements intact, and doesn't take too much extra vertical space
/*
A
B
C */
This is the worst of both worlds, I wouldn't recommend it.
/* A
B
C
*/
This is just better in every way. Alignment is intact. No extra horizontal space is wasted.
// A
// B
// C
It's easier to make changes to a commented section with single-line comments. Compare:
With single line comments, it's only a single action of removing the leading //s in the relevant places
Before:
// A
// B
// C
After:
// A
// B
C // Just had to remove the leading "//" here
With multi-line comments, it requires you "cut" the */ at the end, and paste it at the new end. Two actions.
Before:
/*
A
B
C
*/
After:
/*
A
B
*/ // 1. had to insert "*/" here
C // 2. had to remove "*/" from the end
This isn't a problem in Swift, but in C, multi-line comments aren't nestable. Suppose you have a function that contains a multi-line comment within it. But you want to temporarily comment out that function (for whatever reason, just an example). If both comments are multi-line, this wouldn't compile. This code isn't valid:
/* // This "/*" is treated as the start of a comment block
/* // This "/*" is commented, thus ignored.
*/ // This "*/" is treated as the end of the comment block
*/ // This "*/" tries to close the comment block, but it's not in a comment block. This is invalid.
However, Swift doesn't have this problem. I imagine the parser has an internal "comment block nesting level" that it tracks. Every /* increments it, and every */ decrements that. The comment block is only closed once the "comment block nesting level" is back down to 0.
It's not useless
However, that doesn't mean that multi-line comments don't have their use in Swift. I often use them when I'm playing around with a subexpression of a line. For example, if I have this function call:
someFunction(someValue + 1, someOtherParam)
I can see how a function behaves without that + 1 using a block comment:
someFunction(someValue /* + 1 */, someOtherParam)
Achieving the same thing using only single line comments would require me to do something like:
someFunction(someValue // + 1
, someOtherParam)
or introduce a temporary local variable:
let incrementedValue = someValue // + 1
someFunction(incrementedValue, someOtherParam)
Neither of which are as nice.
While I do not have a concrete answer for you, I'm inclined to suggest the double slash format(//)
I think the Swift Style Guide said it because they are also using it as a default.
What do I mean by that?, for example if you highlight multiple lines and press (cmd+/) it will comment/uncomment all the highlighted lines.
Note: it will uncomment the highlighted lines only if its in the double slash format(//)
Related
What's an easy way to convert a multi-line comment (e.g. JSDoc with each line separated by line breaks) into a paragraph without any line breaks that I can copy into an email or another document?
I know I can use search & replace with regular expressions, but is there a more ergonomic way to do it?
You probably knew that you can use multiple cursors to change multiple lines at once, but did you know you can also use them to remove line breaks? Assume you start with this comment:
/**
* Returns a new `Temporal.LocalDateTime` instance representing the first
* valid time during the current calendar day and time zone of `this`.
*
* The local time of the result is almost always `00:00`, but in rare cases it
* could be a later time e.g. if DST starts at midnight in a time zone. For
* example:
* ```
* const ldt = Temporal.LocalDateTime.from('2015-10-18T12:00-02:00[America/Sao_Paulo]');
* ldt.startOfDay; // => 2015-10-18T01:00-02:00[America/Sao_Paulo]
* ```
*/
First part: use multiple cursors to remove the prefix characters on each line.
Click on the upper-left corner of the comment (the /**).
Now hold down Cmd+Shift (Alt+Shift on PC) and click after the */ on the last line of the comment section.
This will create a columnar, multi-line selection that includes the non-text prefix characters on each line. If the selection doesn't include all the prefix characters, you can hold down the Shift key and use the left or right arrow keys to adjust the width of the selection.
Press the Delete key to remove prefix characters on all lines.
Second part: it's time to delete the line breaks and replace them with spaces. I discovered today that you can use multiple cursors for this part too!
After you've deleted the prefix text above, but before you've pressed any other keys, press the backspace key. It will delete the line breaks but leave each cursor in the same place!
Type the spacebar once to insert one space to replace each line break.
Press ESC to clear multiple selections, and delete the extra space at the start of the line. You may have an extra space(s) at the end of the line too that may need trimming.
Copy the resulting one-line text.
Use Cmd+Z (Ctrl+Z on Windows) to undo the last few changes so your code comment will be back to normal.
Now you can paste the copied text into an email!
The same solution works to replace line breaks with spaces in any multi-line text, not only code comments.
I'm sure that many of you already knew how to do this trick, but I found it so easy and so cool that I thought it was worth sharing as a Q&A here so others can learn about this trick too.
Here's what the steps look like in the VSCode IDE:
Before deleting, you should see something like this:
After deleting prefix characters:
After deleting line breaks (note the multiple cursors are still there):
After inserting spaces in place of the deleted line breaks:
I usually select the first line break, then hit/hold command+D repeatedly to add cursors at all line endings I want to edit. Then, just hit space once.
my code and the terminal .
file = "ex25.py", line 27
words=sort_sentence(sentence)
IndentationError: unindent does not match any other indentation level
The code I wrote in ex25 is:
def print_first_and_last_sorted(sentence):
words =sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
After you define function with the first line, in the second line you need to use proper indentation or spaces. The standard is 4 spaces (4 space keystrokes) or 1 tab.
def print_first_and_last_sorted(sentence):
words =sort_sentence(sentence) # This line and next should be spaced 4 times with
print_first_word(words) # respect to the above one
print_last_word(words)
Your second line is not indented properly. You can compare it with the next lines. They all should be vertically parallel at their start points.
I can't comment but from both the edit and the original post, therefore I can't tell what the indentation actually is.
Python indentation works like blocks of code, similar to other languages except without the curly braces. For example:
def print_first_and_last_sorted(sentence):
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
You may have mixed up spaces & tabs. From this answer, try searching and replacing to replace them with a few spaces.
I'd like to remove colon styling, which typically appears like:
goto:
The code that adds colon styling starts on line 457.
It's not necessary but would be nice if I could remove colon styling only in certain directories like:
/root/project/hi.c
/root/project_remove_colon/hi.c
Thanks!
One way to do this is to set c-label-face-name as a file local variable. For example, in your file /root/project_remove_colon/hi.c you could add the following comment block at the end of the file:
/* Local Variables: */
/* c-label-face-name: font-lock-reference-face */
/* End: */
An issue with this approach, though, is that c-label-face-name is not considered safe as a file-local variable, so when you visit the file, emacs will prompt you like this:
The local variables list in hi.c
contains variables that are risky (**).
Do you want to apply it? You can type
y -- to apply the local variables list.
n -- to ignore the local variables list.
** c-label-face-name : font-lock-reference-face
To avoid this prompt, you could customize safe-local-variable-values to mark the variable c-label-face-name as being safe.
I'm using emacs (24.3.1) along with cc-mode and hideshow for programming c++. I am working on a project, where the coding styles requires that any keywords present in the header file must be repeated in the source file. In case that this is not allowed by the standard, the keyword must be placed in comments. Let me give you and example:
/* virtual */ void MyAwesomeFunction( int arg, int optarg /* = 0 */ ){
// stuff
}
Obviously there is a comment starting the line. It seems that hideshow can't cope with this sort of formatting. When I call hs-hide-all all code blocks are folded correctly, the same is true if I call hs-hide-block from anywhere within the function. However, if I call hs-hide-block whith point beeing somewhere in the opening line of the function (the first line of my codesnippet) now folding occurs and the error message:
(not enough comment lines to hide)
is printed. The only explicit configuration of hideshow I have done so far is:
(setq hs-hide-comments nil)
However, removing this line makes it even worse: Afterwards not even calling hs-hide-all works properly: all inner blocks are folded, but folding at the function level does not occurs for functions with a leading comment.
Anyone knows how to fix this?
It might help to explicitly hide comments first, either just within the region or throughout the buffer. You can use library hide-comnt.el to do that. A description is here.
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$>
}$>