The Terminal is your Friend
Here's a simple workflow to quickly sort lines of text:
- Select text
- Open Terminal
sort | pbcopy
These steps will copy the selected text to the clipboard, run it through the
sort command, then copy it back to your clipboard.
Many text-editors have built-in commands to sort lines of text, however Xcode doesn't. Something I regularly do is sort header
#import statements, property names,
@class forward-declarations, etc…so not being able to quickly sort lines is kind of irritating.
The above technique is pretty quick, but it could be quicker, especially if we could make it a single action.
Automate all the Things!
This is where Automator comes in. Automator lets you define services that are available to other applications from the Services menu in the menu bar and context menu.
Here's how you add a Sort Lines service (originally from epatel on Stack Overflow).
- Launch Automator.
- File > New, choose Service.
- Check the Output replaces selected text option.
- Add a Run Shell Script action.
- Set the shell script body to
sort -f. You can use
sort -f | uniq to get rid of duplicate lines which is useful for things like
- ⌘S to save the Service and name it something like "Sort Lines."
After saving the Sort Lines service it becomes available via the Services menu whenever you have text selected, or by right-clicking any piece of selected text.
Creating a Service menu item is one step closer to adding custom text manipulations that aren't available by default in applications like Xcode. The final step is to assign it to a keyboard shortcut.
The OSX System Preferences > Keyboard > Keyboard Shortcuts preferences pane lets you assign keyboard shortcuts to menu items. Under the Application Shortcuts just add a new shortcut to any or all applications and name it precisely after the service you created ("Sort Lines").
Now you can sort lines of text in any OSX application just by selecting the text and hitting your keyboard shortcut.