Sublime Productivity Code Like a Pro with Today’s Premier Text Editor Josh Earl This book is for sale at http://leanpub.com/sublime-productivity This version was published on 2014-11-22
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. ©2012 - 2014 Josh Earl
Tweet This Book! Please help Josh Earl by spreading the word about this book on Twitter! The suggested hashtag for this book is #sublimetext. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: https://twitter.com/search?q=#sublimetext
Contents Contact Me . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
i
Free Weekly Productivity Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ii
About this Book . . . . . . . . . . . . . . . . . . . . . . Which version of Sublime Text does this book cover? . The short answer . . . . . . . . . . . . . . . . . . That awkward phase . . . . . . . . . . . . . . . . Conventions . . . . . . . . . . . . . . . . . . . . . . . Why are you telling me to click stuff in menus? . Hey, where are the keyboard shortcuts? . . . . . Formatting notes . . . . . . . . . . . . . . . . . .
. . . . . . . .
iii iii iii iii iii iii iv iv
Did you get this book for “free”? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
v
I
1
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
Editor Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1. Side Bar . . . . . . . . . . . . . Toggling the Side Bar . . . . . . Previewing Files . . . . . . . . . Opening Folders . . . . . . . . . Toggling the Open Files Section Menus . . . . . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
2 2 2 3 3 3
2. Command Palette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Keyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5 6
3. Minimap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7
4. Sessions . . . . . . . . . . . . . . . . Viewing the Session File . . . . . . . Tweaking Session Preferences . . . . Disabling Hot Exit . . . . . . . . Disabling Remember Open Files
8 9 9 9 9
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . .
CONTENTS
5. Projects . . . . . . . . . . . . . How Projects Work . . . . . . . Creating Projects . . . . . . . . Adding Folders . . . . . . . . . Opening Projects . . . . . . . . Multiple workspaces per project Navigating in Projects . . . . . Editing Project Files . . . . . . . Project-Specific Settings . . . . Including folders . . . . . . Excluding files and folders Overriding settings . . . . Project File Example . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
11 11 12 12 12 13 14 15 15 15 15 16 16
6. Tabs . . . . . . . . . . Opening Tabs . . . . . Closing Tabs . . . . . . Tearing Tabs Off . . . . Reopening Closed Tabs Switching Tabs . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
18 18 18 19 19 19
7. Panes . . . . . . . . . . . . . . . . . . . . . . Layouts vs. groups . . . . . . . . . . . . . . . Layouts . . . . . . . . . . . . . . . . . . . Groups . . . . . . . . . . . . . . . . . . . Managing layouts . . . . . . . . . . . . . . . . Managing groups . . . . . . . . . . . . . . . . Creating groups . . . . . . . . . . . . . . Arranging groups . . . . . . . . . . . . . Closing groups . . . . . . . . . . . . . . . Rearranging tabs . . . . . . . . . . . . . . . . Move to Next Group . . . . . . . . . . . . Move to Previous Group . . . . . . . . . . Move to numbered group . . . . . . . . . Navigating between panes . . . . . . . . . . . Focus Previous Group / Focus Next Group Focus Numbered Group . . . . . . . . . . Panes: Separate or not? . . . . . . . . . . Moving files between panes . . . . . . . . . . Resizing panes . . . . . . . . . . . . . . . . . . Saving and restoring multi-pane configurations Split View of a Single File . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
21 21 21 21 22 22 22 22 23 23 23 24 24 24 24 25 25 25 26 26 26
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
CONTENTS
II Using the Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 8. Editing Text . . . . . . . . . . . . . . . . . . . Paste and Indent . . . . . . . . . . . . . . . . . Paste from History . . . . . . . . . . . . . . . Indent, Unindent, Reindent . . . . . . . . . . . Insert Line Before/Insert Line After . . . . . . Delete to End/Delete to Beginning . . . . . . . Delete Word Forward/Delete Word Backward Soft Undo/Soft Redo . . . . . . . . . . . . . . Transposing Letters and Words . . . . . . . . . Changing Capitalization . . . . . . . . . . . . Joining Lines . . . . . . . . . . . . . . . . . . . Swapping Lines . . . . . . . . . . . . . . . . . Deleting Lines . . . . . . . . . . . . . . . . . . Duplicating Lines . . . . . . . . . . . . . . . . Wrapping Paragraphs . . . . . . . . . . . . . . Commenting and Uncommenting . . . . . . . Sorting and Reordering Lines . . . . . . . . . . Sorting and Reordering Selected Items . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
28 28 29 30 31 31 32 32 33 33 34 35 35 35 36 36 37 38
9. Selecting Text . . . . . . . Multi-Select . . . . . . . . Split Selection into Lines . Quick Add Next . . . . . . Quick Skip Next . . . . . . Column Selection . . . . . Invert Selection . . . . . . Cleaning up CSV data Filter unwanted lines Strip HTML tags . . . Scoped Selection . . . . . . Words . . . . . . . . . Lines . . . . . . . . . Paragraphs . . . . . . Brackets . . . . . . . Indentation Levels . . Tags . . . . . . . . . . Expand to Scope . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
41 41 44 45 46 47 49 49 49 50 51 51 51 52 52 52 52 53
10.Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Goto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Goto Anything . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
56 56 56
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
CONTENTS
Goto Definition . . . . . . . . . . When does indexing run? . . . . . What’s include in the index? . . . Limitations . . . . . . . . . . . . . Goto Line . . . . . . . . . . . . . . Goto Symbol . . . . . . . . . . . . Goto Symbol in Project . . . . . . What symbols are included? Limitations . . . . . . . . . Combining Goto commands . . . . Jump Forward, Jump Back . . . . . . . Limitations . . . . . . . . . . . . . Scrolling . . . . . . . . . . . . . . . . . Code Folding . . . . . . . . . . . . . . Fold . . . . . . . . . . . . . . . . . Fold Level . . . . . . . . . . . . . Fold All . . . . . . . . . . . . . . . Fold Tag Attributes . . . . . . . . Unfold . . . . . . . . . . . . . . . Unfold All . . . . . . . . . . . . . Bookmarks . . . . . . . . . . . . . . . . Reveal in Side Bar . . . . . . . . . . . . Open Containing Folder . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
57 57 58 58 58 59 59 59 60 60 60 61 61 62 62 62 63 63 65 65 65 66 66
11.Find and Replace . . . . . . . . . . . . . . . What are modes and settings? . . . . . . . . Modes . . . . . . . . . . . . . . . . . . . . . Find, Find Next, Find Previous, Find All Shortcuts . . . . . . . . . . . . . Incremental Find . . . . . . . . . . . . . Replace . . . . . . . . . . . . . . . . . . Preserve Case . . . . . . . . . . . Shortcuts . . . . . . . . . . . . . Quick Find . . . . . . . . . . . . . . . . Find in Files . . . . . . . . . . . . . . . Regular Expressions . . . . . . . . . . . . . . Enabling Regular Expressions . . . . . . Using Regular Expressions . . . . . . . Special Scenarios . . . . . . . . . . . . . . . Line Breaks . . . . . . . . . . . . . . . . Shortcuts . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
67 67 68 68 68 69 69 70 70 70 71 72 72 73 74 74 75
12.Autocomplete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
76
CONTENTS
Basic Usage . . . . . . . Suggestions List . . . . . Disabling Auto Complete Wrap Selection with Tag Close Tag . . . . . . . . Shortcuts . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
76 76 77 77 78 78
13.Vintage mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
79
III Automation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 14.Snippets . . . . . . . . . . . . . . . . . Inserting Snippets . . . . . . . . . . . . Viewing Available Snippets . . . . . . . Wrapping Existing Text . . . . . . . . . Creating Custom Snippets . . . . . . . File Format . . . . . . . . . . . . . Scope . . . . . . . . . . . . Content . . . . . . . . . . . Fields . . . . . . . . . . . . Placeholders . . . . . . . . Environment Variables . . . Implementing the Custom Snippet Installing Snippets . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
81 81 81 82 82 83 83 83 84 84 85 85 86
15.Macros . . . . . . . . . . . . . . . . . . . . What are macros? . . . . . . . . . . . . . . . What are they good for? . . . . . . . . . . . Creating macros . . . . . . . . . . . . . . . . Recording macros . . . . . . . . . . . . Saving . . . . . . . . . . . . . . . . . . Playback . . . . . . . . . . . . . . . . . Editing . . . . . . . . . . . . . . . . . . Creating keyboard shortcuts for macros Limitations . . . . . . . . . . . . . . . . . . No find and replace support . . . . . . . One tab, one macro buffer . . . . . . . . Some commands are ignored . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
87 87 87 87 88 89 89 90 92 93 93 93 94
IV Customizing the Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 16.Command Palette Tweaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
96
CONTENTS
Configuration Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
96 96
17.Menu Enhancements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuration Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Customizing the Context Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
98 98 99
18.Key Bindings . . . . . . . . . Configuration files . . . . . . Creating custom key bindings Context-specific key bindings
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
101 101 102 103
19.Managing Plugins . . . . Package Control . . . . . . Installing Packages . . . . View Installed Packages . . Disabling Packages . . . . Troubleshooting Packages
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
106 106 106 106 107 107
20.Writing Plugins . . . . . . . . . . . What is a plugin? . . . . . . . . . . . The Command Logger plugin . . . . . Creating a new plugin . . . . . . . . Installing the plugin . . . . . . . . . . Testing the example plugin . . . . . . Implementing CommandLogger . . . Integrating with the command palette Learning more . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
109 109 109 110 110 111 111 113 114
V
. . . . . .
. . . . . .
Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
21.Essential Plugins . . . . . . . Extend Menus for the Sidebar File Creation . . . . . . . . . . HTML Generation . . . . . . . Blogging . . . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
117 117 117 117 118
22.Cross-Platform Syncing of Settings and Plugins . . . . . . . . . . . . . . . . . . . . . . 119 23.PHP . . . . . . . . . . . . . . . . . Setting up a New Project . . . . . . Fetch Installs Libraries for You Installing Fetch . . . . . . . . . Configuring Fetch . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
121 121 121 122 122
CONTENTS
Using Fetch . . . . . . . . Code Checking . . . . . . . . Setup . . . . . . . . . . . Linting . . . . . . . . . . Configuration . . . Basic Commands . Usage . . . . . . . Code Sniffing . . . . . . . Configuration . . . Usage . . . . . . . Documenting Your Code . . . Setup . . . . . . . . . . . Usage . . . . . . . . . . . Building Documentation Getting Help . . . . . . . . . . Goto Documentation . . Stack Overflow . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
123 125 126 126 126 127 127 128 128 129 130 131 131 136 138 138 139
24.SASS and SCSS . . . . . . . . . . . . . . . . . . . . . . . . . Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . Syntax Highlighting . . . . . . . . . . . . . . . . . . . . . . . Compiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing the Output Directory . . . . . . . . . . . . . . Preventing Compiled Output from Appearing in Project Automating Compilation . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
140 140 141 144 144 145 146
Keyboard Shortcuts Windows . . . . Side Bar . . . OS X . . . . . . . Side Bar . . . Linux . . . . . . . Side Bar . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
147 147 147 147 148 148 149
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
Contact Me Sublime Productivity is a work in progress. If you’d like to let me know about an error (I’m sure there are a few), or if you just have a question or want to offer some constructive feedback, email me at
[email protected].
Free Weekly Productivity Tips Want a weekly dose of Sublime Text tips to improve your productivity and streamline your workflow? Head on over to http://sublimetexttips.com/newsletter¹ and drop your email address in the signup form. ¹http://sublimetexttips.com/newsletter
About this Book Which version of Sublime Text does this book cover? The short answer The final version of this book will assume you’re using Sublime Text 3. But right now we’re in …
That awkward phase I started writing this book shortly before Sublime Text 2 was released, and most of the content you’ll read was written and tested for ST2. As of this draft, ST3 is in public beta, and I’m officially in the process of updating the manuscript to cover the new version. The Sublime team tends to do extended beta cycles to give users and plugin developers plenty of time to play with the new bits. New features appear from time to time, and existing ones are tweaked in subtle ways. So far, ST3 is looking like an incremental upgrade with lots of under-the-hood improvements but relatively few new features. I’m incorporating the additions into the book naturally, and for now, including a note that calls them out as new in ST3. Plugins are where it gets tricky. Plugins are generally written in Python, and in ST3, the Sublime team switched from Python 2.6 to 3.3. Since Python 3.x includes API changes, existing Sublime plugins have to be updated to work with ST3. The required changes aren’t difficult, according to the Sublime team, and more plugins are adding ST3 support every day. I’ll attempt to only cover plugins that have been updated for ST3, but if you find one that doesn’t work, please bear with me.
Conventions Why are you telling me to click stuff in menus? I love keyboard shortcuts, and Sublime has dozens of great ones. but you won’t find many in the front part of the book. Why is that?
About this Book
iv
In earlier versions of the book, I tried to include the keyboard shortcuts along with the step-by-step instructions. It was repetitive and clumsy, because Sublime’s shortcuts differ radically between the Windows and Linux versions and the OS X versions. It clutters the reading experience to include keyboard shortcuts, because they’re different for each operating system. The menus, on the other hand, are more consistent across platforms. The menus are also more discoverable: If you forget a keyboard shortcut, it’s pretty hard to figure out where to find it. But the menus are all there for you to explore. Plus the menus generally include the keyboard shortcuts, so you can often learn the keyboard shortcut if you know where a feature is in the menu. So even though I firmly believe you should learn the keyboard shortcuts for features you use frequently, I decided that I’d use the menu options where they are available. If there’s no way to do something via the menu, I’ll fall back to the Command Palette, and I’ll only specifically list a keyboard shortcut if there’s no other way to accomplish a task. Mainly give menu-driven instructions to make cross-platform instructions more succinct.
Hey, where are the keyboard shortcuts? Instead of including the keyboard shortcuts in the main portion of the book, I’m in the process of compiling a curated list of the most useful keyboard shortcuts, which will be available in the back of the book.
Formatting notes When I’m providing a walkthrough, things you need to click or execute are in bold. Text you should enter is listed in fixed-width font, as are file paths, names and extensions, and code.
Did you get this book for “free”? I don’t make any effort to put copyright protection (DRM) on this book because I know it’s such a pain for you, the reader. I once bought a novel in ebook format only to realize that I had to use proprietary Adobe software just to open it. Curling up on the couch with my 15” ThinkPad isn’t an enjoyable way to read, and I spent the next 20 minutes scouring the torrent sites in search of a DRM-free copy that I could load on my ereader. That’s no way to treat a customer. If you pay for a book, you should be allowed to view it on any device your heart desires. On the other hand, this book is a lot of hard work to write and update. If a friend sent you a “free” copy of this book, or you downloaded a full copy for “free” … Well, that means I’m not getting paid for my effort, which makes me (and my kids) sad. So if that’s you, and if you’ve found that this book has provided value for you, consider buying a copy at http://sublimeproductivity.com². In addition to a warm fuzzy feeling for doing the right thing, you’ll also get updates to the book as I publish them.
²http://sublimeproductivity.com
I Editor Features
1. Side Bar Sublime’s side bar contains a browsable list of files and folders. You can expand nested folders to show their contents, open the files for editing, or preview their contents. While the side bar provides convenient access to open files and folders, it also imposes some surprising limitations in its out-of-the-box configuration. You can’t can’t drag and drop files or folders to rearrange them, and the right-click menus provide only basic file commands.
Toggling the Side Bar When you first install Sublime, the side bar should be enabled by default. You can quickly toggle it off if you’d like to devote more screen real estate to your code and reenable it when you need to browse for another file. To toggle the side bar: • Click View | Side Bar | Show Side Bar or View | Side Bar | Hide Side Bar. Or press Command+K,Command+B on Mac OS X or Ctrl+K,Ctrl+B on Windows and Linux.
Previewing Files Sublime’s preview feature is one of those subtle touches that can make a big difference in your dayto-day work. I frequently find myself hunting through multiple files, looking for a particular piece of code. In most editors, each file I examine opens in a new tab, and before long I have two dozen tabs open. When you single click a file in the Sublime side bar, Sublime displays its contents in the editing window without creating a new tab. You can scroll through the file, or preview other files as needed. To open the file for editing, double click its entry in the side bar, or just start editing it. Either will pop open a new tab for the file. Preview tabs In Sublime Text 3, single-clicking a file opens the preview in a special temporary tab. You can identify this tab by the italicized file name in the tab’s title. The preview tab is reused when you single-click another file. It’s an improvement over the old model where the preview took over the active tab because it allows you to peek at files while still referring to the files you’re actively working on. If you start editing the file, Sublime promotes the preview tab to a regular tab.
3
Side Bar
Opening Folders The Folders section of the side bar shows any folders you’ve opened in Sublime, as well as the files they contain. To add a folder to the side bar: • Drag the folder from your file explorer into the Sublime side bar. Or, on Mac OS X, drag the folder into the Sublime icon on the dock.
You can tell Sublime not to show selected folders or file types in the side bar. This is convenient for hiding files that Sublime can’t edit, such as .png graphics, or for excluding the compiled outputs of platforms such as CoffeeScript or SASS. To customize Sublime’s file exclusions, see the folder_exclude_patterns, file_exclude_patterns and binary_file_patterns settings in the Preferences.sublime-settings file. You can override the defaults in your user-specific settings, and you can also customize them on a per-project level.
Toggling the Open Files Section By default, the side bar is divided into two sections, Folders and Open Files. The Open Files section shows dots on files that have been modified and close icons on unmodified files. You can hide the Open Files section if you’d prefer, since it doesn’t provide much information that you can’t already glean from your list of tabs. To toggle the Open Files section: • Click View | Side Bar | Hide Open Files or View | Side Bar | Show Open Files.
Menus While the Sublime Side Bar is helpful for basic navigation and for visualizing your project’s structure, it offers only a barebones set of commands for working with the files and folders that make up your project. The Side Bar has three different right-click menus, and they’re all pretty bare bones. Right-clicking a file in the Open Files section reveals only a Close option, which closes the file’s tab.
4
Side Bar
In the Folders section, right-clicking on a folder brings up a menu with a few basic options: New File, Rename…, New Folder, Delete Folder and Find in Folder. New File, New Folder and Rename… open an input panel at the bottom of the screen that allows you to enter the desired file or folder name. The Find in Folder option opens a Find panel and populates the folder name into the Where… field. Deleting a folder with open files When you use the Delete Folder command, Sublime doesn’t close tabs for files that were contained in the deleted folder. The tabs remain open as if nothing happened, but you’ll get an error message if you make changes and attempt to save the file.
Right-clicking a file in the Folders section brings up just three options: Rename, Delete File and Open Containing Folder… Rename opens an input panel where you can type the new file name. Selecting the Delete option removes the file and closes any open tabs associated with it. Version Difference! In Sublime Text 2, deleting a file from the Side Bar removes it from the file system but leaves it open in a tab, changes the tab to unsaved. Easy to accidentally restore the file by saving the tab.
The Open Containing Folder command opens your system file manager to the parent folder of the selected file. Rearranging files Since the Side Bar doesn’t allow you to drag and drop files to reorganize them, using Open Containing Folder to and then shuffling files in your file manager is often the best workaround.
2. Command Palette If you’re a keyboard junkie, you’re going to enjoy Sublime’s Command Palette. It allows you to use almost all of the commands available in the menus without fumbling for the mouse or digging through nested menus with the arrow keys. The palette uses a simple search-based user interface. When you open the command palette, a floating command box appears with an alphabetical list of commands below it. Type a partial command name, such as side bar, and Sublime filters the list using its usual fuzzy matching algorithm.
Command palette
Once you spot the command you’re looking for, such as Toggle Side Bar, use the arrow keys to highlight it, then press Enter. One of my favorite uses for the Command Palette is as an aid for learning Sublime’s keyboard shortcuts. Try to develop the habit of using the Command Palette to perform actions when you can’t remember the keyboard shortcut. When you use the palette to perform an action, such as Find in Files, the keyboard shortcut appears to the right of the command’s name. Also, the full listing of the command name clues you in to where it’s located in the menu.
6
Command Palette
Sublime uses a similar command box interface for other commands, including navigating around in a file, opening other files, and switching projects, and the Package Manager plugin uses the same approach to display a list of plugins you can install. Many third party Sublime plugins also put commands in the Command Palette.
Keyboard Shortcuts OS
Command
Shortcut
Mac OS X
Command Palette
Shift+Command+P
Windows
Command Palette
Ctrl+Shift+P
Linux
Command Palette
Ctrl+Shift+P
Fuzzy matching Sublime relies heavily on filterable lists to help you quickly execute commands, open files and navigate to specific bits of code. This filtering approach is backed by a “fuzzy matching” algorithm that lets you quickly narrow the options without entering long search terms. While literal string matching includes only list items that contain the exact characters you entered in the exact order you entered them, fuzzy matching retains all items that contain the characters you entered somewhere in the text being searched—not necessarily in the exact order your entered them. In the Command Palette, you can use fuzzy matching to create your own easy-to-remember shortcuts. For example, when I find a block of JavaScript online that I want to inspect more closely, I’ll frequently copy and paste it into a new tab in Sublime and set the syntax highlighting to the appropriate language. I can do this quickly using fuzzy matching by launching the Command Palette and typing ssjs, which highlights the Set Syntax: JavaScript command. In Sublime Text 3, fuzzy matching even works when you enter characters out of order, so sssj still matches Set Syntax: JavaScript, even though the j and s are transposed.
.
3. Minimap The minimap is a distinctive feature of Sublime. It’s turned on by default and appears on the righthand side of the screen. It shows a zoomed-out view of the file, as if you’d zoomed out to 5 percent or so. The section of the file that’s currently visible on the screen is highlighted with a rectangle. Helps to keep your bearings when you’re working in a long document. Is a useful navigational aid at times. Sometimes you can recognize sections of code by their shape, even at such a small scale. It’s also useful when you’re searching for terms in a document. The matches are highlighted on the minimap as well as in the editing window, so you can get a sense for how often the search term is used and how the usages are distributed throughout the file. Similarly, when spell checking is enabled, the minimap highlights spelling errors in red. The minimap also allows you to perform some limited navigations directly. You can click on a section of the document to jump to it directly. You can also drag the highlighted part that represents the view point up and down to scroll the file. You can hide the minimap if you find it distracting or just want to reclaim the space for your code. To toggle the minimap: • Click View | Hide Minimap or View | Show Minimap.
4. Sessions When you close and reopen Sublime Text 2, you may notice that the editor reopens any files you were editing before previously. Sublime uses a session to keep track of these open tabs and a whole lot more. Sessions make the editing experience in Sublime feel seamless. Closing the editor to install a plugin or (if you’re a Windows user) reboot your machine is a zero penalty task, since you won’t need to reopen files and reposition windows to get back to the setup you had before quitting the app. You also won’t lose in-progress work because of a feature called hot exit. Hot exit stores unsaved changes to open files in the session. Sublime doesn’t prompt you to save unsaved changes when exiting for this reason. They are squirreled away in the session and can be saved next time you open the editor to work on them. One of my favorite features of Sublime is how hot exit turns it into a great scratch pad. For example, if I need to make a quick note during a phone call, I’ll start a new tab in Sublime and capture the information. The tab will stick around until I can transfer the info somewhere more permanent, and I don’t have to worry about forgetting to save it and losing the information when I close Sublime.
The session file may also include: • • • • • •
Open files, folders, projects History of recently opened files and projects History of recent find and replace terms Size and screen position of the Sublime Text 2 window Extra layout panels (screen splits) Cursor and scroll positions within open files
There’s some overlap between what Sublime stores in the global Session.sublime_session file and in the .sublime-workspace files that accompany a Sublime project file. If you’ve been working on something for a while, you may find that you have several files and folders open, and maybe you’ve split up your screen with a couple of custom layouts. You can save your session as a project that you can return to later to restore your tabs, folders and layouts. Just click Project | Save Project As … and put the project file somewhere safe.
9
Sessions
Viewing the Session File
The session information is stored in a file named Session.sublime_session in the ∼/Library/Application Support/Sublime Text 2/Data/Settings directory on Mac OS X or under %USERPROFILE%\AppData\Roaming\Subli Text 2\Settings on Windows. Like Sublime’s other settings, the session file is formatted as a JSON document, so it’s possible to read and edit it manually using another text editor. I wouldn’t recommend this, as it’s pretty easy to make a change that’ll cause errors when Sublime launches. It comes in handy occasionally, though. I recently upgraded my ThinkPad to Windows 8, and I was able to edit the session file to fix some errors that resulted from changing my username to josh instead of jearl.
Tweaking Session Preferences If you frequently use Sublime to open files from the command line, you may get annoyed when Sublime continually restores previously opened files. You can override the hot exit and restore previous file defaults in your user preferences file.
Disabling Hot Exit When hot exit is disabled, Sublime will always ask whether to save or discard any new or modified files when you exit the application. To disable hot exit: 1. Click Sublime Text 2 | Preferences | Settings – User on Mac OS X, or Preferences | Settings – User on Windows or Linux. Or press Command+, on Mac OS X. 2. On a new line inside the curly braces, add "hot_exit": false. 3. Save and close the file.
Disabling Remember Open Files When hot exit is disabled, Sublime will still restore your previous files unless you turn off the remember open files setting. Changing this setting won’t do anything if hot exit is enabled. I want that 15 minutes of my life back …
To disable remember open files:
Sessions
10
1. Click Sublime Text 2 | Preferences | Settings – User on Mac OS X, or Preferences | Settings – User on Windows or Linux. Or press Command+, on Mac OS X. 2. On a new line inside the curly braces, add "remember_open_files": false. 3. Save and close the file.
5. Projects Whether you’re coding a Ruby on Rails site or writing a book, most text editing tasks involve working with more than one file. Juggling related files using Finder or Windows Explorer is a hassle and forces you to constantly switch applications to hunt for files. Sublime’s projects alleviate this pain. Using projects, you can: • Navigate effortlessly to related files. • Maintain multiple workspaces, including separate sets open files and window layouts, reducing tab clutter. • Improve code consistency among collaborators by specifying project-level overrides for settings such as white space. • Automate repetitive tasks that need to be performed on a set of files. I use several projects to organize different segments of my work, including my blog, this book, and several coding projects. Each of these workspaces is customized for the task at hand: The blog project has an open tab for a post that I’m working on, and another with some reference notes, and my blog’s folder is open in the sidebar. One of the coding projects has a couple of open files, an open folder and a horizontal split layout that allows me to move between a JavaScript file and an HTML file. Thanks to Sublime’s projects, I can switch seamlessly between these workspaces without having to shuffle windows and close tabs, and it frees me from having to leave all of my in-progress work open in the same window.
How Projects Work A Sublime project is a JSON-formatted settings file with a sublime-project extension. This file contains several pieces of information, including: • Folders to be included in the project • Custom settings for the project • Custom build commands for the project The project file is intended to be kept in the root directory of your project, and it can be checked into version control and shared among team members. In addition to the sublime-project file, Sublime also creates a sublime-workspace file to manage details specific to your working environment, including which files you have open and any window layouts you’ve created. Don’t edit this file by hand or commit it into version control, or your team members will hunt you down…
12
Projects
Creating Projects To create a new project: 1. 2. 3. 4.
Click Project | Save Project As …. Browse to the root directory where your project files are saved. Enter a name for the project file. Click Save. Mac OS X users have another way to create a new project: Simply drag a folder or group of files into the Sublime icon on the dock.
Adding Folders Once the project file is created, it’s time to add some folders. I usually add the root folder for the site I’m working on. Any child folders inside of the root folder will automatically be included, as well as the files they contain. To add a folder using the menu: 1. Click Project | Add Folder To Project … 2. Browse to the folder you want to add. 3. Click Open. You can also drag-and-drop folders from a file explorer into the sidebar under the Folders header. When you add folders to the project, Sublime automatically updates the .sublime-project file and saves the changes in the background. To quickly clean out all folders in a project: • Click Project | Remove all folders from project.
Opening Projects As a convenience, Sublime automatically reloads the last open project when launched. But chances are you’ll need to bounce around among several projects frequently, and Sublime makes it easy. To open an existing project:
13
Projects
1. Click Project | Open Project…. 2. Browse to the project file. 3. Click Open. Or, if the project is one you’ve opened recently: 1. Click Project | Recent Projects. 2. Select the project from the list of available choices. The most convenient method is the Switch Project in Window feature, which is available from the menu as well as via a keyboard shortcut. To invoke Switch Project in Window: {#switch-project-in-window} 1. Click Project | Switch Project in Window, or press Control+Command+P on Mac OS X or Ctrl+Alt+P on Windows or Linux. An input box appears, along with a list of available projects. 2. Type part of a project name. The input box supports fuzzy matching, so the list is filtered to projects that contain the entered characters. 3. Press Enter when the desired project is highlighted to open the project.
Multiple workspaces per project Working on a major project often means that you need to shift contexts frequently. You might split your time between front end web coding and server-side development. Or perhaps you’re jumping back and forth between the feature you’re currently working on and one that’s just came back with a few issues from QA. And then there’s that emergency bug fix to the feature you worked on last sprint … Each context shift comes with a small setup cost. There are files to open and close. You might have preferred arrangements of tab groups for different tasks: a three-column view for front end work so you can see HTML, CSS and JavaScript open side by side, two rows for back end work, with your source on top and your unit tests below. You jump between tasks a few times, and before you know it you have 27 unrelated tabs scattered across three tab groups. Sublime’s workspaces are ideal for establishing different contexts within your project. They allow you to create and save multiple arrangements of tab groups and open files per project. You can even have multiple Sublime windows open with separate workspaces to allow you to jump back and forth between contexts quickly. Version Difference! Sublime Text 2 only supports one workspace per project.
14
Projects
Workspaces are JSON files with a .sublime-workspace extension, and they contain everything from your open files and tab groups to your cursor position within those files and your unsaved changes. If you’ve created a project, you already have a primary workspace file—Sublime creates one by default. To create another workspace for the current project, click Project | New Workspace for Project. A new Sublime window opens with a partial copy of your current workspace: Preferences like Side Bar visibility and open folders are carried across, but open tabs are not. If you’re just looking to change a few files without disturbing your current workspace, you can use this new workspace as is and simply close it when you’re ready to return to your original workspace. But if you might want to return to the workspace in the future, click Project | Save Workspace As …. You can also use Save Workspace As to save a workspace from an ad hoc collection of open files without creating a whole project first. Create a dot files workspace Do yourself a favor and make a workspace for that assortment of system configuration files you’re endlessly tweaking.
To switch to a previously saved workspace within the current window, click Project | Open Recent and select the desired workspace, or use the Switch Project in Window command, which opens a filterable list of recent projects and workspaces for you to choose from. If the workspace you’re looking for doesn’t appear in either list, click Project | Open Project … to browse to and open the workspace directly. Bug alert! As of Sublime Text 3 build 3047, opening a project or workspace by double-clicking the file in your file manager creates multiple Sublime windows, each with a separate copy of the project. This is a bug, as far as I can tell. You can work around the problem until it’s fixed by using Open Project when you want to use a project or workspace that isn’t in your recent projects list.
Navigating in Projects Projects really shine when used in concert with the Go to anything feature. Since Go to anything searches all open files and folders, and projects give you control over which folders are open, you can effortlessly jump between files without using the mouse. For example, say you’re working in a large JavaScript project, and you’ve added the root directory for your project.
Projects
15
If you’re editing index.html, all you need to do to jump to script/plugin/myplugin.jquery.js is hit Command+P on Mac OS X or Ctrl+P on Windows or Linux. Then type myp and hit Enter. This is especially convenient when your project has a complex folder structure that’s a pain to navigate with the mouse.
Editing Project Files While Sublime makes some changes to project files in the background, to really put projects to work, you’ll need to edit the files by hand. To open the project for editing: • Click Edit project. The project file opens in a new tab.
Project-Specific Settings A well-customized project file can help keep files organized and consistently formatted, even with multiple team members contributing. They can also help automate routine tasks. The project file has three elements: folders, settings, and build_settings.
Including folders The folders element gives you fine-grained control over how Sublime handles folders within the project. When you add a folder to your project, Sublime adds a new element to the folders array. You can add folders by hand as well. Use relative paths here to make the project file work properly regardless of where the root folder is located.
Excluding files and folders You can also specify folders, files and file types to exclude, both for the project as a whole or just specific subfolders. This is particularly useful for avoiding cluttering up your sidebar with auto generated files. For example, if you’re working on a project that uses SASS or CoffeeScript, by default both style.sass and style.css will show up in your sidebar and in the Go to anything menu. Specifying the following file exclude pattern hides compiled CSS and JavaScript files: 1
"file_exclude_patterns": ["*.css", "*.js"]
Alternately, you could exclude the entire compiled styles folder with the following:
Projects
1
16
"folder_exclude_patterns": ["styles"]
Overriding settings Project files can specify overrides for some user preferences with the settings element. On a multimember team, this can prevent irritations like inconsistent use of tabs and spaces for formatting, and, if the team agrees on spaces, how many spaces should constitute one tab width. Here’s how you could enforce the use of two spaces for indenting code: 1 2 3 4 5
"settings": { "translate_tabs_to_spaces": true, "tab_size": 2 }
The build_systems element allows you to specify a list of custom commands that will be available under the Tools | Build System menu. You can map just about any arbitrary command supported by your platform. For example, the following (fairly useless) entry creates a menu item called List that runs the ls command to print a list of the project’s files and folders in the Sublime console: 1 2 3 4 5 6 7
"build_systems": [ { "name": "List", "cmd": ["ls"] } ]
More useful build tasks could include: • Compile .coffee or .scss files prior to deploying a static website. • Copy files to a staging server with sftp or rsync. • Running a custom bash or PowerShell script to remove stray build files.
Project File Example Here’s an example project file from the Sublime Text documentation so you can see how the pieces fit together:
Projects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
{ "folders": [ { "path": "src", "folder_exclude_patterns": ["backup"] }, { "path": "docs", "name": "Documentation", "file_exclude_patterns": ["*.css"] } ], "settings": { "tab_size": 2 }, "build_systems": [ { "name": "List", "cmd": ["ls"] } ] }
17
6. Tabs Opening Tabs Opening a new tab in Sublime creates a empty, unsaved file, just like in many other text editors. Unlike most editors, however, Sublime keeps track of anything you type in a new tab, regardless of whether you save it as a file or not. Sublime will restore your unsaved work even if you close and restart the app. This is a nice fallback in case of a system crash or dumb mistake. It also makes Sublime useful as a scratch pad for note taking. You can fire up a new tab to jot down a phone number and rest assured that it’ll be there until you close the tab deliberately. To open a new tab: • Click File | New File. Or press Command+N on Mac OSX or Ctrl+N on Windows or Linux. Or double click a blank spot in the tab bar. Tabs with unsaved changes show a dot instead of the normal tab close button. It’s subtle enough that I didn’t notice it at first.
Closing Tabs In addition to closing unneeded tabs the old fashioned way, by clicking their close buttons one at a time, you can also close them with a keyboard shortcut or dispatch them en masse. To close the current tab from the keyboard: • Press Command+W on Mac OS X or Ctrl+W on Windows or Linux. To close all tabs but the currently selected tab: 1. Right-click on the tab you’d like to keep open. 2. Select Close others. To close all tabs to the right of the currently selected tab: 1. Right-click on the desired tab. 2. Select Close others to the right.
19
Tabs
Tearing Tabs Off Sublime supports “tearing” tabs off, similar to most web browsers. The torn-off tab creates a new Sublime Text window. It’s a useful trick when you have two files open and want to refer to one while working in the other, especially if you’re rocking a multi-monitor setup. To tear off a tab: • Click and drag the desired tab outside of Sublime’s tab well.
Reopening Closed Tabs If you inadvertently close a tab, you can quickly get it back with the Reopen Closed File command. Sublime keeps track of the last 10 or so files you’ve opened, and repeatedly invoking Reopen Closed File will bring them back to life, one at a time. Sadly, Sublime won’t restore unsaved tabs once you’ve closed them. To invoke Reopen Closed File: • Click File | Open Recent. Or Press Shift+Command+T on Mac OS X or Ctrl+Shift+T on Windows or Linux.
Switching Tabs You can jump between tabs from the keyboard using three different strategies: • Using the number keys to select a tab by position. • Using the arrow keys to move to the next or previous tab based on the tab’s position in the tab bar. • Using the arrow keys to jump between tabs based on the order in which they were last modified. To jump to one of the first 10 tabs by position: • Press Command+1 through Command+0 on Mac OS X or Alt+1 through Alt+0 on Windows or Linux. To jump to the tab to the left or right of the current tab:
20
Tabs
• Click Goto | Switch File | Next File or Goto | Switch File | Previous File. Or press Option+Command+Right and Option+Command+Left on Mac OS X or Ctrl+PageDown and Ctrl+PageUp on Windows or Linux. To navigate between tabs in the order in which you last viewed them: • Click Goto | Switch File | Next File in Stack or Goto | Switch File | Previous File in Stack. Or press Ctrl+Tab and Ctrl+Shift+Tab.
7. Panes Sometimes it’s handy to keep two or more files visible on screen at the same time. Maybe you’re writing some Backbone.js code and need to see the library’s commented source code as a reference, or maybe you’re hacking an HTML prototype together and find yourself constantly jumping from HTML to CSS and back. You could tear tabs off and create a second Sublime window, but Sublime provides a better solution with panes. Panes allow you to view and edit multiple files in one window in a variety of configurations, including vertical and horizontal splits and various combinations of the two.
Layouts vs. groups Sublime offers two tools for managing multiple panes: layouts and groups.
Layouts Layouts are preconfigured arrangements of panes. You can choose from one, two or three horizontal splits, up to four vertical splits, or a 2-by-2 grid. Using layouts is convenient if one of the supported configurations meets your needs, and it’s the only way to achieve a 2-by-2 grid. Panes created by a layout persist until you change layouts, regardless of whether they contain any tabs.
Groups Groups, on the other hand, are more flexible. There’s no limit to the number of groups you can create. You can also combine horizontal and vertical splits, although as we’ll see, the combinations are somewhat limited. Using groups, you could split your editor window into two columns, then split the right column into two rows. Groups are also more dynamic than layouts. A group’s pane closes when you close the last tab it contains.
22
Panes
Version Difference! The concept of groups is new in Sublime Text 3, and Sublime Text 2 only supports layouts. While layouts are still relevant for Sublime Text 2 users, most ST3 users will likely prefer the additional flexibility that groups offer. The main advantage that layouts still have in Sublime Text 3 is the 2-by-2 grid configuration, which isn’t achievable with groups.
Managing layouts To open a multi-column layout, click View | Layout | Columns: 2, View | Layout | Columns: 3, or View | Layout | Columns: 4. To open a multi-row layout, click View | Layout | Rows: 2 or View | Layout | Rows: 3. To create a two-by-two grid layout ,click View | Layout | Grid: 4. To revert to the default layout, click View | Layout | Single. When you change layouts, the new panes appear to the right or below existing panels, and they don’t have any tabs assigned to them by default. If you switch to a layout with fewer rows or columns, tabs from the panes that disappear are merged into the row above or the column to the left, depending on the type of layout you’re using. Sublime retains the positioning of tabs when you switch from a multi-row layout to a multi-column layout and vice versa. If you go from a two-column layout to a two-row layout, tabs from the rightmost column move to the newly created bottom row.
Managing groups Creating groups To open a new, empty group, click View | Groups | New Group. You can also create a new group and populate it with the file you’re currently editing in one step. Just click View | Groups | Move File to New Group.
Arranging groups The Max Columns setting governs how Sublime arranges groups as you create them. Sublime preferentially creates a new column each time you add a group until you hit the maximum number of columns. Once the maximum number of columns is reached, Sublime starts adding rows to the rightmost column.
23
Panes
To change the the Max Columns setting, click View | Groups and choose the desired number of columns, up to a maximum of five. It’s easy to create a three-pane split, with two columns and two rows on the right. Starting from the default, single-pane layout, set Max Columns to two, then create two new tab groups. If you’d like to split your screen horizontally into two rows, set Max Columns to one. Then add a second tab group. Although it would be handy, it’s not currently possible to add rows to columns on the left side of the screen.
Closing groups The simplest way to get rid of a tab group is to close all of its tabs or move them to another group. The group disappears automatically when you remove the last file. If the current group has a lot of open files, the Close Group command is faster. To close the current tab group, click View | Groups | Close Group. When you close a tab group that has open tabs, the files shift to the previous pane in the pane sequence. Version Difference! The Close Group command isn’t available in Sublime Text 2.
Rearranging tabs The simplest way to move a tab from one pane to another is by dragging its tab and dropping it into desired pane. The Move File commands allow you to accomplish the same task via the menu or keyboard shortcuts.
Move to Next Group The Move to Next Group command shifts the current tab one column to the right or one row down. To use Move to Next Group, click View | Move File to Group | Next. Version Difference! The Move to Next Group command isn’t available in Sublime Text 2.
24
Panes
Move to Previous Group Move to Previous Group nudges the current tab left one column up a row, depending on your screen arrangement. To use Move to Previous Group, click View | Move File to Group | Previous. Version Difference! The Move to Previous Group command isn’t available in Sublime Text 2.
Move to numbered group When you create a multi-pane screen configuration, Sublime assigns numbers to the first nine panes. You can move tabs by referencing these numbers. For example, to move the tab you’re editing to the third pane, click View | Move File to Group | Group 3. Version Difference! Sublime Text 2 only assigned numbers to the first four panes.
Navigating between panes When you’re editing files in several panes simultaneously, you’ll probably need to move from file to file frequently. The Focus Group commands make it simple to jump from pane to pane in these scenarios.
Focus Previous Group / Focus Next Group The Focus Previous Group and Focus Next Group commands allow you to step to the next adjacent pane. These commands are ideal when you’re toggling back and forth between two files. To use step back by one pane, click View | Focus Group | Previous. To step forward to the next pane, click View | Focus Group | Next. In both cases, focus shifts to the last place you edited in the active tab. These commands wrap, so running Focus Next Group when you’re on the last pane will focus the first, and Focus Previous Group will jump to the last pane if you’re editing the first. Version Difference! Focus Previous Group and Focus Next Group are new in Sublime Text 3.
25
Panes
Focus Numbered Group The Focus Previous Group and Focus Next Group commands work well when you have two or three panes open, but what if you’re using a 27” monitor and rocking a three-column layout with four rows in the last column? Cycling through half a dozen panes to get to the one you want gets old in a hurry. Focus Numbered Group allows you to jump directly to a pane with a numeric address. Sublime applies an index to the first nine open panes, numbering columns left to right and then numbering rows top to bottom. Navigating with the Focus Numbered Group command is a matter of picking the right index for the pane you want. Columns are indexed left to right, and rows are numbered top to bottom. The only exception is the 2-by-2 grid layout, in which the top row panes are numbered 1 and 2, from left to right, and the bottom row panels are 3 and 4, also left to right. Version Difference! Sublime Text 2 only assigned numbers to the first four panes.
For example, to jump to the rightmost column of a four-column configuration, click View | Focus Group | Group 4. To switch to the bottom-left pane of a grid view, click View | Focus Group | Group 3.
Panes: Separate or not? Some commands seem to ignore panes, treating all tabs as if they are in the same pane, while others only operate on tabs in the current pane. Jump Back/Jump Forward and Previous File/Next File act as if the panes don’t exist. If you’re editing a file in the right column, Jump Back might switch focus to the left pane. But other commands only work within the current pane. Tab numbers start over in each pane, and Previous File in Stack/Next File in Stack cycle through tabs in the active pane only.
Moving files between panes Once you’re done tweaking your screen configuration, it’s easy to move files around as you work using the Move File to Group commands. When you move a file to another pane, focus shifts to that pane so you can continue editing without missing a beat. To send the current tab to the next adjacent pane, click View | Move File to Group | Next.
26
Panes
To move the tab you’re editing backwards one pane, click View | Move File to Group | Previous. You can also move the active file to a pane by number. To move a file to the rightmost pane in a three-column configuration, for example, click View | Move File to Group | Group 3. Version Difference! The Move File to Group commands are new in Sublime Text 3.
Resizing panes You can resize horizontal and vertical splits to better fit the task at hand. To resize a pane, hover your cursor over the thin separator line until it turns into a double arrow, then drag the pane to the desired size.
Saving and restoring multi-pane configurations Sublime will save and restore your custom pane configurations when you close and restart the program. If you’re working on in a project, any custom layouts you create are stored in the associated sublime-workspace file. When you’re just working on several unrelated files, Sublime will save your layout tweaks in the sublime_session file.
Split View of a Single File While it’s great to keep code files short and concise, sometimes there’s just no getting around that mammoth FAQ page or that epic jQuery plugin file. Naturally the FAQ page has a list of anchor tags that you have to update as you add sections at the bottom, and the jQuery file has 20 local variables declared at the top that you need to refer to constantly. In this situation, the New View into File command will save your scroll wheel—and your sanity. This command opens a copy of the current file in a new tab. Changes made in one tab are reflected instantly in the other tab. To use New View into File, click File | New View into File. When you combine this with a multi-pane layout, you’ll find yourself with less need to scroll and jump around in the document, and you won’t lose your place as often. You can create as many new views as you’d like, and you could even create a grid showing four different sections of the file. Since each view is just a new tab, you can push them to different panes with the Move File to Group command and jump between views with the Focus Group command.
II Using the Editor
8. Editing Text Paste and Indent Pasted code does its best to mess up your carefully formatted file, especially if you’re embedding it into an existing block of code. Typically the leading white space from the copied code is added to the white space from the current code block. For example, here’s some JavaScript I’m working on: 1 2 3 4 5
$(function() { function growBeets() { //TODO implement beet growing algorithm }; });
and in another code file I have some logic that I’m moving into the growBeets function: 1 2 3 4 5 6 7
$(function() { function runSchruteFarm(bulbs) { for (var i = 0; i < bulbs.length; i++) { plant(bulbs[i]); } }; });
But when I position the cursor inside the growBeets function and paste the for loop, disaster ensues: 1 2 3 4 5 6 7
$(function() { function growBeets() { for (var i = 0; i < bulbs.length; i++) { // double the white space!!! plant(bulbs[i]); } }; });
Paste and Indent handles this scenario correctly, calculating the appropriate amount of indentation for first line of the pasted code. To perform a Paste and Indent:
29
Editing Text
1. Copy the desired lines of code to the clipboard. 2. Position the cursor at the correct indentation level. 3. Click Edit | Paste and Indent from the menu. Or press Shift+Command+V on Mac OS X or Ctrl+Shift+V on Windows and Linux.
You can remap the default Paste shortcut to perform a Paste and Indent, which should always do the right thing. Refer to the Key Bindings section for a how-to.
Paste from History Sometimes the C and V keys are just too dang close together. You’ve spent the last couple of minutes digging around for a block of code that you want to reuse, copied it, closed the file, and scrolled back to where you want to paste it into your working file. But instead of hitting the paste shortcut, you fat-finger a copy command. Nerd rage! Paste from History comes to the rescue when you accidentally copy over something you wanted to paste. It’s like a clipboard ring for Sublime, allowing you to retrieve that overwritten code from a list of recently copied items. Version Difference! Goto Symbol in Project was introduced in Sublime Text 3.
To use Paste from History, position your cursor where you want to insert the text, then click Edit | Paste from History. A context menu appears next to your cursor, showing the first few characters from each of the most recent things you’ve copied. Select the desired history item to paste it. You don’t have to do anything extra to include items in your paste history—it automatically stores the last 15 blocks you copied. Sublime doesn’t remove items from the list after you paste them, so you can access them again later. Paste from History only stores text you copy from files open in Sublime, so don’t expect it to rescue that half-finished commit message you copied over. But it also doesn’t include text that you copy in other programs, so it offers an extra margin of safety when you’re grabbing snippets from code files and combining them with a few lines from Stack Overflow. Paste from History isn’t limited to saving you from accidentally copying one too many times. It’s also helpful when you need to copy and paste code from several files, maybe when you’re fleshing out a new file with boilerplate code. Instead of copying individual code blocks, then jumping back to the file you’re building, you can just cruise around, filling up your clipboard history like a shopping cart, then return to your file and paste items where you need them.
30
Editing Text
Conveniently, the history won’t insert duplicate text, so if you’re shopping for snippets and forget whether you’ve copied something, feel free to just copy it again. The paste history is specific to the current Sublime session. If you restart Sublime, the history is reset.
Indent, Unindent, Reindent When I’m shuffling code around, I frequently need to adjust the indentation level. For example, removing an if block might leave a few lines indented one tab width too far. The Indent and Unindent commands move lines in or out by one tab width. The Reindent command attempts to reset the lines relative to the indentation level of the surrounding code. This is useful if you have multiple lines at several different indentation levels. Reindent does seem to get confused by comments, at least in JavaScript, but it’s a good first-pass tool that reduces the amount of manual formatting required on a code block. There’s no keyboard shortcut for Reindent by default, but you can map one yourself if you use it frequently. Refer to the Key Bindings section for a how-to.
To use the Indent command: 1. Position the cursor on the line to be formatted, or select a block of lines. 2. Click Edit | Line | Indent. Or press Command+] on Mac OS X or Ctrl+] on Windows and Linux. To use the Unindent command: 1. Position the cursor on the line to be formatted, or select a block of lines. 2. Click Edit | Line | Unindent. Or press Command+[ on Mac OS X or Ctrl+[ on Windows and Linux. To use the Reindent command: 1. Position the cursor on the line to be formatted, or select a block of lines. 2. Click Edit | Line | Reindent.
Editing Text
31
Insert Line Before/Insert Line After Sometimes it’s necessary to open up space between the line I’m editing and the lines immediately before or after it. For example, I might be writing a line of jQuery code and decide that I should insert a comment above it, or maybe I want to set the line off from the code that follows with a line of white space. Doing this manually involves jumping to the end of the line with End and then pressing Return, or pressing Up and then inserting an extra line. The Insert Line Before and Insert Line After commands make this a one-step operation, inserting a blank line above or below the current line. It’s similar to moving the cursor to the end of the line and pressing Return, but much faster. The cursor jumps to the new line so you can immediately begin typing. Insert Line After will also indent the next line correctly. If, for example, the previous line defines a function, the inserted line will be indented one tab width. To insert a blank line below the current line: • Click Edit | Text | Insert Line Before. Or press Command+Return on Mac OS X or Ctrl+Enter on Windows and Linux. To insert a blank line above the current line: • Click Edit | Text | Insert Line Before. Or press Shift+Command+Return on Mac OS X or Ctrl+Shift+Enter on Windows and Linux.
Delete to End/Delete to Beginning Often it’s necessary to prune the beginning or end of a line, such as when you’re removing part of a chained jQuery statement while keeping the selector, or removing the start or end tags on an HTML element. The usual way to do this is to highlight the text with the mouse or use a combination of the arrow keys Shift and Home or End, but Sublime’s Delete to Beginning and Delete to End commands are a better option. Delete to Beginning deletes all the text and white space preceding the cursor, while Delete to End removes everything that follows the cursor. To use the Delete to Beginning command: • Click Edit | Text | Delete to Beginning. Or press Command+Delete on Mac OS X or Ctrl+K, Ctrl+Backspace on Windows and Linux.
32
Editing Text
To use the Delete to End command: • Click Edit | Text | Delete to End. Or press Ctrl+K on Mac OS X or Ctrl+K, Ctrl+K on Windows and Linux. The Delete to End and Delete Line shortcuts make a nice pair of editing tools, and Sublime recognizes this by making the keyboard shortcuts similar.
Delete Word Forward/Delete Word Backward When you need to surgically remove a few words from the middle of a line, the Delete Word Forward and Delete Word Backward commands are a handy alternative to highlighting text with the mouse or Shift and arrow keys. The Delete Word Forward command deletes from the cursor’s current position to the next space. Delete Word Backward performs the same function in the opposite direction. Both will also delete partial words if the cursor is positioned inside of a word. There are no keyboard shortcuts mapped for these commands on Mac OS X by default, but it’s simple to set them up yourself. Refer to the Key Bindings section for a how-to.
To use the Delete Word Forward command: • Click Edit | Text | Delete Word Forward. Or press Ctrl+Delete on Windows or Linux. To use the Delete Word Backward command: • Click Edit | Text | Delete Word Backward. Or press Ctrl+Backspace on Windows or Linux.
Soft Undo/Soft Redo Undo and redo are extremely useful, but I frequently find that I’ll perform an undo only to realize that the action occurred off screen and I have no idea what, if anything, actually happened. Sublime’s Soft Undo and Soft Redo address this issue by considering cursor movements and text selections as operations that can be reversed. They are rewind and fast forward buttons for your editing session. This ensures that your attention is focused on any text changes that occur.
33
Editing Text
The ability to restore lost selections can be a lifesaver as well. It’s frustrating when an errant click or button press cancels the selection of some text I’ve painstakingly highlighted, maybe a multi-screen block of text, or part of a three-screens wide piece of unwrapped code. In cases like these, executing a Soft Undo will restore the selection. To perform a Soft Undo: • Click the undo menu item under Edit | Undo Selection. (The text of the menu item changes to indicate what will happen when the action is invoked.) Or press Command+U on Mac OS X or Ctrl+U on Windows and Linux. To perform a Soft Redo: • Click the redo menu item under Edit | Undo Selection. (The text of the menu item changes to indicate what will happen when the action is invoked.) Or press Shift+Command+U on Mac OS X or Ctrl+Shift+U on Windows and Linux.
Transposing Letters and Words Typing letters or words out of order usually necessitates a clumsy dance with the Shift and arrow keys, followed by a copy and paste and maybe fixing up the spaces on either side. The Transpose command makes this a painless operation by reversing the position of a pair of letters or words. There’s no keyboard shortcut for Transpose by default on Mac OS X, but it’s easy to set one up. Refer to the Key Bindings section for a how-to.
To use Transpose: 1. Position the cursor between the letters or words you’d like to reverse. 2. Click Edit | Text | Transpose. Or press Ctrl+T on Windows and Linux.
Changing Capitalization For sheer tedium, few tasks can rival deleting words and retyping them to convert ALL CAPS to lowercase. Sublime supports several features for dealing with capitalization chores. The Swap Case option inverts the casing of all selected text, while Title Case capitalizes the first letter of each word. Upper capitalizes all selected letters, while Lower does the opposite. To use the Swap Case command:
34
Editing Text
• Click Edit | Convert Case | Swap Case. To use the Title Case command: • Click Edit | Convert Case | Title Case. To use the Upper command: • Click Edit | Convert Case | Upper. Or press Command+K, Command+U on Mac OS X or Ctrl+K, Ctrl+U on Windows and Linux. To use the Lower command: • Click Edit | Convert Case | Lower. Or press Command+K, Command+L on Mac OS X or Ctrl+K, Ctrl+L on Windows and Linux.
To define keyboard shortcuts for Swap Case or Title Case, refer to the Key Bindings section.
Joining Lines I’ve probably wasted more hours of my life than I care to admit deleting extraneous white spaces when merging two lines of indented code. When I learned how to join lines, I couldn’t believe I’d been pounding Delete unnecessarily. Sublime employs the Join Lines command to join the line below your cursor to the one you’re currently editing. To use the Join Lines command: 1. Position the cursor on the first of the two lines. 2. Click Edit | Line | Join Lines. Or press Command+J on Mac OS X or Ctrl+J on Windows and Linux.
Editing Text
35
Swapping Lines Another common line operation is swapping the position of two lines, or shifting a block of lines up or down in the file. Copy and paste is one option, but if you’ll only be moving the lines a short distance, the Swap Line Up and Swap Line Down commands are a better alternative. To use the Swap Line Up command: 1. Position the cursor on the line to be moved, or highlight one or more lines. 2. Click Edit | Line | Swap Line Up. Or press Ctrl+Command+Up on Mac OS X or Ctrl+Shift+Up on Windows and Linux. To use the Swap Line Down command: 1. Position the cursor on the line to be moved, or highlight one or more lines. 2. Click Edit | Line | Swap Line Down. Or press Ctrl+Command+Down on Mac OS X or Ctrl+Shift+Down on Windows and Linux.
Deleting Lines Deleting an entire line without highlighting it first is simple using the Delete Line command. To use the Delete Line command: 1. Position the cursor on the line to be deleted. 2. Click Edit | Line | Delete Line. Or press Ctrl+Shift+K.
Duplicating Lines Duplicating an entire line or series of lines without copying and pasting is possible with the Duplicate Line command. Duplicate Line inserts a copy of the current line directly below the current line. If multiple lines are highlighted, it performs the same action with the entire block. To use the Duplicate Line command: 1. Position the cursor on the line to be copied, or highlight one or more lines. 2. Click Edit | Line | Duplicate Line. Or press Shift+Command+D on Mac OS X or Ctrl+Shift+D on Windows or Linux.
Editing Text
36
Wrapping Paragraphs I like to keep my lines fairly short, so I have a custom ruler set at column 100. This is great for manually wrapping lines, but sometimes when I’m writing prose, I’ll edit a paragraph and find that my original wrapping is no longer suitable. Sublime makes it painless to fix this with the Wrap Paragraph at Ruler command. To use the Wrap Paragraph at Ruler command: 1. Select a block of text. 2. Click Edit | Wrap | Wrap Paragraph at Ruler. Or press Option+Command+Q on Mac OS X or Alt+Q on Windows or Linux. Sublime also supports wrapping to predefined column widths of 70, 78, 80, 100 and 120 characters. To wrap at a width of 80 characters: 1. Select a block of text. 2. Click Edit | Wrap | Wrap paragraph at 80 characters.
Commenting and Uncommenting Sublime gracefully handles both inline and block comments in a variety of languages with the Toggle Comment and Toggle Block Comment commands. The behavior of these commands differs slightly depending on the language’s support for inline and block comments. CSS and HTML, for example, only support block comments, so the Toggle Comment command will wrap the current line or selected text in block comments, or remove the block comment as appropriate. Toggle Block Comment will insert an empty block comment if nothing is selected, or it will wrap the selected text in a block comment, or remove the block comment if the code is already commented out. JavaScript supports line comments, so Toggle Comment will add or remove line comments, and Toggle Block Comment will use block comments. To use the Toggle Comment command: 1. Position the cursor on the desired line, or select a block of lines. 2. Click Edit | Comment | Toggle Comment. Or press Command+/ on Mac OS X, or Ctrl+/ on Windows or Linux. To use the Toggle Block Comment command: 1. Position the cursor on the desired line, or select a block of lines. 2. Click Edit | Comment | Toggle Block Comment. Or press Option+Command+/ on Mac OS X, or Ctrl+Shift+/ on Windows or Linux.
Editing Text
37
Sorting and Reordering Lines In the past, I’ve occasionally found myself copying lines of text into a spreadsheet program to sort them. Sublime has this covered, though, with several simple sorting algorithms: • • • • •
Sort Lines performs a simple alpha sort. Sort Lines (Case Sensitive) does an alpha sort, starting with capitals. Reverse sorts in reverse alphabetical order, starting with lowercase letters. Shuffle does a pseudo-random sort. Unique removes duplicated lines.
To use the Sort Lines command: 1. Select a block of lines. 2. Click Edit | Sort Lines. Or press F5 on Mac OS X or F9 on Windows or Linux. To use the Sort Lines (Case Sensitive) command: 1. Select a block of lines. 2. Click Edit | Sort Lines (Case Sensitive). Or press Ctrl+F5 on Mac OS X or Ctrl+F9 on Windows or Linux. To use the Reverse command: 1. Select a block of lines. 2. Click Edit | Permute Lines | Reverse. To use the Shuffle command: 1. Select a block of lines. 2. Click Edit | Permute Lines | Shuffle. To use the Unique command: 1. Select a block of lines. 2. Click Edit | Permute Lines | Unique.
38
Editing Text
Sorting and Reordering Selected Items In addition to sorting a solid block of lines, Sublime can perform the same sorting functions on non-sequential lines using the items in the Permute Selections menu. For example, this Sort variation turns this list:
Select several lines …
Into this:
39
Editing Text
And the selections are sorted in place!
To use the Sort Lines command: 1. Select several non-sequential lines. 2. Click Edit | Permute Selection | Sort. To use the Sort Lines (Case Sensitive) command: 1. Select several non-sequential lines. 2. Click Edit | Permute Selection | Sort Lines (Case Sensitive). To use the Reverse command: 1. Select several non-sequential lines. 2. Click Edit | Permute Selection | Reverse. To use the Shuffle command: 1. Select several non-sequential lines. 2. Click Edit | Permute Selection | Shuffle.
Editing Text
To use the Unique command: 1. Select several non-sequential lines. 2. Click Edit | Permute Selection | Unique.
40
9. Selecting Text Multi-Select Multiple cursor mode is a distinctive feature of Sublime, and other selection modes often make use of it. Let’s look at an example that illustrates how useful this feature can be. I’d like to add a CSS class element of tv-shows to each element in the following unordered list: 1 2 3 4 5
The Office Fringe Touch
In most editors, I’d have the option of either formulating a find and replace on the opening li element, or I’d need to enter column selection mode to vertically select a single column and then then type in the text I need in all three rows. Find and replace approaches often end up changing more than intended–I don’t want to add a class to every li in the file, just these three. And column selection mode seems to work a little differently in every text editor, and it always takes me a minute of fumbling around to get it working. Sublime’s multiple selections are much more intuitive. After each opening li, I can just Command+click on Mac OS X or Ctrl+click on Windows and Linux, and then start typing:
42
Selecting Text
Multiple selections in action.
You can even click multiple locations on the same line. Multiple selection can help with many scenarios where you’d normally need to take a couple of minutes to figure out a good find and replace approach or record a macro. Consider the following list: 1 2 3
The Office Fringe Touch
To wrap these items in li elements, you could record a macro where you typed the opening tag, jumped to the end of the line, typed the tag, moved down a line, then jumped to the beginning of the line. Replaying this two times would result in the entire list being formatted. When you have a lot of items to work with, this extra effort is often worthwhile. However, to make a quick, three-line change like this, using multiple selections is much faster. In this scenario, all you need to do is: 1. Insert the cursor at the beginning of the first line. 2. Invoke the Add Next Line command twice. 3. Type the opening tag.
43
Selecting Text
4. Press End. 5. Type the closing tag.
Multiple selections can handle tasks that would otherwise require a macro.
You can combine the multiple selection feature with Sublime’s powerful selection features to perform tasks that would normally require complex macros or fiddling with regular expressions. For example, given a list of items with different CSS classes: 1 2 3 4 5
The X Files
You could quickly change the class names of all items by combining Add Next Line with Expand Selection to Word:
44
Selecting Text
Multiple selections can negate the need for complex regex replaces.
Multiple selections is such a unique feature that it’s sometimes hard to remember it even exists. Spend a few minutes playing around with it, and next time you find yourself making tedious manual edits because there doesn’t seem to be an easy way to automate a task, ask yourself whether you could knock it out with multiple selections.
Split Selection into Lines The Split Selection into Lines command is a great way to quickly append some text to the end of a set of lines. For example, the following lines of JavaScript are missing semicolons at the end, and since I don’t want Douglas Crockford to show up at my house, I’d better add some: 1 2 3 4
$(function () { var mantra = "Eval is evil." sayMantra(mantra) })
Making this change is as simple as selecting the last three rows, invoking Split Selection into Lines, pressing the Right Arrow to cancel the selection, and typing ;. To use Split Selection into Lines:
45
Selecting Text
1. Select the lines of text that you want to edit. 2. Click Selection | Split into Lines. Or press Shift + Command + L on Mac OS X, or Ctrl+Shift+L on Windows or Linux.
Invoking Split into Lines leaves the selected text highlighted. If you want to replace the selected text, you can just start typing. More likely you’ll need to move the cursors before you can do anything useful. Options include the Home and End keys, which move the cursors to the first character in the line or the end of the line respectively, or the Left Arrow and Right Arrow keys. In my experiments, Left Arrow doesn’t always line up the cursors evenly, so if that’s your goal then Home is the best option.
Quick Add Next This command and the next one, Quick Skip Next, make a powerhouse duo. When you select a word and invoke Quick Add Next, Sublime will highlight the next occurrence of the word and insert a multi-select cursor at that point, allowing you to change both words simultaneously. This command is an excellent replacement for simple find-and-replace type changes, especially when you want to limit the changes to a subsection of the file. As an illustration of this command’s usefulness, let’s return to the HTML snippet from an earlier example and add a class name to each li element: 1 2 3 4 5
The Office Fringe Touch
To perform this task, I can simply select the characters
For this example, we’ll use the same trigger word, if, and update the description: 1 2 3 4 5 6
if source.js if block with better formatting
When you have two or more snippets that share a trigger word, typing the trigger and hitting Tab will display a menu that lets you choose which to insert.
Scope The scope value of source.js indicates that this snippet will be available any time Sublime knows you’re editing JavaScript, whether you’re in a .js file, inside of a script block in an HTML file, or in an unsaved file where you’ve manually set the syntax to JavaScript. If you’d like to make a snippet available in any file type, you can use text as the value for the scope element or just leave the scope element empty.
Content The real work happens in the CDATA section. This is where you include your code, field markers and optional placeholder text. Here’s the meat of the original JavaScript if snippet:
Snippets
1
84
if (${1:true}) {${0:$TM_SELECTED_TEXT}};
This short little block illustrates most of what you need to know to write your own snippets. Fields Field markers define the tab stops in the snippet and use the format $1, $2, and so on. Each time the user hits Tab after inserting the snippet, the cursor jumps to the next field marker. The exception is $0, which is an exit marker that ends the tab sequence when the user hits it. One handy trick that our example doesn’t illustrate is duplicated or mirrored fields. If you’d like the user to be able to insert the same text in multiple places at once, duplicating the field marker will cause Sublime to insert a cursor at each location and insert the typed text at each point. This could be useful if you want to create a snippet that inserts a function definition and invokes a callback function: 1 2 3
function myFunction(callback) { callback(); };
The snippet code would include duplicate position markers for the name of the callback: 1 2 3
function ${1:myFunction}(${2:callback}){ ${2:callback}; };
When the user enters a name for the callback function, it updates both the parameter name and the invocation in the function body. Placeholders Field markers can also define placeholder text. When the user tabs to a field with placeholder text, the placeholder is selected, ready to be replaced with whatever the user enters. To add placeholder text to a field, use curly braces around the number and placeholder, and separate the number and placeholder content with a colon: 1
${1:placeholder}
85
Snippets
Environment Variables Sublime recognizes several environment variables that you can incorporate into snippets. The $TM_SELECTED_TEXT variable in the if snippet is a good example. This variable contains any text that the user highlighted before triggering the snippet, and it allows the snippet to wrap the existing highlighted text. Other examples include $TM_FILENAME and $TM_FILEPATH. For more information, see the unofficial Sublime documentation¹. The TM prefix is an example of Sublime’s efforts to be compatible with TextMate. Sublime supports TextMate plugins, and snippets are no exception. It’s an alias for the Sublime $SELECTION variable.
Implementing the Custom Snippet Let’s put the pieces together now and make a better if snippet. I’m picky about white space in my code, so I’d like my if statements formatted on three lines, like this: 1 2 3
if (true) { };
Since I’m mainly modifying the text that the snippet inserts, most of the changes will go in the CDATA section. This section is white space sensitive, so any formatting I apply there will be preserved in the inserted code. Unfortunately, this includes the white space I’d normally use to properly indent the XML. The price of neatly formatted code is a messy snippet file: 1 2 3 4 5 6 7 8 9 10
if source.js if ¹http://docs.sublimetext.info/en/latest/extensibility/snippets.html#environment-variables
Snippets
86
Installing Snippets To install the snippet, just save the file somewhere in Sublime’s Packages directory, which you can locate by launching the Command Palette and typing Browse Packages. Be sure to use the sublime-snippet file extension. I created a subfolder called snippets in the Packages/User directory to keep all of my custom snippets in one place. Once the file is saved, Sublime automatically loads it—no restart necessary.
15. Macros What are macros? A macro is a recorded sequence of commands that you can replay over and over to automate a repetitive task. Macros serve as a gateway to extending Sublime: While they’re not as powerful as full-blown plugins, they’re quick and easy to create, and often more than capable of getting the job done. Once you’ve created and saved a macro, you can assign it a keyboard shortcut and use it just like a first-class Sublime command or plugin. In fact, you may already use macros without realizing it. Some of Sublime’s editing commands are really just macros, including Add Line, Add Line Before, and Delete Line. For a list of these built-in macros, click Tools | Macros.
What are they good for? Macros are best suited for adding little convenience commands that fine-tune the editing experience in Sublime. For example, if you write JavaScript or a C-based language, you might create a macro that jumps to end of the current line, inserts a ; and advances to the next line, all with a single keystroke. If you have to hand-craft a lot of JSON, you could record a macro that jumps to the end of the line, appends a comma, and inserts a new line. Or if you use Sublime to write a lot of prose, you might appreciate a macro that includes trailing white space when you select a whole word for deletion. Macros aren’t always the right tool for the job. Sublime’s current implementation of macros has some limitations. If the task you want to automate involves manipulating files or folders or calling external programs, you might need to write a custom build action or even a full-blown plugin.
Creating macros To illustrate how simple it is to make your own macros, we’ll walk through the whole process, creating a basic macro that you can use when you’re writing JavaScript and other curly brace languages. Then we’ll see how to set up a custom keyboard shortcut to run the macro on demand.
Macros
88
If you’ve ever worked on a project with other developers, you’ve no doubt run into a function or method with a straightforward purpose but an implementation that’s well … interesting. No, scratch that. It’s hideous, an abomination. You want it out of your life yesterday: 1 2 3 4 5 6 7 8 9 10 11
function isLeapYear(year){ // my eyes! the googles, they do nothing! div = year / 4; str = new String( div ); var dec = str.indexOf("."); if ( dec != -1 ) { return false; } else { return true; } }
The example macro we’ll create is called Function Nuke, and it’s useful when you want to keep the declaration of a function or method but delete its implementation. The Function Nuke macro deletes everything inside the curly braces in one keystroke, making it easy to start fresh. (And yep, that’s real code, courtesy of the Daily WTF¹).
Recording macros Before you start recording, it pays to take a minute to think through the exact steps you need your macro to include—and what it should not include. You might even want to rehearse the process once or twice to make sure it’s the most efficient way to accomplish the task. Skipping this step can easily mess up the macro. For example, if you don’t consider that you need to position the cursor correctly before you start recording the macro, you might end up recording some extra cursor movements that will replay when you use the macro, throwing off the result. Does hitting a wrong key mean you’ll have to throw the recording out and start over? Not necessarily. The recorder will capture some mistakes, but you can easily edit them out later. But if you plan to save your macro for later use, a little extra upfront care will make editing easier later on. After you’ve planned the steps in your macro, perform any preliminary steps that you don’t want to include in the recording. For the example macro, this involves positioning the cursor inside the function that you want to nuke. ¹http://thedailywtf.com/Articles/JavaScript_Hacks_.aspx
89
Macros
When you’re ready to start recording, click Tools | Record Macro. You’ll see a Starting to record macro … message in the status bar. Begin executing the steps you want to include in the macro. Take your time here—the macro will always play back at full speed, regardless of how long you might pause between steps. If you execute a command by accident, try to use the Undo command to reverse it. Sublime will remove the errant command and subsequent Undo from the recording. To create the Function Nuke macro, click Selection | Expand Selection to Brackets to highlight the function body. Then press Delete to eliminate the offensive code. Finally, press Enter, which moves the closing curly brace down two lines and positions the cursor on the line below the function declaration, ready for your brilliant new code. When you’re done, click Tools | Stop Recording Macro. You’ll see a Recorded macro with 3 commands message in the status bar.
Saving Sublime stores macros in an in-memory buffer, which means that carefully scripted sequence you just recorded will vaporize if you close Sublime. And there’s just one slot; you’ll stomp all over it if you record another macro. So unless you created a throwaway script for a quick cleanup task, you’ll probably want to save your macro. To save the Function Nuke macro, click Tools | Save macro …. The file save dialog opens to the default location for user macros, which is your Packages\User folder. Enter Function Nuke as the file name, then click Save. Sublime saves the macro as a JSON-formatted text file with a .sublime-macro extension. To access the saved macro, click Tools | Macros | User | Function Nuke. Where should I save macros? Although you can technically save macros in any folder under Packages, stashing your macros under User will make it easier to tell them apart from any plugins you install.
Playback Since a macro is a recorded sequence of commands, triggering a macro is called playback. Before playing back a macro, make sure that you’ve met any required preconditions. For example, the Function Nuke macro assumes that the cursor is positioned inside the function whose body you want to delete. To run an unsaved macro that you’ve just recorded, click Tools | Playback Macro. To execute a saved macro, click Tools | Macros, then look for the macro under the name of the folder where you saved it. If you’ve followed the steps to create Function Nuke, you’ll find it under Tools | Macros | User | Function Nuke.
90
Macros
Editing Sublime does a pretty good job of weeding out mistakes as you record a macro—as long as you use Undo to reverse them. But if you made a typo and fixed it with Backspace, Sublime will faithfully record both the error and subsequent correction. If you’re a perfectionist, you can clean up your macro by hand so it only executes the commands you intended to record. Macros are JSON-formatted files that contain an array of command objects. Each command object consists of args and command properties. Here’s a (pretty useless) macro that executes a single command, equivalent to pressing the Backspace key: 1 2 3 4 5 6
[ { "args": null, "command": "right_delete" } ]
When I first recorded Function Nuke, I inadvertently deleted part of the function body by hand— what can I say, bad code triggers my reflexes. The resulting recording includes some unnecessary commands: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
[ { "args": { "forward": false }, "command": "delete_word" }, { "args": { "forward": false }, "command": "delete_word" }, { "args": { "to": "brackets"
91
Macros
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
}, "command": "expand_selection" }, { "args": null, "command": "right_delete" }, { "args": { "file": "res://Packages/Default/Add Line in Braces.sublime-macro" }, "command": "run_macro_file" } ]
After I remove the extraneous commands, the final version of the Function Nuke macro looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
[ { "args": { "to": "brackets" }, "command": "expand_selection" }, { "args": null, "command": "right_delete" }, { "args": { "file": "res://Packages/Default/Add Line in Braces.sublime-macro" }, "command": "run_macro_file" } ]
When you’re editing macro files by hand, mind your JSON formatting. It’s easy to make a syntax error, which will cause the macro to silently fail when you try to run it.
92
Macros
If you add a question mark, space or backslash, you’ll need to escape it by preceding it with a \. To troubleshoot a failing macro, open the Sublime console and look for an Unable to parse macro message, which should point you to the location of the syntax error. Version Difference! Sublime Text 2 doesn’t tolerate trailing commas following the last property in a JSON object or the final element in an array. You’ll see a parsing error in the console.
By the way, did you happen to notice anything about the last command in Function Nuke? It’s running the Add Line in Braces macro, which moves the closing brace down two lines and indents the cursor. This is a good example of a Sublime “feature” that’s really just a macro.
Creating keyboard shortcuts for macros Now that you’ve saved your custom macro, it’s available under Tools | Macros | User. But seconds matter when you’re staring at code that’s this ugly—and who wants to click and hover through three levels of menus? You can assign a keyboard shortcut to custom macros by following the standard steps to create a key binding, using run_macro_file as the command and supplying the macro’s file path as an argument. Here’s an example that binds Function Nuke to Ctrl+Alt+Shift+N: 1 2 3 4 5 6 7 8 9 10 11
[ { "keys": [ "ctrl+alt+shift+n" ], "command": "run_macro_file", "args": { "file": "res://Packages/User/Function Nuke.sublime-macro" } } ]
Using macros to hack Sublime’s API
.
Since macros are just a JSON-formatted list of commands, you can use them to figure out what API calls Sublime is executing in response to specific keyboard shortcuts or menu clicks. Just fire up the macro recorder, manually trigger the commands you’re interested in, then save the macro
Macros
93
and crack it open to see what Sublime is doing behind the scenes.
.
Limitations No find and replace support Macros in Sublime have a few drawbacks, and the first one might come as a surprise to power users of other text editors: You can’t use find or find and replace in a macro. In fact, Sublime goes so far as to disable the macro commands under the Tools menu if you even have a find panel open. In editors like Vim or emacs, it’s common to create macros to perform tasks like converting a sequence of lines to a comma-separated list by doing a find on the newline character and replacing it with a comma. But since Sublime doesn’t support find or find and replace in macros, there’s no way to do this with a macro. Often it’s simple to accomplish the task by writing a plugin, and scripting Sublime plugins in Python is likely to be easier for many users than, say, working with Vimscript. Creating a plugin is overkill for many cleanup scenarios, though. This is one of the biggest gripes that power users of other text editors express about Sublime, and it’s on my list of things I’d most like to see added in the future.
One tab, one macro buffer In some text editors, such as Vim, you can record macros and store them temporarily in different slots, then replay them as needed. Sublime, however, has just one macro buffer, and you can only have one unsaved macro at a time. If the task at hand calls for several macros, you can always create each macro, save it, then create another. The upside to this is that you’ll be able to use the saved macro again in the future. But it’s a hassle if you’re just looking to do some quick cleanup and the macro won’t be useful later. This single macro buffer implementation has another quirk: If you start recording a macro, then switch tabs, Sublime reenables the Record Macro menu option and allows you to start recording additional macros. But if you think this means you can record multiple macros in parallel, you’re destined for disappointment. Each time you stop a recording, it overwrites the previous unsaved macro.
Macros
94
Some commands are ignored Macros can only execute a subset of Sublime’s commands—for the most part, they can only include commands that operate on a file’s contents. Higher level commands, like those that operate on the file system, are ignored when you’re recording. This means you can’t create a macro that opens a file and makes a couple of changes before saving the file and moving to the next file.
IV Customizing the Editor
16. Command Palette Tweaks Most of the commands in Sublime’s main menu are available through the Command Palette, but there are some curious omissions, like View | Enter Distraction Free Mode and View | Enter Full Screen. I usually enter full screen mode whenever I relaunch Sublime, and I like to jump into distraction free mode when I’m writing. The shortcuts for these two commands are different on Mac and PC, and my efforts to memorize them have thus far failed. So to the menus I went whenever I wanted to change modes. Until, that is, I figured out how to add them to the Command Palette myself.
Configuration Files The commands that appear in the Command Palette are defined in JSON-formatted configuration files with the extension .sublime-commands. Sublime will automatically load any command files it finds under /Data/Packages. A filename search for sublime-commands will turn up numerous examples, especially if you have a lot of plugins installed. But the granddaddy of them all is the file that sets up Sublime’s default Command Palette entries: 1
/Data/Packages/Default/Default.sublime-commands
Adding Commands To add a command to the Command Palette, just create a new .sublime-commands file and save it anywhere under /Data/Packages. The configuration file specifies the text that’s shown in the Command Palette in the caption field and the name of the Sublime API method to execute in the command field:
Command Palette Tweaks
97
Adding the Enter Distraction Free Mode and Enter Full Screen commands to the Command Palette.
1 2 3 4 5 6 7 8 9 10
[ { "caption": "View: Toggle Distraction Free", "command": "toggle_distraction_free" }, { "caption": "View: Toggle Full Screen", "command": "toggle_full_screen" } ]
Only the extension matters when you’re saving a new command file–you can make the file name whatever you want. I created a new directory for my custom commands to keep things tidy: 1
/Data/Packages/User/commands/View.sublime-commands
The new commands are available immediately–you don’t need to restart Sublime. One of the best places to look up commands from the Sublime API is the configuration file for the main application menu. This is located at /Data/Packages/Default/Main.sublime-menu. You can search using the text that appears in the main menu to find the correct API method to call. To find the Enter Distraction Free Mode command, I searched for distraction and found toggle_distraction_free.
17. Menu Enhancements While Sublime’s keyboard shortcuts and Command Palette allow me to edit effortlessly without touching the mouse, there are still times I find myself reaching for the menus. Often I’ll opt for a menu selection when I’m already using the mouse to browse and open arbitrary files in Finder or Windows Explorer. But for some tasks, using the menus is a pain. One common chore I perform is setting the syntax for a snippet of code I’ve copied from a web page. I always have trouble remembering where the Syntax entry is hidden (it’s buried under View | Syntax), and once I find it there’s a submenu with dozens of languages to scan through before I can pick out the one I want. This is easily remedied thanks to Sublime’s menu configuration scheme, which makes it simple to enhance any of Sublime’s menus, including: • • • •
Main (application) menu Sidebar context menu Editor context menu Tab context menu
Configuration Files Menus are defined in JSON-formatted configuration files with the extension .sublime-menu. Sublime automatically loads any menu files it finds under /Data/Packages. Most of the interesting menus are located in /Data/Packages/Default/: 1 2 3 4
/Data/Packages/Default/Main.sublime-menu /Data/Packages/Default/Side Bar.sublime-menu /Data/Packages/Default/Context.sublime-menu /Data/Packages/Default/Tab Context.sublime-menu
The file name is significant, as it lets Sublime know which menu the file modifies. Be sure to name your custom entries accordingly.
Menu Enhancements
99
Customizing the Context Menu To make it easier to set the syntax for a new code snippet, I created an entry in the editor panel’s right-click context menu that contains a shortlist of the languages I use on a daily basis, like HTML, CSS, JavaScript and XML. To add this new context menu entry, I created the following file: Adding a new command to the editing panel’s right-click context menu.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
[ { "caption": "Syntax", "children": [ { "caption": "CSS", "command": "set_file_type", "args": {"syntax": "Packages/CSS/CSS.tmLanguage"} }, { "caption": "HTML", "command": "set_file_type", "args": {"syntax": "Packages/HTML/HTML.tmLanguage"} }, { "caption": "JavaScript", "command": "set_file_type", "args": {"syntax": "Packages/JavaScript/JavaScript.tmLanguage"} }, { "caption": "Markdown", "command": "set_file_type", "args": {"syntax": "Packages/Markdown/Markdown.tmLanguage"} }, { "caption": "Text", "command": "set_file_type", "args": {"syntax": "Packages/Text/Plain text.tmLanguage"} }, { "caption": "XML", "command": "set_file_type",
Menu Enhancements
34 35 36 37 38
100
"args": {"syntax": "Packages/XML/XML.tmLanguage"} } ] } ]
Simple commands might have just caption and command fields. The children array creates submenu that lists the languages. I saved the file in a subfolder of my User folder: 1
/Data/Packages/User/menu/Context.sublime-menu
After I saved the file, my new context menu was available instantly–no need to restart Sublime. If you’re interested in writing plugins, these .sublime-menu files menu files (as well as the .sublime-keymap files) are a good Rosetta Stone for the Sublime API. They contain the API calls for every item listed in the menus.
18. Key Bindings Like other settings in Sublime, keyboard shortcuts, or key bindings, are configured in a text file that you can view and edit. This means you can see a full list of default keyboard shortcuts, although it’s not in the most readerfriendly format. It also means that overriding shortcuts with your own custom bindings is a snap in most cases. The key bindings file uses the official Sublime names for commands, making it a handy starter reference for the Sublime API if you’re looking to develop your own custom plugin.
Configuration files Sublime uses separate keymap files for Mac, Windows and Linux. On a Mac OS X system, the default keymap file is located at: 1
/Data/Packages/Default/Default (OSX).sublime-keymap
On a Windows system, the default keymap file is located at: 1
\Data\Packages\Default\Default (Windows).sublime-keymap
To open the correct default keymap file for your OS: • Click Sublime Text 2 | Preferences | Key Bindings - Default on Mac OS X or Preferences | Key Bindings – Default on Windows and Linux. Skimming through Sublime’s default config files is a great way to learn about the editor.
You don’t want to edit the default .sublime-keymap files, because they get overwritten when Sublime updates itself. Instead, edit the user-specific keymap file instead. Bindings in the user keymap file override Sublime’s defaults. On a Mac OS X system, the user keymap file is located at:
102
Key Bindings
1
/Data/Packages/User/Default (OSX).sublime-keymap
On a Windows system, the user keymap file is located at: 1
\Data\Packages\User\Default (Windows).sublime-keymap
To open the correct user keymap file for your OS: • Click Sublime Text 2 | Preferences | Key Bindings - User on Mac OS X or Preferences | Key Bindings – User on Windows and Linux.
Creating custom key bindings Like other settings in Sublime, keymap files are just JSON-formatted plain text files. The file contains an array of JSON objects, with each object representing one binding. Each binding consists of two parts: an array of keyboard shortcuts and a command to execute. Since the keyboard shortcuts are an array, you can bind multiple shortcuts to a single command. To create a new key binding, just edit the user keymap file to add a new JSON object with the desired keyboard shortcut and command. Here’s an example that remaps Paste and Indent to Ctrl+V, which is useful, and overrides the Undo command to perform a Close instead, which would be a fun way to haze the new guy. 1 2 3 4
[ { "keys": ["ctrl+v"], "command": "paste_and_indent" }, { "keys": ["ctrl+z"], "command": "close" } ]
Here’s the Paste and Indent binding formatted so it’s a little more readable: 1 2 3 4
{ "keys": ["ctrl+v"], "command": "paste_and_indent" }
The default keymap file has a ton of commands listed, so start there if you’re looking to override an existing shortcut or bind one for a command that doesn’t already have one set up.
Key Bindings
103
Context-specific key bindings Sometimes you might want to prevent a keyboard shortcut from firing unless certain conditions are met. Or you might want the same shortcut to trigger different commands based on the language of the current file or surrounding code. Key binding contexts give you this type of fine-grained control over where and when your shortcuts operate. To see how key binding contexts work, let’s implement a new key binding that inserts an end-of-line comment in multiple languages. Sublime already includes the Toggle Comment and Toggle Block Comment commands, but neither makes it particularly convenient to jump to the end of a line of code and insert an explanatory (or apologetic!) comment. Our new EOL Comment command lets you use the same shortcut to insert an inline comment in JavaScript: 1 2 3 4 5 6 7 8 9 10
function getTime(tzCode) { switch(tzCode) { /* snip */ case 87: return 1377953338803; // you don't want to know } }
And a single-line block comment in CSS: 1 2 3
.quote-box { zoom: 1; /* don't hate me, hate ie6 */ }
First, you’ll need to record a couple of macros. In the JavaScript version, you’ll start by pressing End to jump to the end of the line, then press Space, enter // to start the comment, then press Space one more time. Stop recording and save the macro as EOL Comment (JS).sublime-macro. For the CSS version, press End to jump to the end of the line, press Space, then run the Toggle Block Comment command. Save this version of the macro as EOL Comment (CSS).sublime-macro. Now to create the key bindings. The basic key binding format only allows you to bind one command or macro to a particular shortcut:
Key Bindings
1 2 3 4 5 6 7 8 9
104
[ { "keys": ["ctrl+alt+/"], "command": "run_macro_file", "args": { "file": "res://Packages/User/EOL Comment (JS).sublime-macro" } } ]
But key bindings support a context property, which takes an array of objects that act as rules to narrow the scope of your shortcut. Each item in the context array is essentially a simple query that’s executed before the key binding command executes. If all of the context rules are satisfied, the command fires. The following context rule ensures that a binding will only work when you’re editing JavaScript: 1 2 3 4 5 6
"context": [{ "key": "selector", "operand": "source.js", "operator": "equal", "match_all": true }]
To break this example down a bit, the key property determines what type of query to run. Specifying a value of selector means the rule will check the current language scope. You can also query the surrounding text or user preferences. The operand is the value we want to compare the query results to. Since we’re interested in the current language, the example specifies a language scope, but you might also use a boolean value or regular expression. The operator property determines how to compare the queried value to the value required by the operand. A value of equal will make the binding effective in the scope specified by the operand. You can also use not_equal to exclude the targeted language. Here’s what the key bindings look like after applying the context rules:
Key Bindings
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
105
[ { "keys": ["ctrl+alt+/"], "command": "run_macro_file", "args": { "file": "res://Packages/User/EOL Comment (JS).sublime-macro" }, "context": [{ "key": "selector", "operator": "equal", "operand": "source.js", "match_all": true }] }, { "keys": ["ctrl+alt+/"], "command": "run_macro_file", "args": { "file": "res://Packages/User/EOL Comment (CSS).sublime-macro" }, "context": [{ "key": "selector", "operator": "equal", "operand": "source.css", "match_all": true }] } ]
Context rules are capable of much more than just detecting the current language scope. You can also use them to apply different shortcuts based on user preferences, whether a panel is shown or hidden, or whether the surrounding code matches a regular expression. The default keymap file has numerous examples of context rules. For example, Sublime’s implementation of quote auto-pairing is really just a “keyboard shortcut” that fires when you enter " and a few context rules are satisfied, including one that makes sure that auto_match_enabled is true. If all the rules match, the binding triggers a snippet to insert the closing quote and position the cursor. For more details about configuring context-specific bindings, including lists of valid key, operator and operand values, see the the unofficial Sublime documentation key bindings page¹. ¹http://docs.sublimetext.info/en/latest/reference/key_bindings.html
19. Managing Plugins Package Control The Package Control¹ plugin is the plugin to rule all plugins. It allows you to browse and install hundreds of plugins written by happy Sublime Text 2 users. Setting up Package Control involves run a small script in the Sublime Python console, and instructions are available on the Package Control site.
Installing Packages Once Package Control is installed, setting up new plugins is a snap: 1. Press Command+Shift+P on Mac OS X or Ctrl+Shift+P on Windows or Linux. The Command Palette opens. 2. Type install. The Package Control: Install Package command is highlighted. 3. Press Enter. The package list opens. 4. Type part of a package name. The package list shows matching packages. 5. Highlight the package and press Enter. A confirmation appears in the status bar when the installation is complete. 6. Restart Sublime if prompted. Most plugins do not require a restart.
View Installed Packages It’s easy to lose track of what you’ve installed, or forget the keyboard shortcut required to trigger some plugin that you only use occasionally. Fortunately, it’s easy to review your list of installed plugins and read their documentation using the Browse Packages command. To view installed plugins: • Click Sublime Text 2 | Preferences | Browse Packages on Mac OS X or Preferences | Browse Packages on Windows and Linux. The system file explorer launches, displaying the folders for all installed packages. Most packages include a README file that includes usage instructions and keyboard shortcuts. ¹http://wbond.net/sublime_packages/package_control
Managing Plugins
107
Disabling Packages You can temporarily disable packages and plugins without uninstalling them using the ignored_packages setting in your user preferences file. By default, only the Vintage plugin is ignored: 1
"ignored_packages": ["Vintage"]
To disable a package, use Preferences: Browse Packages to find the folder name of the plugin you’d like to turn off. Then run the Preferences: Settings - Default command and grab the ignore_packages setting from the default preferences file. Next, run Preferences: Settings - User and paste the setting into your user preferences file. Add the name of the plugin you want to disable to the ignored_packages array, enclosing the package name in quotes and separating entries with a comma: 1 2 3 4 5
"ignored_packages": [ "Vintage", "Emmet" ]
If you have Package Control installed, it can edit your ignored_packages list for you. Just run Package Control: Disable Package in the Command Palette, then select the unwanted package from the quick panel list. Ignored packages are immediately disabled, and they won’t load the next time Sublime launches. When you first add a package to the ignore list, you may need to restart Sublime for the plugin to be fully disabled, especially if the package contains a plugin.
Troubleshooting Packages Most of the time, Sublime runs smoothly and all is well with the world. But every once it a while, you’ll sit down to work and suddenly things seem like they’ve gone crazy. Usually this is caused by an issue with a plugin, and tracking down the problem child can require some detective work. Whenever Sublime starts acting strange, your first line of defense is restarting the editor. This will flush any bad state from memory and force Sublime to reload all of its plugins. If the odd behavior persists, a good next step is checking to see if any plugins are throwing errors while loading or running commands. Click View | Show Console, then review the console output for error messages.
Managing Plugins
108
One common source of errors is package updates. Package Control automatically updates plugins every time you launch Sublime, and it’s possible that a plugin author pushed a buggy update. It’s easy to introduce bugs when a plugin supports multiple operating systems and Sublime versions. If that’s the case, you can disable the plugin temporarily and report the bug on the plugin’s GitHub page. If you can’t glean any clues from the console output, the process of elimination is your next best bet. Use the Package Control: List Packages command to review the packages you’ve installed and look for likely suspects. Then use Package Control: Disable Package to toggle packages individually. Be sure to restart Sublime before attempting to reproduce the behavior you’re troubleshooting. As a final troubleshooting step, you can try reproducing the issue in a totally clean environment. If you’re a Windows user, the easiest way to do this is to download the portable version of Sublime that corresponds to the version you have installed. Portable installers are available on the Sublime downloads page. On OS X and Linux, you can revert to a clean environment by temporarily moving your user data folder. Instructions are available for Sublime Text 2² and Sublime Text 3³. ²http://www.sublimetext.com/docs/2/revert.html ³http://www.sublimetext.com/docs/3/revert.html
20. Writing Plugins What is a plugin? Before we dive into writing our example plugin, it’s helpful to get a better idea of what plugins are and how they differ from a related concept: packages. A package is simply a collection of files that extends Sublime when properly installed. Packages may include skins and color themes, macros, code snippets, keyboard shortcuts, and programming language definitions that provide syntax highlighting. Plugins are a specific category of Sublime package with several characteristics that set them apart from other packages. While regular packages generally consist of JSON and XML files, plugins are Python scripts. And while packages make use of predefined Sublime commands and events, plugins create new commands by extending one of the Sublime command classes or adding handlers for Sublime’s built-in events. Plugins are the most powerful of Sublime’s extensibility mechanisms. They can combine existing commands and macros to provide new functionality, define new commands, manipulate elements of the Sublime environment such as tabs and text, and display user interface components to define new workflows.
The Command Logger plugin To learn more about how plugins work, we’re going to write a simple plugin that does just one thing—enable command logging. Sublime has a useful, built-in command logging feature that can help you learn more about what’s happening behind the scenes as you use Sublime. When command logging is enabled, Sublime outputs the name of each command as you interact with the editor. For example, hitting the Backspace key while you’re editing some text fires the left_delete command. Sublime also prints any arguments provided to the command. Here’s what the console output looks like when I select some text and copy it with the right-click menu: 1 2 3
command: drag_select {"event": {"button": 1, "x": 98.5, "y": 93.5}} command: context_menu {"event": {"button": 2, "x": 77.5, "y": 415.5}} command: copy
Command logging is useful when you want to modify keyboard shortcuts, write macros or create your own plugins. If you want to change a key binding, you can enable command logging and fire the
Writing Plugins
110
shortcut to see the name of the command, making it easy to find in your Default.sublime-keymap file. But enabling command logging is a hassle. There’s no way to do it from a menu or keyboard shortcut. Instead, you have to open the console and type the following command: 1
sublime.log_commands(True)
The Command Logger plugin that we’re going to create will allow us to bypass the console and enable command logging directly from the command palette.
Creating a new plugin Sublime ships with a menu option that allows you to easily generate the boilerplate code for a new plugin. To get started, click Tools | New Plugin …. Sublime creates a new, unsaved tab and inserts the following boilerplate code: 1 2 3 4 5
import sublime, sublime_plugin class ExampleCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.insert(edit, 0, "Hello, World!")
This is a fully functional Hello World plugin, but before we can try it out, we need to install it.
Installing the plugin Installing the plugin involves saving the file in a subdirectory of your Packages directory, which is where Sublime expects to find plugins. This path differs by operating system and Sublime version, but it’s usually located in your home directory. You don’t need to worry about the exact location just yet. Instead, click File | Save and Sublime opens the system file saving dialog with the Packages directory already selected. Create a new folder under Packages called ConsoleLogger. Open your new folder and save your file as console_logger.py. As soon as you save the file, Sublime springs into action. Sublime monitors the Packages folder constantly for file changes. When it sees that you’ve created or updated a file, it tries load it automatically. To confirm that the plugin loaded correctly, click View | Show Console to open the Sublime console. You should see a line similar to the following near the bottom of the output:
Writing Plugins
1 2
111
Reloading plugin C:\Users\josh\AppData\Roaming\Sublime Text 2\Packages\CommandLo\ gger\command_logger.py
Testing the example plugin Now that Sublime has loaded the plugin, it’s time to test it out. Open a new tab, then enter the following in the Sublime console: 1
view.run_command("example")
If all goes well, Sublime will insert the text, “Hello, World!” at the top of the blank tab you just created.
Implementing CommandLogger At this point, we have a plugin that, while useless, confirms that we have everything set up correctly. Let’s start building something useful, shall we? To begin, we’re going to rename our plugin command: 1 2 3 4 5 6
import sublime, sublime_plugin class ExampleCommand(sublime_plugin.TextCommand): class CommandLoggerCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.insert(edit, 0, "Hello, World!")
Most of the time, when you create a new plugin for Sublime, you’ll be implementing a command. A Sublime command is a Python class that extends one of the three Command classes defined in the sublime_plugin module. Commands also follow a specific naming convention. The class name must end in the word Command and use camel casing to set off each word in the class name. Sublime will convert this command name when the plugin loads by dropping the Command suffix and converting the class name to snake casing, which uses all lowercase letters and underscores to delineate words. That’s why we ran our ExampleCommand above using a command name of example. Every command must also define a run method, which Sublime calls when the command is executed. This method serves as the entry point into your code, and it must accept a certain number of default parameters, depending on the type of command.
Writing Plugins
112
Sublime defines three types of commands: TextCommand, WindowCommand and ApplicationCommand. All of these commands are defined as classes in the sublime_plugin.py file, which is located in Sublime’s installation directory. TextCommand—When you want to manipulate text in a buffer, you’ll need to extend the TextCommand class. TextCommand provides access to the text in the currently active buffer (usually a tab) via a view object. The TextCommand can operate on ordinary tabs as well as the Sublime console and output
panels. WindowCommand—Unlike TextCommand, the WindowCommand class doesn’t require a view to exist in order to operate, so a WindowCommand is available at all times. While a view isn’t required, WindowCommands are still able to manipulate views if they are present. Each WindowCommand has a WindowCommand.window attribute that contains a reference to the Sublime window that created the
command. ApplicationCommand—The ApplicationCommand class provides a lightweight way to create a command that doesn’t need to interact with parts of the Sublime user interface. Just like the other Command classes, ApplicationCommand defines a run method, but it doesn’t get references to a window or view. The Default package includes several examples of ApplicationCommand, including IncreaseFontSizeCommand and DecreaseFontSizeCommand.
Most plugins extend either TextCommand or WindowCommand, but for the Command Logger plugin, we don’t need access to a window or view. We’ll use an ApplicationCommand as the basis for this plugin. Modify the class definition to extend ApplicationCommand: 1 2 3 4 5 6
import sublime, sublime_plugin class CommandLoggerCommand(sublime_plugin.TextCommand): class CommandLoggerCommand(sublime_plugin.ApplicationCommand): def run(self, edit): self.view.insert(edit, 0, "Hello, World!")
Next, we need to update the runmethod’s parameters. Unlike WindowCommand and TextCommand, an ApplicationCommand doesn’t take an edit parameter: 1 2 3 4 5 6
import sublime, sublime_plugin class CommandLoggerCommand(sublime_plugin.ApplicationCommand): def run(self, edit): def run(self): self.view.insert(edit, 0, "Hello, World!")
Finally, replace the body of the run method with our call to Sublime’s log_commands API method:
Writing Plugins
1 2 3 4 5 6
113
import sublime, sublime_plugin class CommandLoggerCommand(sublime_plugin.ApplicationCommand): def run(self): self.view.insert(edit, 0, "Hello, World!") sublime.log_commands(True)
Let’s try it out. First, restart Sublime to make sure command logging is disabled. Then open the console and run the following: 1
sublime.run_command("command_logger")
Click around a bit and you should see output added to the console for each action. Congratulations— you’ve completed your first plugin!
Integrating with the command palette At this point, all we’ve accomplished is replacing one command that you have to type into the console with another. To make it easy to run our new plugin, let’s integrate it with Sublime’s command palette. This is accomplished with a JSON configuration file. Open a new tab and enter the following: 1 2 3 4 5 6
[ { "caption": "Command Logger: Enable command logging", "command": "command_logger" } ]
Save the file in the plugin directory with the name Default.sublime-commands. Sublime will load the file immediately and add a new command palette entry.
114
Writing Plugins
Sublime picks up the new command palette entry instantly.
Learning more As I researched this chapter, I realized I couldn’t do the topic justice in a few pages–it could easily fill an entire book. There’s a lot that goes into creating a useful and polished Sublime plugin that you can share proudly with the world. Rather than agonizing over what to leave out, I decided to write another book that walks through the entire process, from Hello World to publishing on Package Control. It’s titled Writing Sublime Plugins. Here are some highlights: • More than 140 pages packed with code and real examples. • 30 code snapshots that help you can see how the examples work and test them in your own copy of Sublime. • What Sublime plugins can do–and what they can’t.
Writing Plugins
115
• How many of the features you think of as baked into Sublime really aren’t, and how this can help you. • Why anyone with basic programming experience can write a plugin–no Python experience required. • 9 debugging tricks that will save you hours of frustration. • The professional touches that make your plugin stand out from the crowd. • A way to hack the Sublime API to see exactly what is causing an error. • The Rosetta Stone for the Sublime API. • Where to go for more information. • The different types of Sublime plugins, and what each is good for. Ready to dive in? Visit http://writingsublimeplugins.com¹. ¹http://writingsublimeplugins.com
V Recipes
21. Essential Plugins Extend Menus for the Sidebar By default, the Sublime Text 2 sidebar is a bit weak. It allows you to browse through open files and folders, but if you right-click on a file, you’ll get a menu with just a Close command. The SideBarEnhancements¹ plugin fixes this by beefing up the right-click menu, adding a number of commands that you’d expect like Copy, Paste and Delete, as well as Open in Browser, New File … and New Folder …. You can also define your own custom commands, maybe Open in Chrome or Open Command Prompt Here.
File Creation While it’s nice to have the ability to create new files with a right-click, menus are slow when you’re slinging code. The AdvancedNewFile² plugin provides a simple prompt that allows you to generate new files by typing out your desired path and file name. Any nested directories that you include in the path will be generated if they don’t already exist.
HTML Generation The basic concept behind Emmet is simple. When you’re writing HTML, XML or some similar language that consists of nested tags, Emmet allows you to define the tag hierarchy in a single line, using a CSS-like syntax. The plugin expands your one-liner to create the appropriate structure. For example, this: 1
div > ul > li*3
Becomes:
¹https://github.com/titoBouzout/SideBarEnhancements/ ²https://github.com/skuroda/Sublime-AdvancedNewFile
Essential Plugins
1 2 3 4 5 6 7
118
There’s a bit more to it, so after you install the plugin, check out the documentation on the Emmet project site³.
Blogging If you use Sublime for non-coding tasks like blogging, two handy plugins are MarkdownEditing⁴ and WordCount⁵. MarkdownEditing provides syntax highlighting and some handy text editing features, and WordCount tells you when you’ve gone on long enough, displaying the word count in the status bar. ³http://docs.emmet.io/ ⁴https://github.com/ttscoff/MarkdownEditing ⁵https://github.com/SublimeText/WordCount
22. Cross-Platform Syncing of Settings and Plugins Between my day job as a software developer and my freelancing and writing, I bounce around among computers quite a bit. I currently split time among my MacBook Air and a Windows 7 PC, as well as various Linux and Windows virtual machines. After setting up Sublime for the second or third time, I realized that I needed to automate the process of installing packages and tweaking configs. The Windows version of Sublime is available as a portable installation, which keeps all of the files Sublime needs in one place and doesn’t touch the rest of the system. This allows you to install it on a USB key and run it from any PC with the same exact configuration. I use Dropbox for all of my important files, and portable apps sync via Dropbox just as brilliantly as every other type of file. I created a \Programs\Sublime folder in Dropbox and installed the portable version of Sublime there. My Sublime settings and plugins sync seamlessly between Windows PCs, and when I create a new virtual machine, I don’t even have to install Sublime. The Mac version of Sublime, sadly, doesn’t support this. Mac OS X doesn’t have a concept of portable apps, and Sublime places all of its important files in the ∼/Libary/Application Support/Sublime Text 2/ directory. The following bash script removes Sublime’s default settings and plugins directories and creates links to the folders used by the portable Windows installation installed in the ∼/Dropbox/Programs/Sublime/ directory. 1 2 3 4 5 6 7 8 9 10
#!/bin/bash cd rm rm rm
~/Library/Application\ Support/Sublime\ Text\ 2/ -rf ./Packages -rf ./Installed\ Packages -rf ./Pristine\ Packages
ln -s ~/Dropbox/Programs/Sublime/Data/Packages ./Packages ln -s ~/Dropbox/Programs/Sublime/Data/Installed\ Packages ./Installed\ Packages ln -s ~/Dropbox/Programs/Sublime/Data/Pristine\ Packages ./Pristine\ Packages
To take this one step further, you could also consider doing a full installation of Sublime on your Windows PC and set up hard links to the \Packages, Installed Packages and Pristine Packages folders in Dropbox using the mklink command.
Cross-Platform Syncing of Settings and Plugins
120
To create the hard links, launch the Windows command prompt as an administrator, then execute the following commands: 1 2 3 4 5
cd "%PROGRAMFILES(x86)%\Sublime Text 2" mklink /D "Installed Packages" "%USERPROFILE%\Dropbox\Programs\Sublime\Installed\ Packages" mklink /D "Packages" "%USERPROFILE%\Dropbox\Programs\Packages" mklink /D "Pristine Packages" "%USERPROFILE%\Dropbox\Programs\Pristine Packages"
If you’re running a 32-bit version of Windows, the initial cd command above will fail. Use cd "%PROGRAMFILES%\Sublime Text 2" instead.
I’ve encountered two issues with syncing all of Sublime’s configuration files this way. The first issue pertained to syncing project and session files. I was trying to store project files in a central location in Dropbox, and I found that Sublime tended to use full paths instead of relative ones. I later realized that you’re supposed to keep projects in the root directory of the files they pertain to. So if you have a project called MyWebsite, it goes in the MyWebsite root directory. This allows you to check the Sublime .project file into your version control system and share it with other team members. The other main issue related to font sizes. I use a larger font on my Windows PC because I tend to sit back from the screen a bit more than when I’m working on my MacBook. But Sublime doesn’t know that, and the font settings sync along with everything else.
23. PHP Setting up a New Project Starting a new project is both a joy and a chore. Working with a clean slate is fun–no unfamiliar code to grok, no need to worry about breaking existing features. But then … the setup. Copy and paste the files from a previous project. Delete a bunch of files. Delete blocks of code. Update jQuery. Download and unzip libraries from Github. It sucks the joy out of the air in a hurry. Here’s how to quickly bootstrap a new project in Sublime Text. The example involves creating a new WordPress plugin, but the principles apply to any project.
Fetch Installs Libraries for You Fetch¹ is a brilliant, flexible plugin for Sublime that makes it a snap to grab the latest versions of your favorite open source libraries and frameworks. Once you install and configure Fetch, you can install the latest version of jQuery from Sublime with a simple command: ¹https://github.com/weslly/Nettuts-Fetch
122
PHP
The Fetch plugin makes it easy to use your favorite open source libraries.
Installing Fetch If you haven’t already installed Package Control², you’ll need to do that before you can set up Fetch. Once you have Package Control installed, launch the Command Palette, type install package, hit Enter, then type fetch. Hit Enter one more time and Package Control will install Fetch for you.
Configuring Fetch Fetch can download either single files or packages, which are just zip files containing several files. Fetch comes preconfigured with one file, jQuery, and one package, HTML5 Boilerplate. Adding more files and packages is just a matter of making a quick change to Fetch’s configuration file. Let’s configure Fetch to download WordPress Plugin Boilerplate³, which makes it easy to get up and running when you’re starting a new WordPress plugin. First, launch the Command Palette and type fetch: manage, then press Enter to open the Fetch configuration file in a new tab. The jQuery and HTML5 Boilerplate entries illustrate how to add your own files and packages: ²http://wbond.net/sublime_packages/package_control ³https://github.com/tommcfarlin/WordPress-Plugin-Boilerplate
PHP
1 2 3 4 5 6 7 8 9 10 11
123
{ "files": { "jquery": "http://code.jquery.com/jquery.min.js" }, "packages": { "html5_boilerplate": "https://github.com/h5bp/html5-boilerplate/zipball/master" } }
Notice that in both cases, the links allow you to always get the latest versions of these projects. The jQuery link isn’t tied to a specific version of the library, and the Github link always gets the newest commit to the master branch of HTML5 Boilerplate. Also note the zipball portion of the HTML5 Boilerplate link. When you want to download a collection of files, Fetch expects a link to a zipped archive, which it will then extract for you to a folder of your choice. Github allows you to download the latest version of any project by appending /zipball/master to the project’s URL, which works well with Fetch. Here’s the Fetch settings file after adding the WordPress Plugin Boilerplate package: 1 2 3 4 5 6 7 8 9 10 11 12 13
{ "files": { "jquery": "http://code.jquery.com/jquery.min.js" }, "packages": { "html5_boilerplate": "https://github.com/h5bp/html5-boilerplate/zipball/mast\ er", "wordpress_plugin_boilerplate": "https://github.com/tommcfarlin/WordPress-Pl\ ugin-Boilerplate/zipball/master" } }
This example is available for download as a gist⁴.
Using Fetch Now let’s use Fetch to bootstrap a new WordPress plugin. ⁴https://gist.github.com/5517849
124
PHP
Launch the Command Palette and type fetch package, press Enter, then type wordpress and hit Enter again. Fetch prompts you to enter the path where you’d like to unzip your package:
Enter the path where you’d like Fetch to install the package.
After you type a path and press Enter, you’ll see the download progressing in Sublime’s status bar. Once the download completes, open Windows Explorer or Finder and browse to the path you specified, where you’ll see a plugin-boilerplate folder. Rename that folder to whatever you’d like to call your plugin, then drag it into Sublime to open the folder in the side bar. That’s it–you’re ready to go. You’ll probably want to save this folder as a new Sublime project by clicking Project | Save As … so you can easily reopen it later.
125
PHP
Time to start coding!
Having to open your file browser and rename the plugin folder is a little clumsy, but that’s due to a quirk in the WordPress Boilerplate Plugin project, not a shortcoming of Fetch. The WordPress Plugin Boilerplate project uses the plugin-boilerplate subfolder to organize all of the php, js and css files and folders, instead of keeping them in the project’s root directory. Fetch expects the files to live in the root directory. The HTML5 Boilerplate project is structured this way, and you can install it right into the root directory of an existing Sublime project, providing a much smoother workflow.
Code Checking PHP was the first programming language I learned, and man, was it ever a frustrating experience. Even the smallest typo resulted in a non-helpful 500 error, and my debugging repertoire was limited to commenting out blocks of code until the page started working. At the time, I didn’t know about syntax checkers–or even text editors that offered syntax highlighting. The Sublime PHP Code Sniffer plugin⁵ would have saved me many frustrating hours. With sublimephpcs installed and configured, you get automatic error checking every time you save a file. The ⁵https://github.com/benmatselby/sublime-phpcs
126
PHP
plugin highlights errors on the line where they occur, and it even gives you hints as to what the problem might be.
Setup Sublime PHP Code Sniffer is available for installation through Package Control. Just run the install package command and search for sublime-phpcs. When you first install the plugin, though, it won’t do much. Sublime PHP Code Sniffer relies on the following external tools to work its magic: • • • • •
PHP executable PHP_CodeSniffer PHP Mess Detector PHP Coding Standards Fixer Scheck
For sublime-phpcs to use these tools, you need to either ensure that they’re included in your system path or configure them directly in the plugin’s user settings file. You can see a list of the properties you’ll need to configure in the plugin’s default settings file, which you can open from the application menu by clicking Preferences | Package Settings | PHP Code Sniffer | Settings - Default. For more on configuring sublime-phpcs, visit the plugin’s GitHub page⁶.
Linting Configuration To use sublime-phpcs for basic linting, or syntax checking, you first need to make sure that PHP is installed on your local machine. Confirm that the PHP executable is available in your path by running command php --version. You’ll see the PHP version number and copyright information if PHP is set up correctly. Next, open the plugin’s user settings file by clicking Preferences | Package Settings | PHP Code Sniffer | Settings - User. Then set the phpcs_sniffer_run setting to false. After configuring sublime-phpcs on Windows 8, my user settings file looked like this:
⁶https://github.com/benmatselby/sublime-phpcs
127
PHP
1 2 3
{ "phpcs_sniffer_run": false }
The default plugin settings assume you have the external PHP Code Sniffer tool installed and configured, so the plugin won’t work for linting unless you disable sniffing. Basic Commands To see a list of commands for sublime-phpcs, launch the Command Palette and type sniffer:
Listing available commands.
By default, the plugin runs through all of the enabled checks whenever you save a file. The Turn Execute On Save On and Turn Execute On Save Off commands toggle this behavior. The Sniff this file command allows you to check a file without saving it. Clear sniffer marks hides any errors in your file, and the Goto next error‘ and Show previous errors commands allow you to quickly navigate between issues. You can also execute sublime-phpcs commands by right-clicking in the editing panel. Usage To try out linting in sublime-phpcs, open a file with a php extension, add a syntax error to the PHP code, and save the file. Out of the box, sublime-phpcs is configured to check your file every time
128
PHP
you save it, so it will highlight the error and display it in a quick panel:
Linting highlights syntax errors.
The PHP linter checks your file line by line and stops when it encounters an error, so sublime-phpcs will only display the first error it finds. The parser error message displays in the status bar when you click on a highlighted error. Take both the error message and the line highlighting with a grain of salt, though. Often, the real problem is a typo a line or two above the highlighted “error.”
Code Sniffing The sublime-phpcs plugin really begins to shine when you enable its PHP_CodeSniffer integration. PHP_CodeSniffer is a tool that analyzes your code files, looking for common syntax errors and coding standard violations. It can help you write cleaner, more consistent code. Configuration PHP_CodeSniffer⁷ is an external tool written in PHP. Installation varies by operating system, but the easiest way to get it running is using the PEAR package manager. I used these instructions⁸ to set it up on my Windows 8 machine. ⁷http://pear.php.net/package/PHP_CodeSniffer ⁸http://kogentadono.com/2012/10/08/installing-php-5-4-and-php-codesniffer-on-windows/
PHP
129
Once PHP_CodeSniffer is installed, you’ll probably need to tell the sublime-phpcs plugin where to find the tool by setting the phpcs_executable_path setting in your sublime-phpcs user settings file. Here’s what my user settings file looked like with PHP_CodeSniffer configured on Windows 8: 1 2 3 4
{ "show_debug": true, "phpcs_executable_path": "C:\\PHP\\v5.4\\phpcs.bat" }
The "show_debug": true line is optional, but it helped me figure out what I should include in the executable path setting. When this setting is true, sublime-phpcs prints error messages in Sublime’s console when it can’t find the PHP_CodeSniffer tool. If you disabled sniffing as described in the section on linting, make sure to remove the "phpcs_sniffer_run" : false setting in your user settings file. You can pass configuration arguments to PHP_CodeSniffer using the phpcs_additional_args setting. Here’s an example that switches PHP_CodeSniffer from the default PEAR standards to the Zend standards and suppresses warnings: 1 2 3 4 5 6 7 8
{ "show_debug": true, "phpcs_executable_path": "C:\\PHP\\v5.4\\phpcs.bat" "phpcs_additional_args": { "--standard": "Zend", "-n": "" } }
Usage When sublime-phpcs is configured to autorun on save, the workflow for correcting standards violations and coding errors is quite smooth. To illustrate, let’s run the the plugin.php page from the WordPress Plugin Boilerplate through PHP_CodeSniffer and see what it finds:
130
PHP
Sniffing this file found dozens of standards violations.
PHP_CodeSniffer is complaining about multiple violations per line, including missing documentation, use tabs for indentation instead of spaces, method naming conventions, commenting styles and brace formatting. The tabs issue is easy to address: Just run Indentation: Convert to Spaces from the Command Palette. When you save the changes, sublime-phpcs reruns PHP_CodeSniffer and displays the remaining errors in a quick panel. Selecting an error lets you jump directly to the relevant line, where you can make the correction before saving the file and starting the cycle over again. You can also use the Goto next error command to fix multiple errors before saving, or run Show previous errors to bring up the quick panel list again.
Documenting Your Code Well-written documentation is an asset to any code base–as long as the documentation is consistent and kept up to date. Stale documentation is worse than none at all: It lulls you into a false sense of confidence with its lies. Keeping the documentation close to the code it describes makes it more likely that you’ll update it to reflect changes in the code, and the popular PHPDoc⁹ plugin enables you to do just that. ⁹http://phpdoc.org/
131
PHP
PHPDoc is a tool that allows you to document your classes, variables and functions with comments, then generate nicely formatted HTML documentation that’s easy to share, search and read. Several Sublime plugins offer PHPDoc support, but by far the most popular is DocBlockr¹⁰. DocBlockr will help you: • Format block comments by inserting leading asterisks, maintaining indentation and automatically closing the comment. • Document functions by extracting parameter names from the function, including type-hinted variables and default values. • Remember PHPDoc tag names by providing completions for all supported tags.
Setup Getting DocBlockr up and running is just a matter of installing the plugin via Package Control. Search for DocBlockr.
Usage DocBlockr helps with creating new block comments and adding to existing ones. To insert a new block comment, type the opening /** or /*and hit Enter: ¹⁰https://github.com/spadgos/sublime-jsdocs
132
PHP
Creating a new block comment.
And you can add to an existing comment by simply pressing Enter to insert a new line:
133
PHP
Extending an existing comment.
When you start a double-asterisk comment on a line that immediately precedes a function definition, DocBlockr inserts a block comment with placeholder fields for the function description, parameters and return value:
134
PHP
Documenting a function.
You can quickly fill out the template by using Tab to jump from field to field. DocBlockr also tries to make educated guesses about parameter data types based on type hinting or default values, and it examines the function name for clues about the data type of the return value. If you start a new double-asterisk comment on the line above a variable declaration, the plugin guesses at the variable’s data type:
135
PHP
Documenting a variable.
The plugin also provides autocompletions and snippets for PHPDoc tags¹¹, such as @author, @implements and @namespace. Typing @author and hitting Tab inserts a snippet with placeholders for the author name and email address: ¹¹http://www.phpdoc.org/docs/latest/for-users/phpdoc/tag-reference.html
136
PHP
DocBlockr includes snippets for PHPDoc tags.
If you get interrupted while filling out a comment block, leaving a bunch of uncompleted placeholder fields in your comment, just place the cursor back in the comment and run the Reparse comment block command. DocBlockr will detect the remaining fields and allow you to quickly cycle through them with the Tab key.
Building Documentation DocBlockr doesn’t provide support for generating HTML documentation with PHPDoc, but you can easily do this yourself with a custom Sublime build task. First, you’ll need to ensure that the PHPDoc command line tool is available on your machine. The easiest way to install PHPDoc is using PEAR. Step-by-step instructions¹² are available on the PHPDoc site. Make sure you enable the XSL extension for PHP¹³, or you won’t be able to generate HTML documentation. Next, you’ll need to create a custom build system. Click Tools | Build System | New Build System …. Sublime creates a new file with a sublime-build extension. If you’re using Windows, you can use PowerShell to execute the phpdoc command:
¹²http://phpdoc.org/docs/latest/for-users/installation.html ¹³http://php.net/manual/en/book.xsl.php
137
PHP
1 2 3 4
{ "cmd": ["powershell.exe", "phpdoc -d . -t docs"], "shell": true }
When you save the sublime-build file, Sublime will default to the User directory. Save it as PhpDoc.sublime-build. To generate HTML documentation for your project, make sure you’re editing a PHP file in the project, then click Tools | Build System | PhpDoc to switch the build system to your new PHPDoc command. Then click Tools | Build. Sublime displays the build output in the console, as well as any errors that occurred while compiling the documentation:
Build errors appear in the console.
PHPDoc creates a new docs folder in the project’s root directory that contains the HTML output, as well as the CSS and JavaScript required to display the documentation:
138
PHP
PHPDoc generates attractive documentation from your commented code.
Getting Help Chances are, the more experience you gain as a programmer, the quicker you’ll to turn to Google when you’re stumped. If you’d like to make it easier to look up the help you need, you have several options.
Goto Documentation When you need more info about a built-in function or keyword, it’s hard to beat the simplicity of the Goto Documentation plugin¹⁴, which is available for installation in Package Control. Once you’ve installed the plugin, position your cursor in the keyword or function you’d like to look up, then run the Goto Documentation command from the command palette. Goto Documentation will open the relevant documentation in a new tab in your default browser. ¹⁴https://github.com/kemayo/sublime-text-2-goto-documentation
PHP
139
Stack Overflow Stack Overflow¹⁵ is arguably the best resource for programmers on the Internet, and it’s the first place I turn when I find myself stuck on a hard problem. The Stack Overflow plugin¹⁶ makes it even easier to use by allowing you to launch a search directly from Sublime. To search on a code snippet, highlight the relevant text and right-click the selection, then click Stack Overflow Search. Or you can run Stackoverflow: Search Selection from the command palette. To enter a query manually, run the Stackoverflow: Search from Input command. The plugin opens a new tab in your default browser with the results of your search. ¹⁵http://stackoverflow.com ¹⁶https://github.com/ericmartel/Sublime-Text-2-Stackoverflow-Plugin
24. SASS and SCSS SASS¹, short for Syntactically Awesome Style Sheets, is a massively popular tool for web developers that takes a lot of the pain out of writing CSS. Unfortunately, Sublime doesn’t provide a lot of help if you want to use SASS in your project. Package Control lists a number of seemingly useful plugins, but each provides just one or two SASS features–none of them gives you everything you need to use SASS effectively. Then there’s the whole compiling thing–messing with a separate command line tool every time you want to make a CSS tweak is a royal pain. Here’s the setup I use that makes working with SASS as seamless as using plain old CSS.
Preliminaries Since this isn’t a SASS 101 tutorial, I’m going to assume that you’ve already installed SASS and know how to use the command line compiler. If not, here’s a good walkthrough². I’m also assuming that you have Package Control set up in Sublime. If you haven’t encountered it yet, Package Control lets you install hundreds of plugins with just a few keystrokes–without leaving Sublime. The Package Control site³ includes setup instructions.
¹http://sass-lang.com/ ²http://www.metropoliscreative.com/web-development/how-to-install-sass-an-easy-guide-for-developers/ ³http://wbond.net/sublime_packages/package_control/installation
141
SASS and SCSS
Syntax Highlighting The first time you open a sass or scss file, Sublime just shrugs its shoulders and treats it like plain text, rendering your meticulously formatted style rules in monotonous black and white.
Sublime treats SASS and SCSS like plain text by default.
Package Control lists a handful of plugins that add syntax highlighting for SASS. The runaway favorite is the sass-textmate-bundle plugin⁴, called simply Sass in Package Control.
⁴https://github.com/nathos/sass-textmate-bundle
142
SASS and SCSS
After you install the Sass plugin, when you open a scss file you’re greeted with beautifully highlighted code:
The Sass plugin adds syntax highlighting.
But don’t celebrate yet–if you open a sass file, you’ll find it still devoid of color. What gives? If you look in the lower right-hand corner of the screen, you’ll see a clue:
143
SASS and SCSS
A Rails configuration file causes Sublime to treat SASS like HAML.
As it turns out, a line in the Data/Packages/Rails/Ruby Haml.tmLanguage file is hijacking the sass extension and incorrectly setting the syntax to Ruby Haml instead of Sass. I’ve seen “fixes” for this problem that involve editing the Ruby Haml.tmLanguage file itself, or one of the files in the SASS plugin. That’s a bad idea because future updates to either of those packages will overwrite your customization, and you’ll be back where you started. Fortunately, the simplest fix is also the best: Sublime allows you to specify what syntax to use for a given file extension. To force Sublime to correctly highlight sass files: 1. Open a sass file. 2. Click View | Syntax | Open all with current extension as … | Sass.
SASS and SCSS
144
Compiling Messing with the command line SASS compiler is a bit of a hassle–and it’s unnecessary. With help from a couple of plugins, you can configure Sublime to automatically compile your SASS stylesheets every time you save a change. Sublime’s build system feature allows you to create custom build tasks and associate them with specific file types. You can do this by hand in your sublime-project file, or you can let the SASS Build plugin⁵ handle the heavy lifting for you. Installing the SASS Build plugin creates two new entries under Tools | Build: Sass and Sass Compressed. Compiling your SASS files with this plugin is simple. While editing a sass or scss file, just hit Ctrl+B on Windows or Linux or Command+B on OS X. By default, Sublime will use the regular Sass build option, which compiles your SASS and formats the CSS output for easy readability. To create minified CSS files for production, change the build option by clicking Tools | Build | Sass - Compressed.
Changing the Output Directory SASS Build puts the compiled CSS in the same directory as the source file. If you’d like to override this location–maybe you prefer your CSS to live in a separate folder called css that you don’t check into source control–you’ll need to specify your own custom build system in your project file. Open the project for editing by clicking Project | Edit Project, then add the following to the build_systems array: 1 2 3 4 5 6 7 8 9 10 11 12
"build_systems": [ { "name": "Sass", "cmd": [ "sass", "--update", "$file:${file_path}/../css/${file_base_name}.css" ] } ]
For an example sublime-project file with a custom build system specified, see https://gist.github.com/5427477. ⁵https://github.com/jaumefontal/SASS-Build-SublimeText2
SASS and SCSS
145
Preventing Compiled Output from Appearing in Project Wherever you choose to output your compiled CSS, Sublime will automatically show the files in the side bar and in the Goto Anything list. You may like being able to open and browse the CSS itself, but I find it annoying. For one thing, it puts two almost identically named files in the Goto Anything file list: widget.scss and widget.css. And it’s not hard to absent-mindedly edit the css file by mistake, only to see your changes blown away when the file is recompiled later. It’s easy to tell Sublime to ignore the output files, though. To ignore all CSS files in your project, modify the folders section of your sublime-project file: 1 2 3 4 5 6 7
"folders": [ { "/", "file_exclude_patterns": ["*.css"] } ]
To exclude a custom css output folder, add the following to your project file: 1 2 3 4 5 6 7
"folders": [ { "path": "/", "folder_exclude_patterns": ["css"] } ]
To ignore CSS files only in a specific subdirectory, add the subdirectory’s path to the file_exclude_patterns entry: 1 2 3 4 5 6 7
"folders": [ { "path": "/", "file_exclude_patterns" : ["src/styles/*.css"] } ]
For an example sublime-project file with a folder-level exclusion, see https://gist.github.com/5427477.
SASS and SCSS
146
Automating Compilation Building your SASS files straight from Sublime is convenient, but at some point you’re going to spend 30 minutes debugging a crazy stubborn CSS issue only to realize that you actually fixed it 25 minutes ago and just forgot to recompile the scss file. Not that I’m bitter or anything. You can avoid this by installing the SublimeOnSaveBuild plugin⁶, which will automatically execute the default build action whenever you save changes to a file. (It’s also handy when you’re working with CoffeeScript.) SublimeOnSaveBuild supports a filename filter, and by default it’s only configured to run for css, js, sass, less and scss files.
⁶https://github.com/alexnj/SublimeOnSaveBuild
Keyboard Shortcuts Windows Command Jump Back Jump Forward Goto Definition Goto Line Goto Symbol Goto Symbol in Project Paste from History Default Layout Two-Row Layout Three-Row Layout Two-Column Layout Three-Column Layout Four-Column Layout Two-by-Two Grid Layout New Group Move File to New Group Close Group Focus Next Group Focus Previous Group Focus Group 1-9 Move to Next Group Move to Previous Group Move to Group 1-9 Record Macro, Stop Recording Macro Playback Macro
Shortcut Alt+Alt+Shift+F12 Ctrl+G Ctrl+R Ctrl+Shift+R Ctrl+K, Ctrl+V Alt+Shift+1 Alt+Shift+8 Alt+Shift+9 Alt+Shift+2 Alt+Shift+3 Alt+Shift+4 Alt+Shift+5 Ctrl+K, Ctrl+Up Ctrl+K, Ctrl+Shift+Up Ctrl+K, Ctrl+Down Ctrl+K, Ctrl+Right Ctrl+K, Ctrl+Left Ctrl+1 - Ctrl+9 Ctrl+K, Ctrl+Shift+Right Ctrl+K, Ctrl+Shift+Left Ctrl+Shift+1 - Ctrl+Shift+9 Ctrl+Q Ctrl+Shift+Q
Side Bar |:-:|:-:| |Command|Shortcut| |Focus the Side Bar|Ctrl+0| |Highlight next file or folder|Down| |Highlight previous file or folder|Up| |Expand highlighted folder|Right| |Collapse highlighted folder|Left| |Open highlighted file|Enter|
OS X
148
Keyboard Shortcuts
Command Jump Back Jump Forward Goto Definition Goto Line Goto Symbol Goto Symbol in Project Paste from History Default Layout Two-Row Layout Three-Row Layout Two-Column Layout Three-Column Layout Four-Column Layout Two-by-Two Grid Layout New Group Move File to New Group Close Group Focus Next Group Focus Previous Group Focus Group 1-9 Move to Next Group Move to Previous Group Move to Group 1-9 Record Macro, Stop Recording Macro Playback Macro
Shortcut Ctrl+Ctrl+Shift+F12, Command+Alt+Down Ctrl+G Command+R Command+Shift+R Command+K, Command+V Option+Command+1 Shift+Option+Command+2 Shift+Option+Command+3 Option+Command+2 Option+Command+3 Option+Command+4 Option+Command+4 Command+Up Command+Shift+Up Command+Down Command+Right Command+Left Ctrl+1 - Ctrl+9 Command+Right Command+Left Ctrl+Shift+1 - Ctrl+Shift+9 Ctrl+Q Ctrl+Shift+Q
Side Bar |:-:|:-:| |Command|Shortcut| |Focus the Side Bar|Ctrl+0| |Highlight next file or folder|Down| |Highlight previous file or folder|Up| |Expand highlighted folder|Right| |Collapse highlighted folder|Left| |Open highlighted file|Return|
Linux
149
Keyboard Shortcuts
Command Jump Back Jump Forward Goto Definition Goto Line Goto Symbol Goto Symbol in Project Paste from History Default Layout Two-Row Layout Three-Row Layout Two-Column Layout Three-Column Layout Four-Column Layout Two-by-Two Grid Layout New Group Move File to New Group Close Group Focus Next Group Focus Previous Group Focus Group 1-9 Move to Next Group Move to Previous Group Move to Group 1-9 Record Macro, Stop Recording Macro Playback Macro
Shortcut Alt+Alt+Shift+F12 Ctrl+G Ctrl+R Ctrl+Shift+R Ctrl+K, Ctrl+V Alt+Shift+1 Alt+Shift+8 Alt+Shift+9 Alt+Shift+2 Alt+Shift+3 Alt+Shift+4 Alt+Shift+5 Ctrl+K, Ctrl+Up Ctrl+K, Ctrl+Shift+Up Ctrl+K, Ctrl+Down Ctrl+K, Ctrl+Right Ctrl+K, Ctrl+Left Ctrl+1 - Ctrl+9 Ctrl+K, Ctrl+Shift+Right Ctrl+K, Ctrl+Shift+Left Ctrl+Shift+1 - Ctrl+Shift+9 Ctrl+Q Ctrl+Shift+Q
Side Bar |:-:|:-:| |Command|Shortcut| |Focus the Side Bar|Ctrl+0| |Highlight next file or folder|Down| |Highlight previous file or folder|Up| |Expand highlighted folder|Right| |Collapse highlighted folder|Left| |Open highlighted file|Enter|