How to add timestamp to Atom snippets? - atom-editor

I have been trying to figure out how to add add timestamp to Atom Snippets.
'.text.plain':
'Timestamp':
'prefix': 'isoT'
'body': 'new Date().toISOString()'
This just prints the text and without ' it throws an error.
Is it possible to add javascript to an Atom snippet?

This is not possible. Snippets are stored in a CSON file, which is CoffeeScripts equivalent of JSON.
In all likelyhood, there already exists a package that inserts a timestamp. Otherwise, with knowledge of JavaScript, it's fairly easy to write your own. Take note that all commands provided by a package can be bound to a keystroke.

Related

How can I get the source of a file using Cypress?

Selenium has a function called getPageSource that will get the source code of the page. I'm looking for the equivalent in Cypress.
I've tried
cy.get('html:root')
.eq(0)
.invoke('prop', 'outerHTML')
but, it doesn't really return the source of the page. As an example, the source contains ©, but the above cypress command shows it as ©. I want to see the actual source of the page, what I would see if I were to go to the server and open the file up in any plain text editor like notepad.
The naïve answer is to use string.replaceAll()
cy.get('html:root')
.eq(0)
.invoke('prop', 'outerHTML')
.then(pageSource => pageSource.replaceAll('©', '©'))
See dev.w3.org/html5/html-author/charref for a reference chart.
But I have a feeling there is a conversion function somewhere that does any and all occurrences.
Getting the equivalent of "View page source"*
cy.request(my-url)
.its('body') // NB the response body, not the body of your page
.then(content => {
// send content to validator.w3.org
// you can probably cy.visit('validator.w3.org') and manipulate the
// validation page, pasting in content value as required
})

Meteor how to save templates in mongo

I want to give my users the possibility to create document templates (contracts, emails, etc.)
The best option I figured out would be to store these document templates in mongo (maybe I'm wrong...)
I've been searching for a couple of hours now but I can't figure out how to render these document template with their data context.
Example:
Template stored in Mongo: "Dear {{firstname}}"
data context: {firstname: "Tom"}
On Tom's website, He should read: "Dear Tom"
How can I do this?
EDIT
After some researches, I discovered a package called spacebars-compiler that brings the option to compile to the client:
meteor add spacebars-compiler
I then tried something like this:
Template.doctypesList.rendered = ->
content = "<div>" + this.data.content + "</div>"
template = Spacebars.compile content
rendered = UI.dynamic(template,{name:"nicolas"})
UI.insert(rendered, $(this).closest(".widget-body"))
but it doesn't work.
the template gets compiled but then, I don't know how to interpret it with its data context and to send it back to the web page.
EDIT 2
I'm getting closer thanks to Tom.
This is what I did:
Template.doctypesList.rendered = ->
content = this.data.content
console.log content
templateName = "template_#{this.data._id}"
Template.__define__(templateName, () -> content)
rendered = UI.renderWithData(eval("Template.#{templateName}"),{name:"nicolas"})
UI.insert(rendered, $("#content_" + this.data._id).get(0))
This works excepted the fact that the name is not injected into the template. UI.renderWithData renders the template but without the data context...
The thing your are missing is the call to (undocumented!) Template.__define__ which requires the template name (pick something unique and clever) as the first argument and the render function which you get from your space bars compiler. When it is done you can use {{> UI.dynamic}} as #Slava suggested.
There is also another way to do it, by using UI.Component API, but I guess it's pretty unstable at the moment, so maybe I will skip this, at least for now.
Use UI.dynamic: https://www.discovermeteor.com/blog/blaze-dynamic-template-includes/
It is fairly new and didn't make its way to docs for some reason.
There are few ways to achieve what you want, but I would do it like this:
You're probably already using underscore.js, if not Meteor has core package for it.
You could use underscore templates (http://underscorejs.org/#template) like this:
var templateString = 'Dear <%= firstname %>'
and later compile it using
_.template(templateString, {firstname: "Tom"})
to get Dear Tom.
Of course you can store templateString in MongoDB in the meantime.
You can set delimiters to whatever you want, <%= %> is just the default.
Compiled template is essentially htmljs notation Meteor uses (or so I suppose) and it uses Template.template_name.lookup to render correct data. Check in console if Template.template_name.lookup("data_helper")() returns the correct data.
I recently had to solve this exact (or similar) problem of compiling templates client side. You need to make sure the order of things is like this:
Compiled template is present on client
Template data is present (verify with Template.template_name.lookup("data_name")() )
Render the template on page now
To compile the template, as #apendua have suggested, use (this is how I use it and it works for me)
Template.__define__(name, eval(Spacebars.compile(
newHtml, {
isTemplate: true,
sourceName: 'Template "' + name + '"'
}
)));
After this you need to make sure the data you want to render in template is available before you actually render the template on page. This is what I use for rendering template on page:
UI.DomRange.insert(UI.render(Template.template_name).dom, document.body);
Although my use case for rendering templates client side is somewhat different (my task was to live update the changed template overriding meteor's hot code push), but this worked best among different methods of rendering the template.
You can check my very early stage package which does this here: https://github.com/channikhabra/meteor-live-update/blob/master/js/live-update.js
I am fairly new to real-world programming so my code might be ugly, but may be it'll give you some pointers to solve your problem. (If you find me doing something stupid in there, or see something which is better done some other way, please feel free to drop a comment. That's the only way I get feedback for improvement as I am new and essentially code alone sitting in my dark corner).

Set default language for new files

Newly created files in Atom are always "Plain Text". How can I change this so that new files will automatically be in another language, for example "Shell Script (Bash)"? I want to do this because auto indentation does not work with Plain Text files.
Had this problem as well, there is a plugin called default-language that will do this for you.
Search atom for default-language, install and open its settings. Type the name of the language you want Atom to default to, e.g. Shell Script (if in doubt, copy from the language selection menu) in the Default Language field. Next time you open a script with no extension (or shebang) it'll default to the language you set.
The following code, added to your init.coffee, will do what you're asking:
atom.workspace.observeTextEditors (editor) ->
default_scope = 'source.shell'
original = editor.getGrammar()
# If the editor has "null" grammar (aka unset)
if original? and original is atom.grammars.grammarForScopeName('text.plain.null-grammar')
default_grammar = atom.grammars.grammarForScopeName(default_scope)
if default_grammar? # check if desired grammar is already loaded
editor.setGrammar(default_grammar)
else
# grammar was not loaded yet, so add a callback as grammars load
callback = atom.grammars.onDidAddGrammar (grammar) ->
if grammar.id is default_scope
# once we've loaded the grammar, set it and dispose of the callback
editor.setGrammar(grammar)
callback.dispose()
Things to note:
The init.coffee file is where you can customize Atom without having to write a package
The observeTextEditors method sets a callback that is called upon each TextEditor creation for currently open and future editors
The code above:
Checks the grammar that the editor was created with
If and only if it is the default ("null") grammar, it sets the editor's grammar to the Shell grammar once it's loaded
Disposes of the callback to check for grammar loading once it's done with it
This should solve the TypeError: Cannot call method 'getScore' of undefined that happens for the first file opened in a new window.
To default to a different grammar, just change the default_scope = 'source.shell' line to use the scope of whatever grammar you'd like.
Firstly, CTRL+SHIFT+L is your friend. It's unfortunately not a permanent solution, but nice to know about.
Of course, we'd prefer a more permanent solution. A couple of the other answers are now obsolete due to API changes in Atom. Below is a more up-to-date version. Inspiration initially came from this discussion, but the other answers here seem to follow the same concept as well.
Place this in your init.coffee file (File -> Open Your Init Script):
extname = require("path").extname
fileTypes =
".wxs": "text.xml"
".wxi": "text.xml"
".wixobj": "text.xml"
nullGrammar = atom.grammars.selectGrammar("text.plain.null-grammar")
atom.workspace.observeTextEditors (editor) ->
grammar = atom.grammars.selectGrammar(fileTypes[extname(editor.getPath())])
editor.setGrammar grammar if editor.getGrammar() is nullGrammar and grammar isnt nullGrammar
Basically, you define have an array of file types, and the grammars (AKA syntax highlighting) that you want to associate them with. Find each editor, find out if it has a selected grammar already, and if not, attempt to give it one if we find one.
The one issue I've had with this is that the syntax highlighting only works if you open files after you've already launched Atom; if you open a file that results in Atom launching (say by double clicking on it's icon in your favourite OS), syntax highlighting won't for that file until you re-open it.
You need to create a mapping in your config.cson file.
"*":
core:
customFileTypes:
"source.shell": [
"sh"
"shell"
]
For mapping .sh and .shell files to shell script syntax.
Have a look at this bit of code: (you can can then change 'text.html.basic' to whichever syntax you require)
editor = atom.workspace.getActiveTextEditor()
cursor = editor.getLastCursor()
valueAtCursor = atom.config.get(cursor.getScopeDescriptor(), 'my-package.my-setting')
valueForLanguage = atom.config.get(editor.getRootScopeDescriptor('text.html.basic'), 'my-package.my-setting')
For reference please see: Scope Descriptors # https://atom.io/docs/latest/advanced/scopes-and-scope-descriptors

Add a timestamp and info to a saved CSS/HTML file

Looking for a way to add a custom timestamp(and maybe some extra info) inside a CSS/HTML file everytime you save the file. Is there an extention for brackets, sublime or dreamweaver that does this, Or perhaps some other way to do this?
Thanks
I think this post will give you a Sublime Text plugin that should do what you ask.
In Brackets, you can configure the snippets extension to insert a timestamp manually, like the answer above for Sublime. Here's how: https://stackoverflow.com/a/18844762/1172352.
Similar to the Sublime answer, it would be a bit trickier to do it automatically every time you save. There's not yet a clean hook in Brackets for pre-save processing. Several extensions get around this by listening for a post-save event and saving quickly a second time. You could probably write a timestamp-auto-inserter extension by borrowing their code for that pattern.
Anything that runs automatically would also need a little extra code to find the old timestamp and replace it -- both the snippets solution here and the Sublime solution above just insert the timestamp wherever the cursor/selection is. A regular expression should do the trick for detection.
You'd also want to screen out other file types. Bringing it all together, it would look something like this for Brackets:
function documentSavedHandler(event, doc) {
// TODO: need a little extra code here to ignore save events triggered
// by ourself, to avoid infinite loop
var langId = doc.getLanguage().getId();
if (langId === "html" || langId === "css") {
var pos = /* use regexp to find old timestamp */;
doc.replaceRange(timestampStr, posStart, posEnd);
CommandManager.execute(Commands.FILE_SAVE);
}
}

Add a timestamp in brackets editor, maybe using snippets?

I would like to be able to insert a current timestamp into a document in brackets using a hotkey, or a menu item or some other menu - for example
Timestamp: '20131009T232028'
would be a good format.
It seems to me that I should be able to do it with the snippets extension, and it even looks to me like that functionality might already be implemented, but not sure how to get the mustache templates in javascript.json to output the correctly formatted date.
Anyone have an example of how to do this?
It doesn't look like that exact format is supported by the Snippets extension, but you can get something like this pretty easily:
timestamp: 9/17/2013 10:09:18 AM
To add this template:
Help > Show Extensions Folder
Navigate to user/jrowny.brackets.snippets/data
Open javascript.json
Add this item:
{
"name": "Timestamp",
"trigger": "t",
"usage": "t",
"description": "Insert timestamp into file",
"template": "timestamp: $${DATETIME}"
}
Restart Brackets
Now you can insert the snippet in any file by typing "t" followed by Ctrl+Alt+V
If you need a very specific date format, you should be able to patch the source code by editing SnippetPresets.js where your extension is installed. (Don't forget to send your improvements back to the original author as a pull request!)

Resources