196

As a C# developer, I have become highly dependent on the automatic formatting in Visual Studio 2008. Specifically, I will use the CTRL + K , D keyboard shortcut to force things back into shape after my sloppy implementation.

I am now trying to learn Objective-C and am missing certain features in Xcode, but probably none are quite as painful as the formatting shortcut. My Google searches have yielded nothing built in, though it seems there are some hacks. Am I missing something or does this feature not exist natively in Xcode?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
jslatts
  • 9,307
  • 5
  • 35
  • 38
  • 1
    Third party solution using UniversalIndentGUI: http://blog.carbonfive.com/2009/08/iphone/code-formatting-in-xcode – jslatts Oct 15 '09 at 23:26
  • 1
    There are some good links to Xcode scripting solutions in the answers to this [SO question](http://stackoverflow.com/questions/1510915/code-formating-in-xcode) – nall Oct 15 '09 at 20:27
  • Thanks for the link. I did find this as well: http://blog.carbonfive.com/2009/08/iphone/code-formatting-in-xcode It covers basically the same technique as your link. I will give it a try and see how well it works. – jslatts Oct 15 '09 at 23:25
  • Similar to this question; answer has menu item and keyboard shortcut to re-indent code: http://stackoverflow.com/questions/3558709/fix-code-indentation-in-xcode – Basil Bourque Aug 14 '13 at 08:20
  • 2
    has there be any innovation from Apple in the last 5 years on this? Is this question still relevant or has XCode now a new and better solution to format code? – mm24 May 27 '14 at 16:31
  • @mm24 after 5 years more, no much changes in re-indent affected :) – Mahdi Moqadasi Mar 13 '19 at 11:04
  • omg how in 2020 is this a thing? – Antony Stubbs Jun 26 '20 at 17:24

19 Answers19

444

That's Ctrl + i.

Or for low-tech, cut and then paste. It'll reformat on paste.

Rose Perrone
  • 61,572
  • 58
  • 208
  • 243
Ken
  • 12,933
  • 4
  • 29
  • 32
  • Thanks! That is helpful, especially since the menu doesn't actually show the keyboard shortcut. – jslatts Oct 15 '09 at 20:07
  • Dang, Ctrl+I is now 'profile' in Xcode 4... thanks a lot, apple. – Richard J. Ross III Nov 02 '11 at 17:09
  • 44
    But this only does indentation. What about moving braces, taking care of line breaks, etc? – Peter Ajtai Apr 30 '12 at 00:56
  • 18
    It shouldn't be accepted as it doesn't perform all the things a code formatter would handle. It just re-indents, – powerj1984 Jan 14 '13 at 21:20
  • 4
    Good tip. Extra lame that XCode doesn't have this. – AndrewK Dec 10 '13 at 03:41
  • 4
    yes @powerj1984. I am also disappointed with this. It does not add proper spaces after `,`, `=` or other operators. What it does just intent. Nothing else. Mac really needs to learn from Microsoft here. – shashwat Apr 17 '14 at 04:03
  • @Anton, can't be an accepted answer as it really doesn't reformat the code, it adds indentation (which is by far code formatting). – rodrigoelp Apr 24 '14 at 02:14
  • This does not reformat code. This feature is called `Re-Indent` – Julian F. Weinert Mar 11 '15 at 16:31
  • Auto-indent is a sub-thing of auto-format (which as well included deleting and adding white spaces, braces, brackets and such). And therefore should not be considered auto-format. Sadly the correct answer is "There is no such thing on Xcode" – dergab Apr 17 '15 at 12:44
145

Unfortunately, Xcode doesn't have anything nearly as extensive as VS or Jalopy for Eclipse available. There are SOME disparate features, such as Structure > Re-Indent as well as the auto-formatting used when you paste code into your source file. I am totally with you, though; there definitely should be something in there to help with formatting issues.

Siddharth
  • 9,349
  • 16
  • 86
  • 148
Marc W
  • 19,083
  • 4
  • 59
  • 71
  • 4
    Thank you, at least I know I am not missing something. Auto-identing does help dull the pain some what, but I will have to look into a third-party solution. – jslatts Oct 15 '09 at 20:06
  • 5
    this shouldn't be selected as the answer. the answer below from @ken is correct – Ryan Angilly Feb 08 '13 at 16:44
  • @RyanAngilly Notice the year this question was answered. Many things have changed with Xcode since then. ;-) – Marc W Mar 01 '13 at 15:38
  • 1
    @RyanAngilly ken only described how to auto-indent. That's not what "format" (with white space and new-line addition and removal and such things) really means. – dergab Apr 17 '15 at 12:40
  • 6
    Indentation can be fixed with control-i, that wil indent all selected lines. – zaph Sep 05 '15 at 16:32
36

I'd like to recommend two options worth considering. Both quite new and evolving.

ClangFormat-Xcode (free) - on each cmd+s file is reformatted to specific style and saved, easy to deploy within team

An Xcode plug-in to format your code using Clang's format tools, by @travisjeffery.

With clang-format you can use Clang to format your code to styles such as LLVM, Google, Chromium, Mozilla, WebKit, or your own configuration.

Objective-Clean (paid, didn't try it yet) - app raising build errors if predefined style rules are violated - possibly quite hard to use within the team, so I didn't try it out.

With very minimal setup, you can get Xcode to use our App to enforce your rules. If you are ever caught violating one of your rules, Xcode will throw a build error and take you right to the offending line.

matm
  • 7,059
  • 5
  • 36
  • 50
34

In xcode, you can use this shortcut to Re-indent your source code

Go to file, which has indent issues, and follow this :

  • Cmd + A to select all source codes

  • Ctrl + I to re-indent

Hope this helps.

Sumit Badsara
  • 769
  • 9
  • 23
Nguyen Minh Binh
  • 23,891
  • 30
  • 115
  • 165
18

My personal fav PrettyC wantabe is uncrustify: http://uncrustify.sourceforge.net/. It's got a few billion options however so I also suggest you download UniversalIndentGUI_macx, (also on sourceforge) a GUI someone wrote to help set the options the way you like them.

You can then add this custom user script to uncrustify the selected text:

#! /bin/sh
#
# uncrustify!
echo -n "%%%{PBXSelection}%%%"
/usr/local/bin/uncrustify -q -c /usr/local/share/uncrustify/geo_uncrustify.cfg -l oc+ <&0
echo -n "%%%{PBXSelection}%%%"
geowar
  • 4,397
  • 1
  • 28
  • 24
14

I also feel xcode should have this function. So I made an extension to do it: Swimat

Simple install by brew cask install swimat preview

You can give it a try, see https://github.com/Jintin/Swimat for more information.

Jintin
  • 1,426
  • 13
  • 22
13

You can use Command + A to select all content and next Ctrl + I to format the selected content.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Paweł Walaszek
  • 381
  • 3
  • 13
8

Cmd A + Ctrl I

Or Cmd A And then Right Click. Goto Structure -> Re-Indent

j0k
  • 22,600
  • 28
  • 79
  • 90
yuvi
  • 1,019
  • 2
  • 14
  • 21
7

Consider buying yourself a license for AppCode, an intelligent Objective-C IDE that helps iOS/OS X developers. AppCode is fully compatible with Xcode, but goes beyond Xcode in adding powerful features.

AppCode an Objective-C variant of the Intellij IDEA IDE from JetBrains. They are also authors of popular ReSharper extension to Visual Studio, which main purpose from here seems like a desperate attempt to bring a touch of IDEA experience to a Microsoft product.

AppCode is using its own code analyser which gives close-to-perfect refactoring and code navigation support. There is an ability to re-indent and completely reformat code also (although I still keep missing a couple of formatting settings in hard cases, but mostly it works well).

You might try the trial version, of course.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
jazzcat
  • 544
  • 7
  • 11
6

Swift - https://github.com/nicklockwood/SwiftFormat

It provides Xcode Extension as well as CLI option.

jaym
  • 1,253
  • 13
  • 18
5

CTRL + i

that's it.

(no COMMAND + i)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
LianY
  • 153
  • 2
  • 3
  • 7
    This has been mentioned as an answer 4 times already - please read the other answers before answering. – fishinear Dec 29 '15 at 13:03
  • Also, CMD+i is the same as going to Product -> Profile which is not the same as formatting. – inga Feb 03 '16 at 11:13
4

You can also have a look at https://github.com/octo-online/Xcode-formatter which is a formatter based on Uncrustify and integrated into Xcode. Works like a charm.

omartin
  • 116
  • 1
  • 5
4

You could try that XCode plugin https://github.com/benoitsan/BBUncrustifyPlugin-Xcode

Just clone github repository, open plugin project in XCode and run it. It will be installed automatically. Restart Xode before using formatter plugin.

Don't forget to install uncrustify util before. Homebrew, for exmaple

brew install uncrustify

P.S. You can turn on "after save formatting" feature at Edit > Format Code > BBUncrustifyPlugin Preferences > Format On Save

Hope this will be useful for u ;-)

romanvbabenko
  • 96
  • 1
  • 5
3

I suggest using ClangFormat. In order to install, please follow these steps:

  1. Install Alcatraz package manager for XCode Supports Xcode 5+ & OS X 10.9+
  2. After installation restart XCode.
  3. Open XCode -> Window Menu -> Package Manager
  4. Search (find) ClangFormat and install it. After installation again restart XCode.
  5. Now at XCode menu you can use Edit -> Clang Format submenu for formatting.

You can choose different types of formatting. Also by enabling Format On Save you can gain auto-format capability.

enter image description here

csonuryilmaz
  • 1,715
  • 24
  • 24
  • 1
    This is no longer available on XCode 8+ – Nathan F. Aug 09 '17 at 21:58
  • Yes, you're right @NathanFiscaletti I've upgraded from 7.2 to 9.2 and above solution not working anymore. But I found a solution. I'll add a new post! – csonuryilmaz Apr 10 '18 at 12:22
  • I installed Alcatraz but *ClangFormat* plugin is not supported on Xcode 9 anymore. https://github.com/travisjeffery/ClangFormat-Xcode/issues/129 – csonuryilmaz Apr 10 '18 at 13:39
1

If your Xcode version 3.x , you should use "User Script" With Uncrustify , here this a Example:

#!/bin/sh

echo -n "%%%{PBXSelection}%%%"
$YOURPATH_TO_UNCRUSTIFY/uncrustify -q -c $YOURPATH_TO_UNCRUSTIFY_CONFIG/CodeFormatConfig.cfg -l OC+
echo -n "%%%{PBXSelection}%%%"

add above to your Xcode "User Script".

if Xcode version 4.x , I think you should read this blog : Code Formatting in Xcode 4,

In this way , used the "Apple Services" , but it's not good enough , cause too slow experience, does anyone has the same thing ?

why apple drop "user script" .... xD

poplax
  • 11
  • 2
1

First, Examine XCode Preferences "Indentation" section. You can customize things quite a bit there...

For more fine grained control, refer to the XCode User Defaults document from apple. (May require a developer login to view). For example, I was able to disable the "indent on paste" by entering the following in terminal:

defaults write com.apple.XCODE PBXIndentOnPaste No

to read back your setting:

defaults read com.apple.XCODE PBXIndentOnPaste
SteveS
  • 514
  • 3
  • 16
1

This only works for languages with are not whitespace delineated, but my solution is to remove all whitespace except for spaces, then add a newline after characters that usually delineate EOL (e.g. replace ';' with ';\n') then do the ubiquitous ^+i solution.

I use Python.

Example code, just replace the filenames:

python -c "import re; open(outfile,'w').write(re.sub('[\t\n\r]','',open(infile).read()).replace(';',';\n').replace('{','{\n').replace('}','}\n'))"

It 's not perfect (Example: for loops), but I like it.

blerbl
  • 11
  • 2
1

We can use Xcode Formatter which uses uncrustify to easily format your source code as your team exactly wants to be!.

Installation The recommended way is to clone GitHub project or download it from https://github.com/octo-online/Xcode-formatter and add the CodeFormatter directory in your Xcode project to get : Xcode shortcut-based code formatting: a shortcut to format modified sources in the current workspace automatic code formatting: add a build phase to your project to format current sources when application builds all sources formatting: format all your code with one command line your formatting rules shared by project: edit and use a same configuration file with your project dev team 1) How to setup the code formatter for your project Install uncrustify The simplest way is to use brew: $ brew install uncrustify

To install brew: $ ruby –e “$(curl –fsSkl raw.github.com/mxcl/homebrew/go)”

Check that uncrustify is located in /usr/local/bin $ which uncrustify

If your uncrustify version is lower than 0.60, you might have to install it manually since modern Objective-C syntax has been added recently. Add CodeFormatter directory beside your .xcodeproj file

Check that your Xcode application is named "Xcode" (default name) You can see this name in the Applications/ directory (or your custom Xcode installation directory). Be carefull if you have multiple instances of Xcode on your mac: ensure that project's one is actually named "Xcode"! (Why this ? This name is used to find currently opened Xcode files. See CodeFormatter/Uncrustify_opened_Xcode_sources.workflow appleScript). Install the automator service Uncrustify_opened_Xcode_sources.workflow Copy this file to your ~/Library/Services/ folder (create this folder if needed).Be careful : by double-clicking the .workflow file, you will install it but the file will be removed! Be sure to leave a copy of it for other users.

How to format opened files when building the project Add a build phase "run script" containing the following line:

sh CodeFormatter/scripts/formatOpendSources.sh

How to format files in command line

To format currently opened files, use formatOpenedSources.sh:

$sh CodeFormatter/scripts/formatOpendSources.sh

To format all files, use formatAllSources.sh:

$sh CodeFormatter/scripts/formatAllSources.sh PATH

PATH must be replaced by your sources path.

E:g; if project name is TestApp then the command will be

$sh CodeFormatter/scripts/formatAllSources.sh TestApp

it will look for all files in the project and will format all the files as configured in uncrustify_objective_c.cfg file.

How to change formatter’s rules

Edit CodeFormatter/uncrustify_objective_c.cfg open with TextEdit

Ajeet Sharma
  • 214
  • 2
  • 9
0

Well I was searching for an easy way. And find out on medium.

First to copy the json text and validate it on jsonlint or something similar. Then to copy from jsonlint, already the json is formatted. And paste the code on Xcode with preserving the format, shortcut shift + option + command + v

Shad
  • 1,587
  • 2
  • 20
  • 29