Hi so I am writing a lot of server side javascript and I would like the ability to refactor while editing with emacs. Is this possible? Thanks!
By refactor I mean like how in eclipse while editing Java you can refactor one variable called for example "variableOne" into "variable1" and now all other 15 times you wrote "variableOne" becomes "variable1".
Probably the most sophisticated JavaScript refactoring library for Emacs is Magnar Sveen's js2-refactor. Its list of supported refactorings includes
rv is rename-var: Renames the variable on point and all occurrences in its lexical scope.
which sounds a lot like what you're looking for. It also supports a number of other very useful common rafactoring actions.
Assuming you're on Emacs 24, I recommend installing it using the MELPA repository. If you're still on Emacs 23 you'll have to upgrade or manually install package.el before you can MELPA.
If you are looking for just renaming variables, you might also want take a look at tern. The advantage it has compared to js2-refactor (which I use too) is that it has a concept of projects so you can rename a certain variable across multiple files in a project. It also provides other features like jump-to-definition and auto-completions (which are quite accurate).
Here are some general options for renaming a variable
1) Multiple cursors - It has a useful command mc/mark-all-like-this-dwim, which marks all the occurences of the selected text in current context you can then edit all the occurrences simultaneously.
2) Wgrep - This package enables one to apply changes done in grep buffer to respective files. This is useful when I have to replace a word across many files, in such situations use rgrep to search the word in multiple files. Then enable wgrep in the resulting grep buffer, mark the word to replaced with multiple-cursors (you can also use query-replace), make the changes and then do wgrep-save-all-buffers and all my changes are saved!
Your question seems to be more about renaming variables than about refactoring in general. The two places to start for information about using Emacs to rename parts of your code are these:
Emacs Wiki Search and Replace category page. This includes search-and-replace across multiple files (e.g. of your project).
The Emacs manual: use C-h r to enter the manual from Emacs.
Then use hit the key i to look something up in the index (with completion):
i search and replace commands takes you to the section about replacement commands.
i search and replace in multiple files takes you to the section about Searching and Replacing with Tags Tables.
For Emacs support for projects, see the Emacs Wiki Projects category page.
Related
Background: I've been developing a bunch of browsers extensions on production sites (Yelp, Zillow, Trulia, Reddit) which use react. I've yet to take a course on React (I'm planning on doing it) but my questions are:
How stably named are the classes in production react sites (many of the classes have weird numbers and letters appended) and if they are not stable, how often do they change and is there any way to get a more stable selector for these types of items?
When classes are completely non-human readable, is there any way to view the class name in a more human readable format? e.g. <div class="_2jJNpBqXMbbyOiGCElTYxZ">
I'd hate to build these extensions and have them break whenever there is a minor release (I know they will break as the site is significantly updated but would prefer if they were stable for minor releases).
Example: Targeting a span like this
<span class="lemon--span__373c0__3997G text__373c0__2Kxyz reviewCount__373c0__2r4xT text-color--black-extra-light__373c0__2OyzO text-align--left__373c0__2XGa-">865</span>
with a queryselection like this:
const ratingCountTarget = result
.closest('.mainAttributes__373c0__1r0QA')
.querySelector('.reviewCount__373c0__2r4xT');
There's no way to get the original names and nothing precludes the site developers from updating the random parts any day or several times a day so find a way to not depend on the exact names.
Try finding the non-randomized attributes
Use relations between elements (combinators)
Use partial matching like foo.querySelector('[class*="reviewCount"]')
And get ready to having your extension inevitably break even if only occasionally.
I'm using the paper_trail gem to auto-create a versions history of my Page model.
In pages#show, I display the versions like so:
The most important element is the diff which shows the difference between the previous and the currently displayed version of a field, e.g. content. It looks like a diff on GitHub, and it is marked up well using <ins> for insertions and <del> for deletions.
The sad thing is that at the time being, I generate this diff using https://code.google.com/p/google-diff-match-patch/, a JavaScript library that's run in the browser of the user. I've done it this way because I didn't manage to find a Ruby gem or similar that does the same in a similar elegant way.
Well, I found https://github.com/samg/diffy and https://github.com/pvande/differ, but the diff of both gems aren't close as elegant: differ needs to know manually whether to diff by line, word, or character (while the used JavaScript decides this automatically and uses a combination of these options which feels very intuitive to me), and diffy doesn't offer an option for this. I don't know exactly how the JavaScript works, but it states that "Myer's diff algorithm" is used internally:
This library implements Myer's diff algorithm which is generally considered to be the best general-purpose diff. A layer of pre-diff speedups and post-diff cleanups surround the diff algorithm, improving both performance and output quality.
You can try it here: https://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html
Maybe use the following two strings to see a typical example of two versions of a page:
This is the about page.
Put markdowwn formated content here.
and
This is the about page.
Put markdown formatted here content.
A [link to page 11](11). And another one: [](11).
It results in something like this:
The problem with this approach is that it's run in the browser, so I can't mutate the generated code in my Rails application anymore. So I wonder whether there's an easy way to get similar diff results using e.g. a command line tool like diff? Maybe even git could be of use?
Should files be named something-with-hyphens.js, camelCased.js, or something else?
I didn't find the answer to this question here.
One possible naming convention is to use something similar to the naming scheme jQuery uses. It's not universally adopted but it is pretty common.
product-name.plugin-ver.sion.filetype.js
where the product-name + plugin pair can also represent a namespace and a module. The version and filetype are usually optional.
filetype can be something relative to how the content of the file is. Often seen are:
min for minified files
custom for custom built or modified files
Examples:
jquery-1.4.2.min.js
jquery.plugin-0.1.js
myapp.invoice.js
I'm not aware of any particular convention for javascript files as they aren't really unique on the web versus css files or html files or any other type of file like that. There are some "safe" things you can do that make it less likely you will accidentally run into a cross platform issue:
Use all lowercase filenames. There are some operating systems that are not case sensitive for filenames and using all lowercase prevents inadvertently using two files that differ only in case that might not work on some operating systems.
Don't use spaces in the filename. While this technically can be made to work there are lots of reasons why spaces in filenames can lead to problems.
A hyphen is OK for a word separator. If you want to use some sort of separator for multiple words instead of a space or camelcase as in various-scripts.js, a hyphen is a safe and useful and commonly used separator.
Think about using version numbers in your filenames. When you want to upgrade your scripts, plan for the effects of browser or CDN caching. The simplest way to use long term caching (for speed and efficiency), but immediate and safe upgrades when you upgrade a JS file is to include a version number in the deployed filename or path (like jQuery does with jquery-1.6.2.js) and then you bump/change that version number whenever you upgrade/change the file. This will guarantee that no page that requests the newer version is ever served the older version from a cache.
There is no official, universal, convention for naming JavaScript files.
There are some various options:
scriptName.js
script-name.js
script_name.js
are all valid naming conventions, however I prefer the jQuery suggested naming convention (for jQuery plugins, although it works for any JS)
jquery.pluginname.js
The beauty to this naming convention is that it explicitly describes the global namespace pollution being added.
foo.js adds window.foo
foo.bar.js adds window.foo.bar
Because I left out versioning: it should come after the full name, preferably separated by a hyphen, with periods between major and minor versions:
foo-1.2.1.js
foo-1.2.2.js
...
foo-2.1.24.js
The question in the link you gave talks about naming of JavaScript variables, not about file naming, so forget about that for the context in which you ask your question.
As to file naming, it is purely a matter of preference and taste. I prefer naming files with hyphens because then I don't have to reach for the shift key, as I do when dealing with camelCase file names; and because I don't have to worry about differences between Windows and Linux file names (Windows file names are case-insensitive, at least through XP).
So the answer, like so many, is "it depends" or "it's up to you."
The one rule you should follow is to be consistent in the convention you choose.
I generally prefer hyphens with lower case, but one thing not yet mentioned is that sometimes it's nice to have the file name exactly match the name of a single module or instantiable function contained within.
For example, I have a revealing module declared with var knockoutUtilityModule = function() {...} within its own file named knockoutUtilityModule.js, although objectively I prefer knockout-utility-module.js.
Similarly, since I'm using a bundling mechanism to combine scripts, I've taken to defining instantiable functions (templated view models etc) each in their own file, C# style, for maintainability. For example, ProductDescriptorViewModel lives on its own inside ProductDescriptorViewModel.js (I use upper case for instantiable functions).
I have a grammar for a domain specific language, and I need to create a javascript code editor for that language. Are there any tools that would allow me to generate
a) a javascript incremental parser
b) a javascript auto-complete / auto-suggest engine?
Thanks!
An Example of implementing content assist (auto-complete)
using Chevrotain Javascript Parsing DSL:
https://github.com/SAP/chevrotain/tree/master/examples/parser/content_assist
Chevrotain was designed specifically to build parsers used (as part of) language services tools in Editors/IDEs.
Some of the relevant features are:
Automatic Error Recovery / Fault tolerance because editors and IDEs need to be able to handle 'mostly valid' inputs.
Every Grammar rule may be used as the starting rule as an Editor/IDE may only want to implement incremental parsing for performance reasons.
You may want jison, a js parser generator. In terms of auto-complete / auto-suggest...most of the stuff out there I know if more based on word completion rather than code completion. But once you have a parser running I don't think that part is too difficult..
This is difficult. I'm doing the same sort of thing myself.
One approach is:
You need is a parser which will give you an array of the currently possible ASTs for the text up until the token before the current cursor position.
From there you can see the next token can be of a number of types (usually just one), and do the completion, based on the partial text.
If I ever get my incremental parser working, I'll send a link.
Good luck, and let me know if you find a package which does this.
Chris.
I have a web application that uses TONS of javascript, and as usual, there are a lot of textual constants that will be displayed to the user embedded in the code itself.
What do you think is the best way to make this localizable?
I know I need to take those strings off of the code and replace them with constants, which will be defined into some external place.
For the server side, ASP.Net provides some very neat capabilities for dealing with this.
What's the best to do this in Javascript?
The best idea I have is to have a JS file with ALL the string constants of the JS of the site (i'd have different copies of this, for each language), and then on each page, I include this script first, before all the others.
This seems like the most centralized way, that also wastes the least bandwidth.
Are there any other better approaches?
Thanks!
here's how we did it (in ASP.net), pretty much along the lines of what you've mentioned:
1) Created two javascript files: one which defines all javascript functions/DOM manipulations as required by the site, and, second called Messages.js: this defines all the string literals that need to be localized, something like var ALERT_MSG = "Alert message in english".
2) Created different version of the Messages.js, one for each locale that we are supporting and localized the strings. The localized js files were named using messages.locale.js naming convention (for eg. messages.fr-FR.js).
3) Included the js files within the "ScriptManager" and provided the ResourceUICultures for the Messages.js file: this ensures that the correct localized file is embedded in the html output (if you are not using ASP.net you can build this basic functionality by doing some culture sniffing and including the appropriate js file).
4) Voila!
Your approach makes sense. Details:
I'd have the strings for each language in an object.
localized={"cat":"chat","dog":"chien"};
Then in code:
localized["cat"]
The quotations around of the keys and the array notation (rather than the more common object dot notation) are to avoid collisions with JavaScript reserved words.
There is a gettext library but I haven't used it.
Your approach sounds good enough.
If you have lots of strings and you are concerned about the bulkiness of the file you may want to consider a script that creates a single javascript file for each language by concatenating the code javascript and the locale javascript and then applying something like Minify.
You'll waste some CPU cycles on publishing but you'll save some round trips...
There's a library for localizing JavaScript applications: https://github.com/wikimedia/jquery.i18n
The strings are stored in JSON files, as pretty much everybody else suggests, but it has a few more features:
It can do parameter replacement, supports gender (clever he/she handling), number (clever plural handling, including languages that have more than one plural form), and custom grammar rules that some languages need.
The only requirement is jQuery.