tags:

views:

337

answers:

3

Any XCode shortcut for wrapping a text selection in opening & closing brackets - { }, ( ) or [ ]?

Growing tired of removing the "}" that XCode automatically enters after I type "{" in cases where I've already got code in the editor that wants to be inside the new brackets.

A: 

You can uncheck the preference to automatically add the closing brace.

Or you could add this little script to your User Scripts:

alt text

cdespinosa
Mostly works except it seems to remove all the line feeds from the selected text so everything ends up on one line... i know the compiler doesn't care but...I DO! Any ideas how to retain the formatting?
Meltemi
Try using `'%%%{PBXSelectedText}%%%'` to insert the text as indicated in my answer.
Lawrence Johnston
A: 

Apple released a Tech Q&A regarding this. Alas, doesn't handle closing curly but still seems better than moving all selected code to a single line.

Meltemi
+1  A: 

Here's an Xcode user script which should not wipe out new lines in the text.

#!/usr/bin/python
#
# Wraps selection in braces.
# Set Input to "Selection".
# Set Output to "Replace Selection".

tabChar = '\t' # Replace with spaces if desired
input = '''%%%{PBXSelectedText}%%%'''

print "{"
for line in input.splitlines():
  print tabChar + line
print "}"

See the Script Input Variables section of the Xcode Workspace Guide for more information on %%%{PBXSelectedText}%%% and the other available input variables.

EDIT: added support for indenting the code to be surrounded by a given amount. Right now the indent must be hard coded. It may be possible to get this value from, e.g., the Xcode preferences file, but I didn't go that far.

Lawrence Johnston
you da man! one last quibble...know what needs to be added to the script to automatically tab indent the selection before the braces come in? If not it's easy enough just to type ⌘-] before activating script. thx again! this has been annoying me for months.
Meltemi
Try the updated script above.
Lawrence Johnston