How do you use a replace command in a Sublime Text 2 snippet? - sublimetext2

I have defined a snippet in Sublime Text 2 as follows:
<snippet>
<content><![CDATA[
<cfqueryparam cfsqltype="cf_sql_${1:integer}" value="$SELECTION">
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<!-- <tabTrigger>hello</tabTrigger> -->
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<!-- <scope>source.python</scope> -->
</snippet>
This works correctly to create a cfQueryParam tag around the selected text, and highlights the part of the cfSqlType that I may need to change for different data types.
However, when using this for strings I need to first click on each side of the value, delete the single quotes, then select the value and hit my keybind for the snippet. This requires two mouse clicks, a double-click, and three keypresses, in addition to more precise mouse aiming. With integers I require only a double click and one keypress. As I have several thousand files to go through doing these replaces, this will make the difference of many hours of work.
Is it possible to put something in the snippet that will cause it to remove a particular character, in this case single quotes? I assume some sort of replace is possible, but I cannot find anything in the docs.

The official docs are kind of sparse, but the community-developed unofficial documentation is much more complete. Boost PCRE-style regexes are supported in snippets, see here for information. I'll leave it up to you to develop the regex for removing the quotes :)
Alternatively, there are a couple of plugins that could help you: Expand Selection to Quotes and Unquote. Each time you run the Expand Selection to Quotes command, it expands the selection to the next set of quotes:
Start with this:
run command once to select string inside quotes:
run command again to select quotes:
then run Unquote command to delete quotes, leaving selection:
I'd suggest creating a macro that runs expand_selection_to_quote twice, unquote once, and then your snippet. Bind this to a different key binding than your original snippet, so you can use the snippet just for individual words, and the macro for strings.
Good luck!

Related

Simple macros for HTML

My html file contains in many places the code
It is too short and it doesn't really make sense to replace it with a code like
<span class="three-spaces"></span>
I would like to replace it with something like
##TS##
or
%%TS%%
and the file should start with something like:
SET TS = " "
Is there any way to write the HTML this way? I am not looking for compiling a source file into a HTML. I am looking for a solution that allows directly writing macros into HTML files.
Later edit: I'm coming with another example:
I also need to transform
lnk(http://www.example.com)
into
<a target="_blank" href="http://www.example.com">http://www.example.com</a>
Instead of telling him WHY he should not do something, how about telling him HOW he could do it? Maybe his example is not an appropriate need for it, but there's other situations where being able to create a macro would be nice.
For example... I have an HTML page that I'm working on that deals with unit conversions and quite often, I'm having to type things like "cm/in" as "cm/in" or for volumes "cu-cm/cu-in" as "cm3/in3". It would be really nice from a typing and readability standpoint if I could create macros that were just typed as "%%cm-per-in%%, %%cc-per-cu-in%% or something like that.
So, the line in the 'sed' file might look like this:
s/%%cc-per-cu-in%%/<sup>cm<sup>3<\/sup><\/sup>\/<sub>in<sup>3<\/sup><\/sub>/g
Since the "/" is a field separator for the substitute command, you need to explicitly quote it with the backslash character ("\") within the replacement portion of the substitute command.
The way that I have handled things like this in the past was to either write my own preprocessor to make the changes or if the "sed" utility was available, I would use it. So for this sort of thing, I would basically have a "pre-HTML" file that I edited and after running it through "sed" or the preprocessor, it would generate an HTML file that I could copy to the web server.
Now, you could create a javascript function that would do the text substitution for you, but in my opinion, it is not as nice looking as an actual preprocessor macro substitution. For example, to do what I was doing in the sed script, I would need to create a function that would take as a parameter the short form "nickname" for the longer HTML that would be generated. For example:
function S( x )
{
if (x == "cc-per-cu-in") {
document.write("<sup>cm<sup>3</sup></sup>/<sub>in<sup>3</sup></sub>");
} else if (x == "cm-per-in") {
document.write("<sup>cm</sup>/<sub>in</sub>");
} else {
document.write("<B>***MACRO-ERROR***</B>");
}
}
And then use it like this:
This is a test of cc-per-cu-in <SCRIPT>S("cc-per-cu-in");</SCRIPT> and
cm-per-in <SCRIPT>S("cm-per-in");</SCRIPT> as an alternative to sed.
This is a test of an error <SCRIPT>S("cc-per-in");</SCRIPT> for a
missing macro substitution.
This generates the following:
This is a test of cc-per-cu-in cm3/in3
and cm-per-in cm/in as an alternative to sed. This is a test of an error MACRO-ERROR for a missing macro substitution.
Yeah, it works, but it is not as readable as if you used a 'sed' substitution.
So, decide for yourself... Which is more readable...
This...
This is a test of cc-per-cu-in <SCRIPT>S("cc-per-cu-in");</SCRIPT> and
cm-per-in <SCRIPT>S("cm-per-in");</SCRIPT> as an alternative to sed.
Or this...
This is a test of cc-per-cu-in %%cc-per-cu-in%% and
cm-per-in %%cm-per-in% as an alternative to sed.
Personally, I think the second example is more readable and worth the extra trouble to have pre-HTML files that get run through sed to generate the actual HTML files... But, as the saying goes, "Your mileage may vary"...
EDITED: One more thing that I forgot about in the initial post that I find useful when using a pre-processor for the HTML files -- Timestamping the file... Often I'll have a small timestamp placed on a page that says the last time it was modified. Instead of manually editing the timestamp each time, I can have a macro (such as "%%DATE%%", "%%TIME%%", "%%DATETIME%%") that gets converted to my preferred date/time format and put in the file.
Since my background is in 'C' and UNIX, if I can't find a way to do something in HTML, I'll often just use one of the command line tools under UNIX or write a small 'C' program to do it. My HTML editing is always in 'vi' (or 'vim' on the PC) and I find that I am often creating tables for alignment of various portions of the HTML page. I got tired of typing all the TABLE, TR, and TD tags, so I created a simple 'C' program called 'table' that I can execute via the '!}' command in 'vi', similar to how you execute the 'fmt' command in 'vi'. It takes as parameters the number of rows & columns to create, whether the column cells are to be split across two lines, how many spaces to indent the tags, and the column widths and generates an appropriately indented TABLE tag structure. Just a simple utility, but saves on the typing.
Instead of typing this:
<TABLE>
<TR>
<TD width=200>
</TD>
<TD width=300>
</TD>
</TR>
<TR>
<TD>
</TD>
<TD>
</TD>
</TR>
<TR>
<TD>
</TD>
<TD>
</TD>
</TR>
</TABLE>
I can type this:
!}table -r 3 -c 2 -split -w 200 300
Now, with respect to the portion of the original question about being able to create a macro to do HTML links, that is also possible using 'sed' as a pre-processor for the HTML files. Let's say that you wanted to change:
%%lnk(www.stackoverflow.com)
to:
www.stackoverflow.com
you could create this line in the sed script file:
s/%%lnk(\(.*\))/<a href="\1">\1<\/a>/g
'sed' uses regular expressions and they are not what you might call 'pretty', but they are powerful if you know what you are doing.
One slight problem with this example is that it requires the macro to be on a single line (i.e. you cannot split the macro across lines) and if you call the macro multiple times in a single line, you get a result that you might not be expecting. Instead of doing the macro substitution multiple times, it assumes the argument to the macro starts with the first '(' of the first macro invocation and ends with the last ')' of the last macro invocation. I'm not a sed regular expression expert, so I haven't figured out how to fix this yet. For the multiple line portion though, a possible fix would be to replace all the LF characters in the file with some other special character that would not normally be used, run sed on that result, and then convert the special characters back to LF characters. Of course, the problem there is that the entire file would be a single line and if you are invoking the macro, it is going to have the results that I described above. I suspect awk would not have that problem, but I have never had a need to learn awk.
Upon further reflection, I think there might be an easier solution to both the multi-line and multiple invocation of a macro on a single line -- the 'm4' macro preprocessor that comes with the 'C' compiler (e.g. gcc). I haven't tested it much to see what the downside might be, but it seems to work well enough for the tests that I have performed. You would define a macro as such in your pre-HTML file:
define(`LNK', `$1')
And yeah, it does use the backwards single quote character to start the text string and the normal single quote character to end the text string.
The only problem that I've found so far is that is that for the macro names, it only allows the characters 'A'-'Z', 'a'-'z', '0'-'9', and '' (underscore). Since I prefer to type '-' instead of '', that is a definite disadvantage to me.
Technically inline JavaScript with a <script> tag could do what you are asking. You could even look into the many templating solutions available via JavaScript libraries.
That would not actually provide any benefit, though. JavaScript changes what is ultimately displayed, not the file itself. Since your use case does not change the display it wouldn't actually be useful.
It would be more efficient to consider why is appearing in the first place and fix that.
This …
My html file contains in many places the code
… is actually what is wrong in your file!
is not meant to use for layout purpose, you should fix that and use CSS instead to layout it correctly.
is meant to stop breaking words at the end of a line that are seperated by a space. For example numbers and their unit: 5 liters can end up with 5 at the end of the line and liters in the next line (Example).
To keep that together you would use 5 liters. That's what you use for and nothing else, especially not for layout purpose.
To still answer your question:
HTML is a markup language not a programming language. That means it is descriptive/static and not functional/dynamic. If you try to generate HTML dynamically you would need to use something like PHP or JavaScript.
Just an observation from a novice. If everyone did as purists suggest (i.e.-the right way), then the web would still be using the same coding conventions it was using 30 years ago. People do things, innovate, and create new ways, then new standards, and deprecate others all the time. Just because someone says "spaces are only for separating words...and nothing else" is silly. For many, many years, when people typed letters, they used one space between words, and two spaces between end punctuation and the next sentence. That changed...yeah, things change. There is absolutely nothing wrong with using spaces and non-breaking spaces in ways which assist layout. It is neither useful nor elegant for someone to use a long span with style over and over and over, rather than simple spaces. You can think it is, and your club of do it right folks might even agree. But...although "right", they are also being rather silly about it. Question: Will a page with 3 non-breaking spaces validate? Interesting.

How to create typing shortcuts in Sublime Text 2?

I am back to using Sublime Text 2 after some time and I noticed that I had made shortcuts to type certain expressions faster. For example, in Java, the common System.out.println() is immediately suggested as the first choice after typing pr in the editor since pr was the trigger that I chose for System.out.println(). After typing pr, I press enter and System.out.println() is written on the editor.
I don't remember how I did this or what is the name of the procedure to do this (hence, it is hard to search it online). All I remember was editing some text file in Sublime and adding the shortcut.
Creating snippets or "shortcuts" is easy in Sublime Text.
For your example, you would simply have to do the following:
Go to Tools > New Snippet...
Inside the CDATA brackets, put the code snippet you want to be generated
Uncomment the tabTrigger tag and put "pr" inside it. This is the shortcut you want to use to generate the snippet.
Uncomment the scope tag and put source.java inside it. This will make the this snippet only show up when you're working with Java files.
Save the file to your Packages > User folder and name the file whatever you want. Make sure you end it with a sublime-snippet extension.
In this example, I saved it as println.sublime-snippet. This is what it ended up looking like in the end:
<snippet>
<content><![CDATA[
System.out.println();
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>pr</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<scope>source.java</scope>
</snippet>
You can learn more about customizing your snippets with things like tab stops here.
Take a look in your Java snippets:
Windows:
%APPDATA%/Sublime Text 2/Packages/Java/println.sublime-snippet
OSX:
~/Library/Application Support/Sublime Text 2/Packages/Java/println.sublime-snippet
Linux:
~/.Sublime Text 2/Packages/Java/println.sublime-snippet
And edit the tabTrigger tag as follows (should originally contain pl):
<snippet>
<content><![CDATA[System.out.println($1);$0]]></content>
<tabTrigger>pr</tabTrigger> <!-- Update this to pr-->
<scope>source.java</scope>
<description>println</description> <!-- I changed this to System.out.println -->
</snippet>
Now, typing pr in a Java file will bring up the autocomplete list. The first entry will read 'pr', and to the right of it, whatever you have between the <description> tags.
Pressing Tab or Return after typing "pr" will fill in System.out.println() and leave your cursor between the brackets.
You may also need to edit the "private" snippet, located in the same directory, to change it's trigger to something other than "pr" (pri, etc).

How to stop PyCharm from autocompleting HTML and Django template tags?

When I'm writing Django templates with PyCharm it automatically closes them; this is reasonably helpful when I'm starting a new tag, but if my intention is to place some already existing content inside a different tag it tends to get a bit annoying, as I then have to delete or move the closing tag, e.g. I'll end up with something like this.
<div></div>Already existing text.
Is there any way of disabling this feature?
You can modify the smart keys functionality of the Editor by doing the following:
Go to Settings --> Editor --> General --> Smart Keys
Uncheck "insert closing tag on tag completion" under the "XML/HTML" section.
Apprently, there is a way to achieve this already in PyCharm.
Select the desired code fragment.
Do one of the following:
On the main menu, choose Code | Surround With
Press Ctrl+Alt+T
A pop-up window displays the list of enclosing statements according to the context.
Select the desired surround statement from the list. To do that, use the mouse cursor, up and down arrow keys, or a shortcut key displayed next to each element of the list.
Here is the relevant documentation for Wrapping
Here is the documentation for unwrapping
EDIT:
The Shortcut for Tags is Ctrl+Alt+J
Here is the relevant documentation for tags

Sublime Text 3 Snippets

I am creating some snippets in ST3 that are essentially divs with special classes. After using the tab trigger to initiate the snippet the cursor is always at the end of the snippet, can I specify where the cursor is after the snippet is initiated?
Use $0 to indicate the exit point, and $1, $2, etc. to indicate different tab stops within the snippet, and the form ${1:foo} to indicate a default value. This way you can customize your code when you run the snippet, for example being able to input different class names or ids. For example, the following code creates a new div when you type newdiv, allowing you to customize the id and class by hitting Tab to move from field to field. When those are completed, the cursor ends up between the opening and closing tag:
<snippet>
<content><![CDATA[
<div id="${1:foo}" class="${2:bar}">$0</div>
]]></content>
<tabTrigger>newdiv</tabTrigger>
<scope>text.html</scope>
</snippet>
Please see the snippets page at the unofficial docs, as well as the snippets reference for more information, including how to work with selections and using regexes on content or input. There are also certain environment variables available regarding the current document and working environment.

Ordering the items in the command palette overlay in Sublime Text 2

With the help from fraxel on this question: Assigning multiple snippets to a single key binding I was able to create a handy popup menu to organize all my snippets in the way Textmate works.
Is it possible to tell ST2 what order I want them to appear in in the overlay command palette? Right now they are seemingly random and I'd love to be able to set some order to them.
I can't tell how ST2 orders them.
More:
All of my snippets have file names that indicate their language:
e.g.
PHP_mySQLLoop.sublime-snippet
PHP_mySQLi.sublime-snippet
HTML_basePage.sublime-snippet
jQuery_ajax.sublime-snippet
The <description> I use is also standard:
JMR PHP, mySQL Loop
JMR PHP, mySQLi
JMR HTML, Base page
JMR jQuery, $ajax
Changing PHP_mySQLi.sublime-snippet to PHP_1_mySQLi.sublime-snippet or 1_PHP_mySQLi.sublime-snippet had no effect nor did changing it's description.
I do not have the <scope> set for any snippet at his point...maybe I should...?
(This is on OS X, not sure if that has anything to do with this...)