Top tips (for Sublime Text, Sass, CSS, Terminal and more)
This post is a random collection of tips in no particular order. It’s an extension of the ‘Top Tips’ talk I gave at the Manchester McrFRED event at the beginning of the year. I always meant to write it up as a post and never got around to it.
They are things that made me go ‘A-ha!’ when I found/figured them out (in a knowing sense, not an Alan Partridge sense). May be you know them all – maybe there will be one or two you hadn’t come across. Let’s find out.
Sublime Text
Clipboard history in Sublime Text (ST3 only)
In OS X Yosemite Alfred has been largely ‘Sherlocked’. OS 10.10’s Spotlight now covers much of Alfred’s capabilities although clipboard history is a notable exception. As Sublime Text is where I find a clipboard history most useful I wondered if any plugins provided the functionality – turns out you don’t need a plugin, it’s baked right into Sublime Text 3! Press CMD+Option+v and you’ll see a list of all the copies/cuts you have performed in Sublime Text.
Find and replace only in current project
If you move between Sublime projects it’s easy to inadvertently perform a find and replace on the wrong set of files. For example, suppose project 1 has a path like this Sites/project1
. When you CMD+Shift+F you will get that path in the ‘Where:’ field. Then you switch to another project that has a path of Sites/project2
, when you again press CMD+Shift+F you once again get Sites/project1
in the ‘Where:’ field. If you have the same sort of strings in that second project it’s entirely possible to ruin your day and not even realise you have done it. You can avoid this problem entirely by using <project>
in the ‘Where:’ field and that will automatically switch the context for you. 🙂
Transpose elements
This has to be one of the most underused, undocumented and under-appreciated features of Sublime. Let’s say you have two chunks of text. Could be whole paragraphs, could be two variables. For example, consider this:
.thing {
padding: .5rem .8rem;
}
If the two paddings are in the wrong order just select them both (hold down CMD and select) and press CTRL+t. Just like that – they are switched!
Select parent wrapper
CMD+Shift+K – in HTML with a cursor within an element, this selects the wrapping element
Cut/paste current line
With nothing selected pressing CTRL+X cuts the current line. In working on an HTML file, if cursor is at the beginning of an element, CTRL+V pastes ABOVE the current line.
Do stuff around current line
CMD+L selects the current line, CTRL+CMD+UP/DOWN shifts it up or down. Shift+CMD+Return puts a blank line above (CMD+Return puts a blank line below).
Move to ‘parenthesis’
CTRL+M will move to each parenthesis in CSS (CMD+M will merely irritate you)
Re-indent the whole file with a single key
Sure you can select the whole file, then go Edit > Line > Reindent but we can do better. Add this in your key mapping and adjust to suit (I have it set to F10 here):
{ "keys": ["f10"], "command": "reindent", "args": {"single_line": false}}
sublime.log_input(True)
– press enter and then use your keys.
Use EasyMotion to jump about instead of a mouse
EasyMotion is great for keeping away from the mouse. Highly recommend using it to jump up and down the screen without needing to reach for the mouse.
Select entire rules in CSS (or any paragraph)
If you ever want to select an entire CSS/Sass rule this key binding will do the job: CTRL+R (amend to suit)
You will need to add this to your *.sublime-keymap file (Preferences > Key Bindings User)
[
{ "keys": ["command+shift+r"], "command": "goto_symbol_in_project" },
{ "keys": ["ctrl+r"], "command": "expand_selection_to_paragraph" }
]
That example also includes a specific binding for ‘Goto symbol in project’ – my personal favourite feature of Sublime.
Jump between CSS rules
We can take the prior example up to 11. Want to jump up and down between rules in style sheets? I added this to my key bindings: (source: https://www.sublimetext.com/forum/viewtopic.php?f=2&t=3563)
{"keys": ["alt+up"], "command": "move", "args": {"by": "stops", "empty_line": true, "forward": false}},
{"keys": ["alt+down"], "command": "move", "args": {"by": "stops", "empty_line": true, "forward": true}},
{"keys": ["shift+alt+up"], "command": "move", "args": {"by": "stops", "empty_line": true, "forward": false, "extend": true}},
{"keys": ["shift+alt+down"], "command": "move", "args": {"by": "stops", "empty_line": true, "forward": true, "extend": true}}
This is like a paragraph selector, moving from one blank line to the next – works well for CSS.
You can press Alt/Option+Up/Down to skip up and down over CSS rules – throw a Shift in there and you can select rules as you go.
Stop hyphens separating words
This is helpful if you use dashes in class selectors. Open your Preferences.sublime-settings and add this:
"word_separators": "./\\()\"':,.;<>~!@#$%^&*|+=[]{}`~?"
All I have done is remove -
from the Regex that’s found in the default. Now you can press CMD+D and select the entire selector.
Super charge select word (make it copy at the same time)
As I’d taken the time to amend the word separators so I could easily select an entire CSS selector like this .namespace-Thing_Variant
I thought I may as well super charge the selection facility. I wanted to map CTRL+D so that it selected a word and automatically copied it – rather than having to press CMD+D and then CMD+C. The way to do this is with a Macro. However, I couldn’t understand why my macro and keybinding wasn’t working. As usual, Stack Overflow provided the answer.
You need to make a macro file called ‘select-copy.sublime-macro’ and save it in the Packages/User folder with this content:
[
{
"command": "expand_selection",
"args": {"to": "word"}
},
{
"command": "copy"
}
]
Then add this to your keybindings:
{"keys": ["ctrl+d"], "command": "run_macro_file", "args": {"file": "Packages/User/select-copy.sublime-macro" }}
Now when you press CTRL+D the word/selector is both selected and copied simultaneously.
Cycle through previous edit points
CTRL+- (Minus). Shift+CTRL+- (Minus) takes you forward. I love that!
Regex search and replace
Ensure regex button is selected and then type this in the search field.
\s*console\.log(.*);
That will let you select all console.log files. For example, this will be selected:
console.log('hello');
Or if you have already got some comments, which may be commented already, only select uncommented ones:
(?<!//)(?<!// )console\.log(.*);
The two parts in parenthesis prevent matches of ‘//’ or ‘// ’. With the parts you want found you can then delete them all or manipulate them in some other way. Maybe comment them all out:
Here is the replace part:
/\/\ console.log($1);
The two forward slashes escape the back slashes so we get this:
// console.log('hello');
Here’s another example if you want to find all the mixing you have included but not a certain sort. For example, if I want all mixing apart from my media query generator:
This would be find all words that begin with @include but DON’T include MQ
^(?!.*MQ).*@include.*$
Need to ‘fix’ spaced code copied from somewhere and need it tabbed?
Sometimes, the Edit > Lines > Re-indent thing doesn’t work for me. But it’s still possible to get the job done. Open ‘Find and Replace’, switch on Regex mode and enter the number of spaces in the Find field. In the replace field enter \t
.
Text pedantry
If you are a pedant with your source files you can tidy up others mistakes. For example, in Sass/CSS:
:([a-zA-z0-9#])
will match this: property:value;
You can then replace with this:
: $1
And you will get this:
property: value;
Ah!!!! Sanity returns (source: http://www.bearpanther.com/2013/09/12/sublime-text-search-and-replace-with-regular-expressions/)
Fix double return issues
Find two new lines in CSS (source: http://stackoverflow.com/questions/4475042/replacing-multiple-blank-lines-with-one-blank-line-using-regex-search-and-replac):
\n\s*\n\s*
And then replace them with one:
\n\n
Pro tip for building Regex
If your Regex-fu is weak, here’s a great (and relatively simple way) to build regular expressions: http://www.regexr.com/
Amend CSS lint results
Despite using a pre-processor, I like to regularly check the CSS being output. CSS Lint is a big help here but I disagree with some of its tests. Thankfully it’s highly configurable:
From https://gist.github.com/benfrain/6052505
{
// CSSLint rules you wish to define as errors. Must be an array. Leave blank to include all default rules.
"errors": [],
// CSSLint rules you wish to define as warnings. Must be an array. Leave blank to include all default rules.
"warnings": [],
// CSSLint rules you wish to ignore. Must be an array. Leave blank to include all default rules.
"ignore": ["floats","universal-selector","box-model","unqualified-attributes"]
}
General Sass/CSS:
Remove default spinners in WebKit (and soon in Firefox) input boxes
It’s possible to remove the default ‘spinners’ in number based inputs. Consider this:
<input type="number" min="0" max="10"></input>
For WebKit browsers you can do:
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
}
In Firefox too:
input[type="number"] {
-moz-appearance:textfield;
}
Together in Sass:
input[type="number"] {
&::-webkit-inner-spin-button {
-webkit-appearance: none;
}
-moz-appearance: textfield;
}
Make your own tint and shade functions for Sass
If you’ve ditched Compass or Bourbon you might still want the tint and shade colour manipulations. Make your own:
// Add percentage of white to a color
@function tint($color, $percent){
@return mix(white, $color, $percent);
}
// Add percentage of black to a color
@function shade($color, $percent){
@return mix(black, $color, $percent);
}
Make reminder notes in Sass
When you’re refactoring and placing styles in other partials, it’s common to hit code and think – WTF? Rather than chase it down there and then, just make a note to yourself:
@warn "Ben, WTF is this section doing? Do we still need it?"
The @warn
will print out the string on compile as a constant reminder of your shortcomings.
Sibling (adjacent and general) in Sass:
I don’t know why but getting adjacent/general sibling selectors written in the nested Sass syntax always confused me. Here’s how to do it:
In this instance, s2
it it is the same level as s1
(general sibling):
.s2 {
.s1 ~ & {
background-color: hotpink;
}
}
If S2 directly follows S1 (adjacent sibling):
.s2 {
.s1 + & {
background-color: hotpink;
}
}
Ditch unneeded dependencies
If you use Grunt and Sass, ditch Compass and Bourbon if you can. It will speed compile significantly.
Simple UI vertical centring
This is a popular and well known technique. On the off chance you haven’t seen it:
.c1 {
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
Useful when the height of the element isn’t known. Support is great too: Everything but IE8 (prefixes needed)
Fix fixed positioning on Android 2.2 and 2.3
Need to fix position something on Android 2.2 or 2.3? Add -webkit-backface-visibility: hidden; and it (generally) acts as you would expect. More here: http://benfrain.com/easy-css-fix-fixed-positioning-android–2–2–2–3/
Nth-child shenanigans
Nth-child selectors afford great power. Let’s take a look:
Ranges
You can select ranges with NTH child. For example:
div:nth-child(n+2):nth-child(-n+4) {}
Filter ranges
You can further filter based on even
or odd
:
div:nth-child(n+2):nth-child(-n+4):nth-child(even) {}
Filter elements
Or go nuts and use different elements to further delineate scope:
div:nth-child(n+2):nth-child(-n+4):nth-child(even):nth-of-type(3) {}
Filter with negation
Or add some negation in there:
div:nth-child(n+2):not(:nth-child(even)) {}
Filter with general sibling and nth-last-child
I was stuck trying to select only the last row of three items when all the items were in a single wrapper. I’d given up hope and sent out a Tweet in desperation:
I think this is impossible using just CSS. I'd love to be proved wrong though: http://t.co/1BVCrikP9o
Help me Obi-Wan …— Ben Frain (@benfrain) October 3, 2014
Within minutes, the Sass nutter, Hugo Giraudel had responded:
https://twitter.com/HugoGiraudel/status/518055528829030400
I can’t remember the origin of this technique. It think I saw Lea Verou talk about it (but I can’t quite locate the source – feel free to correct me if you know). Anyway, it’s genius. Here’s my annotated code to explain how it works:
.WrappingElement {
// First get me every 3rd item then only affected last three items
&:nth-child(3n+1):nth-last-child(-n+3),
// Now get me every one after that same collection too.
&:nth-child(3n+1):nth-last-child(-n+3) ~ .Elements {
/* Styles */
}
}
You can obviously amend the numbers to any situation, switch it up in Media Queries, ‘whatevs’ as the kids say.
Nth-range written in nested Sass syntax
With Sass you can also nest one within another if it helps you. I actually prefer these type of selections on one line but you do what suits you —I’m not your father (I’m not am I? Pretty sure that would be impossible):
&:nth-child(n+2) {
&:nth-child(-n+4) {
width: 19.8734177%;
}
}
HTML5 Video Controls
With WebKit you can style all the shadow DOM elements of the native video player:
video::-webkit-media-controls-fullscreen-button {}
video::-webkit-media-controls-play-button {}
video::-webkit-media-controls-timeline {}
video::-webkit-media-controls-current-time-display{}
video::-webkit-media-controls-time-remaining-display {}
video::-webkit-media-controls-time-remaining-display {}
video::-webkit-media-controls-mute-button {}
video::-webkit-media-controls-toggle-closed-captions-button {}
video::-webkit-media-controls-volume-slider {}
Terminal:
Limit searches
If you use Oh My ZSH you can limit searches back through commands. For example, search previous Git commands like this:
git
(then press the up arrow to previous Git commands)
or
grunt
(then press up to search prior Gulp commands)
Terminal has tabs
In the words of Michael Caine, “Not a lot of people know that”. CMD+T will open a new one.
Place your cursor where you want
Alt+Click on a line where you want the cursor and then start typing.
Clear the screen
CTRL+L – think I got that one from Dennis Gaebel
Make Grunt squeal like a piggy
This is childish but I like using grunt-play Grunt to tell me when it has finished running (arguably not a great choice in a shared work environment):
Gruntfile.js:
play: {
fanfare: {
file: 'source/monster_grunt_pig_.mp3'
}
},
grunt.loadNpmTasks('grunt-play');
Use Node Sass
If you use Grunt/Gulp and Sass make the switch to Node-sass via grunt-sass/gulp-sass – it’s like fast dude. More: http://benfrain.com/lightning-fast-sass-compiling-with-libsass-node-sass-and-grunt-sass/
Clean out your node-modules
Every once in a while your node-modules can get in a muddle. If you need to nuke ’em you can run:
[sudo] `npm prune --production`
Then run [sudo] npm install
to rebuild.
Use Autoprefixer for more accurate prefixing
Use the Grunt Autoprefixer plugin. If you use Sass through Ruby, you will find it far faster than Compass and Bourbon for prefixes and also means your authoring stylesheets can be free of prefixing bloat. Furthermore it’s also incredibly accurate. Don’t have Grunt? There are Autoprefixer versions for Sublime Text, Atom, Brackets and Visual Studio: https://github.com/postcss/autoprefixer
Image Editors
Export SVG from Fireworks
Fireworks can export to SVG with the help of an extension – not perfect but a big help: http://fireworks.abeall.com/extensions/commands/#Export
Accurate colour selection from Fireworks CS6
This is only for users stuck on Fireworks CS6 – there is a weird bug that prevents the correct colour being picked. To get the correct colour value in Fireworks, when the colour palette opens, click the rectangular colour window to the left of the HEX/RGB values and the values will update to the correct value. You can now click the ‘copy/paste’ button to store the correct value on your clipboard.
Clean SVGs from Illustrator
If you are exporting SVGs from Illustrator, make sure you go in to the file after and delete the nonsense or use a tool like SVGO to clean up the unneeded attributes. Also, if making complex SVG shapes, remove points that are unseen by the user – they just add mathematical complexity to the shape which equates to file size.
HTML
Use a
tags around anything
Wrap <a>
tags around whatever you want. HTML5 doesn’t give a hoot.
Slow annoying app links
Making an app and want an annoying link to it on iOS devices:
<meta name="apple-itunes-app" content="app-id=XXXXXXXXX">
Or remove the browser Chrome in iOS (if saved to desktop):
<meta name="apple-mobile-web-app-capable" content="yes"/>
Start IDs and classes with numbers
You can start HTML5 IDs and Classes with numbers if you want. Just be sure to select them in CSS as attributes or unicode.
For example:
[class="2013"] {
/* stuff */
}
Lean on the DOM but bend it to your will when needed
It makes sense to lean on the natural order of things when it comes to elements but if you are working on a very complex DOM, and need to shave off bytes, you can lighten the load by making a b
or i
tag a block level element by default and use that instead.
Dev Tools
I’m talking Chrome here but most of the Dev Tools have equivalent functionality.
Move nodes
In Chrome Dev Tools you can drag nodes around. Really handy for those ‘I wonder if’ moments.
Emulate/troublshoot mobile browsers
You can also emulate mobile devices in Chrome and other dev tools now. But if you do a lot of mobile browser testing, go a stage further and install the Android SDK and Virtual Device Manager and the iOS Simulator (part of xCode). It’s a good fallback option if you don’t have a plethora of devices to look at.
Extra headers in Network panel
The networks panel has a number of optional headers. I always like to enable content-encoding for a quick way of checking which assets on a site are being delivered Gzipped. Just right-click on the headers section and tick the options you want to seat.
Easily delete local and session storage (amongst others)
The resources tab has sections for local and session storage so if you can quickly delete those items without emptying the whole cache.
Firefox Dev Tools are excellent (again)
I’m a fan of the Firefox Dev Tools. It’s just a shame they lack the parity that Chrome enjoys with so many mobile platforms. There is even Vim key bindings in the Firefox Dev Tools for those that way inclined: https://developer.mozilla.org/en-US/docs/Tools/Keyboard_shortcuts
Git – checkout the contents of a repo straight into a folder
A minor frustration for me with Git was whenever I cloned a repository with git clone repo
, it always ended up in an extra folder. Well, Matt Mitchell pointed out to me that is doesn’t have to be this way. For example, if you want to check the contents of a repository out into the folder you are in, you can just do this: git clone repo .
(note the full stop/period at the end). You could also specify a path if you like: git clone repo path/to/folder
.
Conclusion
Hope there were a couple in there that were of use, feel free to comment with your own top tip (I do LOVE a top tip).
Thanks for the tips.
You briefly mentioned CMD + D for sublime, but I use this a lot. E.g. as a quick search and replace or to remove all console.log() statements I put the cursor on one, repeatedly hit CMD + D until they are all selected, then CMD + L to select all the lines, then Delete.
I couldn’t get your CTRL + – (Minus) to work in sublime. Nothing happens, which is a shame as that sounds dead handy.