Javascript autocomplete current line and add {} curly braces? - javascript

In VS Code, is there a way I can use keyboard combination like "ctrl+enter" to finish the current line and add { automatically at end of the line? instead of that i have to go to the end of the line my self and type { for it.
For example, when I typed if, VS code gives me if () blocks automatically, and I started typing condition in the braces.
if (condition)
// while the cursor is after 'n' but before ')'
When I'm at the end of the "condition", I have to use arrow key to move to the end and add {}. Do you program Javascript in this way or you have better tools/keyboard shortcut to use?
While I'm programming in Python, most IDE like VScode or Pycharm provides quick completion keyboard shortcut like "ctrl+shift+enter" to finish the line by adding ":" at end of the sentence, which applies to both defining functions, if, for, conditions. But unfortunately I haven't found such a way in Javascript world yet.

Search for snippets on the VS extension section ,I think you can find it there for any programming language .

Related

VSCode doesn't recognize JS-Expression in TypeScript

I started to work with Angular for a work-related project and am following this tutorial https://www.youtube.com/watch?v=2OHbjep_WjQ&t=1874s (minute 50:30)
Which led me to following code-snippet
i=0;
doSomeHeavyTask()
{
console.log('Called ${this.i++} times');
}
The browser should print following message into the console:
Called 0 times
Called 1 times
...
But VSCode doesnt recognize
${this.i++}
as an JS-expression, therefore it prints just the plain text.
The syntax also doesn't get highlighted and is handled like a normal string.
I can't find the reason behind this behaviour and couldn't find any other person with that problem. I would be happy if somebody could come up with a suggestion or a solution :)
You used the wrong character for the template literal syntax. It should be the backtick (on keyboard, usually left of the 1 key), not the single quotation mark.
console.log(`Called ${this.i++} times`);

Why does Eclipse not un-indent braces in JavaScript?

I have pored over the formatting settings on Eclipse for hours and found no solution to this problem:
Video of issue
When I type the opening curly brace on the line immediately following an if, else or function line the ending brace is automatically added, but neither conform to my formatting rules (i.e. the braces should be aligned with the if, else or function text).
The way it looks:
if (a)
{
}
The way it should look (and does after running the formatter):
if (a)
{
}
I would chalk it up to a deficiency in Eclipse except for one thing: when editing PHP, Java or C++ code it works as I'd desire; the braces are un-indented appropriately.
It's because Javascript formatting is exactly like that.
The if statement standards:
if (a) {
// your code
}
And if you use an Array of Objects, for example:
var arr = [
{ prop: 'value', prop2: 5 },
{ prop: 'value', prop2: 5 }
];
It's working exactly as it was intended to. Take a look at this Javascript's style guide.
This is just because the formatter is not applied after you write the code. Here is the way to do it.
On Eclipse, go to Window>Preferences
Under JavaScript>Code Style>Formatter, create a New Profile.
On creation of new profile or on edit, you would be shown with a window to change the format style. Go to Braces.
For Blocks, choose Next Line
Click OK. Confirm the profile and click OK.
Now, after you write the following:
if (true)
{
}
Use formatter to make changes for you, usually by Ctrl+Shift+F or from menu by Source>Format. You may apply formatting to selected piece of code too.
Update
Once you have the above setting, go to Window>Preferences>JavaScript>Editor>Save Actions, enable Perform the selected actions on save and Format source code which would make the this operation better.

How to disable "special commands" in node.js REPL?

Problem Node REPL has some "special commands" like .break and .save. I never use these, but I do very frequently try and paste into the REPL code that's formatted like so:
words.append('ul')
.classed('my-class', true)
.selectAll('li.new-class')
.data((tuple, tupleIdx) => obj[tupleIdx])
.enter()
.append('li')
.classed('new-class', true)
.text(d => '' + foo(d));
(This is d3.js code but similar things happen when using Promises, a chain of .then(...)s starting on each line.)
Of course node complains about "invalid REPL keyword" when it sees .classed or .then on its own line and proceeds to print a sequence of error messages several screens long.
Tenuous pseudo-workaround I've worked around this with a regexp in Vim that moves any whitespace between closing parens and dots to after the dot (:%s/)\n\(\s*\)\./).\r\1/ for completeness) but this is tedious and often I want to copy-paste from a browser and not switch to Vim to reformat some code.
Question Is there any way to disable node REPL "features" which, while well-intentioned, conflict with standard JavaScript practices, such as lines starting with dots?
Or is this too complicated for a terminal application, and if so, is there a way I can communicate with the node REPL via a browser's JS console (not node-monkey which only handles console.log)
PS. This question is mainly about lines starting with . but another such conflict is _ (worked around thankfully by n_).
You can make your own custom REPL. That option should give you maximal control over how your repl behaves.
Since the main problem here is pasting multi-line code into the default repl, as a workaround, try using the .editor special command.
Enter editor mode (Ctrl+D to finish, Ctrl+C to cancel).
It's also mentioned in the answer to this question about writing multiple lines in the node repl
If you're also interested in saving keystrokes, when entering the editor, autocomplete seems to kick in after typing ".ed" so you can shave off three keystrokes in that sense.
You can simply delete the command from the instance:
const replServer = repl.start(/* ... */)
delete replServer.commands.load;
You can even define the whole commands object, take a look at the reference implementation:
https://github.com/nodejs/node/blob/main/lib/repl.js
Here's something tentative: using node-copy-paste, I wrote a tiny module that allows me to paste() the contents of clipboard and evals it after fixing lines starting with ..
This goes in paste.js:
var cp = require('copy-paste'); // npm install node-copy-paste
module.exports = function() {
return eval(cp.paste().replace(/\n\s*\./g, "."));
};
Then in node REPL, paste = require('./paste'); paste() will make it go. Very brittle but it might solve the problem often enough to be valuable.

Please explain this usage of a colon in javascript

I'm making a library, and I often inspect the result of Closure Compiler's output to see how it's doing things (I do have unit tests, but I still like to see the compiled code for hints of how it could compress better).
So, I found this very weird piece of code, which I never seen before.
variable : {
some();
code()
}
Note: this is not an object literal! Also, there is no ? anywhere that would make it a ?: conditional.
That code is in a regular function block (an IIFE).
variable, in this case, is an undefined variable. There's no code making it true, false, or whatever, and just to make sure, I put a console.log in there and indeed, I get a ReferenceError.
Please do note that I test my code in IE8 too, so this isn't just in modern browsers. It seems to be standard, plain old javascript.
So let's experiment with it. Firing up Chrome's console, I get this:
undeclaredVariable:{console.log('does this get logged?')} // yes it does.
trueValue:{console.log('what about this?')} // same thing.
falseValue:{console.log('and this?')} // same thing.
but then...
(true):{console.log('does this work too?')} // SyntaxError: Unexpected token :
...and...
so?{console.log('is this a conditional?')}:{alert(123)} // Unexpected token .
So what does it do?
thisThing:{console.log('is used to declare a variable?')}
thisThing // ReferenceError: thisThing is not defined
Please, I'd love it if someone could explain to me what this code is meant to do, or at least what it does.
It is a label
Provides a statement with an identifier that you can refer to using a
break or continue statement.
For example, you can use a label to identify a loop, and then use the
break or continue statements to indicate whether a program should
interrupt the loop or continue its execution.
Another common place you see it is when people stick the wonderful and useless javascript: on event handlers.
This is a label (the bit ending with a colon) followed by a block (the code surrounded by the curly brackets).
Blocks usually follow control statements, like if(...) { /*block*/ }, but they can also simply stand on their own, as in your example.
Labels allow jumping up several loops at a time with a continue or break; see the linked MDN page for several examples, such as:
var itemsPassed = 0;
var i, j;
top:
for (i = 0; i < items.length; i++){
for (j = 0; j < tests.length; j++)
if (!tests[j].pass(items[i]))
continue top;
itemsPassed++;
}
Here, top: is a label that code inside the inner loop can jump to, in order to escape to the outer loop.
For the sake of anyone who doesn't know what JSON is, and sees a colon in what might actually be an object, and is trying to figure out what it is, and finds this discussion, a colon is also used in JSON. There is a practice of embedding functions in a JSON object. Which might be confusing (As it was to me) for anyone who happens to see this for the first time. (Everyone isn't born with the knowledge of JSON and JavaScript programmed into their brains.) So if you find yourself at this discussion, and you think that every time you see a colon in JavaScript, that it's a label, it might not be. It might be that it's a colon after a label, OR it might be part of JSON. In fact, a colon in JSON being shown as a string, is a lot more common than a label. JSON in the form of an object, will be displayed as [object Object], with all the content hidden. So, unless the JSON is in the form of a string, and you display an object to the console (console.log(object)) all you will see is [object Object]. It is common practice to write JavaScript code, wrapped in an object. In that case you will see the JSON in the form of code. That's when you'll ask yourself, "What is this? and what is that colon for?" Then you'll find yourself at this discussion, and be told that it's a label, when it's really part of JSON. The topic of this discussion is worded: "Please explain this usage of a colon in javascript", and then the "correct answer" is marked as having to do with a label. The correct answer is that a colon can be used in more than one way. So, if you don't know what JSON is, or think you know (like I did, but didn't really understand) read about it here:
JSON.org
That is just a label.
you can use continue [label name] (or break) in a loop to go to a label.
More explanations of what they are can be seen throughout the interwebs.
it is used for labeling an statement in jsvascript.check more detail here.
the labeled statement can be used with break and continue later.

Javascript refactoring in Vim

I don't need anything super fancy, but some scope aware refactoring would be nice.
Refactoring something in function scope is one of the most common scenarios for me:
var funyfun = function(arg1, arg2) {
arg1 = ...arg2;
arg2....();
}
Is there a vim plugin that would allow me to refactor arg1, for ex, in the scope of that function or do I have to invent my own "select block, find, replace" shortcut.
For extra kudos, something that would "refactor on the fly" as I type, so I can see where changes are being made. Netbeans does an excellent job of this.
This is not limited to a certain block, but this how I would do it with plain Vim:
Move cursor on top of arg1 and type *N
Type ciw and insert replacement.
Now you can use n and N to navigate the occurrences and by pressing . Vim will redo the replacement on the current match
Here's a shortcut for it:
" Simple word refactoring shortcut. Hit <Leader>r<new word> on a word to
" refactor it. Navigate to more matches with `n` and `N` and redo refactoring
" by hitting the dot key.
map <Leader>r *Nciw
Sound a bit like you only want renaming instead of refactoring. Full refactoring is tricky for Javascript, though some IDEs provide approximations. Since the question is about Vim specifically, and hacks aren't excluded, I'll just jump on the scope-aware aspect:
I've got a modified DoctorJS to generate scope-aware tags, with a Vim plugin for scope-aware navigation based on those tags (see blog post/screencast).
The hacky part comes in how navigation is implemented for Vim: I generate a search pattern that includes the scope of the variable and excludes all nested scopes for the same name. So, you could use that search pattern (function scoped_tags#FindTagInScope) to implement renaming (only if all uses are in the same file, and it doesn't exclude comments and the like..). Or you could use the scoped navigation to jump through variable occurrences manually and use '.' to rename them..
A few JavaScript-aware commands for Vim are provided by tern_for_vim, such as :TernRename for scope-aware renaming of variables, :TernDef for jumping to the definition of the thing under the cursor, and so on. You will need to have nodejs and npm installed, make sure to read the installation instructions in the repo.
As a partial solution you can use Eclim with JSDT, which allows you to use power of Eclipse refactoring/debugging/auto-completion/plugins with Vim.
In my experience, it may be a bit slow on older machines, but it's worth giving it a try.
In addition to doing actual scope-aware refactoring and the like, consider :%s/varName/newNav/gc. Per :help :s_c, the c flag passed to :s enters a quick confirmation mode for find/replace operations that prompts you (y/n) on whether each match should be replaced or not.
you can do:
:.,/^}/ s/\<arg1\>/new_name/g
the .,/^}/ is a range that many Ex commands accept: from cursor line to next line starting with a closing brace.
Benoit and Epeli has some good points, however, I find it a bit tedious to write .,/^}/ before my substitute statement, and since it only modifies code from the cursor position to the next line starting with a }, it depends on having the cursor position at the beginning of the function or block (and it will not work for an entire function with an if statement).
So instead I use visual mode in combination with textobjects. For instance, typing vi{ will select all the code inside the closest matching pair of {}, va{ will include the {} characters, and if you do this with visual line (vi{V), you'll get the entire function declaration as well. Then you can just do a :s/\<arg1\>/new_name/g to rename arg1 to new_name, including function parameters.

Categories

Resources