Changing JS Indenting in Atom Keymap.cson - javascript

I'm trying to update my keymap.cson file so that JavaScript source is indented slightly differently. I do not want it to de-indent case and default statements in a switch.
By default, Atom will format this way:
switch(x) {
case 1:
//stuff
case 2:
//stuff
default:
//stuff
}
I like my case statements to be indented once (and //stuff to be indented once more).
So I'm trying to edit my keymap to make it format things this way:
switch(x) {
case 1:
//stuff
case 2:
//stuff
default:
//stuff
}
Unfortunately, whatever I try, I can't get it to stop decreasing the indentation as soon as I hit the spacebar after "case".
From the Keymaps Documentation it looks like putting the following coffeescript in my keymap.cson file should disable the default behavior and add my new behavior (which omits |case|default from the second line of the regular expression) should do the trick but I'm not sure why it's not working:
'.source.js':
'editor':
'decreaseIndentPattern': 'unset!'
'.source.js':
'editor':
'decreaseIndentPattern': '(?x)
^(.*\\*/)?\\s*(\\}|\\))
| ^\\s* else \\s*$
'
I think the original keymap is in the language-javascript package here.

I determined that this probably isn't technically a Keymap so it can't be overridden in keymap.cson. What I ended up doing was forking the language-javascript repo, making my change, uninstalling the original language-javascript package, and installing my custom fork instead.
Would still like to know if there is a way to update this at runtime instead; with this solution I will have to manually keep my fork up to date with any upstream changes.
Edit: Just an update for this particular change, it was actually accepted into the official language-javascript package via PR #36.

Related

Arrow function "expression expected" syntax error

I want to transform this code:
var formatQuoteAmount = function (tx) {
return Currency.toSmallestSubunit(tx.usd, 'USD');
};
var quoteAmounts = res.transactions.map(formatQuoteAmount);
into an anonymous arrow function. I've written this:
var quoteAmounts = res.transactions.map(tx => Currency.toSmallestSubunit(tx.usd, 'USD'));
I get expression expected syntax error at the arrow. I looked up the default syntax here and seems like the syntax of my code is correct. Any ideas what the problem might be?
I have it working with this syntax:
var quoteAmounts = res.transactions.map(function (tx) {
return Currency.toSmallestSubunit(tx.usd, 'USD')
});
but I want to make it a one-liner, with an arrow-function.
Running on node v5.3.0
I had the error expression expected reported by Webstorm when editing a Node.js program. In this case the solution is to set the language version to a version that supports this feature.
The following is what i did that work for me.
(1) I change the JavaScript language option to ECMAScript 6 as show in the selected answer by #Joe23
(2) I close the Webstorm project/application.
(3) Navigate to the project folder and delete the .idea folder in it. I believe this is the folder webstorm generated to keep information about the project/application.
(4) I reopen my project in webstorm and the errors are gone.
Arrow functions are available by default on the latest versions of node and other javascript runtimes. You need to enable support for them only if you're dealing with a really old runtime (0.12 and earlier if I recall correctly) in which case you need to add the "--harmony" flag when you start the node process.

CodeMirror: make atomic range of token

I'm implementing CodeMirror to use as an editor for special files that require some syntax highlighting. I wrote my own parser for it, but now I face the following problem: there is a specific kind of token that I would always like to mark as an atomic range (with doc.markText).
I would have thought that there would exist some event handler for when tokens have been parsed, containing {line, ch} objects for its start and end positions. Reading through the docs, this does not seem to exist, so I would write my own, but the problem is that there seems to be no way to get any kind of position data whatsoever related to the parser.
What would be the best way to go about this? There are really crude ways like registering a change handler or iterating over the whole contents every few seconds, but of course this should be avoided.
I've forked the CodeMirror github repo and made an event that fires when a token gets parsed.
The syntax is this:
"tokenParsed" (instance: CodeMirror, start: {ch, line}, end: {ch, line}, style: String, text: String)
And then I handle it as follows:
myCodeMirror.on("tokenParsed", function(instance, start, end, style, text) {
if(!instance.findMarksAt(end).length) { //check if the mark doesn't exist yet
if(style && style.indexOf("param") > -1) {
instance.markText(start, end, {atomic: true});
}
}
});
If anyone wants this, see my repository.

Is it possible to alter javascript with google closure compiler?

I'm working on a modular component framework and have different needs for the code in my test environment vs production. Each component has its own js file and these are being compiled together for production use, but left separate in my dev environment.
In production I want to trap errors in various stages of initialization so as to not break the call stack. In my development (uncompressed javascript), I do not want to trap the errors, so I can quickly get line numbers, etc to find where the breaks occur. Is there any way to use the closure compiler to manipulate a javascript file (such as removing a flagged line such as a comment opener and closer) that might allow me to do this?
For instance:
proto.instantiateChildFromDescriptor = function(childObj, callback, customDiv){
/*ProductionErrorTrap
try{
/**/
//code for instantiating a module
/*ProductionErrorTrap
}catch(e){
console.log("problem instantiating child in " + this.getName());
console.error(e);
}
/**/
}
replacing /*ProductionErrorTrap with /*ProductionErrorTrap*/ would work nicely (so is removing my stars on the second comment block, but they are there)
I can't do this with a find and replace on the files themselves because it would mess with github. I suppose I could create a new copy of the files, run a find and replace on them and compile *those files, but It would be nice if I could do it all in the closure compiler.
Thanks
I think messing with compiled results, matching comments to emulate ifdefs is pretty unelegant.
You could actually do something like this:
debugTry(function() {
alert('This is code that might cause an error');
},function(e) {
alert('Whoops! Caught error '+e);
});
Then while debugging you do:
function debugTry(test,handle) {
try {
test();
} catch(e) {
handle(e);
}
}
And in production:
function debugTry(test,handle) {
test();
}
Closure Compiler is pretty smart. With the first debugTry the example compiles to:
try{alert("This is code that might cause an error")}
catch(a){alert("Whoops! Caught error "+a)};
With the second debugTry it compiles to:
alert("This is code that might cause an error");
As you see, the unnecessary code is detected and eliminated.
Of course, things would be easier if you didn't conditionally include a try block. If it's just some statements included conditionally, not changing the structure of other code, you can do:
/** #const */ var debug = false;
if(debug) {
alert('Yay for debugging!');
}
The alert will be compiled away.
Use compiler flags for advanced mode.
from:
https://developers.google.com/closure/compiler/docs/js-for-compiler
#define {Type} description
For example:
/** #define {boolean} */
var ENABLE_DEBUG = true;
/** #define {boolean} */
goog.userAgent.ASSUME_IE = false;
Indicates a constant that can be overridden by the compiler at compile-time. With the example above, you can pass the flag --define='ENABLE_DEBUG=false' to the compiler to change the value of ENABLE_DEBUG to false.
Stephen Chung's comment seems to be the best approach. Adding his comments as an answer to this question for anyone else with this problem. I entered the following into my code
proto.updateProperties = function(propsObj){
/** #preserve ProductionErrorTrap try{ /**/
//do stuff here
/** #preserve ProductionErrorTrap }catch(e){console.log("problem updating properties in " + this.getName());console.error(e);}/**/
}
After compressing the javascript I just run a find and replace on the compressed file, remove the line breaks and replace ProductionErrorTrap with ProductionErrorTrap*/ and everything seems to work fine without making a mess of the repository.
Thanks Stephen!

How can I rename a jsTree node

I am not talking about $("#demo1").jstree("rename",node) which makes the node editable for the user. I am talking about the name being changed within the code. For example my nodes are all prefixed with a 2 digit number "[01]" so before I call $("#demo1").jstree("rename",node) I want to strip out the prefix, and put it back in once the user has finished editing. I have tried selecting "#nodeid a" but inside the hyperlink there is an ins tag and this gets replaced if i replace the URL contents. The documentation hasn't been helpful and I havent had much luck looking through the libraries code, can any help me? Chris
The recommended method is to use rename_node
$("#demo1").jstree('rename_node', node , text );
Please keep in mind that by default all modifications to the tree are
prevented (create, rename, move, delete). To enable them set
core.check_callback to true
$('#demo1').jstree({
'core': {
'check_callback': true,
/// rest of the options...
}
});
Rename your node (alternative, not recommended)
$("#demo1").jstree('set_text', node , text );
Debugging
If you still encounter trouble, you can use this method to get the last error.
$('#demo1').jstree(true).last_error()
For older versions (v1.*)
$("#demo1").jstree('rename_node', [node , text] );
$("#demo1").jstree('set_text', [node , text] );
See also:
this jsfiddle for the comparison and example of both methods.
Interaction with jsTree (how to call API methods)
API documentation of rename_node
API documentation of set_text
I believe there is an syntax error with respect to the square braces "[" in the above answer. I use jsTree 3.0.4 and this is the correct syntax -
right - $("#demo1").jstree('set_text',node,text);
wrong - $("#demo1").jstree('rename_node', [node , text] );
Example -
$("#tree_3").jstree('set_text',"#idSelectorForNode" ,"NewName");
You should turn on the switch to allow the rename operation, such as:
$('#container').jstree({
'core' : {
'check_callback' : function (operation, node, node_parent, node_position, more) {
// operation can be 'create_node', 'rename_node', 'delete_node', 'move_node' or 'copy_node'
// in case of 'rename_node' node_position is filled with the new node name
return operation === 'rename_node' ? true : false;
}
});
You can use this for updating node text with jstree refresh:
$("#demo1").jstree(true).rename_node(node , "Renamed_Text");

Flymake quits right ahead after loading with js2-mode

When opening .js files, js2-mode and, subsequently, flymake-js is
automatically loaded. But flymake unloads right ahead with the message
Toggling flymake-mode off; better pass an explicit argument.
However, when enabling it manually, using M-x flymake-mode, it keeps
activated. Has anybody encountered similar behavior and has fixed it?
My setup:
I followed the instructions on emacswiki to set up Flymake to work with
the most recent js2-mode with a little modification:
(add-hook 'js2-mode-hook '(lambda () (flymake-js-load)))
instead of
(add-hook 'javascript-mode-hook '(lambda () (flymake-js-load)))
Probably, somewhere in your hook, there is a statement like :
(flymake-mode t)
you need to change it to :
(flymake-mode 1)
I read the documentation on flymake-mode. It says:
flymake-mode is an interactive compiled Lisp function in `flymake.el'.
(flymake-mode &optional ARG)
Minor mode to do on-the-fly syntax checking.
When called interactively, toggles the minor mode.
With arg, turn Flymake mode on if and only if arg is positive.
If and only if the arg is positive. Not non-nil. But the page on
http://www.emacswiki.org/emacs/FlymakeJavaScript which suggests a definition for flymake-js-load, shows (flymake-mode t) .
That seems wrong.

Categories

Resources