Sublime Productivity

156

description

sublime productivity guide

Transcript of Sublime Productivity

Sublime ProductivityCode 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 thishashtag 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ivWhich version of Sublime Text does this book cover? . . . . . . . . . . . . . . . . . . . . . iv

The short answer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ivThat awkward phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv

Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ivWhy are you telling me to click stuff in menus? . . . . . . . . . . . . . . . . . . . . . ivHey, where are the keyboard shortcuts? . . . . . . . . . . . . . . . . . . . . . . . . . vFormatting notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v

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

I Editor Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1 Side Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Toggling the Side Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Previewing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Opening Folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Toggling the Open Files Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 Command Palette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Keyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

3 Minimap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

4 Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Viewing the Session File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Tweaking Session Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Disabling Hot Exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

CONTENTS

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

5 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11How Projects Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Creating Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Adding Folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Opening Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Multiple workspaces per project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Navigating in Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Editing Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Project-Specific Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Including folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Excluding files and folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Overriding settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Project File Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

6 Tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Opening Tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Closing Tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Tearing Tabs Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Reopening Closed Tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Switching Tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

7 Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Layouts vs. groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Managing layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Managing groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

Creating groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Arranging groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Closing groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Rearranging tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Move to Next Group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Move to Previous Group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Move to numbered group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Navigating between panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Focus Previous Group / Focus Next Group . . . . . . . . . . . . . . . . . . . . . . . . 24Focus Numbered Group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Panes: Separate or not? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Moving files between panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Resizing panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Saving and restoring multi-pane configurations . . . . . . . . . . . . . . . . . . . . . . . . 26

CONTENTS

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

II Using the Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

8 Editing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28Paste and Indent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28Paste from History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Indent, Unindent, Reindent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Insert Line Before/Insert Line After . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Delete to End/Delete to Beginning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Delete Word Forward/Delete Word Backward . . . . . . . . . . . . . . . . . . . . . . . . 32Soft Undo/Soft Redo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32Transposing Letters and Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Changing Capitalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Joining Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Swapping Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Deleting Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Duplicating Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Wrapping Paragraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36Commenting and Uncommenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36Sorting and Reordering Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Sorting and Reordering Selected Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

9 Selecting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Multi-Select . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Split Selection into Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44Quick Add Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Quick Skip Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46Column Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Invert Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Cleaning up CSV data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Filter unwanted lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Strip HTML tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

Scoped Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51Paragraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Brackets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Indentation Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Expand to Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

10 Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

CONTENTS

Goto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56Goto Anything . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56Goto Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57When does indexing run? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57What’s include in the index? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Goto Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Goto Symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59Goto Symbol in Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

What symbols are included? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Combining Goto commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60Jump Forward, Jump Back . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Scrolling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Code Folding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Fold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Fold Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Fold All . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63Fold Tag Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63Unfold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65Unfold All . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

Bookmarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65Reveal in Side Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66Open Containing Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

11 Find and Replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67What are modes and settings? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Find, Find Next, Find Previous, Find All . . . . . . . . . . . . . . . . . . . . . . . . . 68Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Incremental Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Preserve Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

Quick Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70Find in Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Enabling Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Using Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Special Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74Line Breaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

CONTENTS

12 Autocomplete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76Basic Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76Suggestions List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76Disabling Auto Complete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Wrap Selection with Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Close Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

13 Vintage mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

III Automation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

14 Snippets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Inserting Snippets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Viewing Available Snippets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Wrapping Existing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82Creating Custom Snippets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84Placeholders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

Implementing the Custom Snippet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85Installing Snippets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

15 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87What are macros? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87What are they good for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Creating macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

Recording macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88Saving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89Playback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90Creating keyboard shortcuts for macros . . . . . . . . . . . . . . . . . . . . . . . . . 92

Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93No find and replace support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93One tab, one macro buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93Some commands are ignored . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

CONTENTS

IV Customizing the Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

16 Command Palette Tweaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Configuration Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Adding Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

17 Menu Enhancements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98Configuration Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98Customizing the Context Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

18 Key Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Configuration files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Creating custom key bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Context-specific key bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

19 Managing Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106Package Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106Installing Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106View Installed Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

V Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

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

21 Cross-Platform Syncing of Settings and Plugins . . . . . . . . . . . . . . . . . . . . . . 110

22 PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112Setting up a New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

Fetch Installs Libraries for You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112Installing Fetch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113Configuring Fetch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113Using Fetch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

Code Checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117Linting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117Basic Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

Code Sniffing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

CONTENTS

Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120Documenting Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122Building Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129Goto Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129Stack Overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

23 SASS and SCSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131Syntax Highlighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132Compiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

Changing the Output Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Preventing Compiled Output from Appearing in Project . . . . . . . . . . . . . . . . 136Automating Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

Keyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

Side Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

Side Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

Side Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

Special Offer for TradePub Readers:Get Future Updates at a 20% DiscountSublime Productivity is packed with tips that’ll help you master Sublime Text, but there’s even moreon 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 tohttp://sublimeproductivity.com¹ and enter discount code TRADEPUB at checkout for 20% off theminimum price.

This offer is only good through September 21, 2013, so claim your discount today².

¹http://sublimeproductivity.com²http://sublimeproductivity.com

Contact MeSublime Productivity is a work in progress. If you’d like to let me know about an error (I’m surethere are a few), or if you just have a question or want to offer some constructive feedback, emailme at [email protected].

Free Weekly Productivity TipsWant a weekly dose of Sublime Text tips to improve your productivity and streamline yourworkflow?

Head on over to http://sublimetexttips.com/newsletter³ and drop your email address in the signupform.

³http://sublimetexttips.com/newsletter

About this BookWhich 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’llread 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 tocover the new version.

The Sublime team tends to do extended beta cycles to give users and plugin developers plenty oftime to play with the new bits. New features appear from time to time, and existing ones are tweakedin subtle ways.

So far, ST3 is looking like an incremental upgrade with lots of under-the-hood improvements butrelatively 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 Sublimeteam switched from Python 2.6 to 3.3. Since Python 3.x includes API changes, existing Sublimeplugins have to be updated to work with ST3. The required changes aren’t difficult, according to theSublime 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’twork, 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 thefront 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-stepinstructions. It was repetitive and clumsy, because Sublime’s shortcuts differ radically between theWindows and Linux versions and the OS X versions.

It clutters the reading experience to include keyboard shortcuts, because they’re different for eachoperating system.

The menus, on the other hand, are more consistent across platforms. The menus are also morediscoverable: If you forget a keyboard shortcut, it’s pretty hard to figure out where to find it. Butthe 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 usefrequently, I decided that I’d use the menu options where they are available. If there’s no wayto do something via the menu, I’ll fall back to the Command Palette, and I’ll only specifically list akeyboard 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 ofcompiling a curated list of the most useful keyboard shortcuts, which will be available in the backof 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, andcode.

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 sucha pain for you, the reader. I once bought a novel in ebook format only to realize that I had to useproprietary Adobe software just to open it. Curling up on the couch with my 15” ThinkPad isn’tan enjoyable way to read, and I spent the next 20 minutes scouring the torrent sites in search of aDRM-free copy that I could load on my ereader. That’s no way to treat a customer. If you pay fora 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 paidfor 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 acopy 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 asI publish them.

⁴http://www.sublimeproductivity.com

I Editor Features

1 Side BarSublime’s side bar contains a browsable list of files and folders. You can expand nested folders toshow 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 somesurprising limitations in its out-of-the-box configuration. You can’t can’t drag and drop files orfolders 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 toggleit off if you’d like to devote more screen real estate to your code and reenable it when you need tobrowse for another file.

To toggle the side bar:

• Click View | Side Bar | Show Side Bar or View | Side Bar | Hide Side Bar.Or pressCommand+K,Command+B onMac OS X orCtrl+K,Ctrl+B onWindows and Linux.

Previewing Files

Sublime’s preview feature is one of those subtle touches that can make a big difference in your day-to-day work. I frequently find myself hunting through multiple files, looking for a particular pieceof code. In most editors, each file I examine opens in a new tab, and before long I have two dozentabs open.

When you single click a file in the Sublime side bar, Sublime displays its contents in the editingwindow 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 willpop open a new tab for the file.

Preview tabsIn Sublime Text 3, single-clicking a file opens the preview in a special temporary tab. Youcan identify this tab by the italicized file name in the tab’s title. The preview tab is reusedwhen you single-click another file.

It’s an improvement over the old model where the preview took over the active tab becauseit 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.

Side Bar 3

Opening Folders

The Folders section of the side bar shows any folders you’ve opened in Sublime, as well as the filesthey 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 isconvenient for hiding files that Sublime can’t edit, such as .png graphics, or for excludingthe compiled outputs of platforms such as CoffeeScript or SASS. To customize Sublime’sfile exclusions, see the folder_exclude_patterns, file_exclude_patterns and binary_-

file_patterns settings in the Preferences.sublime-settings file. You can override thedefaults in your user-specific settings, and you can also customize them on a per-projectlevel.

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

You can hide the Open Files section if you’d prefer, since it doesn’t provide much information thatyou 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 yourproject.

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.

Side Bar 4

In the Folders section, right-clicking on a folder brings up a menu with a few basic options: NewFile, 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 foldername. The Find in Folder option opens a Find panel and populates the folder name into the Where…field.

Deleting a folder with open filesWhen you use the Delete Folder command, Sublime doesn’t close tabs for files that werecontained in the deleted folder. The tabs remain open as if nothing happened, but you’llget 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 OpenContaining Folder… Rename opens an input panel where you can type the new file name. Selectingthe 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 butleaves it open in a tab, changes the tab to unsaved. Easy to accidentally restore the file bysaving the tab.

The Open Containing Folder command opens your system file manager to the parent folder of theselected file.

Rearranging filesSince the Side Bar doesn’t allow you to drag and drop files to reorganize them, usingOpen Containing Folder to and then shuffling files in your file manager is often the bestworkaround.

2 Command PaletteIf you’re a keyboard junkie, you’re going to enjoy Sublime’s Command Palette. It allows you touse almost all of the commands available in the menus without fumbling for the mouse or diggingthrough nested menus with the arrow keys.

The palette uses a simple search-based user interface. When you open the command palette, afloating command box appears with an alphabetical list of commands below it. Type a partialcommand name, such as side bar, and Sublime filters the list using its usual fuzzy matchingalgorithm.

Command palette

Once you spot the command you’re looking for, such as Toggle Side Bar, use the arrow keys tohighlight it, then press Enter.

One of my favorite uses for the Command Palette is as an aid for learning Sublime’s keyboardshortcuts. Try to develop the habit of using the Command Palette to perform actions when youcan’t remember the keyboard shortcut. When you use the palette to perform an action, such as Findin Files, the keyboard shortcut appears to the right of the command’s name. Also, the full listing ofthe command name clues you in to where it’s located in the menu.

Command Palette 6

Sublime uses a similar command box interface for other commands, including navigating aroundin a file, opening other files, and switching projects, and the Package Manager plugin uses the sameapproach to display a list of plugins you can install. Many third party Sublime plugins also putcommands 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 matchingSublime relies heavily on filterable lists to help you quickly execute commands, open files andnavigate to specific bits of code. This filtering approach is backed by a “fuzzy matching” algorithmthat 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 enteredin the exact order you entered them, fuzzy matching retains all items that contain the charactersyou entered somewhere in the text being searched—not necessarily in the exact order your enteredthem.

In the Command Palette, you can use fuzzy matching to create your own easy-to-remembershortcuts. 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 theappropriate language. I can do this quickly using fuzzy matching by launching the CommandPalette 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 stillmatches Set Syntax: JavaScript, even though the j and s are transposed.

3 MinimapThe minimap is a distinctive feature of Sublime. It’s turned on by default and appears on the right-hand side of the screen. It shows a zoomed-out view of the file, as if you’d zoomed out to 5 percentor 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 aidat 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 theminimap as well as in the editing window, so you can get a sense for how often the search term isused and how the usages are distributed throughout the file.

Similarly, when spell checking is enabled, the minimap highlights spelling errors in red.

Theminimap also allows you to perform some limited navigations directly. You can click on a sectionof the document to jump to it directly. You can also drag the highlighted part that represents theview 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 SessionsWhen you close and reopen Sublime Text 2, you may notice that the editor reopens any files youwere editing before previously. Sublime uses a session to keep track of these open tabs and a wholelot more.

Sessions make the editing experience in Sublime feel seamless. Closing the editor to install a pluginor (if you’re a Windows user) reboot your machine is a zero penalty task, since you won’t need toreopen 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 unsavedchanges to open files in the session. Sublime doesn’t prompt you to save unsaved changes whenexiting for this reason. They are squirreled away in the session and can be saved next time you openthe 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 inSublime and capture the information. The tab will stick around until I can transfer the infosomewhere more permanent, and I don’t have to worry about forgetting to save it andlosing 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 andin 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 severalfiles and folders open, and maybe you’ve split up your screen with a couple of customlayouts. You can save your session as a project that you can return to later to restore yourtabs, folders and layouts. Just click Project | Save Project As … and put the project filesomewhere safe.

Sessions 9

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 onMacOSX or under %USERPROFILE%\AppData\Roaming\SublimeText 2\Settings on Windows.

Like Sublime’s other settings, the session file is formatted as a JSON document, so it’s possible toread and edit it manually using another text editor. I wouldn’t recommend this, as it’s pretty easyto 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 tofix 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 whenSublime continually restores previously opened files. You can override the hot exit and restoreprevious 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 modifiedfiles 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 theremember open files setting.

Changing this setting won’t do anything if hot exit is enabled. I want that 15 minutes ofmy 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 ProjectsWhether you’re coding a Ruby on Rails site or writing a book, most text editing tasks involveworking with more than one file. Juggling related files using Finder or Windows Explorer is a hassleand 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 forsettings 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, andseveral coding projects. Each of these workspaces is customized for the task at hand: The blog projecthas an open tab for a post that I’mworking on, and another with some reference notes, andmy blog’sfolder is open in the sidebar. One of the coding projects has a couple of open files, an open folderand 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 toshuffle windows and close tabs, and it frees me from having to leave all of my in-progress workopen in the same window.

How Projects Work

A Sublime project is a JSON-formatted settings file with a sublime-project extension. This filecontains 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 checkedinto version control and shared among team members.

In addition to the sublime-project file, Sublime also creates a sublime-workspace file to managedetails specific to your working environment, including which files you have open and any windowlayouts you’ve created. Don’t edit this file by hand or commit it into version control, or your teammembers will hunt you down…

Projects 12

Creating Projects

To create a new project:

1. Click Project | Save Project As ….2. Browse to the root directory where your project files are saved.3. Enter a name for the project file.4. Click Save.

Mac OS X users have another way to create a new project: Simply drag a folder or groupof 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 siteI’m working on. Any child folders inside of the root folder will automatically be included, as wellas 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 andsaves 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 chancesare you’ll need to bounce around among several projects frequently, and Sublime makes it easy.

To open an existing project:

Projects 13

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 themenu 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 Xor Ctrl+Alt+P on Windows or Linux. An input box appears, along with a list of availableprojects.

2. Type part of a project name. The input box supports fuzzy matching, so the list is filtered toprojects 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 splityour time between front end web coding and server-side development. Or perhaps you’re jumpingback and forth between the feature you’re currently working on and one that’s just came back witha few issues from QA. And then there’s that emergency bug fix to the feature you worked on lastsprint …

Each context shift comes with a small setup cost. There are files to open and close. You might havepreferred arrangements of tab groups for different tasks: a three-column view for front end work soyou can see HTML, CSS and JavaScript open side by side, two rows for back end work, with yoursource on top and your unit tests below. You jump between tasks a few times, and before you knowit you have 27 unrelated tabs scattered across three tab groups.

Sublime’s workspaces are ideal for establishing different contexts within your project. They allowyou to create and save multiple arrangements of tab groups and open files per project. You can evenhave multiple Sublime windows open with separate workspaces to allow you to jump back and forthbetween contexts quickly.

Version Difference!Sublime Text 2 only supports one workspace per project.

Projects 14

Workspaces are JSON files with a .sublime-workspace extension, and they contain everything fromyour 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 bydefault.

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 SideBar 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 usethis newworkspace 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 fileswithout creating a whole project first.

Create a dot files workspaceDo yourself a favor and make a workspace for that assortment of system configurationfiles you’re endlessly tweaking.

To switch to a previously saved workspace within the current window, click Project | Open Recentand select the desired workspace, or use the Switch Project in Window command, which opens afilterable list of recent projects and workspaces for you to choose from. If the workspace you’relooking for doesn’t appear in either list, click Project | Open Project … to browse to and open theworkspace directly.

Bug alert!As of Sublime Text 3 build 3047, opening a project or workspace by double-clicking thefile in your file manager creates multiple Sublime windows, each with a separate copy ofthe project. This is a bug, as far as I can tell. You can work around the problem until it’sfixed by using Open Project when you want to use a project or workspace that isn’t in yourrecent projects list.

Navigating in Projects

Projects really shine when used in concert with the Go to anything feature. Since Go to anythingsearches all open files and folders, and projects give you control over which folders are open, youcan 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 directoryfor your project.

Projects 15

If you’re editing index.html, all you need to do to jump to script/plugin/myplugin.jquery.js ishit Command+P on Mac OS X or Ctrl+P onWindows or Linux. Then typemyp and hit Enter. Thisis especially convenient when your project has a complex folder structure that’s a pain to navigatewith 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 withmultiple 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 theproject. 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 properlyregardless 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 justspecific subfolders.

This is particularly useful for avoiding cluttering up your sidebar with auto generated files. Forexample, 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 thefollowing 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 multi-member 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 availableunder the Tools | Build System menu. You can map just about any arbitrary command supportedby 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 piecesfit together:

Projects 17

{

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

}

]

}

6 TabsOpening 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 ofwhether you save it as a file. Sublime will restore your unsaved work even if you close and restartthe app.

This is a nice fallback in case of system crashes or dumb mistakes. It also makes Sublime useful as ascratch pad for note taking. You can fire up a new tab to jot down a phone number and rest assuredthat 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 subtleenough 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 atime, 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.

Tabs 19

Tearing Tabs Off

Sublime supports “tearing” tabs off, similar to most web browsers. The torn-off tab creates a newSublime Text window. It’s a useful trick when you have two files open and want to refer to onewhile 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 ClosedFile 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 thetab bar.

• Using the arrow keys to jump between tabs based on the order in which they were lastmodified.

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

To jump to the tab to the left or right of the current tab:

Tabs 20

• Click Goto | Switch File | Next File or Goto | Switch File | Previous File.Or pressOption+Command+Right andOption+Command+Left onMacOSX orCtrl+PageDownand 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 PanesSometimes it’s handy to keep two or more files visible on screen at the same time. Maybe you’rewriting 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 fromHTML to CSS and back. You could tear tabs off and create a second Sublime window, but Sublimeprovides 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 horizontalsplits, 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 theonly way to achieve a 2-by-2 grid.

Panes created by a layout persist until you change layouts, regardless of whether they contain anytabs.

Groups

Groups, on the other hand, are more flexible. There’s no limit to the number of groups you cancreate. You can also combine horizontal and vertical splits, although as we’ll see, the combinationsare somewhat limited.

Using groups, you could split your editor window into two columns, then split the right column intotwo rows.

Groups are also more dynamic than layouts. A group’s pane closes when you close the last tab itcontains.

Panes 22

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 preferthe additional flexibility that groups offer. The main advantage that layouts still have inSublime 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, orView | 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 theydon’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 mergedinto 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-columnlayout and vice versa. If you go from a two-column layout to a two-row layout, tabs from therightmost 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. Sublimepreferentially creates a new column each time you add a group until you hit the maximum numberof columns. Once the maximum number of columns is reached, Sublime starts adding rows to therightmost column.

Panes 23

To change the the Max Columns setting, click View | Groups and choose the desired number ofcolumns, 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 thedefault, 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 asecond tab group.

Although it would be handy, it’s not currently possible to add rows to columns on the left side ofthe 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 panesequence.

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

TheMove File commands allow you to accomplish the same task via themenu 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.

Panes 24

Move to Previous Group

Move to Previous Group nudges the current tab left one column up a row, depending on your screenarrangement.

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 fileto file frequently. The Focus Group commands make it simple to jump from pane to pane in thesescenarios.

Focus Previous Group / Focus Next Group

The Focus Previous Group and Focus Next Group commands allow you to step to the next adjacentpane. 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 nextpane, click View | Focus Group | Next. In both cases, focus shifts to the last place you edited in theactive tab.

These commands wrap, so running Focus Next Group when you’re on the last pane will focus thefirst, 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.

Panes 25

Focus Numbered Group

The Focus Previous Group and Focus Next Group commands work well when you have two or threepanes open, but what if you’re using a 27” monitor and rocking a three-column layout with fourrows in the last column? Cycling through half a dozen panes to get to the one you want gets old ina hurry.

Focus Numbered Group allows you to jump directly to a pane with a numeric address. Sublimeapplies an index to the first nine open panes, numbering columns left to right and then numberingrows top to bottom.

Navigating with the Focus Numbered Group command is a matter of picking the right index for thepane you want.

Columns are indexed left to right, and rows are numbered top to bottom. The only exception is the2-by-2 grid layout, in which the top row panes are numbered 1 and 2, from left to right, and thebottom 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 | FocusGroup | 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 othersonly 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 editinga 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, andPrevious 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 workusing the Move File to Group commands. When you move a file to another pane, focus shifts to thatpane 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.

Panes 26

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 athree-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 theprogram. If you’re working on in a project, any custom layouts you create are stored in the associatedsublime-workspace file. When you’re just working on several unrelated files, Sublime will save yourlayout 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 thatmammoth FAQ page or that epic jQuery plugin file. Naturally the FAQ page has a list of anchor tagsthat you have to update as you add sections at the bottom, and the jQuery file has 20 local variablesdeclared 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 reflectedinstantly 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 andjump 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 fourdifferent sections of the file. Since each view is just a new tab, you can push them to different paneswith the Move File to Group command and jump between views with the Focus Group command.

II Using the Editor

8 Editing TextPaste and Indent

Pasted code does its best to mess up your carefully formatted file, especially if you’re embedding itinto an existing block of code. Typically the leading white space from the copied code is added tothe 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 indentationfor first line of the pasted code.

To perform a Paste and Indent:

Editing Text 29

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 shouldalways 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 minutesdigging around for a block of code that you want to reuse, copied it, closed the file, and scrolledback 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 topaste. It’s like a clipboard ring for Sublime, allowing you to retrieve that overwritten code from alist 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 charactersfrom 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 storesthe last 15 blocks you copied. Sublime doesn’t remove items from the list after you paste them, soyou can access them again later.

Paste from History only stores text you copy from files open in Sublime, so don’t expect it to rescuethat half-finished commit message you copied over. But it also doesn’t include text that you copyin other programs, so it offers an extra margin of safety when you’re grabbing snippets from codefiles 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’salso helpful when you need to copy and paste code from several files, maybe when you’re fleshingout a new file with boilerplate code. Instead of copying individual code blocks, then jumping back tothe file you’re building, you can just cruise around, filling up your clipboard history like a shoppingcart, then return to your file and paste items where you need them.

Editing Text 30

Conveniently, the history won’t insert duplicate text, so if you’re shopping for snippets and forgetwhether 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 isreset.

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 surround-ing code. This is useful if you have multiple lines at several different indentation levels. Reindentdoes seem to get confused by comments, at least in JavaScript, but it’s a good first-pass tool thatreduces 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 youuse 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 immediatelybefore or after it. For example, I might be writing a line of jQuery code and decide that I shouldinsert a comment above it, or maybe I want to set the line off from the code that follows with a lineof white space.

Doing this manually involves jumping to the end of the line with End and then pressing Return, orpressing Up and then inserting an extra line.

The Insert Line Before and Insert Line After commands make this a one-step operation, insertinga blank line above or below the current line. It’s similar to moving the cursor to the end of the lineand pressing Return, but much faster. The cursor jumps to the new line so you can immediatelybegin typing.

Insert Line After will also indent the next line correctly. If, for example, the previous line defines afunction, 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 onMacOSX orCtrl+Shift+Enter onWindows 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 achained jQuery statement while keeping the selector, or removing the start or end tags on an HTMLelement. The usual way to do this is to highlight the text with the mouse or use a combination ofthe arrow keys Shift and Home or End, but Sublime’s Delete to Beginning and Delete to Endcommands are a better option.

Delete to Beginning deletes all the text and white space preceding the cursor, while Delete to Endremoves 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 andLinux.

Editing Text 32

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.

TheDelete to End andDelete Line shortcuts make a nice pair of editing tools, and Sublimerecognizes 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 WordForward and Delete Word Backward commands are a handy alternative to highlighting text withthe 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 deletepartial 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, butit’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 realizethat 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 textselections as operations that can be reversed. They are rewind and fast forward buttons for yourediting session. This ensures that your attention is focused on any text changes that occur.

Editing Text 33

The ability to restore lost selections can be a lifesaver as well. It’s frustrating when an errant click orbutton press cancels the selection of some text I’ve painstakingly highlighted, maybe a multi-screenblock of text, or part of a three-screens wide piece of unwrapped code. In cases like these, executinga 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 changesto indicate what will happen when the action is invoked.) Or press Command+U on Mac OSX 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 toindicate what will happen when the action is invoked.) Or press Shift+Command+U on MacOS 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 arrowkeys, followed by a copy and paste and maybe fixing up the spaces on either side.

The Transpose commandmakes this a painless operation by reversing the position of a pair of lettersor words.

There’s no keyboard shortcut for Transpose by default on Mac OS X, but it’s easy to setone 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 tolowercase. 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 firstletter of each word. Upper capitalizes all selected letters, while Lower does the opposite.

To use the Swap Case command:

Editing Text 34

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

To use the Lower command:

• Click Edit | Convert Case | Lower.Or pressCommand+K, Command+L onMacOSX orCtrl+K, Ctrl+L onWindows and Linux.

To define keyboard shortcuts for Swap Case or Title Case, refer to the Key Bindingssection.

Joining Lines

I’ve probably wasted more hours of my life than I care to admit deleting extraneous white spaceswhen merging two lines of indented code. When I learned how to join lines, I couldn’t believe I’dbeen pounding Delete unnecessarily.

Sublime employs the Join Lines command to join the line below your cursor to the one you’recurrently 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 linesup or down in the file. Copy and paste is one option, but if you’ll only be moving the lines a shortdistance, 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 onWindows 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 theDuplicate Line command.

Duplicate Line inserts a copy of the current line directly below the current line. If multiple lines arehighlighted, 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 formanually wrapping lines, but sometimes when I’m writing prose, I’ll edit a paragraph and find thatmy original wrapping is no longer suitable.

Sublime makes it painless to fix this with theWrap 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 languageswith theToggleComment andToggle BlockComment commands. The behavior of these commands differs slightlydepending on the language’s support for inline and block comments.

CSS and HTML, for example, only support block comments, so the Toggle Comment commandwill wrap the current line or selected text in block comments, or remove the block comment asappropriate. Toggle Block Comment will insert an empty block comment if nothing is selected, orit will wrap the selected text in a block comment, or remove the block comment if the code is alreadycommented out.

JavaScript supports line comments, so Toggle Comment will add or remove line comments, andToggle 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 sortthem. 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.

Editing Text 38

Sorting and Reordering Selected Items

In addition to sorting a solid block of lines, Sublime can perform the same sorting functions onnon-sequential lines using the items in the Permute Selections menu.

For example, this Sort variation turns this list:

Select several lines …

Into this:

Editing Text 39

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 40

To use the Unique command:

1. Select several non-sequential lines.2. Click Edit | Permute Selection | Unique.

9 Selecting TextMulti-Select

Multiple cursor mode is a distinctive feature of Sublime, and other selection modes often make useof it.

Let’s look at an example that illustrates how useful this feature can be. I’d like to add a CSS classelement 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 thenthen type in the text I need in all three rows. Find and replace approaches often end up changingmore than intended–I don’t want to add a class to every li in the file, just these three. And columnselection mode seems to work a little differently in every text editor, and it always takes me a minuteof fumbling around to get it working.

Sublime’s multiple selections are much more intuitive. After each opening li, I can just Com-mand+click on Mac OS X or Ctrl+click on Windows and Linux, and then start typing:

Selecting Text 42

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 ofminutes 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 thebeginning of the line. Replaying this two times would result in the entire list being formatted. Whenyou 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. Inthis 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.

Selecting Text 43

4. Press End.5. Type the closing </li> tag.

Multiple selections can handle tasks that would otherwise require a macro.

You can combine themultiple selection featurewith Sublime’s powerful selection features to performtasks that would normally require complexmacros or fiddlingwith regular expressions. For example,given a list of items with different CSS classes:

<li class="current">The Office</li>

<li class="current">Fringe</li>

<li class="current">Touch</li>

<li class="reruns">24</li>

<li class="reruns">The X Files</li>

You could quickly change the class names of all items by combining Add Next Line with ExpandSelection to Word:

Selecting Text 44

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 fewminutes playing around with it, and next time you find yourself making tedious manualedits because there doesn’t seem to be an easy way to automate a task, ask yourself whether youcould 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 ofa set of lines. For example, the following lines of JavaScript are missing semicolons at the end, andsince 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:

Selecting Text 45

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 theselected text, you can just start typing. More likely you’ll need to move the cursors beforeyou can do anything useful. Options include the Home and End keys, which move thecursors to the first character in the line or the end of the line respectively, or the LeftArrow and Right Arrow keys. In my experiments, Left Arrow doesn’t always line up thecursors 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 wordand invoke Quick Add Next, Sublime will highlight the next occurrence of the word and insert amulti-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, especiallywhenyou 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 earlierexample 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 invokeQuick 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.

Selecting Text 46

Quick Skip Next

When making multiple selections with Quick Add Next, it’s often useful to skip one or moreoccurrences of the word you’re replacing. The Quick Skip Next allows you to jump over the nextinstance 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 seriesthat are in reruns differently from the ones that are still running:

<ul>

<li class="shows">The Office</li>

<li class="shows">The A Team</li>

<li class="shows">Fringe</li>

<li class="shows">The X Files</li>

<li class="shows">Touch</li>

<li class="shows">Knight Rider</li>

</ul>

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

Quick Add Next and Quick Skip Next work together

Selecting Text 47

The name Quick Skip Next is a little misleading. A better name might just be “quickskip.” When I started playing with this feature, I expected that highlighting a match andthen invokingQuick Skip Nextwould immediately skip the second item and highlight thethird. Instead, what happens is that Sublime unhighlights the current line and jumps to thenext 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 toskip.

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 asguilty as I am, you’ve probably copied a code snippit into your file, only to find that some hard-codedline numbers came with it:

1. $(function() {

2. console.log("Check out my mad copy and paste skillz.");

3. });

Column Selection is tailor made for this situation and similar scenarios where you need to quicklyperform a similar edit on multiple lines. Invoking Column Selection while pressing Up Arrow orDown Arrow adds a second cursor on the line above or below the current line, and pressing LeftArrow 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-shapedarea. One difference between the traditional box selection feature in most editors and Sublime’simplementation is a result of Sublime’s multiple cursor editing feature. If you box select a group oflines of differing lengths, Sublime will insert a cursor at the endof each line, which breaks out of thecolumn selection behavior:

Selecting Text 48

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. OnWindows and Linux, click and hold the scroll wheel while clicking while dragging aroundthe 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+DownArrow 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.

Selecting Text 49

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 youwant 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 simultaneouslyselect the text that was not previously highlighted. By combining Invert Selection with multi-selector regular expressions and a little creativity, you can quickly accomplish tasks like zapping unwantedlines 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 namesfrom the following CSV list, you could use multi-select to carefully highlight the last name andcomma 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 regularexpression, 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 asection 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 tagsfor deletion.

Selecting Text 51

Scoped Selection

When I’m coding, I oftenwant to select all of the text inside of a set of matching parentheses, bracketsor 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 amore elegant solution: scoped text selection.

When using scoped selection, repeatedly hitting a single keyboard shortcut will first select the textinside of the current set of braces or parentheses, then expand the selection out to include the nextset 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.

Selecting Text 52

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

Brackets

The Expand Selection to Brackets command will select any text that falls inside the current set ofparentheses, square brackets or curly braces.When invoked repeatedly, it will then select the bracketsthemselves, then select inside the next set of matching brackets, and so on. It’s a convenient way tohighlight 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 thatdon’t use a lot of braces and brackets like Ruby, CoffeeScript, Python and SQL. Selecting the bodyof 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 committingto memory. A quick example will illustrate the two main uses of this command. Take a look at thefollowing form:

Selecting Text 53

<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 andinner 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 theusername field, and the command selects neighboring content that falls within the the wrappingparent 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 tagsthemselves, then the contents of the next set of parent tags, and so on until it reaches the rootelement.

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 toremember than the more specialized selection commands, and most of the time it does the rightthing.

Starting from the current cursor position, Expand Selection to Scope works its way outward untilit finds a logical stopping place for the selection, such as a containing set of parentheses. This isperfect 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

Selecting Text 54

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 NavigationGoto

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 outwhere functions and variables are defined, and even open a file at a specific line number—all withouttaking your hands off the keyboard.

Master these, and you’ll never again find yourself digging through subfolder after subfolder in theSide 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 Sublimeproject. This is useful for languages like CoffeeScript and SASS, which by default compile coffeeand 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 forthe file’s name.

To use Goto Anything, click Goto | Goto Anything and enter part of the filename in a text inputoverlay. 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 highlightit, then press Enter to load the file in a new tab.

Navigation 57

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

Goto Definition

Keeping your code tidy often means breaking your code up into small, tightly focused bits, eachwith its own file. Organizing your project this way means it’s easier to jump into any one file andquickly understand its purpose. But there’s a downside.

When you have dozens or hundreds of files to navigate, it’s challenging to remember where avariable or function was originally defined, leaving you to root around in the code with your favoritesearch tool.

Goto Definition solves this problem by continuously scanning your code and building an indexof function and class definitions. When you trigger Goto Definition, you’ll see a filterable list ofmatching definitions, allowing you to quickly jump to the exact line of code where you defined thatfunction.

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 bydragging it into Sublime’s Side Bar. Goto Definition only indexes projects and folders—it won’tinclude arbitrary open tabs.

Then position your cursor in a variable or function name and clickGoto | Goto Definition. If there’sonly one possible match, you’ll jump straight to it, otherwise Sublime will display a filterable list ofpossible matches. As you highlight matches in the list, you’ll see a preview of the file to help youdecide which file is the one you’re looking for. If you change your mind, or if a peek at the previewis 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 monitorsthe folder for changes and updates its index whenever you add or remove a file or when you savea change. It’ll even reindex changed files when you modify them in other programs or update to anew revision in your version control tool.

Folder and project indexes are cached, so Sublime won’t reindex your project every time you openit.

Navigation 58

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

How to monitor indexingSublime’s indexing is fast—it finishes almost instantly on small projects, and even bigprojects don’t take long: Indexing the Ruby on Rails source code, 2,601 files in all, takesaround 20 seconds on my ultrabook-class laptop. But if you think Sublime is choking whiletrying to index your project, or if you just want to see when Sublime’s indexer runs, openthe Sublime console and enter sublime.log_indexing(True). Sublime will log a consolemessage 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 specifiedin the Symbol List.tmPreferences file, which is located in Default.sublime-package. The scopesection 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, thesame files that control syntax highlighting.

Limitations

Goto Definition uses Sublime’s language definition files to make decisions about what to include inthe 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’renot indexed. Triggering Goto Definition on a JavaScript variablemay show a list of similarly namedfunctions. 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 languageagnostic. If you create two methods with the same name in different languages, both will show upin 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’redebugging 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.

Navigation 59

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 namefilters 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 nameand press Enter or Returnwhen the correct symbol is highlighted. Sublime jumps to and selects thespecified symbol.

The Goto Symbol command is quite useful for some languages, less so for others: It’s great forJavaScript, 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 GotoSymbol 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 Definitionallows you to jump to the definition of the symbol under your cursor, Goto Symbol in Project letsyou 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 typinguntil the symbol you’re interested in is highlighted. You’ll see a preview of the file in the currenttab. 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 positionsyour cursor at the beginning of the symbol.

If a symbol with the same name is defined in multiple files, hitting Enter or Return closes thesymbols overlay and opens a filterable list of matching files. Press Up or Down to see previews ofthe 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 alsoincludes 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 Symbolin Project lists types and functions, but individual languages can include additional symbols. ForJavaScript, the symbol index is limited to named function definitions and functions that are assignedto objects as properties, while functions assigned to variables aren’t included. In Ruby projects, thesymbols list includes class definitions, modules, and methods.

Limitations

Like Goto Definition, Goto Symbol in Project doesn’t discriminate by language. If your projectincludes code in multiple languages, you’ll see their symbols mixed together regardless of whichlanguage you’re currently using. And if you create a symbol with the same name in two languagesin 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 GotoAnything 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 prepopulatedwith a prefix character, like the : for Goto Line? By entering that special character when you’reusing 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:42wouldopen index.html at line 42.

When you enter an @ after a file name, the options list changes to display a list of symbols availablein the file. For example, typing script@ren might open script.js and jump to a function namedrender.

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 theterm 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 getdisoriented. You hit a couple of keystrokes and suddenly you’re in the middle of a completelydifferent file in who-knows-what folder.

The Jump Back and Jump Forward commands make it easy to retrace your footsteps and remindyourself how the different pieces of code relate.

Navigation 61

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 locationto a history stack. Jump Back and Jump Forward work like the back and forward buttons in a webbrowser, 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 along file, such as when you’re simultaneously modifying a function’s definition and its usage inthat massive jQuery plugin file, or to switch between multiple related files, such as an HTML fileand 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 editinghistory.

If you Jump Back to a previous edit point, then open another file, Sublime drops your Jump Forwardhistory, and the new editing path replaces it.

Also, Sublime only maintains your history for the current editing session. If you close the editor, thehistory is cleared.

Scrolling

The Line Up and Line Down commands will nudge the screen up or down one line without movingthe 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 onWindows or Linux.

The Scroll to Selection command will jump to an off screen selection, or, if you’ve selected a largerblock 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.

Navigation 62

Code Folding

If you’re not familiar with it, code folding collapses multiple lines of code together, allowing youto hide some of the code’s details while you look at the bigger picture. Folding up all the majorfunctions in a big JavaScript file, for example, can produce an outline-like view of the file, helpingyou understand the file at a high level.

Sublime supports folding in many languages, including “curly brace” languages like JavaScript andmarkup languages like HTML and XML.

Sublime generally leaves the first and last lines of a folded section of code visible, and the hiddenlines 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 foldmarker.

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 anif statement nested inside of a function block, Sublime will fold the if block first. Triggering Foldagain 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 codefolding 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 indentedby three tab widths. Sublime supports folding at indentation levels 2 through 9. If you find yourselfwishing you could fold more than 9 levels of nested code, now is a good time to sit quietly and thinkabout 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 amisnomer, as this command doesn’t recursively fold nested code blocks as the name implies. Thinkof 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 XMLdocuments. By hiding each tag’s attributes, it brings the structure and content of your documentto the fore when you’re looking for missing tags or editing a piece of content in a document withhorrendous inline styling (shudder).

Navigation 64

To invoke Fold Tag Attributes:

• Click Edit | Code Folding | Fold Tag Attributes.

Navigation 65

Or press Command+K, Command+T on Mac OS X or Ctrl+K, Ctrl+T onWindows 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 foldedcode 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 wantto 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 aconvenient way to mark the sections you’re interested in and cycle through them with fewkeystrokes.

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 usethem 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 donewithout worrying about where in the project file structure a particular file is located. But as a projectgrows, you inevitably end up with multiple files that share the same file name, and sometimes youneed 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 highlightsthe 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 SideBar from the context menu.

Reveal in Side Bar works on file previews as well as open files.

Open Containing Folder

Tasks like renamingmultiple 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 jumpinto 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 selectOpenContaining Folder… from the context menu. Or right-click a file in the Side Bar and select the Open ContainingFolder… context menu item.

Open Containing Folder works in file previews as well as open files.

11 Find and ReplaceI’ll be honest: Before I sat down to write this chapter, I’d steered clear of Sublime’s Find features. Myinitial attempts to use it left me frustrated–find seemed fickle. There were even a few times when Icouldn’t even get it to pick out a word I was staring at on my screen. It’s right there! Why can’t yousee it?

After a little experimentation, though, I overcame my confusion and discovered some features Ireally 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 findmodeswithslightly 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 thesearch panel. These settings are global–they affect how all searches operate, even if you only enablethem for one mode. These settings are both useful and powerful, but if you don’t realize they’reenabled 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 differentmodes 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 aword.Matches are highlightedwith a light outline, and they’re also highlighted in the minimap. The main disadvantage of thistype of find is that clicking anywhere in the document will cancel the selection and remove thehighlighting from the matches.

For more involved searches, you’ll want to open the Find panel. By default, any text you’vehighlighted is copied into the search field on the Find panelwhen you first open it. (You can disablethis 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 fieldand then using the the up and down arrows.

With the Find panel open, matches remain highlighted while you navigate through and edit yourfile.

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 starttyping if you’d like to replace it.

Find All highlights all occurrences of a match and enters multiple cursor mode, allowing you toreplace all occurrences of the match simultaneously without using the Replace panel.

Shortcuts

Mac OS X:

Find: Command+FFind Next : Command+GFind Previous: Shift+Command+GFind All: Alt+EnterExit Find: Esc

Windows and Linux:

Find: Ctrl+FFind Next : F3Find Previous: Shift+F3Find All: Alt+EnterExit Find: Esc

Find and Replace 69

Incremental Find

Incremental Find is useful for quick navigations. When you perform a regular Find …, the Findpanel remains open until you manually dismiss it.

When you use Incremental Find, the editing window scrolls to the first match following yourcurrent cursor position as soon as you begin typing a search term.

Pressing Enter selects thematch for editing and dismisses the search panel, while Shift+Enter scrollsbackward to the first match prior to the current cursor position. Esc cancels the search and returnsyou to previous editing point.

Multi-edit with Incremental FindAfter performing an Incremental Find, you can press Alt+Enter to select all occurancesof 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 avariable 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 theReplace button will substitute the value entered in the Replace With field, then highlight the nextmatch.

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 buttonallows 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 beprepopulated into the Find What field.

When the Replace panel is open, you can hit Ctrl+Shift+E on Windows and Linux or Com-mand+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 supportsa Preserve Case setting that looks at the positioning of capital letters in a matched word andcapitalizes 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 sentenceand 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 ReplaceWith: 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+GFind All: Option+Enter Replace Next : Option+Command+E Replace All: Ctrl+Option+EnterToggle Preserve Case: Option+Command+A Insert Newline in Find What or Replace With: Com-mand+Enter Copy Selected to Replace With: Command+Shift+E

Quick Find

TheQuick Find command is a convenient way to search for other occurances of the word currentlyunder the cursor.

When you execute Quick Find, the next match for the word under the cursor is highlighted. Youcan 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 andinserts 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 atonce.

With the Where field, you can restrict the search to specific file types and folders. By default, thesearch includes all open files and folders.

Where filters support wildcards using an asterisk, and you can chain together multiple filters byseparating themwith a comma. The following filter will include all JavaScript files except the jQuerylibrary:

*.js,-jquery*

To see examples of the syntax for adding folders or including and excluding files, click the …, thenchoose the desired option. If you chose Add Exclude Filter or Add Include Filter, Sublime insertsa file filter example. If you chose Add Folder, a file browser launches that allows you to select theappropriate folder.

To reset the Where field to the default value, click the … button to the right of the field, then clickClear.

You can customize the way Sublime displays your search results with the Use Buffer and ShowContext buttons, located to the left of the Find field. When Use Buffer is enabled, search resultsdisplay 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 aboveand 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 arerisky business, and Sublime takes pains to ensure that you don’t do something you’ll regret. Whenyou click Replace, a prompt specifies the number of matches for the Find term and asks you toconfirm 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 changebefore saving it.

The Replace field remembers the last value you entered each time you relaunch Find in Files, sowatch that you don’t accidentally run Replace when you just want to use Find in Files.

Multi-line find and replaceAlthough it’s hard to tell by default, the Find and Replace boxes both support multi-lineinput. If you drag the top of the Find in Files panel upward, both boxes expand to a heightof 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 invalu-able. If you’re not familiar with regex syntax, it provides a powerful pattern matching language thatyou 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 helpSublime’s regular expression engine relies on Boost syntax, which derives from the Perlregex 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. Thiscan be pretty confusing: When regex searching is enabled, Sublime will often seem to fail to findmatches if your search includes special characters.

The Regular expression toggle is located to the left of the input fields in the find panels. The labelis 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

Find and Replace 73

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 isformatted, 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 helpyou tackle some common editing tasks.

For example, in the following list of names, the regular expression [A-Za-z]+,\s[A-Za-z]+matchesthe 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 quickbreakdown of the different components:

• [A-Za-z] matches any capital or lowercase letter, and adding the + makes it match one ormore 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 crutchRegular expressions aren’t my strong suit, so I rely heavily on Sublime’s real time searchhighlighting when I’m crafting a regex. It gives me instant feedback, shortening the errorpart 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 usefulwhen you’re manually hacking together some HTML or cleaning up the formatting on a piece oftext. I have a client who likes to send me long pieces of writing that he’s manually formatted withhard 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+HToggle 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+RReplace once: Option+Command+E Replace All: Control+Option+Return

12 AutocompleteAuto complete allows you to use long descriptive names for your variables and functions withoutwearing out your typing fingers. It also reduces typos and prompts you when you forget what younamed something.

Basic Usage

Although it’s not obvious, Sublime’s auto complete feature is available in all files and contexts—evenwhen you’re editing plain text.

To auto complete a word, type a few characters from the word, then press Tab to insert the bestmatch. You can cycle to the next item in the list of matches by immediately pressing Tab again.

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

Suggestions List

The auto complete suggestions list appears automatically while you’re editing source code files andwhen you start a tag in an HTML file.

The list includes keywords that are built into the language, the names of functions and variablesthat exist in the current document, and any snippets that might be available. Many plugins add newitems 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 byimmediately pressing Tab again.

You can bring up a list of available completions in any context with the Show Completionscommand. This command pops up a list of words and snippets that match the characters you’vealready typed.

Autocomplete 77

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

Auto-inserting snippetsIf you trigger Show Completions when there’s only one available choice, Sublime willautomatically 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, youcan 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 oneor even two seconds keeps it from interrupting your flow while still allowing it to prompting youwhen 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 userpreferences:

"auto_complete": false

Even with auto complete disabled, you can still summon the suggestion list with the ShowCompletions 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 orsome existing HTML with a set of matching tags.

For example, to wrap span tags around oneword 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 theselection, and the p in the opening tag is selected. Just begin typing to replace the placeholder p inthe opening tag.The closing tag automatically updates to match.

Autocomplete 78

Close Tag

It’s nice to use snippets to insert matching HTML tags whenever possible. But sometimes, especiallywhen you’re editing a chunk of existing HTML, you’ll find that you have an opening tag but noclosing tag.

To close an open tag, position the cursor at the point where you’d like to insert the tag, then selectEdit | 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 searchesbackward through your code until it finds a tag, then inserts a matching closing tag. If yourtag is already closed, you’ll end up with two closing tags.

Shortcuts

Windows and Linux:

Show Completions: Ctrl+SpaceWrap Selection with Tag: Alt+Shift+W Close Tag: Alt+.

Mac OS X:

ShowCompletions:Ctrl+SpaceWrap Selection with Tag:Ctrl+Shift+WClose Tag:Command+Alt+.

13 Vintage modeSublime’s vintage mode, which emulates Vim, provides a goldmine of keyboard navigation tech-niques. Vintage mode is beyond the scope of this post, but it’s worth looking into if you’ve nevertried 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 characterwithout 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 textaround, it’s a worthwhile investment that will reap major returns in your daily productivity.

III Automation

14 SnippetsSnippets are little chunks of boilerplate code or text that you can insert with a few keystrokes. They’regreat 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 newtasks in your custom to-do list format.

Sublime comes with snippets for a number of popular languages and markup styles, includingHTML, JavaScript, CSS, Ruby, Rails (tons and tons of these) and PHP, and snippets for otherlanguages 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 typea trigger word, then press Tab. This inserts the desired snippet and positions the cursor at the pointwhere you’re most likely to begin editing.

Depending on the snippet, there may be several additional editable fields that you can quickly cyclethrough 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 hittingTab inserts the following:

if (true) {};

The true is placeholder text. Hitting Tab a second time highlights the placeholder, allowing youto type a conditional statement to replace the placeholder. Press Tab one more time and the cursorjumps between the curly braces so you can begin implementing the code that will be invoked whenthe condition is met.

You can also cycle backwards through these fields by pressing Shift+Tab, and you can exit thesequence by pressing Esc.

Viewing Available Snippets

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

Snippets 82

One way to see the snippets available for a given context is to select Tools | Snippets. This launchesa 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-snippetextension. To open this folder, select Sublime Text 2 | Preferences | Browse Packages on Mac OSX 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 textsnippet. 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 isone example.

To wrap a few lines of code in an if block, first select the lines you’d like to wrap. Launch theCommand 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 allowsyou to use fuzzy matching to quickly find the appropriate snippet.

Wrapping snippets around existing text with the Command Palette is a little awk-ward. If you find yourself using the same snippets repeatedly you can define a cus-tom keybinding for your favorites. Here’s an example that binds Ctrl+Shift+I to theif 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 project-specific snippets to share with your team members.

A Sublime snippet is a simple XML format, saved with the extension sublime-snippet. To see howa snippet is structured, let’s reimplement and then tweak the JavaScript if block snippet that shipswith Sublime. This included snippet inserts the following code when you type if and press Tab:

if (true) {};

Snippets 83

File Format

Each snippet file includes a trigger word, the code or text to insert, optional placeholders that denoteeditable regions, a scope that indicates what language the snippet represents, and a description thatappears 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 andhitting 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 knowsyou’re editing JavaScript, whether you’re in a .js file, inside of a script block in an HTML file, orin 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 forthe 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 andoptional 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 theuser 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 theuser to be able to insert the same text in multiple places at once, duplicating the field marker willcause 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 acallback 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 theinvocation 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 placeholdertext to a field, use curly braces around the number and placeholder, and separate the number andplaceholder content with a colon:

${1:placeholder}

Snippets 85

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 thatthe user highlighted before triggering the snippet, and it allows the snippet to wrap the existinghighlighted 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. Sublimesupports 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 mycode, so I’d like my if statements formatted on three lines, like this:

if (true) {

};

Since I’mmainly modifying the text that the snippet inserts, most of the changes will go in the CDATAsection. This section is white space sensitive, so any formatting I apply there will be preserved inthe inserted code. Unfortunately, this includes the white space I’d normally use to properly indentthe 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 youcan locate by launching the Command Palette and typing Browse Packages. Be sure to usethe 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 MacrosWhat are macros?

A macro is a recorded sequence of commands that you can replay over and over to automate arepetitive task.

Macros serve as a gateway to extending Sublime: While they’re not as powerful as full-blownplugins, 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 afirst-class Sublime command or plugin.

In fact, you may already use macros without realizing it. Some of Sublime’s editing commands arereally just macros, including Add Line, Add Line Before, and Delete Line. For a list of these built-inmacros, click Tools | Macros.

What are they good for?

Macros are best suited for adding little convenience commands that fine-tune the editing experiencein Sublime.

For example, if you write JavaScript or a C-based language, you might create a macro that jumps toend 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 trailingwhite 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 hassome limitations. If the task you want to automate involves manipulating files or folders or callingexternal 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 bracelanguages. 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 ormethod with a straightforward purpose but an implementation that’s well … interesting. No, scratchthat. 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 thedeclaration of a function or method but delete its implementation.

The Function Nuke macro deletes everything inside the curly braces in one keystroke, making iteasy 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 yourmacro to include—and what it should not include. You might even want to rehearse the process onceor 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 needto position the cursor correctly before you start recording the macro, you might end up recordingsome 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? Notnecessarily. The recorder will capture some mistakes, but you can easily edit them out later. Butif you plan to save your macro for later use, a little extra upfront care will make editing easier lateron.

After you’ve planned the steps in your macro, perform any preliminary steps that you don’t wantto include in the recording. For the example macro, this involves positioning the cursor inside thefunction that you want to nuke.

¹http://thedailywtf.com/Articles/JavaScript_Hacks_.aspx

Macros 89

When you’re ready to start recording, click Tools | Record Macro. You’ll see a Starting to recordmacro … message in the status bar.

Begin executing the steps you want to include in the macro. Take your time here—the macro willalways 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 willremove the errant command and subsequent Undo from the recording.

To create the Function Nuke macro, click Selection | Expand Selection to Brackets to highlight thefunction body. Then press Delete to eliminate the offensive code. Finally, press Enter, which movesthe closing curly brace down two lines and positions the cursor on the line below the functiondeclaration, ready for your brilliant new code.

When you’re done, click Tools | Stop Recording Macro. You’ll see a Recorded macro with 3commands message in the status bar.

Saving

Sublime stores macros in an in-memory buffer, which means that carefully scripted sequence youjust recorded will vaporize if you close Sublime. And there’s just one slot; you’ll stomp all over it ifyou record another macro. So unless you created a throwaway script for a quick cleanup task, you’llprobably want to save your macro.

To save the Function Nuke macro, click Tools | Save macro …. The file save dialog opens to thedefault location for user macros, which is your Packages\User folder. Enter Function Nuke as the filename, then click Save. Sublime saves themacro as a JSON-formatted text file with a .sublime-macroextension.

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 yourmacros 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 youwant 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 folderwhere you saved it. If you’ve followed the steps to create Function Nuke, you’ll find it under Tools| Macros | User | Function Nuke.

Macros 90

Editing

Sublime does a pretty good job of weeding out mistakes as you record a macro—as long as you useUndo to reverse them. But if you made a typo and fixed it with Backspace, Sublime will faithfullyrecord both the error and subsequent correction.

If you’re a perfectionist, you can clean up your macro by hand so it only executes the commandsyou intended to record.

Macros are JSON-formatted files that contain an array of command objects. Each command objectconsists of args and command properties. Here’s a (pretty useless) macro that executes a singlecommand, 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 byhand—what can I say, bad code triggers my reflexes. The resulting recording includes someunnecessary commands:

[

{

"args":

{

"forward": false

},

"command": "delete_word"

},

{

"args":

{

"forward": false

},

"command": "delete_word"

},

{

"args":

{

"to": "brackets"

Macros 91

},

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

[

{

"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 syntaxerror, which will cause the macro to silently fail when you try to run it.

Macros 92

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 objector 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’srunning the Add Line in Braces macro, which moves the closing brace down two lines and indentsthe 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 secondsmatter when you’re staring at code that’s this ugly—and who wants to click and hover through threelevels of menus?

You can assign a keyboard shortcut to custommacros by following the standard steps to create a keybinding, 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 APISince macros are just a JSON-formatted list of commands, you can use them to figure out whatAPI 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 usersof 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 evenhave a find panel open.

In editors like Vim or emacs, it’s common to create macros to perform tasks like converting asequence of lines to a comma-separated list by doing a find on the newline character and replacingit with a comma.

But since Sublime doesn’t support find or find and replace in macros, there’s no way to do this witha macro.

Often it’s simple to accomplish the task by writing a plugin, and scripting Sublime plugins in Pythonis likely to be easier for many users than, say, working with Vimscript. Creating a plugin is overkillfor many cleanup scenarios, though.

This is one of the biggest gripes that power users of other text editors express about Sublime, andit’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 differentslots, 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 createanother. The upside to this is that you’ll be able to use the saved macro again in the future. But it’sa 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, thenswitch tabs, Sublime reenables the Record Macro menu option and allows you to start recordingadditional macros.

But if you think this means you can record multiple macros in parallel, you’re destined fordisappointment. 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 includecommands that operate on a file’s contents. Higher level commands, like those that operate on thefile 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 savingthe file and moving to the next file.

IV Customizing the Editor

16 Command Palette TweaksMost of the commands in Sublime’s main menu are available through the Command Palette, butthere are some curious omissions, like View | Enter Distraction Free Mode and View | EnterFull Screen. I usually enter full screen mode whenever I relaunch Sublime, and I like to jump intodistraction free mode when I’m writing. The shortcuts for these two commands are different on Macand PC, and my efforts to memorize them have thus far failed. So to the menus I went whenever Iwanted 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 configurationfiles with the extension .sublime-commands. Sublime will automatically load any command files itfinds under /Data/Packages.

A filename search for sublime-commands will turn up numerous examples, especially if you havea lot of plugins installed. But the granddaddy of them all is the file that sets up Sublime’s defaultCommand 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 itanywhere under /Data/Packages.

The configuration file specifies the text that’s shown in the Command Palette in the caption fieldand 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 namewhatever 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 isthe configuration file for the main application menu. This is located at/Data/Packages/Default/Main.sublime-menu. You can search using the text that appearsin the main menu to find the correct API method to call. To find the Enter DistractionFree Mode command, I searched for distraction and found toggle_distraction_free.

17 Menu EnhancementsWhile Sublime’s keyboard shortcuts and Command Palette allow me to edit effortlessly withouttouching the mouse, there are still times I find myself reaching for the menus. Often I’ll opt for amenu selection when I’m already using the mouse to browse and open arbitrary files in Finder orWindows Explorer.

But for some tasks, using the menus is a pain. One common chore I perform is setting the syntaxfor a snippet of code I’ve copied from a web page. I always have trouble remembering where theSyntax entry is hidden (it’s buried under View | Syntax), and once I find it there’s a submenu withdozens 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 toenhance 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 sureto 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’sright-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 submenuthat 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 APIcalls for every item listed in the menus.

18 Key BindingsLike other settings in Sublime, keyboard shortcuts, or key bindings, are configured in a text file thatyou can view and edit.

This means you can see a full list of default keyboard shortcuts, although it’s not in the most reader-friendly format. It also means that overriding shortcuts with your own custom bindings is a snap inmost cases.

The key bindings file uses the official Sublime names for commands, making it a handystarter 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 whenSublime updates itself. Instead, edit the user-specific keymap file instead. Bindings in the userkeymap file override Sublime’s defaults.

On a Mac OS X system, the user keymap file is located at:

Key Bindings 102

/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 | KeyBindings – 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 bindingconsists of two parts: an array of keyboard shortcuts and a command to execute. Since the keyboardshortcuts 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 desiredkeyboard shortcut and command.

Here’s an example that remaps Paste and Indent toCtrl+V, which is useful, and overrides theUndocommand 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 tooverride an existing shortcut or bind one for a command that doesn’t already have one setup.

Key Bindings 103

Context-specific key bindings

Sometimes you might want to prevent a keyboard shortcut from firing unless certain conditions aremet. Or you might want the same shortcut to trigger different commands based on the language ofthe current file or surrounding code. Key binding contexts give you this type of fine-grained controlover 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-linecomment in multiple languages. Sublime already includes the Toggle Comment and Toggle BlockComment commands, but neither makes it particularly convenient to jump to the end of a line ofcode and insert an explanatory (or apologetic!) comment.

Our new EOL Comment command lets you use the same shortcut to insert an inline comment inJavaScript:

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 Endto jump to the end of the line, then press Space, enter // to start the comment, then press Space onemore 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 BlockComment 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 commandor 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 tonarrow the scope of your shortcut. Each item in the context array is essentially a simple querythat’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. Specifyinga value of selector means the rule will check the current language scope. You can also query thesurrounding text or user preferences.

The operand is the value we want to compare the query results to. Since we’re interested in thecurrent language, the example specifies a language scope, but you might also use a boolean value orregular expression.

The operator property determines how to compare the queried value to the value required by theoperand. 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 canalso use them to apply different shortcuts based on user preferences, whether a panel is shown orhidden, or whether the surrounding code matches a regular expression.

The default keymap file has numerous examples of context rules. For example, Sublime’s implemen-tation of quote auto-pairing is really just a “keyboard shortcut” that fires when you enter " and afew context rules are satisfied, including one that makes sure that auto_match_enabled is true. If allthe 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, operatorand operand values, see the the unofficial Sublime documentation key bindings page¹.

¹http://docs.sublimetext.info/en/latest/reference/key_bindings.html

19 Managing PluginsPackage Control

The Package Control¹ plugin is the plugin to rule all plugins. It allows you to browse and installhundreds of plugins written by happy Sublime Text 2 users.

Setting up Package Control involves run a small script in the Sublime Python console, andinstructions 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 Com-mand 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 triggersome plugin that you only use occasionally. Fortunately, it’s easy to review your list of installedplugins and read their documentation using the Browse Packages command.

To view installed plugins:

• Click Sublime Text 2 | Preferences | Browse Packages onMac OS X or Preferences | BrowsePackages on Windows and Linux. The system file explorer launches, displaying the foldersfor all installed packages.

Most packages include a README file that includes usage instructions and keyboardshortcuts.

¹http://wbond.net/sublime_packages/package_control

V Recipes

20 Essential PluginsExtend Menus for the Sidebar

By default, the Sublime Text 2 sidebar is a bit weak. It allows you to browse through open files andfolders, 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 ofcommands 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 Chromeor 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’reslinging code. The AdvancedNewFile² plugin provides a simple prompt that allows you to generatenew files by typing out your desired path and file name. Any nested directories that you include inthe 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 similarlanguage 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. Forexample, 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 Emmetproject 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 Word-Count 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 Settingsand Plugins

Between my day job as a software developer and my freelancing and writing, I bounce aroundamong 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 processof installing packages and tweaking configs.

The Windows version of Sublime is available as a portable installation, which keeps all of the filesSublime needs in one place and doesn’t touch the rest of the system. This allows you to install it ona 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 asevery other type of file. I created a \Programs\Sublime folder in Dropbox and installed the portableversion 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.

TheMac version of Sublime, sadly, doesn’t support this. Mac OS X doesn’t have a concept of portableapps, 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 linksto the folders used by the portableWindows installation installed in the∼/Dropbox/Programs/Sublime/

directory.

#!/bin/bash

cd ~/Library/Application\ Support/Sublime\ Text\ 2/

rm -rf ./Packages

rm -rf ./Installed\ Packages

rm -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 yourWindows 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 executethe 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. Usecd "%PROGRAMFILES%\Sublime Text 2" instead.

I’ve encountered two issues with syncing all of Sublime’s configuration files this way. The first issuepertained to syncing project and session files. I was trying to store project files in a central locationin Dropbox, and I found that Sublime tended to use full paths instead of relative ones. I later realizedthat you’re supposed to keep projects in the root directory of the files they pertain to. So if you havea project called MyWebsite, it goes in the MyWebsite root directory. This allows you to check theSublime .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 tosit back from the screen a bit more than when I’m working on my MacBook. But Sublime doesn’tknow that, and the font settings sync along with everything else.

22 PHPSetting up a New Project

Starting a new project is both a joy and a chore. Working with a clean slate is fun–no unfamiliarcode 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 anew 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 ofyour favorite open source libraries and frameworks.

Once you install and configure Fetch, you can install the latest version of jQuery from Sublime witha simple command:

¹https://github.com/weslly/Nettuts-Fetch

PHP 113

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, hitEnter, 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. Addingmorefiles and packages is just a matter of making a quick change to Fetch’s configuration file.

Let’s configure Fetch to downloadWordPress Plugin Boilerplate³, which makes it easy to get up andrunning when you’re starting a new WordPress plugin.

First, launch the Command Palette and type fetch: manage, then press Enter to open the Fetchconfiguration 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. ThejQuery link isn’t tied to a specific version of the library, and the Github link always gets the newestcommit to the master branch of HTML5 Boilerplate.

Also note the zipball portion of the HTML5 Boilerplate link. When you want to download acollection of files, Fetch expects a link to a zipped archive, which it will then extract for you to afolder 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

PHP 115

Launch the Command Palette and type fetch package, press Enter, then type wordpress and hitEnter 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 youspecified, where you’ll see a plugin-boilerplate folder. Rename that folder to whatever you’dlike 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 byclicking Project | Save As … so you can easily reopen it later.

PHP 116

Time to start coding!

Having to open your file browser and rename the plugin folder is a little clumsy, but that’sdue to a quirk in the WordPress Boilerplate Plugin project, not a shortcoming of Fetch. TheWordPress Plugin Boilerplate project uses the plugin-boilerplate subfolder to organizeall of the php, js and css files and folders, instead of keeping them in the project’s rootdirectory. Fetch expects the files to live in the root directory. The HTML5 Boilerplate projectis structured this way, and you can install it right into the root directory of an existingSublime 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 limitedto 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 highlight-ing.

The Sublime PHP Code Sniffer plugin⁵ would have saved me many frustrating hours. With sublime-phpcs installed and configured, you get automatic error checking every time you save a file. The

⁵https://github.com/benmatselby/sublime-phpcs

PHP 117

plugin highlights errors on the line where they occur, and it even gives you hints as to what theproblem might be.

Setup

Sublime PHP Code Sniffer is available for installation through Package Control. Just run the installpackage command and search for sublime-phpcs.

When you first install the plugin, though, it won’t do much. Sublime PHP Code Sniffer relies on thefollowing 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 systempath 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, whichyou can open from the application menu by clicking Preferences | Package Settings | PHP CodeSniffer | 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 PHPis installed on your local machine. Confirm that the PHP executable is available in your path byrunning command php --version. You’ll see the PHP version number and copyright informationif PHP is set up correctly.

Next, open the plugin’s user settings file by clicking Preferences | Package Settings | PHP CodeSniffer | Settings - User. Then set the phpcs_sniffer_run setting to false. After configuringsublime-phpcs on Windows 8, my user settings file looked like this:

⁶https://github.com/benmatselby/sublime-phpcs

PHP 118

{

"phpcs_sniffer_run": false

}

The default plugin settings assume you have the external PHP Code Sniffer tool installed andconfigured, 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 TurnExecute 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 hidesany errors in your file, and the Goto next error‘ and Show previous errors commands allow youto 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 PHPcode, and save the file. Out of the box, sublime-phpcs is configured to check your file every time

PHP 119

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-phpcswill only display the first error it finds.

The parser error message displays in the status bar when you click on a highlighted error. Take boththe error message and the line highlighting with a grain of salt, though. Often, the real problem is atypo 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 andcoding 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, butthe easiest way to get it running is using the PEAR package manager. I used these instructions⁸ toset 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 tofind 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 theexecutable path setting. When this setting is true, sublime-phpcs prints error messages in Sublime’sconsole 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 Zendstandards 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 standardsviolations and coding errors is quite smooth.

To illustrate, let’s run the the plugin.php page from theWordPress Plugin Boilerplate through PHP_-CodeSniffer and see what it finds:

PHP 121

Sniffing this file found dozens of standards violations.

PHP_CodeSniffer is complaining about multiple violations per line, including missing documenta-tion, use tabs for indentation instead of spaces, method naming conventions, commenting styles andbrace formatting.

The tabs issue is easy to address: Just run Indentation: Convert to Spaces from the CommandPalette.

When you save the changes, sublime-phpcs reruns PHP_CodeSniffer and displays the remainingerrors in a quick panel. Selecting an error lets you jump directly to the relevant line, where you canmake 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 Showprevious 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 consistentand kept up to date. Stale documentation is worse than none at all: It lulls you into a false sense ofconfidence with its lies.

Keeping the documentation close to the code it describes makes it more likely that you’ll update itto reflect changes in the code, and the popular PHPDoc⁹ plugin enables you to do just that.

⁹http://phpdoc.org/

PHP 122

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 automat-ically closing the comment.

• Document functions by extracting parameter names from the function, including type-hintedvariables 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

PHP 123

Creating a new block comment.

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

PHP 124

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, parametersand return value:

PHP 125

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 ordefault 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 pluginguesses at the variable’s data type:

PHP 126

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 placeholdersfor the author name and email address:

¹¹http://www.phpdoc.org/docs/latest/for-users/phpdoc/tag-reference.html

PHP 127

DocBlockr includes snippets for PHPDoc tags.

If you get interruptedwhile filling out a comment block, leaving a bunch of uncompleted placeholderfields in your comment, just place the cursor back in the comment and run the Reparse commentblock command. DocBlockr will detect the remaining fields and allow you to quickly cycle throughthem with the Tab key.

Building Documentation

DocBlockr doesn’t provide support for generating HTML documentation with PHPDoc, but you caneasily 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 thePHPDoc site. Make sure you enable the XSL extension for PHP¹³, or you won’t be able to generateHTML 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

PHP 128

{

"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 asPhpDoc.sublime-build.

To generate HTML documentation for your project, make sure you’re editing a PHP file in theproject, then click Tools | Build System | PhpDoc to switch the build system to your new PHPDoccommand. Then click Tools | Build.

Sublime displays the build output in the console, as well as any errors that occurred while compilingthe 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:

PHP 129

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 Googlewhen 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 ofthe 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 lookup, 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 firstplace I turn when I find myself stuck on a hard problem. The Stack Overflow plugin¹⁶ makes it eveneasier 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 StackOverflow 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 SCSSSASS¹, short for Syntactically Awesome Style Sheets, is a massively popular tool for web developersthat takes a lot of the pain out of writing CSS. Unfortunately, Sublime doesn’t provide a lot of helpif you want to use SASS in your project.

Package Control lists a number of seemingly useful plugins, but each provides just one or two SASSfeatures–none of them gives you everything you need to use SASS effectively. Then there’s thewhole compiling thing–messing with a separate command line tool every time you want to make aCSS 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 andknow 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 ityet, Package Control lets you install hundreds of plugins with just a few keystrokes–without leavingSublime. 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

SASS and SCSS 132

Syntax Highlighting

The first time you open a sass or scss file, Sublime just shrugs its shoulders and treats it like plaintext, 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 runawayfavorite is the sass-textmate-bundle plugin⁴, called simply Sass in Package Control.

⁴https://github.com/nathos/sass-textmate-bundle

SASS and SCSS 133

After you install the Sass plugin, when you open a scss file you’re greeted with beautifullyhighlighted 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:

SASS and SCSS 134

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 sassextension 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 oneof the files in the SASS plugin. That’s a bad idea because future updates to either of those packageswill 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 agiven file extension.

To force Sublime to correctly highlight sass files: 1. Open a sass file. 2. Click View | Syntax | Openall 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 helpfrom a couple of plugins, you can configure Sublime to automatically compile your SASS stylesheetsevery time you save a change.

Sublime’s build system feature allows you to create custom build tasks and associate them withspecific file types. You can do this by hand in your sublime-project file, or you can let the SASSBuild 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 hitCtrl+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 formatsthe 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 overridethis location–maybe you prefer your CSS to live in a separate folder called css that you don’t checkinto 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 thebuild_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 theside 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, itputs 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 blownaway 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 tospend 30 minutes debugging a crazy stubborn CSS issue only to realize that you actually fixed it 25minutes 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 executethe default build action whenever you save changes to a file. (It’s also handy when you’re workingwith 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 ShortcutsWindows

Command ShortcutJump Back Alt+-Jump Forward Alt+Shift+-Goto Definition F12Goto Line Ctrl+GGoto Symbol Ctrl+RGoto Symbol in Project Ctrl+Shift+RPaste from History Ctrl+K, Ctrl+VDefault Layout Alt+Shift+1Two-Row Layout Alt+Shift+8Three-Row Layout Alt+Shift+9Two-Column Layout Alt+Shift+2Three-Column Layout Alt+Shift+3Four-Column Layout Alt+Shift+4Two-by-Two Grid Layout Alt+Shift+5New Group Ctrl+K, Ctrl+UpMove File to New Group Ctrl+K, Ctrl+Shift+UpClose Group Ctrl+K, Ctrl+DownFocus Next Group Ctrl+K, Ctrl+RightFocus Previous Group Ctrl+K, Ctrl+LeftFocus Group 1-9 Ctrl+1 - Ctrl+9Move to Next Group Ctrl+K, Ctrl+Shift+RightMove to Previous Group Ctrl+K, Ctrl+Shift+LeftMove to Group 1-9 Ctrl+Shift+1 - Ctrl+Shift+9Record Macro, Stop Recording Macro Ctrl+QPlayback Macro 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 highlightedfolder|Left| |Open highlighted file|Enter|

OS X

Keyboard Shortcuts 139

Command ShortcutJump Back Ctrl+-Jump Forward Ctrl+Shift+-Goto Definition F12, Command+Alt+DownGoto Line Ctrl+GGoto Symbol Command+RGoto Symbol in Project Command+Shift+RPaste from History Command+K, Command+VDefault Layout Option+Command+1Two-Row Layout Shift+Option+Command+2Three-Row Layout Shift+Option+Command+3Two-Column Layout Option+Command+2Three-Column Layout Option+Command+3Four-Column Layout Option+Command+4Two-by-Two Grid Layout Option+Command+4New Group Command+UpMove File to New Group Command+Shift+UpClose Group Command+DownFocus Next Group Command+RightFocus Previous Group Command+LeftFocus Group 1-9 Ctrl+1 - Ctrl+9Move to Next Group Command+RightMove to Previous Group Command+LeftMove to Group 1-9 Ctrl+Shift+1 - Ctrl+Shift+9Record Macro, Stop Recording Macro Ctrl+QPlayback Macro 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 highlightedfolder|Left| |Open highlighted file|Return|

Linux

Keyboard Shortcuts 140

Command ShortcutJump Back Alt+-Jump Forward Alt+Shift+-Goto Definition F12Goto Line Ctrl+GGoto Symbol Ctrl+RGoto Symbol in Project Ctrl+Shift+RPaste from History Ctrl+K, Ctrl+VDefault Layout Alt+Shift+1Two-Row Layout Alt+Shift+8Three-Row Layout Alt+Shift+9Two-Column Layout Alt+Shift+2Three-Column Layout Alt+Shift+3Four-Column Layout Alt+Shift+4Two-by-Two Grid Layout Alt+Shift+5New Group Ctrl+K, Ctrl+UpMove File to New Group Ctrl+K, Ctrl+Shift+UpClose Group Ctrl+K, Ctrl+DownFocus Next Group Ctrl+K, Ctrl+RightFocus Previous Group Ctrl+K, Ctrl+LeftFocus Group 1-9 Ctrl+1 - Ctrl+9Move to Next Group Ctrl+K, Ctrl+Shift+RightMove to Previous Group Ctrl+K, Ctrl+Shift+LeftMove to Group 1-9 Ctrl+Shift+1 - Ctrl+Shift+9Record Macro, Stop Recording Macro Ctrl+QPlayback Macro 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 highlightedfolder|Left| |Open highlighted file|Enter|