

Handy text manipulation tricks in Sublime Text 2 - joshearl
http://whiletruecode.com/post/7-handy-text-manipulation-tricks-sublime-text-2

======
edanm
Any article that talks about tricks in Sublime Text 2 without mentioning
Multiple Cursors is... lacking (no offense to the OP).

For anyone that doesn't know it, Multiple Cursors is the ONE BRILLIANT FEATURE
that Sublime Text has. Don't get me wrong, tt's great in many other ways too,
but Multiple Cursors is, IMO, a feature that should become part of every
friggin' text editor in existence, it's that important. And it only exists in
Sublime Text.

It gives you multiple cursors at seperate places in your document. Each one
acts completely independently, moving around with your commands. Everything
works as expected, including copy-pasting (it will match the copy-pastes up to
your cursors).

Most text editors have a column-select mode, except that Multiple Cursors are
the same thing on steroids:

1\. The selections don't have to be contiguous. So if you have a bunch of:

<div>

    
    
      <p> Text And more Text</p>
    
      <p> Something </p>
    

</div>

You can put the cursor only on the <p>s.

2\. Since each cursor acts independently, you can do operations that you
simply can't do in column mode. For example, place the cursor on each <p>,
select to the end of that </p>, and delete the text. This is even if the
contents of the </p> are completely different.

3\. Multi Cursor gives the same power as macros, but: They're visual! You see
all the changes you're making in realtime. Any long-time vim user has probably
recorded a macro, tried playing it back, and discovered that it didn't work.
Well, with Multi Cursors, you see the cursor and changes in real-time. Make a
wrong command? Undo it instantly.

Want an example of another actual use case? I used to have a plugin for
Sublime Text that let me split a selection into multiple selections, based on
a character. So, let's say I had this code:

foo(int a, char b, char c)

I could select the paramater list, run my shortcut to split by ",", then I'd
get a different selection on each paramater. Then, I could simply multi-select
three lines below it inside the actual function, paste, and I've got this
code:

foo(int a, char b, char c)

    
    
      int a
    
      char b
    
      char c
    

A dead-simple editing task I do 300 times a day.

Another example? Let's say I have two "if" blocks in the top of a function:

if (somecondition):

    
    
      return
    

if (anothercondition):

    
    
      return
    

Now, let's say for a second that I just realized I don't want to return, I
want to do some processing, then return. This happens a few times a day for
me. I just multi-select both "if"s, hit enter, and add the code. If it's two
functions and I need to use the function names, I can even go back, copy the
function name, and paste it as part of the processing!!

Phew. If it seems I'm a fanboy for Multiple Cursors, I totally am. It's a
brilliant tool that only exists in Sublime Text. I've unfortunately gone back
to Vim, and am too far in Vim's world to manage working in Sublime Text, which
is why I miss multiple cursors so much!

But I AM working on a Vim plugin that gives Vim Multiple-Cursors. Been working
on it for a while, but I think I'm getting near a more-or-less stable version.
Hopefully, it will be released soon.

</way-too-long-rant>

~~~
dave1010uk
I guess you are aware Sublime Text 2 has a Vim mode. As someone who's gone
"far in Vim's world", how do you think this compares to regular Vim? I'm
starting to learn Vim commands in ST2 but I don't know if "proper" Vim is
required to get fully into Vim.

~~~
edanm
I'll be brutally honest. I think it's a great effort, and almost moved back to
Sublime Text w Vintage mode several times. And each time, I'll run a command
that Vintage mode doesn't have yet, and leave.

I'd love it if ST managed to replace vim. I (very unfortunately!) don't see it
happening soon. Vim just has so many features and so many plugins.

NOTE: Half of my plugins in Vim are only there to make vim behave like a
decent, modern editor. In fact, half of my plugins in Vim are there to make it
behave more like Sublime Text.

------
damncabbage
Vim equivalents if you're feeling jealous (matching the order in the article):

    
    
      J    Join line.
    
      ddp  Swap line with the one below.
      ddkP Swap line with the one above.
    
      dd   Delete current line
      yyp  Duplicate line
    
      gq}  Rewrap a paragraph.
    
      Vu   Lowercase a line
      VU   Uppercase a line
    
    

Sort the selection by the Unix `sort` command (eg. sort -rn for reverse
numeric order):

    
    
      V <select your lines>
      :!sort
    
    

It goes a bit pear-shaped for these ones, though:

    
    
      Title-Case:
      :s/\<\(\w\)\(\w*\)\>/\u\1\L\2/g
    
      Twiddle/Flip Case:
      function! TwiddleCase(str)
        if a:str ==# toupper(a:str)
          let result = tolower(a:str)
        elseif a:str ==# tolower(a:str)
          let result = substitute(a:str,'\(\<\w\+\>\)', '\u\1', 'g')
        else
          let result = toupper(a:str)
        endif
        return result
      endfunction
      vnoremap ~ ygv"=TwiddleCase(@")<CR>Pgv
    
    

I'm a bit stumped on toggling comments, though. Any ideas?

~~~
jurre
I think macvim has this because I've been doing it for as long as i remember,
or maybe it's in Janus though.

~~~
damncabbage
This is all plain vim, so this'll work in MacVim, GVim and Janus (just MacVim
and a bundle of plugins).

~~~
jurre
sorry i meant command / to toggle comments

------
forbes
I use both Emacs and vim on a daily basis. Emacs is my main editor and vim is
for quickly dropping in to make a change in a terminal either locally or on a
server.

Both are amazing. Both are rock solid. Both are infinitely extensible. Both
are free as in beer and as in freedom.

I'm not afraid of paying good money for software. I don't think it is
necessary to pay for a closed-source text editor when such good open-source
options exist that can do everything the commercial product can do and more.

TextMate (and now Sublime Text) have been popular in the hacker community,
particularly with Rails people. The only advantage I can see is eye-candy.
They look great on Macs.

I tried TextMate and put it in the trash as soon as I found it had no split
windows. Not only that, I couldn't add split windows even if I had the time.
If vim or Emacs is missing something, you can add it.

End of rant.

~~~
huskyr
Have you actually tried Sublime? It has split windows. And you can extend is
pretty easily using packages. I've read many posts of vi and Emacs hardcore
users who actually liked Sublime.

~~~
forbes
Yes I have. My comment about split windows was about TextMate, which 4 years
later still doesn't have them. (Coming in TextMate 2, which will be released
sometime after Half Life 3.)

Sublime has the eye candy, that I was talking about. It looks great. The
'birds eye' view is nice, but not particularly useful. There is nothing that
it can do that it can do that Emacs/vim can't do or couldn't do with a few
minutes of macro-recording/scripting. This is why I am saying it isn't worth
the money. The open-source alternatives are superb.

~~~
kylebrown
I don't want to need a cheat sheet to use my text editor, I already need them
for the programming language, the regexes, mathematical notation, etc. I don't
want to spend a few minutes doing macros/scripting, I want to spend my minutes
on the problem domain I'm actually working on. I don't like modes (see NO
MODES in the Bret Victor talk), and I like positioning my cursor with a mouse.

I haven't paid for Sublime (yet), but I'm still much less annoyed by the
occasional nag-boxes than by modes. I don't see a future in emacs/vim, but I
am anxiously awaiting an intelligent editor such as LightTable.

~~~
forbes
Remembering shortcuts for Sublime would be no different to remembering
shortcuts for Emacs/vim/whatever. I agree with the 'no modes' sentiment which
is why I find Emacs more natural than vim for the bulk of my work.

If you forget the short-cut for a command in Emacs, you can hit M-x, type in
the name of the command (with completion to help you) and once you execute the
command Emacs will TELL you the shortcut for next time (if there is one
assigned). Best feature ever.

------
jskinner
A few more handy ones:

Line Manipulation:

    
    
      Select Line (press again to select subsequent lines): Command+L / Ctrl+L
      Split multi-line selection into multiple selections, one per line:
        Command+Shift+L / Ctrl+Shift+L
      Delete to BOL: Command+Delete / Ctrl+Shift+Backspace
      Delete to EOL: Control+K / Ctrl+K,Ctrl+K or Ctrl+Shift+Delete
      Delete Line: Control+Shift+K / Ctrl+Shift+K
      Insert Newline After: Command+Return / Ctrl+Enter
      Insert Newline Before: Command+Shift+Return / Ctrl+Shift+Enter
    

Multiple Selections:

    
    
      Add next occurrence of current word to selection: Command+D / Ctrl+D
      Select all occurrences of current word: Control+Command+G / Alt+F3
      Undo through selection changes: Command+U / Ctrl+U

------
dmarble
Sublime Text 2 – Useful Shortcuts

<https://gist.github.com/1736542>

~~~
creamyhorror
I think this is even handier than the original submission. Upvoted.

------
scottjad
Not a complete list, but some Emacs equivalents:

    
    
      M-^ delete-indentation (or join-line)
      C-x C-t transpose-lines
      kill-line
      M-0 C-k kill to beginning of line
      djcb-duplicate-line (not built-in)
      M-q fill-paragraph
      C-c c comment-uncomment
      M-c capitalize-word...
      org-move-line-up
      C-u M-| sort

~~~
yoklov
M-^ is one of my favorite commands in emacs. I use both sublime and emacs on a
daily basis (Sublime has better support for the languages I use at work), and
it's a constant source of frustration that C-j in Sublime text joins the line
below with the current line, whereas M-^ joins the line above.

I guess that's what I get for not using one editor for everything :p

------
bemmu
I'm doing Google App Engine Python stuff with Sublime Text 2.

Is there any way to get it to somehow guess at function signatures? So if I
start writing do_something(... I could see the args that do_something()
expects. Assuming it's just a function that is plainly defined somewhere in my
project folder would be enough for me.

Another thing is when I am testing the app in localhost and it spits out error
messages indicating the line number(s) where I sinned, it would be nice to
somehow be able to jump to them.

~~~
aaroneous
Have you seen CodeIntel? <https://github.com/Kronuz/SublimeCodeIntel>

------
cageface
Now that I've gotten used to first class refactoring support in the Jetbrains
products any other editor just seems archaic. IntelliJ has all the features
mentioned in this article _and_ intelligent code restructuring.

~~~
_casperc
Does it allow you to have multiple projects open at the same time yet? That
was what prevented me from using it earlier.

~~~
cageface
Yes:

[http://www.jetbrains.com/idea/webhelp/opening-multiple-
proje...](http://www.jetbrains.com/idea/webhelp/opening-multiple-
projects.html)

~~~
_casperc
Sorry, I should have been more clear. I meant multiple projects in the same
workspace, like what netbeans or eclipse has (or even Sublime).

I really like being able to navigate in all my open projects at the same time.
Not having it is a no-go for me.

------
daurnimator
My favourite feature is definently multiple cursors; Ctrl+D selects the next
occurance of your highlighted word, Alt+F3 selects all occurances.

~~~
cheatercheater
That's interesting. Can you edit all selected occurrences at once? I don't
think there's an immediate analogue in Vim.

~~~
edanm
There is no analogue in Vim. It's the one thing I hate about vim.

~~~
tincholio
:%s/original/new/g

------
sirn
My favorite: in HTML editing mode you can press Ctrl-Shift-A to select
enclosing tag and modify both open and close tag at the same time. Very handy
when editing HTML files (although I'm not sure if this is Sublime's built-in
or from any third party package I installed.)

------
Kilimanjaro
I've changed some key bindings to suit my taste, like:

    
    
        Cmd-D: Duplicate line
        Cmd-L: Delete line
        Cmd-T: Insert HTML tag
        Cmd-B: Open in browser
        Ctrl+Up/Dn: Toggle lines
        Ctrl+a/e/i/o/u: Accented á é í ó ú
    

Sublime Text 2 has become my favorite editor, fully customizable and plenty of
plugins available.

~~~
simonsarris
Can you share with us how you made these bindings? Specifically open in
browser? using

    
    
        	{ "keys": ["f8"], "command": "openInBrowser" },
    

Didn't work on my windows machine when I made it.

~~~
Kilimanjaro
Here is how I did it for Safari, change accordingly.

Go to Tools/BuildSystem/NewBuildSystem... Type this in:

    
    
        {
            "cmd": ["open", "-a", "Safari", "$file"],
            "selector": "html"
        }
    

Save it in your sublime/packages/user folder as 'Open in Safari.sublime-build'

That's it.

It should show up in your Tools/BuildSystem and should be selected for all
html files. So when you hit Cmd+B it uses that build system to just show the
file in Safari.

There are other ways like mapping Cmd+B directly to a python snippet like:

    
    
        import sublime, sublime_plugin, webbrowser
    
        class OpenBrowserCommand(sublime_plugin.TextCommand):
           def run(self,edit):
              url = self.view.file_name()
              webbrowser.open_new(url)
    

but for me the first option was simpler.

------
mistercow
Sublime Text makes me feel silly for loving a text editor so much. Now if only
it would do text completion across multiple files...

~~~
damncabbage
Is there a CTags plugin you can use?

~~~
mistercow
Possibly, but that's a lot fancier and less "just works" than I'm interested
in. I just want the same extremely simple "what words have I seen before"
autocompletion that you get on a file-by-file basis, but as if I had every
open file concatenated into one.

------
RegularK
I often paste into it texts from other sources, and enable syntax highlight
quickly using the command palette. For example, if I paste an XML into a new
tab, I'd click

CTRL+SHIFT+P - X - Enter

The first part opens the command palette, the second selects XML syntax, and
enter applies it.

------
FootballMuse
Sort is F9 on my machine, not F5.

------
jacobolus
For whatever it’s worth, all of these are copied directly from TextMate. :-)

~~~
jskinner
While I did try to be compatible with TextMate key bindings where possible, I
believe only a handful of the key bindings mentioned in the article are
actually common between the two.

~~~
jacobolus
Most of them are identical. The capitalization and line joining shortcuts are
slightly different.

------
mmcnickle
You can also rebind these to any key combination you like.

Sublime Text 2 is great, and they have a free (unlimited) demo; no excuse to
not try it out. Well worth the money for me.

------
1285964
Control + G will let you jump to a line number. Also, Ctrl + F and then a
colon (:) will do the same thing. I use it all the time and it it extremely
handy.

------
warmwaffles
I delete lines with the cut command.

