Sublime text

Page 1


Sublime Productivity Code Like a Pro with Today’s Premier Text Editor Josh Earl ©2012 - 2013 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/#sublimetext


Contents Special Offer for TradePub Readers: Get Future Updates at a 20% Discount . . . . . . . .

i

Contact Me . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ii

Free Weekly Productivity Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

iii

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 . . . . . . . . . . . . . . . . . .

. . . . . . . .

iv iv iv iv iv iv v v

Did you get this book for “free”? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

vi

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 . . . .

8 9 9 9

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . . . .

. . . .

. . . .


CONTENTS

Disabling Remember Open Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9

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

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

21 21 21 21 22 22 22 22 23 23 23 24 24 24 24 25 25 25 26 26

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .


CONTENTS

Split View of a Single File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

26

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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

56

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . .


CONTENTS

Goto . . . . . . . . . . . . . . . . . . . Goto Anything . . . . . . . . . . . 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 . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

56 56 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


CONTENTS

12 Autocomplete . . . . . . Basic Usage . . . . . . . Suggestions List . . . . . Disabling Auto Complete Wrap Selection with Tag Close Tag . . . . . . . . Shortcuts . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

76 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


CONTENTS

IV Customizing the Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 16 Command Palette Tweaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuration Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

96 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 .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

106 106 106 106

V

. . . .

. . . .

. . . .

Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

20 Essential Plugins . . . . . . . Extend Menus for the Sidebar File Creation . . . . . . . . . . HTML Generation . . . . . . . Blogging . . . . . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

108 108 108 108 109

21 Cross-Platform Syncing of Settings and Plugins . . . . . . . . . . . . . . . . . . . . . . 110 22 PHP . . . . . . . . . . . . . . . . . Setting up a New Project . . . . . . Fetch Installs Libraries for You Installing Fetch . . . . . . . . . Configuring Fetch . . . . . . . Using Fetch . . . . . . . . . . . Code Checking . . . . . . . . . . . Setup . . . . . . . . . . . . . . Linting . . . . . . . . . . . . . Configuration . . . . . . Basic Commands . . . . Usage . . . . . . . . . . Code Sniffing . . . . . . . . . . Configuration . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

112 112 112 113 113 114 116 117 117 117 118 118 119 119


CONTENTS

Usage . . . . . . . Documenting Your Code . . . Setup . . . . . . . . . . . Usage . . . . . . . . . . . Building Documentation Getting Help . . . . . . . . . . Goto Documentation . . Stack Overflow . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

120 121 122 122 127 129 129 130

23 SASS and SCSS . . . . . . . . . . . . . . . . . . . . . . . . . Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . Syntax Highlighting . . . . . . . . . . . . . . . . . . . . . . . Compiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing the Output Directory . . . . . . . . . . . . . . Preventing Compiled Output from Appearing in Project Automating Compilation . . . . . . . . . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

131 131 132 135 135 136 137

Keyboard Shortcuts Windows . . . . Side Bar . . . OS X . . . . . . . Side Bar . . . Linux . . . . . . . Side Bar . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

138 138 138 138 139 139 140

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . . .

. . . . . . .

. . . . . . .


Special Offer for TradePub Readers: Get Future Updates at a 20% Discount Sublime Productivity is packed with tips that’ll help you master Sublime Text, but there’s even more on the way. I publish regular updates to the book, and in the coming weeks I’m planning to cover: • Editing more efficiently with vintage mode • Creating your own Sublime plugins • The best tweaks and plugins for Ruby, JavaScript and PHP development And for a limited time, you can grab these future upgrades at a 20% discount. Just head over to http://sublimeproductivity.com¹ and enter discount code TRADEPUB at checkout for 20% off the minimum price. This offer is only good through September 21, 2013, so claim your discount today². ¹http://sublimeproductivity.com ²http://sublimeproductivity.com


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 josh@sublimeproductivity.com.


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

v

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://www.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://www.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, its 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’s come in handy a couple of times, 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: "file_exclude_patterns": ["*.css", "*.js"]

Alternately, you could exclude the entire compiled styles folder with the following:


Projects

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: "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: "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

{ "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. Sublime will restore your unsaved work even if you close and restart the app. This is a nice fallback in case of system crashes or dumb mistakes. 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: $(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: $(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: $(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: <ul> <li>The Office</li> <li>Fringe</li> <li>Touch</li> </ul>

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: The Office Fringe Touch

To wrap these items in li elements, you could record a macro where you typed the opening <li> tag, jumped to the end of the line, typed the </li> 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 <li> tag.


43

Selecting Text

4. Press End. 5. Type the closing </li> 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: <li <li <li <li <li

class="current">The Office</li> class="current">Fringe</li> class="current">Touch</li> class="reruns">24</li> class="reruns">The X Files</li>

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: $(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: <ul> <li>The Office</li> <li>Fringe</li> <li>Touch</li> </ul>

To perform this task, I can simply select the characters <li in the first element, then press invoke Quick Add Next twice to select the next two occurrences. Once all of the elements are highlighted, I press Right Arrow to cancel the selection and type class="tv-shows". To invoke Quick Add Next: 1. Select the text you’d like to change. 2. Click Find | Quick Add Next in the application menu. Or press Command+D on Mac OS X or Ctrl+D on Windows or Linux.


46

Selecting Text

Quick Skip Next When making multiple selections with Quick Add Next, it’s often useful to skip one or more occurrences of the word you’re replacing. The Quick Skip Next allows you to jump over the next instance of the word you’re selecting. For example, let’s say we would like to apply a CSS class to our list of TV shows to style the series that are in reruns differently from the ones that are still running: <ul> <li <li <li <li <li <li </ul>

class="shows">The Office</li> class="shows">The A Team</li> class="shows">Fringe</li> class="shows">The X Files</li> class="shows">Touch</li> class="shows">Knight Rider</li>

Starting on the first list item, I position the cursor in the word shows, then invoke Quick Add Next twice to highlight the class name and move down a line, then Quick Skip Next twice, then invoke Quick Add Next, then Quick Skip Next, resulting in the following selection:

Quick Add Next and Quick Skip Next work together


47

Selecting Text

The name Quick Skip Next is a little misleading. A better name might just be “quick skip.” When I started playing with this feature, I expected that highlighting a match and then invoking Quick Skip Next would immediately skip the second item and highlight the third. Instead, what happens is that Sublime unhighlights the current line and jumps to the next match. Once I understood it was simple to make the selections I was after.

To invoke Quick Skip Next: 1. Invoke Quick Add Next until you’ve highlighted an instance of the word that you want to skip. 2. Press Command+K, Command+D on Mac OS X or Ctrl+K, Ctrl+D on Windows or Linux.

Column Selection Copying and pasting code from the Internet is bad, right? But we all do it sometimes. If you’re as guilty as I am, you’ve probably copied a code snippit into your file, only to find that some hard-coded line numbers came with it: 1. 2. 3.

$(function() { console.log("Check out my mad copy and paste skillz."); });

Column Selection is tailor made for this situation and similar scenarios where you need to quickly perform a similar edit on multiple lines. Invoking Column Selection while pressing Up Arrow or Down Arrow adds a second cursor on the line above or below the current line, and pressing Left Arrow or Right Arrow extends the selected area to the left or right. Some text editors call this “box selection” because you can click and drag to select a square-shaped area. One difference between the traditional box selection feature in most editors and Sublime’s implementation is a result of Sublime’s multiple cursor editing feature. If you box select a group of lines of differing lengths, Sublime will insert a cursor at the endof each line, which breaks out of the column selection behavior:


48

Selecting Text

Column selecting whole lines results in cursors at the end of each line

This is useful for quickly appending text to the end of several lines. To use Column Selection with the mouse: • On Mac OS X, press and hold Option while dragging around the desired selection. On Windows and Linux, click and hold the scroll wheel while clicking while dragging around the desired selection. To use Column Selection via the keyboard: 1. Press Ctrl+Shift+Down Arrow or Ctrl+Shift+Up Arrow on Mac OS X or Ctrl+Alt+Down Arrow or Ctrl+Shift+Up Arrow on Windows or Linux. 2. Use Shift+Left Arrow and Shift+Right Arrow to expand the selection horizontally.

Once a selection area is defined, you can move it around as a unit with the arrow keys.


49

Selecting Text

Invert Selection Occasionally you may find that you want to delete the contents of a file and keep just a few lines. Or maybe you’re cleaning up some text and realize that it would be simpler to select the text you want to retain. The Invert Selection command is ideal for these scenarios. As its name implies, Invert Selection will deselect any text that was highlighted and simultaneously select the text that was not previously highlighted. By combining Invert Selection with multi-select or regular expressions and a little creativity, you can quickly accomplish tasks like zapping unwanted lines in a data file or stripping HTML tags from a block of text.

Version Difference! The Invert Selection command is new in Sublime Text 3.

Let’s look at a few scenarios where Invert Selection might be useful.

Cleaning up CSV data Even with Sublime’s multi select, it’s often a pain to select text for deletion. To extract first names from the following CSV list, you could use multi-select to carefully highlight the last name and comma in each row: Knope,Leslie Swanson,Ron Haverford,Tom Perkins,Ann Ludgate,April

But a simpler alternative is to use multi-select to highlight all the first names, then click Selection | Invert Selection to highlight the unwanted text for deletion.

Filter unwanted lines By combining Find and Invert Selection, you can easily filter out lines that don’t match a pattern, such as deleting everyone not named Josh in the following list:


Selecting Text

50

Knope,Leslie Earl,Josh Swanson,Ron Haverford,Tom Perkins,Ann Turner,Josh Ludgate,April

Open the Find panel and enable the Regular expression option, then enter the following regular expression, which matches all lines containing the word Josh: ^.*Josh

Click Find All to highlight the two matching lines. Run Invert Selection, then click Edit | Text | Delete Line to eliminate the non-matching lines.

Strip HTML tags With another regex, Invert Selection can remove HTML tags from a block of text. Let’s clean up a section of the Sublime release notes: <span style="font-size: 10pt">Release Date: 8 July 2013</span> <ul> <li>Removed expiry date</li> <li>Backported various fixed from Sublime Text 3</li> <li>Improved minimap click behavior. The old behavior is available via the <t\ t>minimap_scroll_to_clicked_text</tt> setting</li> <li>Added <tt>copy_with_empty_selection</tt> setting, to control the behavior\ of the copy and cut commands when no text is selected</li> </ul>

Launch Find and make sure the Regular expression option is enabled. Enter the following regex, which matches text that’s wrapped with HTML tags: (?<=>)(.+?)(?=<)

Click Find All to select the text between the tags. Then run Invert Selection, highlighting the tags for deletion.


Selecting Text

51

Scoped Selection When I’m coding, I often want to select all of the text inside of a set of matching parentheses, brackets or curly braces, maybe to change the parameters in a method call or delete the body of a function. There’s always the mouse or just Shift+Left Arrow or Shift+Right Arrow, but Sublime offers a more elegant solution: scoped text selection. When using scoped selection, repeatedly hitting a single keyboard shortcut will first select the text inside of the current set of braces or parentheses, then expand the selection out to include the next set of braces, and so on, all the way up to selecting the entire contents of the file. Sublime understands several different types of scopes, depending on the context: • • • • • •

Word Line Paragraph Brackets Indentation level Tag

Words To use Expand Selection to Word: 1. Position the cursor in the word you’d like to select. 2. Click Selection | Expand Selection to Word. Or press Command+D on Mac OS X or Ctrl+D on Windows or Linux.

Lines To use Expand Selection to Line: 1. Position the cursor in the line you’d like to select. 2. Click Selection | Expand Selection to Line. Or press Command+L on Mac OS X or Ctrl+L on Windows or Linux.


52

Selecting Text

Paragraphs To use Expand Selection to Paragraph: 1. Position the cursor in the paragraph you’d like to select. 2. Click Selection | Expand Selection to Paragraph. If you find yourself using this command frequently, consider mapping it to a keyboard shortcut.

Brackets The Expand Selection to Brackets command will select any text that falls inside the current set of parentheses, square brackets or curly braces. When invoked repeatedly, it will then select the brackets themselves, then select inside the next set of matching brackets, and so on. It’s a convenient way to highlight method parameters and whole code blocks with a single shortcut. To use Expand Selection to Brackets: 1. Position the cursor inside a set of matching parentheses, brackets or braces. 2. Click Selection | Expand Selection to Brackets. Or press Ctrl+Shift+M.

Indentation Levels The Expand Selection to Indentation Level command is useful for programming in languages that don’t use a lot of braces and brackets like Ruby, CoffeeScript, Python and SQL. Selecting the body of the CoffeeScript function is a snap with this command: $ -> executeDumpsterJump() console.log("Parkour!")

To use Expand Selection to Indentation Level: 1. Position the cursor anywhere in a line at the indentation level you’d like to select. 2. Click Selection | Expand Selection to Indentation Level. Or press Shift+Command+J on Mac OS X, or Ctrl+Shift+J on Windows or Linux.

Tags If you code a lot of HTML or XML, the Expand Selection to Tag command is worth committing to memory. A quick example will illustrate the two main uses of this command. Take a look at the following form:


53

Selecting Text

<h1>Contact Me</h1> <form method="post"> <input type="text" name="username"></input> <input type="text" name="email"></input> </form>

When the cursor is positioned inside an opening or closing tag, such as the h1 tags in the example, invoking Expand Selection to Tag will highlight the contents of the tags, including any text and inner HTML they may contain. In this case, it selects the text Contact Me. Position the cursor on the text or inner HTML within a tags, such as in the opening tag for the username field, and the command selects neighboring content that falls within the the wrapping parent tag. Here, it selects both input elements because they fall inside the form tag. Repeatedly invoking the command expands the selection outward, first selecting the enclosing tags themselves, then the contents of the next set of parent tags, and so on until it reaches the root element. To use Expand Selection to Tag: 1. Position the cursor within the text you’d like to select. 2. Click Selection | Expand Selection to Tag. Or press Shift+Command+A on Mac OS X, or Ctrl+Shift+A on Windows or Linux.

Expand to Scope The Expand Selection to Scope command is a quick, catch-all selection tool that is easier to remember than the more specialized selection commands, and most of the time it does the right thing. Starting from the current cursor position, Expand Selection to Scope works its way outward until it finds a logical stopping place for the selection, such as a containing set of parentheses. This is perfect for selecting the parameters in a method call. Invoke it again, and it’ll look for the next broadest scope, and so on, until the entire file is selected. Let’s try some selections on a simple jQuery snippet to get a better idea of how this works in practice. I’ll start by placing the cursor inside of the parentheses for console.log():

Starting cursor position


54

Selecting Text

Invoking Expand Selection to Scope selects all of the text inside of the parentheses:

First selection

Repeating the command expands the selection outwards and includes the parentheses:

Second selection

I can keep walking up to wider scopes to include the curly braces for the anonymous function:

Third selection

And eventually the entire method body:

Fourth selection

To use Expand Selection to Scope: 1. Position the cursor within the text you’d like to select.


Selecting Text

55

2. Click Selection | Expand Selection to Scope. Or press Shift+Command+Space on Mac OS X, or Ctrl+Shift+Space on Windows or Linux.


10 Navigation Goto Under the Goto menu lives a collection of Sublime’s most useful navigation features. With these commands, you can quickly open any file in your current project by name, figure out where functions and variables are defined, and even open a file at a specific line number—all without taking your hands off the keyboard. Master these, and you’ll never again find yourself digging through subfolder after subfolder in the Side Bar.

What files do the Goto commands work on? In general, the Goto commands operate on: • All open tabs • Files included in folders that are open in the Side Bar • Files that live in folders that are part of the current project You can also exclude folders and files from the Goto commands by customizing your Sublime project. This is useful for languages like CoffeeScript and SASS, which by default compile coffee and sass files to js and css files with the same filename.

.

Goto Anything The Goto Anything command lets you quickly open files in your current project by searching for the file’s name. To use Goto Anything, click Goto | Goto Anything and enter part of the filename in a text input overlay. A list of matches appears, filtered by Sublime’s fuzzy matching algorithm. Keep typing until the file you want to open is at the top of the list, or use the arrow keys to highlight it, then press Enter to load the file in a new tab.


57

Navigation

Opening multiple files A new feature in Sublime Text 3 allows you to open multiple files without reopening the Goto Anything overlay. Highlighting the file name and pressing Right Arrow opens the file in a new tab and keeps the overlay open, ready for you to make another selection or modify your entry.

Goto Definition Keeping your code tidy often means breaking your code up into small, tightly focused bits, each with its own file. Organizing your project this way means it’s easier to jump into any one file and quickly understand its purpose. But there’s a downside. When you have dozens or hundreds of files to navigate, it’s challenging to remember where a variable or function was originally defined, leaving you to root around in the code with your favorite search tool. Goto Definition solves this problem by continuously scanning your code and building an index of function and class definitions. When you trigger Goto Definition, you’ll see a filterable list of matching definitions, allowing you to quickly jump to the exact line of code where you defined that function.

Version Difference! Goto Definition was introduced in Sublime Text 3.

To use Goto Definition, you’ll first need create a project, or at least open your project folder by dragging it into Sublime’s Side Bar. Goto Definition only indexes projects and folders—it won’t include arbitrary open tabs. Then position your cursor in a variable or function name and click Goto | Goto Definition. If there’s only one possible match, you’ll jump straight to it, otherwise Sublime will display a filterable list of possible matches. As you highlight matches in the list, you’ll see a preview of the file to help you decide which file is the one you’re looking for. If you change your mind, or if a peek at the preview is all you needed, hit Esc to return to your editing.

When does indexing run? Sublime immediately indexes a folder the first time you open it or add it to a project. Then it monitors the folder for changes and updates its index whenever you add or remove a file or when you save a change. It’ll even reindex changed files when you modify them in other programs or update to a new revision in your version control tool. Folder and project indexes are cached, so Sublime won’t reindex your project every time you open it.


58

Navigation

While the current file isn’t indexed until you save your changes, Goto Definition works on new functions and classes as soon as you create them.

How to monitor indexing Sublime’s indexing is fast—it finishes almost instantly on small projects, and even big projects don’t take long: Indexing the Ruby on Rails source code, 2,601 files in all, takes around 20 seconds on my ultrabook-class laptop. But if you think Sublime is choking while trying to index your project, or if you just want to see when Sublime’s indexer runs, open the Sublime console and enter sublime.log_indexing(True). Sublime will log a console message whenever indexing starts or finishes.

What’s include in the index? By default, Sublime indexes functions and classes. The default list of symbols to index is specified in the Symbol List.tmPreferences file, which is located in Default.sublime-package. The scope section of this file tells the indexer to include functions and types by default. Individual programming language packages can override this default in their tmLanguage files, the same files that control syntax highlighting.

Limitations Goto Definition uses Sublime’s language definition files to make decisions about what to include in the index. Since it’s just scanning your code for patterns and not actually compiling or executing it, you may notice some limitations as you use Goto Definition. For example, patterns used to simulate class-like behavior in JavaScript aren’t true types, so they’re not indexed. Triggering Goto Definition on a JavaScript variable may show a list of similarly named functions. And in C++ projects, Goto Definition won’t pick up methods that are defined in macros. Mixed-language projects highlight another limitation to this feature: Goto Definition is language agnostic. If you create two methods with the same name in different languages, both will show up in the list of options when you invoke Goto Definition.

Goto Line The Goto Line command jumps the cursor to the beginning of the specified line. It’s handy if you’re debugging some JavaScript in the browser and get an error with a line number. To use Goto Line, click Goto | Goto Line. An input overlay appears, prepopulated with a :. Enter the desired line number and hit Enter.


59

Navigation

Goto Symbol Sublime’s Goto Symbol command allows you to quickly jump to and select symbols like functions, classes and HTML elements in whatever file you’re currently editing. Goto Symbol displays a filterable list of all symbols in the file. Typing part of the function’s name filters the list using fuzzy matching, so you don’t have to type the entire function name. To use Goto Symbol while editing a file, click Goto | Goto Symbol. The input overlay appears, prepopulated with an @, as well as a list of all symbols in the file. Type part the desired symbol name and press Enter or Return when the correct symbol is highlighted. Sublime jumps to and selects the specified symbol. The Goto Symbol command is quite useful for some languages, less so for others: It’s great for JavaScript, pretty good for HTML, and not much help in C#. In a JavaScript file, you’ll see a list of all functions defined in the file. In an HTML file, the Goto Symbol list shows all elements with IDs, which makes sense but isn’t as powerful.

Goto Symbol in Project Goto Symbol in Project is closely related to the Goto Definition command. But while Goto Definition allows you to jump to the definition of the symbol under your cursor, Goto Symbol in Project lets you look up any arbitrary symbol by name, regardless of what file it’s defined in.

Version Difference! Goto Symbol in Project was introduced in Sublime Text 3.

To use Goto Symbol in Project, click Goto | Goto Symbol in Project …. An input overlay appears, along with a list of all indexed symbols. The symbols list supports fuzzy matching, so start typing until the symbol you’re interested in is highlighted. You’ll see a preview of the file in the current tab. Sublime highlights the line with the matching symbol and centers it in the screen. If only one definition for the selected symbol, hitting Enter opens the appropriate file and positions your cursor at the beginning of the symbol. If a symbol with the same name is defined in multiple files, hitting Enter or Return closes the symbols overlay and opens a filterable list of matching files. Press Up or Down to see previews of the files, then hit Enter again to open the one you want.

What symbols are included? Unlike Goto Definition, which only works on projects or open folders, Goto Symbol in Project also includes symbols found in open tabs that aren’t contained in an open folder.


Navigation

60

It does, however, use the same indexing strategy as Goto Definition. By default, Goto Symbol in Project lists types and functions, but individual languages can include additional symbols. For JavaScript, the symbol index is limited to named function definitions and functions that are assigned to objects as properties, while functions assigned to variables aren’t included. In Ruby projects, the symbols list includes class definitions, modules, and methods.

Limitations Like Goto Definition, Goto Symbol in Project doesn’t discriminate by language. If your project includes code in multiple languages, you’ll see their symbols mixed together regardless of which language you’re currently using. And if you create a symbol with the same name in two languages in the same project, Sublime will prompt you to choose which file contains the symbol you want.

Combining Goto commands You can combine Sublime’s file-specific Goto commands like Goto Line and Goto Symbol with Goto Anything to instantly navigate to any line of code in your project. Remember how some of the Goto commands just opened an input overlay that was prepopulated with a prefix character, like the : for Goto Line? By entering that special character when you’re using Goto Anything, you can open a file and jump right to a line, symbol or search term. Typing a : after the file name opens the file at the specified line number, so entering index:42 would open index.html at line 42. When you enter an @ after a file name, the options list changes to display a list of symbols available in the file. For example, typing script@ren might open script.js and jump to a function named render. Append the # symbol to a file name and the options list displays a list of keywords in the file. Inputting mailspec#send runs a search in mailbox.spec.js and jumps to the first match for the term send. As always, Goto commands combined in this way support fuzzy matching.

Jump Forward, Jump Back Powerful navigation commands like Goto Definition and Goto Symbol make it really easy to get disoriented. You hit a couple of keystrokes and suddenly you’re in the middle of a completely different file in who-knows-what folder. The Jump Back and Jump Forward commands make it easy to retrace your footsteps and remind yourself how the different pieces of code relate.


61

Navigation

Version Difference! Jump Back and Jump Forward were added in Sublime Text 3.

Every time you open a new tab or insert your cursor on a line of code, Sublime adds that location to a history stack. Jump Back and Jump Forward work like the back and forward buttons in a web browser, allowing you to navigate easily between points in your editing history. You can also use these commands to toggle back and forth between related sections of code in a long file, such as when you’re simultaneously modifying a function’s definition and its usage in that massive jQuery plugin file, or to switch between multiple related files, such as an HTML file and its style sheet. To use Jump Back to return to a previous edit point, click Goto | Jump Back. To navigate forward, click Goto | Jump Forward.

Limitations Jump Back and Jump Forward only work on open tabs. If you close a file, it drops out of your editing history. If you Jump Back to a previous edit point, then open another file, Sublime drops your Jump Forward history, and the new editing path replaces it. Also, Sublime only maintains your history for the current editing session. If you close the editor, the history is cleared.

Scrolling The Line Up and Line Down commands will nudge the screen up or down one line without moving the cursor, allowing you to peek at that one off screen line of code without losing your place. To invoke Line Up or Line Down: • Press Ctrl+Option+Up or Ctrl+Option+Down on Mac OS X, or Ctrl+Up or Ctrl+Down on Windows or Linux. The Scroll to Selection command will jump to an off screen selection, or, if you’ve selected a larger block of text, it will scroll to the bottom of the selected region. To invoke Scroll to Selection: • Click Goto | Scroll | Scroll to Selection. Or press Ctrl+L on Mac OS X or Ctrl+K, Ctrl+C on Windows or Linux.


62

Navigation

Code Folding If you’re not familiar with it, code folding collapses multiple lines of code together, allowing you to hide some of the code’s details while you look at the bigger picture. Folding up all the major functions in a big JavaScript file, for example, can produce an outline-like view of the file, helping you understand the file at a high level. Sublime supports folding in many languages, including “curly brace” languages like JavaScript and markup languages like HTML and XML. Sublime generally leaves the first and last lines of a folded section of code visible, and the hidden lines are replaced with a marker that resembles the three dots in an ellipsis. When code is folded, you can accidentally delete all of the hidden code by deleting the fold marker.

Fold The Fold command collapses the block-level scope that surrounds the cursor’s current position. Huh? If you’re inside a function block, Sublime will collapse the function. However, if you’re editing an if statement nested inside of a function block, Sublime will fold the if block first. Triggering Fold again will fold the entire function. To invoke Fold: • Click Edit | Code Folding | Fold. Or press Option+Command+[ on Mac OS X or Ctrl+Shift+[ on Windows or Linux. Sublime seems to rely on white space to determine how to fold sections of code. If code folding isn’t working as expected, confirm that you’ve indented everything properly.

Fold Level The Fold Level commands allow you to collapse all code blocks at a particular indentation level. So Fold Level 3 will fold only if statements, functions and other types of blocks that are indented by three tab widths. Sublime supports folding at indentation levels 2 through 9. If you find yourself wishing you could fold more than 9 levels of nested code, now is a good time to sit quietly and think about the choices you’re making in life. To fold everything that’s indented by three tab widths:


Navigation

63

• Click Edit | Code Folding | Fold Level 3. Or press Command+K, Command+2 on Mac OS X or Ctrl+K, Ctrl+2 on Windows or Linux.

Fold All The Fold All command will fold everything that is indented one tab width. Fold All seems like a misnomer, as this command doesn’t recursively fold nested code blocks as the name implies. Think of it as Fold Level 1 instead and it makes more sense. To invoke Fold All: • Click Edit | Code Folding | Fold All. • Or press Command+K, Command+1 on Mac OS X or Ctrl+K, Ctrl+1 on Windows or Linux.

Fold Tag Attributes The Fold Tag Attributes command is a lifesaver when you’re editing cluttered HTML and XML documents. By hiding each tag’s attributes, it brings the structure and content of your document to the fore when you’re looking for missing tags or editing a piece of content in a document with horrendous inline styling (shudder).


Navigation

To invoke Fold Tag Attributes: • Click Edit | Code Folding | Fold Tag Attributes.

64


Navigation

65

Or press Command+K, Command+T on Mac OS X or Ctrl+K, Ctrl+T on Windows or Linux. Use the Unfold and Unfold All commands to expand sections of your document as needed.

Unfold Use the Unfold command to open a single folded item, such as a function definition. Any folded code that’s nested inside this block, such as an if statement, will remain folded. To invoke Unfold: 1. Position the cursor in the statement or element you’d like to expand. 2. Click Edit | Code Folding | Unfold. Or press Option+Command+] on Mac OS X or Ctrl+Shift+] on Windows or Linux.

Unfold All Unfold All unfurls all the folds you’ve made throughout your file. It’s a reset button when you want to view the file as a whole again. To invoke Unfold All: • Click Edit | Code Folding | Unfold All. Or press Command K, Command J on Mac OS X or Ctrl+K, Ctrl+J on Windows or Linux.

Bookmarks When you’re jumping around between several sections in a large file, bookmarks provide a convenient way to mark the sections you’re interested in and cycle through them with few keystrokes. The bookmarks also appear listed by line number under Goto | Bookmarks. Bookmarks only work within the current file; you can’t set bookmarks in two different files and use them to jump back and forth between the documents. To create or delete a bookmark, use the Toggle Bookmark command: 1. Position the cursor at the location you’d like to bookmark. 2. Click Goto | Bookmarks | Toggle Bookmark. Or press Command+F2 on Mac OS X or Ctrl+F2. To jump to the next bookmark:


Navigation

66

• Click Goto | Bookmarks | Next Bookmark. Or press F2. To jump to the previous bookmark: • Click Goto | Bookmarks | Next Bookmark. Or press Shift+F2. To remove all bookmarks in the file: • Click Goto | Bookmarks | Clear Bookmarks. Or press Shift+Command+F2 on Mac OS X or Ctrl+Shift+F2.

Reveal in Side Bar With navigation commands like Goto Anything at your disposal, you can get a lot of work done without worrying about where in the project file structure a particular file is located. But as a project grows, you inevitably end up with multiple files that share the same file name, and sometimes you need to know just which index.erb you’re editing. The Reveal in Side Bar command expands the parent folders of the file you’re editing and highlights the file name so you can see exactly where it lives in the hierarchy. To use Reveal in Side Bar, right-click an open file in the editor window, then select Reveal in Side Bar from the context menu. Reveal in Side Bar works on file previews as well as open files.

Open Containing Folder Tasks like renaming multiple files or reorganizing a folder are best accomplished with a file manager, but when you’re deep in your project file structure, it’s a hassle to drill down to the appropriate folder. The Open Containing Folder command makes this context switch easier by allowing you to jump into your file explorer at the same level as the file you’re editing. To use Open Containing Folder, right-click in the editor window and select Open Containing Folder … from the context menu. Or right-click a file in the Side Bar and select the Open Containing Folder… context menu item. Open Containing Folder works in file previews as well as open files.


11 Find and Replace I’ll be honest: Before I sat down to write this chapter, I’d steered clear of Sublime’s Find features. My initial attempts to use it left me frustrated–find seemed fickle. There were even a few times when I couldn’t even get it to pick out a word I was staring at on my screen. It’s right there! Why can’t you see it? After a little experimentation, though, I overcame my confusion and discovered some features I really liked. Now I often use Sublime’s search in place of my previous go-to tool, grep.

What are modes and settings? Part of my confusion stemmed from the fact that Sublime supports several different find modes with slightly different user interfaces. I didn’t understand which modes did what. The modes include: • • • • •

Find Quick Find Incremental Find Find in Files Replace

There are also several search settings that you can toggle with cryptically marked buttons in the search panel. These settings are global–they affect how all searches operate, even if you only enable them for one mode. These settings are both useful and powerful, but if you don’t realize they’re enabled you’ll get unexpected results. The most important settings include: • Regular expression • Case sensitive • Whole word If Find starts acting erratically, chances are one of these settings is enabled. Keep these different modes and settings in mind as you experiment with Find.


Find and Replace

68

Modes Find, Find Next, Find Previous, Find All You can perform a basic Find just by highlighting or double-clicking a word. Matches are highlighted with a light outline, and they’re also highlighted in the minimap. The main disadvantage of this type of find is that clicking anywhere in the document will cancel the selection and remove the highlighting from the matches. For more involved searches, you’ll want to open the Find panel. By default, any text you’ve highlighted is copied into the search field on the Find panel when you first open it. (You can disable this if you like by setting find_selected_text=false in your user settings file.) You can cycle through recent entries in the Find and Replace fields by clicking in the field and then using the the up and down arrows.

With the Find panel open, matches remain highlighted while you navigate through and edit your file. You can navigate from match to match with the Find, Find Next and Find Previous commands. These commands jump to the next available match and highlight it, which allows you to just start typing if you’d like to replace it. Find All highlights all occurrences of a match and enters multiple cursor mode, allowing you to replace all occurrences of the match simultaneously without using the Replace panel.

Shortcuts Mac OS X: Find: Command+F Find Next: Command+G Find Previous: Shift+Command+G Find All: Alt+Enter Exit Find: Esc Windows and Linux: Find: Ctrl+F Find Next: F3 Find Previous: Shift+F3 Find All: Alt+Enter Exit Find: Esc


Find and Replace

69

Incremental Find Incremental Find is useful for quick navigations. When you perform a regular Find ‌, the Find panel remains open until you manually dismiss it. When you use Incremental Find, the editing window scrolls to the first match following your current cursor position as soon as you begin typing a search term. Pressing Enter selects the match for editing and dismisses the search panel, while Shift+Enter scrolls backward to the first match prior to the current cursor position. Esc cancels the search and returns you to previous editing point.

Multi-edit with Incremental Find After performing an Incremental Find, you can press Alt+Enter to select all occurances of the match and insert a multi-edit cursor at the end of each.

Windows and Linux: Incremental Search: Ctrl+I Incremental Search (Reverse): Ctrl+Shift+I Mac OS X: Incremental Search: Command+I Incremental Search (Reverse): Command+Shift+I

Replace The Replace panel allows you to perform repetitive edits in the current file such as renaming a variable or updating a block of repeated code or markup. When you enter a term in the Find What field, Sublime highlights the first match. Clicking the Replace button will substitute the value entered in the Replace With field, then highlight the next match. The Replace All button replaces every instance of the matched term and closes the Replace panel. If you’d prefer to review each match individually, you can use the Replace button. The Find button allows you to skip replacing a match and jump to the next one. As with other search-related commands, text you select before opening the Replace panel will be prepopulated into the Find What field. When the Replace panel is open, you can hit Ctrl+Shift+E on Windows and Linux or Command+Shift+E on Mac OS X to copy any selected text into the Replace With field. The Replace panel supports multi-line values for the Find What and Replace With fields.


Find and Replace

70

Preserve Case In addition to the standard search-related settings like matching on whole words, Replace supports a Preserve Case setting that looks at the positioning of capital letters in a matched word and capitalizes letters in the same positions in the replacement string. Preserve Case is useful when you’re replacing words that may occur both at the start of a sentence and in the middle, such as replacing always with never in this example: Always say always.

It’s also handy for changing terms that are embedded in camel- and Pascal-cased variable names, such as swapping the more specific button for element in this example: function logElementClick(elementName) { console.log(elementName + "clicked!"); }

Shortcuts Windows and Linux: Open Replace Panel: Ctrl+H Find: F3 Find (Reverse): Shift+F3 Find All: Alt+Enter Replace Next: Ctrl+Shift+H Replace All: Ctrl+Alt+Enter Toggle Preserve Case: Alt+A Copy Selected to Replace With: Ctrl+Shift+E Insert Newline in Find What or Replace With: Ctrl+Enter Mac OS X: Open Replace Panel: Option+Command+F Find: Command+G Find (Reverse): Shift+Command+G Find All: Option+Enter Replace Next: Option+Command+E Replace All: Ctrl+Option+Enter Toggle Preserve Case: Option+Command+A Insert Newline in Find What or Replace With: Command+Enter Copy Selected to Replace With: Command+Shift+E

Quick Find The Quick Find command is a convenient way to search for other occurances of the word currently under the cursor. When you execute Quick Find, the next match for the word under the cursor is highlighted. You can run the command multiple times to jump to cycle through matches in sequence. A related command, Quick Find All, highlights all occurances of the word under the cursor and inserts cursors at each location. Windows and Linux: Quick Find: Ctrl+F3 Quick Find (Reverse): Ctrl+Shift+F3 Mac OS X: Quick Find: Alt+Command+G Quick Find: Shift+Alt+Command+G


Find and Replace

71

Find in Files Find in Files allows you to search and perform find-and-replace operations across multiple files at once. With the Where field, you can restrict the search to specific file types and folders. By default, the search includes all open files and folders. Where filters support wildcards using an asterisk, and you can chain together multiple filters by separating them with a comma. The following filter will include all JavaScript files except the jQuery library: *.js,-jquery*

To see examples of the syntax for adding folders or including and excluding files, click the …, then choose the desired option. If you chose Add Exclude Filter or Add Include Filter, Sublime inserts a file filter example. If you chose Add Folder, a file browser launches that allows you to select the appropriate folder. To reset the Where field to the default value, click the … button to the right of the field, then click Clear. You can customize the way Sublime displays your search results with the Use Buffer and Show Context buttons, located to the left of the Find field. When Use Buffer is enabled, search results display in a new tab; otherwise they appear in an output panel at the bottom of the screen. With Show Context enabled, you’ll see the line containing your search term plus two lines above and below the match, instead of just a single line with the matching term. To open a file from the list of results and jump to the matching line, double-click the file name. The Replace field allows you to do simple multi-file edits. Multi-file find-and-replace operations are risky business, and Sublime takes pains to ensure that you don’t do something you’ll regret. When you click Replace, a prompt specifies the number of matches for the Find term and asks you to confirm that you want to replace all matches with the value in the Replace field. After you confirm, each modified file opens in a new, unsaved tab, so you have the opportunity to review each change before saving it. The Replace field remembers the last value you entered each time you relaunch Find in Files, so watch that you don’t accidentally run Replace when you just want to use Find in Files.

Multi-line find and replace Although it’s hard to tell by default, the Find and Replace boxes both support multi-line input. If you drag the top of the Find in Files panel upward, both boxes expand to a height of several lines. You can paste in multi-line entries or press Ctrl+Enter to insert newlines.

Windows and Linux:


Find and Replace

72

Find in Files: Ctrl+Shift+F Mac OS X: Find in Files: Command+Shift+F

Regular Expressions For advanced find and find-and-replace scenarios, Sublime’s regular expression support is invaluable. If you’re not familiar with regex syntax, it provides a powerful pattern matching language that you can use to match words, phrases and lines. If you can figure out the right regular expression, that is—regex syntax is notoriously tricky to get right.

Advanced syntax help Sublime’s regular expression engine relies on Boost syntax, which derives from the Perl regex system. For advanced scenarios, check out the Boost documentation¹.

Enabling Regular Expressions You can enable the regular expression setting from any of Sublime’s find panels. It’s a global setting, so if you turn it on for Find in Files you’ll be in regex mode next time you go to use Replace. This can be pretty confusing: When regex searching is enabled, Sublime will often seem to fail to find matches if your search includes special characters. The Regular expression toggle is located to the left of the input fields in the find panels. The label is just a period and a star: ¹http://www.boost.org/doc/libs/1_47_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html


73

Find and Replace

Toggling regular expressions.

When a find panel is focused, you can also toggle regular expression mode with a keyboard shortcut. Windows and Linux: Toggle Regular Expressions: Alt+R Mac OS X: Toggle Regular Expressions: Option+Command+R

Using Regular Expressions Regular expressions are powerful because they allow you to find matches based on the way text is formatted, rather than limiting you to simple exact text matches. Regular expression syntax is a topic unto itself, so we’ll only cover a few examples that will help you tackle some common editing tasks. For example, in the following list of names, the regular expression [A-Za-z]+,\s[A-Za-z]+ matches the names formatted in lastname, firstname format:


Find and Replace

74

Jim Halpert Pam Beesly Howard, Ryan Michael Scott Schrute, Dwight

If you’re not used to regular expressions, that example probably looks like gibberish. Here’s a quick breakdown of the different components: • [A-Za-z] matches any capital or lowercase letter, and adding the + makes it match one or more letters. • ,\s matches a comma followed by a space. This regex thus matches one or more capital or lowercase letters, followed by a comma and space, followed by one or more capital or lowercase letters.

A regex crutch Regular expressions aren’t my strong suit, so I rely heavily on Sublime’s real time search highlighting when I’m crafting a regex. It gives me instant feedback, shortening the error part of the trial-and-error equation.

Special Scenarios Line Breaks Finding line breaks (or newlines, or carriage returns, whatever you want to call them) is often useful when you’re manually hacking together some HTML or cleaning up the formatting on a piece of text. I have a client who likes to send me long pieces of writing that he’s manually formatted with hard returns. I have to remove them before I can import the text into WordPress or Adobe InDesign. Sublime’s regular expression mode makes it simple to zap extra line breaks. Here’s how: 1. Open the Replace panel by clicking Find | Replace …. 2. Enable regular expression mode by clicking the cryptic .* button. (Hover over the buttons to see a tooltip if you’re not sure which is the right one.) 3. Enter \n in the Find What field. Sublime highlights matches in real time as you enter your search, so you should see selections appear at the end of each line. 4. Enter your replacement text in the Replace With field. 5. Click Replace or Replace All to make your substitutions.


Find and Replace

75

Shortcuts Windows and Linux: Show Replace panel: Ctrl+H Toggle Regular expression mode: Alt+H Replace once: Ctrl+Shift+H Replace All: Ctrl+Alt+Enter Mac OS X: Show Replace panel: Option+Command+F Toggle Regular expression mode: Option+Command+R Replace once: Option+Command+E Replace All: Control+Option+Return


12 Autocomplete Auto complete allows you to use long descriptive names for your variables and functions without wearing out your typing fingers. It also reduces typos and prompts you when you forget what you named something.

Basic Usage Although it’s not obvious, Sublime’s auto complete feature is available in all files and contexts—even when you’re editing plain text. To auto complete a word, type a few characters from the word, then press Tab to insert the best match. You can cycle to the next item in the list of matches by immediately pressing Tab again.

Word shortcuts Auto complete uses fuzzy matching, which allows you to invent your own shorthand for words you use frequently. For example, auto completing on sub will insert subject, then sublime if they’re both included in the same file. But sbl only matches sublime, which saves some typing.

Suggestions List The auto complete suggestions list appears automatically while you’re editing source code files and when you start a tag in an HTML file. The list includes keywords that are built into the language, the names of functions and variables that exist in the current document, and any snippets that might be available. Many plugins add new items to the auto complete list. Once the correct word is highlighted, press Tab to insert it. Esc closes the suggestions list without inserting a completion. If you accidentally insert the wrong completion, you can cycle through the available choices by immediately pressing Tab again. You can bring up a list of available completions in any context with the Show Completions command. This command pops up a list of words and snippets that match the characters you’ve already typed.


77

Autocomplete

To use Show Completions, type part of the word or snippet, then click Edit | Show Completions.

Auto-inserting snippets If you trigger Show Completions when there’s only one available choice, Sublime will automatically insert the completion. Try it by creating a blank html file, then typing ht and triggering the command.

Disabling Auto Complete If you find that the constant flicker of the auto complete suggestion list makes it hard to focus, you can increase the delay before the suggestion list appears, or you can disable it altogether. By default, the auto complete menu appears after 50 milliseconds. Bumping that interval up to one or even two seconds keeps it from interrupting your flow while still allowing it to prompting you when you pause to remember what you named that variable that’s scrolled out of view. To increase the delay before the suggestion list appears, add the following to your user preferences: "auto_complete_delay": 1000

To prevent auto complete from prompting you automatically, add the following to your user preferences: "auto_complete": false

Even with auto complete disabled, you can still summon the suggestion list with the Show Completions command.

Wrap Selection with Tag When you’re working with HMTL or XML, it’s often useful to be able to wrap a piece of text or some existing HTML with a set of matching tags. For example, to wrap span tags around one word in a sentence, highlight the word you’d like to wrap, then run HTML: Wrap Selection with Tag from the command palette. A brace of p tags wraps the selection, and the p in the opening tag is selected. Just begin typing to replace the placeholder p in the opening tag.The closing tag automatically updates to match.


78

Autocomplete

Close Tag It’s nice to use snippets to insert matching HTML tags whenever possible. But sometimes, especially when you’re editing a chunk of existing HTML, you’ll find that you have an opening tag but no closing tag. To close an open tag, position the cursor at the point where you’d like to insert the tag, then select Edit | Tag | Close Tag from the application menu.

Close Tag isn’t that smart! Close Tag doesn’t try to determine if a tag has already been properly closed. It searches backward through your code until it finds a tag, then inserts a matching closing tag. If your tag is already closed, you’ll end up with two closing tags.

Shortcuts Windows and Linux: Show Completions: Ctrl+Space Wrap Selection with Tag: Alt+Shift+W Close Tag: Alt+. Mac OS X: Show Completions: Ctrl+Space Wrap Selection with Tag: Ctrl+Shift+W Close Tag: Command+Alt+.


13 Vintage mode Sublime’s vintage mode, which emulates Vim, provides a goldmine of keyboard navigation techniques. Vintage mode is beyond the scope of this post, but it’s worth looking into if you’ve never tried Vim. Some examples of keyboard navigation features in vintage mode include: • Move the cursor without taking your fingers off of the home keys. • Scroll up and down the page by half or a full screen of text without using PgUp or PgDown. • Jump around within a line word by word, or jump to the next occurrence of a character without pounding Right or Left a hundred times. There’s a steep learning curve with vintage mode, but if you spend all day pushing lines of text around, it’s a worthwhile investment that will reap major returns in your daily productivity.


III Automation


14 Snippets Snippets are little chunks of boilerplate code or text that you can insert with a few keystrokes. They’re great time savers. While most snippets are meant to make routine code formulations easier to type, you can define your own snippets to help you format blog post in Markdown or easily create new tasks in your custom to-do list format. Sublime comes with snippets for a number of popular languages and markup styles, including HTML, JavaScript, CSS, Ruby, Rails (tons and tons of these) and PHP, and snippets for other languages and libraries such as jQuery and CoffeeScript are available for installation as plugins.

Inserting Snippets There are several ways to insert snippets into your document. The most common approach is to type a trigger word, then press Tab. This inserts the desired snippet and positions the cursor at the point where you’re most likely to begin editing. Depending on the snippet, there may be several additional editable fields that you can quickly cycle through to finish implementing the code you’re writing. Let’s look at a quick JavaScript example. While you’re editing a JavaScript file, typing if and hitting Tab inserts the following: if (true) {};

The true is placeholder text. Hitting Tab a second time highlights the placeholder, allowing you to type a conditional statement to replace the placeholder. Press Tab one more time and the cursor jumps between the curly braces so you can begin implementing the code that will be invoked when the condition is met. You can also cycle backwards through these fields by pressing Shift+Tab, and you can exit the sequence by pressing Esc.

Viewing Available Snippets Sublime makes an effort to filter snippets by context, which includes both the file type and the surrounding code. By default, the snippets available when you’re editing an HTML file include common HTML tags and PHP code blocks. Jump inside a script tag, though, and you’ll have access to JavaScript snippets.


82

Snippets

One way to see the snippets available for a given context is to select Tools | Snippets. This launches a Command Palette that’s filtered to only include relevant snippets. Another option is cruising though the Data/Packages folder, looking for files with the sublime-snippet extension. To open this folder, select Sublime Text 2 | Preferences | Browse Packages on Mac OS X or Preferences | Browse Packages on Windows or Linux. One useful snippet that seems to be available in all file types is the lorem ipsum filler text snippet. Type lorem hit Tab and Sublime will insert a paragraph of nonsensical faux Latin.

Wrapping Existing Text Some snippets can be wrapped around existing code or text. The if snippet we looked at above is one example. To wrap a few lines of code in an if block, first select the lines you’d like to wrap. Launch the Command Palette and type snip if. Press Enter to insert the highlighted snippet. Prefixing the snippet name with snip restricts the Command Palette matches to snippets and allows you to use fuzzy matching to quickly find the appropriate snippet. Wrapping snippets around existing text with the Command Palette is a little awkward. If you find yourself using the same snippets repeatedly you can define a custom keybinding for your favorites. Here’s an example that binds Ctrl+Shift+I to the if snippet: { “keys”: [“ctrl+shift+i”], “command”: “insert_snippet”, “args”: { “name”: “Packages/JavaScript/if.sublime-snippet” } }

Creating Custom Snippets It’s easy to define custom snippets, which can be useful if you want to define your own projectspecific snippets to share with your team members. A Sublime snippet is a simple XML format, saved with the extension sublime-snippet. To see how a snippet is structured, let’s reimplement and then tweak the JavaScript if block snippet that ships with Sublime. This included snippet inserts the following code when you type if and press Tab: if (true) {};


83

Snippets

File Format Each snippet file includes a trigger word, the code or text to insert, optional placeholders that denote editable regions, a scope that indicates what language the snippet represents, and a description that appears when you invoke the snippet from the Command Palette. Here’s an empty snippet file: <snippet> <content><![CDATA[]]></content> <tabTrigger></tabTrigger> <scope></scope> <description></description> </snippet>

For this example, we’ll use the same trigger word, if, and update the description: <snippet> <content><![CDATA[]]></content> <tabTrigger>if</tabTrigger> <scope>source.js</scope> <description>if block with better formatting</description> </snippet>

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

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: function myFunction(callback) { callback(); };

The snippet code would include duplicate position markers for the name of the callback: 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: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: 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: <snippet> <content> <![CDATA[if (${1:true}) { ${0:$TM_SELECTED_TEXT} };]]> </content> <tabTrigger>if</tabTrigger> <scope>source.js</scope> <description>if</description> </snippet> ¹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: 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: [ { "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: [ { "args": { "forward": false }, "command": "delete_word" }, { "args": { "forward": false }, "command": "delete_word" }, { "args": { "to": "brackets"


91

Macros

}, "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: [ { "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 anUnable 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: [ { "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


Macros

93

up the macro recorder, manually trigger the commands you’re interested in, then save the macro 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: /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.

[ { "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: /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/: /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.

[ { "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",


Menu Enhancements

100

"command": "set_file_type", "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: /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: /Data/Packages/Default/Default (OSX).sublime-keymap

On a Windows system, the default keymap file is located at: \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

/Data/Packages/User/Default (OSX).sublime-keymap

On a Windows system, the user keymap file is located at: \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. [ { "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: { "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: function getTime(tzCode) { switch(tzCode) { /* snip */ case 87: return 1377953338803; // you don't want to know } }

And a single-line block comment in CSS: .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

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: "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

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


V Recipes


20 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: div > ul > li*3

Becomes:

¹https://github.com/titoBouzout/SideBarEnhancements/ ²https://github.com/xobb1t/Sublime-AdvancedNewFile


Essential Plugins

109

<div> <ul> <li></li> <li></li> <li></li> </ul> </div>

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


21 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. #!/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

111

To create the hard links, launch the Windows command prompt as an administrator, then execute the following commands: 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.


22 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


113

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

114

{ "files": { "jquery": "http://code.jquery.com/jquery.min.js" }, "packages": { "html5_boilerplate": "https://github.com/h5bp/html5-boilerplate/zipball/maste\ r" } }

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: { "files": { "jquery": "http://code.jquery.com/jquery.min.js" }, "packages": { "html5_boilerplate": "https://github.com/h5bp/html5-boilerplate/zipball/maste\ r", "wordpress_plugin_boilerplate": "https://github.com/tommcfarlin/WordPress-Plu\ gin-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


115

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.


116

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


117

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


118

PHP

{ "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


119

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

120

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: { "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: { "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:


121

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/


122

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


123

PHP

Creating a new block comment.

And you can add to an existing comment by simply pressing Enter to insert a new line:


124

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:


125

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:


126

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


127

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


128

PHP

{ "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:


129

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

130

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


23 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


132

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


133

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:


134

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

135

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: "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

136

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: "folders": [ { "/", "file_exclude_patterns": ["*.css"] } ]

To exclude a custom css output folder, add the following to your project file: "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: "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

137

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


139

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


140

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|


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.