Emacs problematic JavaScript indentation - javascript

I'm following the Douglas Crockford's code convention, but I can't get the correct identation in JS mode in Emacs. I tried to customize the indent options of the mode, tried another modes like js3, but nothing seems to work.
When I have parenthesis, and I have to break the expression, Emacs indent like this:
this.offices.each(this.addOfficesToMap,
this);
While the convention that I'm following, says that I should leave just 4 spaces when an expression is broken up. So the indentation should look like:
this.offices.each(this.addOfficesToMap,
this);
Any idea of how I can change the indentation on broken up expressions?

The behaviour you want to change is hard-coded into a function called js--proper-indentation. An inelegant fix to your problem would be to replace the function in your .emacs:
(require 'cl)
(eval-after-load "js" '(defun js--proper-indentation (parse-status)
"Return the proper indentation for the current line."
(save-excursion
(back-to-indentation)
(cond ((nth 4 parse-status)
(js--get-c-offset 'c (nth 8 parse-status)))
((nth 8 parse-status) 0) ; inside string
((js--ctrl-statement-indentation))
((eq (char-after) ?#) 0)
((save-excursion (js--beginning-of-macro)) 4)
((nth 1 parse-status)
;; A single closing paren/bracket should be indented at the
;; same level as the opening statement. Same goes for
;; "case" and "default".
(let ((same-indent-p (looking-at
"[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
(continued-expr-p (js--continued-expression-p)))
(goto-char (nth 1 parse-status)) ; go to the opening char
(if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
(progn ; nothing following the opening paren/bracket
(skip-syntax-backward " ")
(when (eq (char-before) ?\)) (backward-list))
(back-to-indentation)
(cond (same-indent-p
(current-column))
(continued-expr-p
(+ (current-column) (* 2 js-indent-level)
js-expr-indent-offset))
(t
(+ (current-column) js-indent-level
(case (char-after (nth 1 parse-status))
(?\( js-paren-indent-offset)
(?\[ js-square-indent-offset)
(?\{ js-curly-indent-offset))))))
;; If there is something following the opening
;; paren/bracket, everything else should be indented at
;; the same level.
;; Modified code here:
(unless same-indent-p
(move-beginning-of-line 1)
(forward-char 4))
;; End modified code
(current-column))))
((js--continued-expression-p)
(+ js-indent-level js-expr-indent-offset))
(t 0)))) )
I have modified three lines of code towards the bottom of the function. If you want your indentation to be 8 chars instead of 4, change the (forward-char 4) line accordingly.
Note that js--proper-indentation (and the js library) requires the cl.el library, but that using eval-after-load mucks this up. So you need to explicitly require cl in your .emacs for this to work.
Note that this 'solution' hard codes a 4 space indentation only for the situation you indicate, and does not handle nested code at all. But knowing the point in the code that deals with your situation should at least point you towards the bit that needs work for a more sophisticated solution.

you can try https://github.com/mooz/js2-mode ...it's a fork js2-mode but with some impovements like good indentation...other way is read this article: http://mihai.bazon.net/projects/editing-javascript-with-emacs-js2-mode .. but sincerely it's better idea replace the old js2-mode ..it has several improvements https://github.com/mooz/js2-mode/wiki/Changes-from-the-original-mode ...hope this can help you...

You can file a feature request on js3-mode at https://github.com/thomblake/js3-mode/issues
Do you have a link to a style guide?

BTW, while the indentation conventions vary from language to language, and the preferences can even vary between users (such as in the above case), there is a fair bit of overlap and there are often ways to write your code such that there is little disagreement.
E.g. your above code could be written:
this.offices.each(
this.addOfficesToMap,
this
);
or
this.offices.each
(this.addOfficesToMap,
this);
and most indentation styles would largely agree on how to indent it.

Related

Changing indentation style in atom editor (javascript code)

I've used microsoft's vscode for some months, but since 2 updates the indentation is broken for me, without a way to fix it. I therefore consider switching to atom. I was working with atom before, and never had this problem, but now it seems to have the same (wrong for me) behaviour as vscode:
if (xxx) // press enter here and type 'something();'
should result in
if (xxx)
something();
but it results in
if (xxx)
something();
It will work completely finde if you add { }, but without them its like the above.
How can I fix this in atom? The basic identation settings don't seem to cover this.
My way of doing this si to always use {} (also because I'm using linter-standard-js) That way, you type
if (myCondition) {}
When you return between the accolades, you get the following
if (myCondition) {
// indented and here you go
}
You can add extra conditions for Atom to change the indent level in your config.cson file, following the lead of the packages that define those conditions in the first place. Add the following to the top level of config.cson and Atom will automatically add a level of indentation after a line that matches the regular expression if\s*\(.*\)$. If you already have a .source.js entry, make sure to change that instead of just pasting this bit in.
'.source.js':
editor:
increaseIndentPattern: '(?x)
\\{ [^}"\']* $
| \\[ [^\\]"\']* $
| \\( [^)"\']* $
| if\\s*\\(.*\\)$
'

Implementing if-condition in preprocessor

For a project of mine, I want to implement a customized preprocessor in JavaScript that mimics the GNU C Preprocessor (i.e. gcc -E).
This preprocessor I wrote already has most things working, except conditionals. So, #ifdef, #ifndef, #else and #endif is what I am stuck at.
My code thus far: preprocessor.js (permanent link)
I'd be glad to hear about suggestions on how to implement it! :)
Maintain a stack of conditions and keep skipping lines as long as any condition is false. In pseudocode:
for each line
if line == "#if <cond>"
conditions.push(<cond>)
else if line == "#else"
conditions.push(!conditions.pop())
else if line == "#endif"
conditions.pop()
else if all conditions are true
everything fine, handle line
else
skip line
Better approach would be parsing into the AST which will contain clearly defined base blocks and control flow graphs.
For example "if" (conditional) construct can be expressed as
conditional
|
-- test
-- consequent base block
-- [alternate bb]
-- [elseif 1]
|
-- test
-- consequent
...
This approach is much more flexible and allows creating full-scale language with functions, loops, contexts, etc.
Good example can be seen in Builder preprocessor: https://github.com/electricimp/Builder

Javascript else on a new line

When creating an if block, I was wondering if there was any reason beyond personal preference to use the standard bracket formatting vs the second one I listed.
I've run code in the second format without any obvious issues (no ASI or unexpected errors), just looking for some clarification or insight on if there could be any possible issues in the future if I permanently switch to this style.
// Standard formatting
if (true) {
} else {
}
// Other formatting
if (true) {
}
else {
}
Spaces and tabs are not considered to be significant in Javascript in most cases. (I believe all, but I can't find a source for that)
You can technically put all of your code on one line (as most minification algorithms do), but that won't be very readable. In your own code, it comes down to solely personal preference, it will not cause any errors or cause the code to run slower if there are spaces (though more spaces will take longer to load if the JS is not minified).
Best practice is to keep your code style consistent throughout your projects.
None, they are equivalent if you wanted you could put the code in one line as well and it would work. Usually people have personal preferences, as well as some companies require you to write the code in a specific way in order to standardize it and make it so anyone taking over your project knows what to expect.
You don't even need the brackets, it wil just work:
http://jsfiddle.net/4ywahnof/1/
(function () {
var t = 1;
if (t == 1) alert("hi");
else alert("no hi");
})();

Coding convention in Javascript: use of spaces between parentheses

According to JSHint, a Javascript programmer should not add a space after the first parenthesis and before the last one.
I have seen a lot of good Javascript libraries that add spaces, like this:
( foo === bar ) // bad according to JSHint
instead of this way:
(foo === bar) // good according to JSHint
Frankly, I prefer the first way (more spaces) because it makes the code more readable. Is there a strong reason to prefer the second way, which is recommended by JSHint?
This is my personal preference with reasons as to why.
I will discuss the following items in the accepted answer but in reverse order.
note-one not picking on Alnitak, these comments are common to us all...
note-two Code examples are not written as code blocks, because syntax highlighting deters from the actual question of whitespace only.
I've always done it that way.
Not only is this never a good reason to defend a practice in programming, but it also is never a good reason to defend ANY idea opposing change.
JS file download size matters [although minification does of course fix that]
Size will always matter for Any file(s) that are to be sent over-the-wire, which is why we have minification to remove unnecessary whitespace. Since JS files can now be reduced, the debate over whitespace in production code is moot.
moot: of little or no practical value or meaning; purely academic.
moot definition
Now we move on to the core issue of this question. The following ideas are mine only, and I understand that debate may ensue. I do not profess that this practice is correct, merely that it is currently correct for me. I am willing to discuss alternatives to this idea if it is sufficiently shown to be a poor choice.
It's perfectly readable and follows the vast majority of formatting conventions in Javascript's ancestor languages
There are two parts to this statement: "It's perfectly readable,"; "and follows the vast majority of formatting conventions in Javascript's ancestor languages"
The second item can be dismissed as to the same idea of I've always done it that way.
So let's just focus on the first part of the statement It's perfectly readable,"
First, let's make a few statements regarding code.
Programming languages are not for computers to read, but for humans to read.
In the English language, we read left to right, top to bottom.
Following established practices in English grammar will result in more easily read code by a larger percentage of programmers that code in English.
NOTE: I am establishing my case for the English language only, but may apply generally to many Latin-based languages.
Let's reduce the first statement by removing the adverb perfectly as it assumes that there can be no improvement. Let's instead work on what's left: "It's readable". In fact, we could go all JS on it and create a variable: "isReadable" as a boolean.
THE QUESTION
The question provides two alternatives:
( foo === bar )
(foo === bar)
Lacking any context, we could fault on the side of English grammar and go with the second option, which removes the whitespace. However, in both cases "isReadable" would easily be true.
So let's take this a step further and remove all whitespace...
(foo===bar)
Could we still claim isReadable to be true? This is where a boolean value might not apply so generally. Let's move isReadable to an Float where 0 is unreadable and 1 is perfectly readable.
In the previous three examples, we could assume that we would get a collection of values ranging from 0 - 1 for each of the individual examples, from each person we asked: "On a scale of 0 - 1, how would you rate the readability of this text?"
Now let's add some JS context to the examples...
if ( foo === bar ) { } ;
if(foo === bar){};
if(foo===bar){};
Again, here is our question: "On a scale of 0 - 1, how would you rate the readability of this text?"
I will make the assumption here that there is a balance to whitespace: too little whitespace and isReadable approaches 0; too much whitespace and isReadable approaches 0.
example: "Howareyou?" and "How are you ?"
If we continued to ask this question after many JS examples, we may discover an average limit to acceptable whitespace, which may be close to the grammar rules in the English language.
But first, let's move on to another example of parentheses in JS: the function!
function isReadable(one, two, three){};
function examineString(string){};
The two function examples follow the current standard of no whitespace between () except after commas. The next argument below is not concerned with how whitespace is used when declaring a function like the examples above, but instead the most important part of the readability of code: where the code is invoked!
Ask this question regarding each of the examples below...
"On a scale of 0 - 1, how would you rate the readability of this text?"
examineString(isReadable(string));
examineString( isReadable( string ));
The second example makes use of my own rule
whitespace in-between parentheses between words, but not between opening or closing punctuation.
i.e. not like this examineString( isReadable( string ) ) ;
but like this examineString( isReadable( string ));
or this examineString( isReadable({ string: string, thing: thing });
If we were to use English grammar rules, then we would space before the "(" and our code would be...
examineString (isReadable (string));
I am not in favor of this practice as it breaks apart the function invocation away from the function, which it should be part of.
examineString(); // yes; examineString (): // no;
Since we are not exactly mirroring proper English grammar, but English grammar does say that a break is needed, then perhaps adding whitespace in-between parentheses might get us closer to 1 with isReadable?
I'll leave it up to you all, but remember the basic question:
"Does this change make it more readable, or less?"
Here are some more examples in support of my case.
Assume functions and variables have already been declared...
input.$setViewValue(setToUpperLimit(inputValue));
Is this how we write a proper English sentence?
input.$setViewValue( setToUpperLimit( inputValue ));
closer to 1?
config.urls['pay-me-now'].initialize(filterSomeValues).then(magic);
or
config.urls[ 'pay-me-now' ].initialize( fitlerSomeValues ).then( magic );
(spaces just like we do with operators)
Could you imagine no whitespace around operators?
var hello='someting';
if(type===undefined){};
var string="I"+"can\'t"+"read"+"this";
What I do...
I space between (), {}, and []; as in the following examples
function hello( one, two, three ){
return one;
}
hello( one );
hello({ key: value, thing1: thing2 });
var array = [ 1, 2, 3, 4 ];
array.slice( 0, 1 );
chain[ 'things' ].together( andKeepThemReadable, withPunctuation, andWhitespace ).but( notTooMuch );
There are few if any technical reasons to prefer one over the other - the reasons are almost entirely subjective.
In my case I would use the second format, simply because:
It's perfectly readable, and follows the vast majority of formatting conventions in Javascript's ancestor languages
JS file download size matters [although minification does of course fix that]
I've always done it that way.
Quoting Code Conventions for the JavaScript Programming Language:
All binary operators except . (period) and ( (left parenthesis) and [ (left bracket) should be separated from their operands by a space.
and:
There should be no space between the name of a function and the ( (left parenthesis) of its parameter list.
I prefer the second format. However there are also coding style standards out there that insist on the first. Given the fact that javascript is often transmitted as source (e.g. any client-side code), one could see a slightly stronger case with it than with other languages, but only marginally so.
I find the second more readable, you find the first more readable, and since we aren't working on the same code we should each stick as we like. Were you and I to collaborate then it would probably be better that we picked one rather than mixed them (less readable than either), but while there have been holy wars on such matters since long before javascript was around (in other languages with similar syntax such as C), both have their merits.
I use the second (no space) style most of the time, but sometimes I put spaces if there are nested brackets - especially nested square brackets which for some reason I find harder to read than nested curved brackets (parentheses). Or to put that another way, I'll start any given expression without spaces, but if I find it hard to read I insert a few spaces to compare, and leave 'em in if they helped.
Regarding JS Hint, I wouldn't worry- this particular recommendation is more a matter of opinion. You're not likely to introduce bugs because of this one.
I used JSHint to lint this code snippet and it didn't give such an advice:
if( window )
{
var me = 'me';
}
I personally use no spaces between the arguments in parentheses and the parentheses themselves for one reason: I use keyboard navigation and keyboard shortcuts. When I navigate around the code, I expect the cursor to jump to the next variable name, symbol etc, but adding spaces messes things up for me.
It's just personal preference as it all gets converted to the same bytecode/binary at the end of the day!
Standards are important and we should follow them, but not blindly.
To me, this question is about that syntax styling should be all about readability.
this.someMethod(toString(value),max(value1,value2),myStream(fileName));
this.someMethod( toString( value ), max( value1, value2 ), myStream( fileName ) );
The second line is clearly more readable to me.
In the end, it may come down to personal preference, but I would ask those who prefer the 1st line if they really make their choice because "they are used it" or because they truly believe it's more readable.
If it's something you are used to, then a short time investment into a minor discomfort for a long term benefit might be worth the switch.

__LINE__ equivalent in Javascript

Is there any way to get the source line number in Javascript, like __LINE__ for C or PHP?
There is a way, although more expensive: throw an exception, catch it immediately, and dig out the first entry from its stack trace. See example here on how to parse the trace. The same trick can also be used in plain Java (if the code is compiled with debugging information turned on).
Edit: Apparently not all browsers support this. The good news is (thanks for the comment, Christoph!) that some browsers export source file name and line number directly through the fileName and lineNumber properties of the error object.
The short answer is no.
The long answer is that depending on your browser you might be able to throw & catch an exception and pull out a stack trace.
I suspect you're using this for debugging (I hope so, anyway!) so your best bet would be to use Firebug. This will give you a console object; you can call console.trace() at any point to see what your programme is doing without breaking execution.
You can try to run C preprocessor (f.e. cpp from GNU Compiler Collection) on your javascript files -- either dynamically with each request or statically, by making this operation be applied every time you change your javascript files. I think the javascript syntax is similar enough for this to work.
Then you'd have all the power of C preprocessor.
You can use this in vanilla JS:
function getLine(offset) {
var stack = new Error().stack.split('\n'),
line = stack[(offset || 1) + 1].split(':');
return parseInt(line[line.length - 2], 10);
}
Object.defineProperty(window, '__LINE__', {
get: function () {
return getLine(2);
}
});
You will now have access to the global variable __LINE__
A __LINE__ in C is expanded by a preprocessor which literally replaces it with the line number of the current input. So, when you see
printf("Line Number: %d\r\n", __LINE__);
the compiler sees:
printf("Line Number: %d\r\n", 324);
In effect the number (324 in this case) is HARDCODED into the program. It is only this two-pass mechanism that makes this possible.
I do not know how PHP achieves this (is it preprocessed also?).
I think preprocessing makes more sense, in that it adds no runtime overhead. An alternative to the C preprocessor is using perl, as in the 2 step procedure below:
1 – add “Line # 999 \n” to each line in the script that you want numbered, e.g.,
alert ( "Line # 999 \n"+request.responseText);
2 – run the perl below:
cat my_js.js | perl -ane "{ s/Line # \d+ /Line # $. /; print $_;}" > C_my_js.js; mv C_my_js.js my_js.js
There is one workaround.
Usually the __ LINE __ combined with the __ FILE __ is used for marking a locations in code and the marking is done to find that location later.
However, it is possible to achieve the same effect by using Globally Unique Identifiers (GUID-s) in stead of the __ LINE __ and __ FILE __. Details of the solution reside in the COMMENTS.txt of a BSD-licensed toolset that automates the process.

Categories