Sublime Text 3 - jQuery snippet with $ not working - code-snippets

I wrote that little snippet to help my workflow in Sublime Text 3:
<snippet>
<content><![CDATA[
(function ($) {"use strict";$(function () {$1});}(jQuery));
]]></content>
Optional: Tab trigger to activate the snippet
<tabTrigger>self.function</tabTrigger>
<!-- Optional: Scope the tab trigger will be active in -->
<scope>source.js</scope>
<!-- Optional: Description to show in the menu -->
<description>self.trigger.function</description>
</snippet>
The contextual menu display is when I start to type "self" in a javascript file, but when I hit "Enter", nothing is pasted to my file.
Any idea why that is?
Thanks

You need to escape $ if you want that character to appear literally. Or else SublimeText would assume it to be a Variable field. So just do this -
(function (\$) {"use strict";\$(function () {$1});}(jQuery));
Now it'll work. Details are under the content section of the documentation.

Related

Rails - Trix - Add HR - insertAttachment not a function

I am trying to add a horizontal line option to the Trix editor in Rails 6.1.4. The example that I am finding for this (https://codepen.io/javan/pen/oQpevW) works perfectly, as long as it runs in CodePen. When I implement the example I am getting the option on the toolbar, but when I attempt to use it, I get the error message that "insertAttachment" is not a function.
addEventListener("trix-initialize", (event) ->
toolbarElement = event.target.previousSibling
blockTools = toolbarElement.querySelector("[data-trix-button-group=block-tools]")
if !!blockTools
blockTools.insertAdjacentHTML("afterbegin", '<button type="button" class="trix-button" data-trix-action="x-horizontal-rule" title="Horizontal Rule" tabindex="-1">-</button>')
)
addEventListener("trix-action-invoke", (event) ->
if (event.actionName == "x-horizontal-rule")
editor = event.target
attachment = new Trix.Attachment({ content: "<hr>", contentType: "application/vnd.trix.horizontal-rule.html" })
editor.insertAttachment(attachment)
)
As an interesting side-note, the initialize event was always triggered on the edit div, not the toolbar div, so I had to grab the previous sibling of the event target, otherwise the "block-tools" button group was never found. The "trix-action-invoke" event is triggering as it should and I have verified that the target is the correct div.
Because the example is using Trix 1.0.0, I tried with this version as well, but it generated the error message stating "Trix.Attachment is not a constructor".
I read a post for a different issue ("new Trix is not defined" when using Basecamp / Trix Editor) that implied that there could be a problem with Trix not being loaded yet by the time I want to use it, and it suggested to pull the JS from cloudflare directly, but this didn't solve my issue.
Any suggestions on what could be done to get this to work?

Watir Scraping Rails - Set date of input that exists? but is not present

Good morning everybody,
I have been trying to scrape this page: https://www.aftnet.be/MyAFT/Competitions/Tournaments but I have run into some problems.
Collapsed Search Form
Search Form
If you click > Recherche détaillée , a search form appears along with the OK button to run it. The markup of the page is not that great but with the following I manage to run the search with no specific search criterion set:
browser.button(text: 'OK').fire_event "onclick"
However for my current use I would need to be able to specify the date range:
browser.input(id: 'periodStartDate').exists? --> TRUE
browser.input(id: 'periodEndDate').exists? --> TRUE
browser.input(id: 'periodStartDate').present? --> FALSE
browser.input(id: 'periodEndDate').present? --> FALSE
I have tried setting the value of those using browser.input(id: 'periodStartDate').value ='03/06/2021' but to no avail.
I also tried : browser.text_field(id: 'periodStartDate').set('03/06/2021') but that also did not work.
I have come to wonder whether it was because it was not possible to set a value of an element that exists but is not present so I tried to click > Recherche détaillée with Watir to collapse the search form and then have the search fields present. But I also haven't managed to make it work using : browser.link(text: 'Recherche détaillée').click
What I truly do not understand is that:
browser.link(text: 'Recherche détaillée').exists? --> TRUE
browser.link(text: 'Recherche détaillée').present? --> FALSE
Watir basically seems to not see that anchor present when it is visible when opening the page by default.
At this stage I don't know what else to try and that's why I'm here hoping someone can help me!
Thanks in advance!

How to add custom code snippets in VSCode?

Is it possible to add custom code snippets in Visual Studio Code? And if so, how? VSCode is based on Atom, so it should be possible.
Hit > shift + command + p and type snippets
Select Preferences: Configure User Snippets
Choose the language type for which you want to add the custom snippet in the vscode inputbox
vscode has comments to explain on how to add a snippet, as described on :> vsdoc or you can follow the next link with a short guide:
Lets say, we want to open custom snippets for the language GO. Then we can do:
Hit > command + p
Type: go.json + enter And you land on the custom snippet page
Snippets are defined in a JSON format and stored in a per-user (languageId).json file. For example, Markdown snippets go in a markdown.json file.
Using tools:
Snippet Generator extension (recommended)
Online snippet generator
Option 1 - Use the Snippet Generator extension.
It supports code to JSON conversion with optional scope support and space to \t conversion.
Demo:
Option 2 - Another extension is snippet-creator (deprecated).
After installing it, all you have to do is to :
Select the code that you want to make a snippet.
Right-click on it and select "Command Palette"(or Ctrl+Shift+P).
Write "Create Snippet".
Choose the type of files needed to be watched to trigger your snippet shortcut.
Choose a snippet shortcut.
Choose a snippet name.
Option 3 - check this website. you can generate snippets for vs code, sublime text, and atom.
Once snippet being generated on this site. Go to the respective IDE's snippet file and paste the same. For example for a JS snippet in VS code go to File->preference->user snippet then it opens javascript.json file then paste the snippet code from an above site inside this and we are good to go.
As of version 0.10.6 you can add custom snippets. Read the documentation on Creating your Own Snippets.
You can find/create custom snippets by placing the json file in C:\Users\<yourUserName>\AppData\Roaming\Code\User\snippets.
For example, a custom javascript snippets would be in a \snippets\javascript.json
You can also publish you snippets which is a really neat feature as well. John Papa created a nice angular + typescript snippet you can download as an extension in the marketplace.
Here is an example snippet taken for the documentation on a javascript for loop:
"For Loop": {
"prefix": "for",
"body": [
"for (var ${index} = 0; ${index} < ${array}.length; ${index}++) {",
"\tvar ${element} = ${array}[${index}];",
"\t$0",
"}"
],
"description": "For Loop"
},
Where
For Loop is the snippet name
prefix defines a prefix used in the IntelliSense drop down. In this case for.
body is the snippet content.
Possible variables are:
$1, $2 for tab stops
${id} and ${id:label} and ${1:label} for variables
Variables with the same id are connected.
description is the description used in the
IntelliSense drop down
You can check out this video for a quick short tutorial
https://youtu.be/g1ouTcFxQSU
Go to File --> Preferences --> User Snippets. Select your preferred language.
Now type the following code to make a for loop snippet:
"Create for loop":{
"prefix": "for",
"body":[
"for(int i = 0; i < 10; i++)",
"{",
" //code goes here",
"}"
],
"description": "Creates a for loop"
}
You are done.
Type "for" in the editor and use the first prediction.
SHORTCUT
install snippet-creator extension (now deprecated).
Highlight the code that you need to make snippet.
press ctrl+shift+P and type "Create snippet" on the command palette and
press ENTER.
select language for which you want to create snippet(eg:-CPP), then type
snippet name, type snippet shortcut and then type snippet description.
You are now good to go.
Type the snippet shortcut in the editor that you entered in step 4, and select the prediction (if no prediction comes press ctrl+space) that comes first.
Hope this helps :)
Note: goto File->Preferences->User Snippets. Then select the language in which youcreated the snippet. You will find the snippet there.
You can add custom scripts, go to File --> Preferences --> User Snippets. Select your preferred language.
If you choose Javascript you can see default custom script for console.log(' '); like this:
"Print to console": {
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"
},
There's a VSCode Plugin called: snippet-creator (now deprecated).
After installing it , all you have to do is to:
Select the code that you want to make it a snippet.
Right click on it and select "Command Palette"(or Ctrl+Shift+P).
Write "Create Snippet".
Choose type of files needed to be watched to trigger your snippet shortcut.
Choose a snippet shortcut.
Choose a snippet name.
That's All.
Note : if you want to edit your snippets , you will find them in [fileType].json
Example : Ctrl+P , then select "javascript.json"
I tried by adding snippets in javascriptreact.json but it didn't worked for me.
I tried adding snippets into global scope, and it's working like charm.
FILE --> Preferences --> User snippets
here select New Global Snippets File, give name javascriptreact.code-snippets.
For other languages you can name like [your_longuage].code-snippets
This is an undocumented feature as of now but is coming soon. There is a folder you can add them to and they will appear, but it may change (its undocumented for a reason).
Best advice is to add this to the uservoice site and wait til its final. But it is coming.
On MacOS:
Open the VSCode
Code -> Preferences -> User Snippets
Search for "python" (or any language)
Write your snippet like this:
{
"Write pdb": {
"prefix": "pdb",
"body": [
"import pdb; pdb.set_trace()",
"$2"
],
"description": "Write pdb.set_trace() to debug Python scripts"
}
}
Save the file with command + S.
VSCode introduce this in version 0.5, see here.
Snippet syntax follows the TextMate snippet syntax and can write in User Preferences.
If you'd rather not deal with writing your snippets in JSON, check out Snipster. It lets you write snippets as you would write the code itself - not having to wrap each line in quotes, escape characters, add meta information, etc.
It also lets you write once, publish anywhere. So you can use your snippet in VS Code, Atom, and Sublime, plus more editors in the future.
This may not be a real answer (as some have answered above), but if you're interested in creating custom code snippets for other people, you can create extensions using yeoman and npm (which by default comes along with NodeJS) . NOTE: This is only for creating snippets for other's systems. But it also works for you too! Except you need JS code for whole thing.
You can add custom scripts, go to File --> Preferences --> User Snippets. Select your preferred language.
Like mine code is go, I do it as below:
"channel code": {
"prefix": "make_",
"body": [
"${1:variable} := make(chan ${2:type}, ${3:channel_length})",
"$4"
]
}
explanation: $1 will take your tabs & to give hints what are those tabs values, we make it like ${1:some_variable} which could give us hints what are those
I hope, it helps!

Override snippet in Sublime Text

In Sublime Text 2, I'd like to create a snippet for Rails image_tag.
I want it to be a trigger, but it seems that it is already taken by <input>.
I'd like to remove <input> snippet at all. I've looked through most of Sublime packages, but I cannot find it anywhere.
Is there an easy way to find or override the <input> snippet?
First, if you are dead set on using it to trigger the snippet, you will need to edit this file:
~/Library/Application Support/Sublime Text 2/Packages/HTML/HTML.tmLanguage
and remove input from the string
<key>begin</key>
<string>(</?)((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite|code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|label|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|var)\b)</string>
Next, comment out this line
{ "trigger": "input", "contents": "<input>" },
from ~/Library/Application Support/Sublime Text 2/Packages/HTML/HTML.sublime-completions
input should now be free to use as you like in HTML scopes.
Go to Tools -> New Snippet... and the write the following:
<snippet>
<content><![CDATA[
<%= image_tag ${1}, ${2} %>
]]></content>
<tabTrigger>it</tabTrigger>
</snippet>
And finally save the snippet.
This snippet it's working perfectly for me.

Sphinx, reStructuredText show/hide code snippets

I've been documenting a software package using Sphinx and reStructuredText.
Within my documents, there are some long code snippets. I want to be able to have them hidden as default, with a little "Show/Hide" button that would expand them (Example).
Is there a standard way to do that?
You don't need a custom theme. Use the built-in directive container that allows you to add custom css-classes to blocks and override the existsting theme to add some javascript to add the show/hide-functionality.
This is _templates/page.html:
{% extends "!page.html" %}
{% block footer %}
<script type="text/javascript">
$(document).ready(function() {
$(".toggle > *").hide();
$(".toggle .header").show();
$(".toggle .header").click(function() {
$(this).parent().children().not(".header").toggle(400);
$(this).parent().children(".header").toggleClass("open");
})
});
</script>
{% endblock %}
This is _static/custom.css:
.toggle .header {
display: block;
clear: both;
}
.toggle .header:after {
content: " ▶";
}
.toggle .header.open:after {
content: " ▼";
}
This is added to conf.py:
def setup(app):
app.add_css_file('custom.css')
Now you can show/hide a block of code.
.. container:: toggle
.. container:: header
**Show/Hide Code**
.. code-block:: xml
:linenos:
from plone import api
...
I use something very similar for exercises here: https://training.plone.org/5/mastering-plone/about_mastering.html#exercises
You can use the built-in HTML collapsible details tag by wrapping the code in two raw HTML directives
.. raw:: html
<details>
<summary><a>big code</a></summary>
.. code-block:: python
lots_of_code = "this text block"
.. raw:: html
</details>
Produces:
<details>
<summary><a>big code</a></summary>
<pre>lots_of_code = "this text block"</pre>
</details>
I think the easiest way to do this would be to create a custom Sphinx theme in which you tell certain html elements to have this functionality. A little JQuery would go a long way here.
If, however you want to be able to specify this in your reStructuredText markup, you would need to either
get such a thing included in Sphinx itself or
implement it in a Sphinx/docutils extension...and then create a Sphinx theme which knew about this functionality.
This would be a bit more work, but would give you more flexibility.
There is a very simplistic extension providing exactly that feature: https://github.com/scopatz/hiddencode
It works rather well for me.
The cloud sphinx theme has custom directive html-toggle that provides toggleable sections. To quote from their web page:
You can mark sections with .. rst-class:: html-toggle, which will make the section default to being collapsed under html, with a “show section” toggle link to the right of the title.
Here is a link to their test demonstration page.
sphinx-togglebutton
Looks like a new sphinx extension has been made to do just this since this question has been answered.
Run: pip install sphinx-togglebutton
Add to conf.py
extensions = [
...
'sphinx_togglebutton'
...
]
In rst source file:
.. admonition:: Show/Hide
:class: dropdown
hidden message
since none of the above methods seem to work for me, here's how I solved it in the end:
create a file substitutions.rst in your source-directory with the following content:
.. |toggleStart| raw:: html
<details>
<summary><a> the title of the collapse-block </a></summary>
.. |toggleEnd| raw:: html
</details>
<br/>
add the following line at the beginning of every file you want to use add collapsible blocks
..include:: substitutions.rst
now, to make a part of the code collapsible simply use:
|toggleStart|
the text you want to collapse
..code-block:: python
x=1
|toggleEnd|
Another option is the dropdown directive in the sphinx-design extension. From the docs:
Install sphinx-design
pip install sphinx-design
Add the extension to conf.py in the extensions list
extensions = ["sphinx_design"]
Use the dropdown directive in your rst file:
.. dropdown::
Dropdown content

Resources