Edit Source Code

You write and edit code with the Xcode source editor, which has many professional-level features, such as automatic formatting, code completion and correction, and online documentation. You can discover most of these features by looking in the Edit and Editor menus as well as Control-clicking in the editor to see the contextual menu. This chapter briefly reviews the features you are likely to use most often and describes some features that you might not discover easily by yourself.

In addition to writing and editing code in the source editor, you can set breakpoints, view the values of variables, step through running code, and review issues found during builds or code analysis. These features are part of the debugging and build-run workflows, and so are discussed in other chapters (see “Debug and Tune Your App” and “Configure Your Project”).

Customize the Source Editor with Xcode Preferences

Here are some of the ways you can customize both the appearance and function of the source editor in Xcode preferences by using the Fonts & Colors, Text Editing, and Key Bindings panes.

Modify Syntax-Aware Fonts and Text Colors

Xcode parses code based on the language (as determined from the filename extension) and assigns a syntactic label to each token or string: comment, keyword, class name defined in the project, other class name, and so forth. By default, Xcode assigns a color and font to each syntactic type to make it easier for you to read the code. Xcode Fonts & Colors preferences allows you to select among several font and color themes; for example, the Presentation theme increases the font sizes so that the text is easier to read when projected on a screen. You can also create your own custom font and color theme. For example, in Figure 5-1, symbols defined in the project are given a distinct color to make them easier to pick out.

Figure 5-1  Fonts & Colors preferences

Customize the appearance of source code and console text by changing their colors and fonts in Fonts & Colors preferences. For example, you could display your code comments in purple in the source editor. For the console, you could set your debugger input and your debugger output to a 14-point font.

Customize the keyboard shortcut for a command by editing its key sequence in the Key Bindings preferences pane.

Set Your Text-Editing and Automatic Indentation Preferences

You can set several preferences that control the appearance and behavior of the source editor—including whether line numbers are displayed, how delimiter balancing and the code focus ribbon work, and some aspects of code completion—in the Editing pane of Text Editing preferences.. You can control many of the automatic-indenting features of the editor in the Indentation pane of Text Editing preferences. Control-click in either pane to see a help article that describes the use of the fields.

Enter Code Quickly and Accurately with the Help of the Source Editor

The source editor includes several features that help you enter code and avoid mistakes:

Speed Up Typing with Code Completion

When you begin typing the name of a symbol that Xcode has indexed, it offers an inline suggestion for completing the symbol name plus a list of possibilities (Figure 5-2). Click an item in the suggestion list or use the Up Arrow and Down Arrow keys to select one. As you do so, the inline suggestion changes as well. Furthermore, as you can see in the figure, if you open the Symbol inspector in the utility pane, you can read documentation about each selection. You can turn off automatic code completion in the Text Editing pane of Xcode preferences, but you can always invoke code completion by pressing Control–Space bar or Esc.

Figure 5-2  Code completion

Finish entering a symbol by accepting an Xcode suggestion for completion. The proposed symbol is based on the text you have typed so far and the surrounding context. Continue typing to refine the list of choices.

Code completion inline quick help is shown in Figure 5-3. Code completion placeholders for parameters are shown in Figure 5-4.

Figure 5-3  Quick Help for code completion
Figure 5-4  Placeholders in code completion text

Balances Delimiters Automatically

When you create a new file or edit an existing one, Xcode determines the source language from the filename extension and attempts to determine the syntax of the text based on the source type. For example, a file with a .h or .m extension is assumed to be a variety of C and formatted accordingly. In that case, the editor indents the text according to the rules you set in Text Editing preferences and uses fonts and colors for the various syntax elements (variables, constants, comments, and so forth) according to the settings in the Fonts & Colors pane of Xcode preferences.

When you’re writing code, type an opening brace ({), and continue typing, Xcode automatically adds a closing brace (}) unless you’ve deactivated this feature in Text Editing preferences. There are several other features that help you to balance delimiters, including double-clicking a delimiter to select the entire expression.

bullet
To get assistance in balancing delimiters

Do one of the following:

  • Type an opening brace.

    Xcode automatically inserts a closing brace after you enter a line break. (If you don’t want closing braces automatically inserted, choose Xcode > Preferences, click Text Editing, and deselect “Automatically insert closing ‘}’”.)

  • Use the Right Arrow key to move the insertion point past a closing delimiter.

    Xcode briefly highlights its counterpart.

  • Double-click any delimiter.

    Xcode selects everything up to and including the matching delimiter.

  • Position the pointer over the focus ribbon.

    Xcode highlights the scope at that location.

  • Type a closing brace or other delimiter.

    Xcode causes its counterpart to blink.

  • Choose Editor > Structure > Balance Delimiter.

    Xcode selects the text surrounding the insertion point, up to the nearest set of enclosing delimiters.

Have Fix-it Flag Errors as You Type

When your target is set to use the LLVM compiler, a feature called Fix-it scans your source text as you type.

Correct mistakes with Fix-it as you enter source code.

Find and Display Related Content

Xcode provides several features that help you find content related to the code you’re currently editing: you can open a file based on a partial string, you can jump to a symbol definition, you can navigate to related content using a button in the jump bar in the primary editor or in a split editor, or you can split the editor and have Assistant find related content for you.

Open a FIle Quickly

Sometimes you may need to open a file whose location you don’t know, or you may want to open the file that defines a particular symbol, such as a variable, method, or class. The Open Quickly command finds files that define a specified symbol or whose filename contains a specified string. Open Quickly searches are case insensitive and limited to the current project and the active SDK.

bullet
To use the Open Quickly command
  1. Choose Open Quickly from the File menu.

  2. In the search field, type any portion of the name of the file you want to open or the symbol you want to find.

  3. From the search results list, double-click the file you want to open, or select the file you want to open and click Open.

    image: ../art/open_quickly.png

In filename-based searches, Xcode searches for header files, implementation files, model files, nib files, plist files, and project packages. In symbol-name–based searches, it searches source code files only.

Split the Editor Area to Display Related Content

Xcode allows you to split the editor pane to provide multiple views of the same file or to view multiple files at once.

To split the editor, open an assistant editor pane by choosing View > Editor > Assistant or by clicking the Assistant button in the workspace toolbar (Figure 5-5).

Figure 5-5  The Assistant button
bullet
To see the same file in each pane
  1. Open an assistant editor pane.

  2. Select Manual from the Assistant pop-up menu (“To set the behavior of the assistant editor”).

    You can view any portion of the file in either split plane, and you can edit the file in either pane. Any changes made in one pane are instantly reflected in the other.

    image: ../art/split_editor.png

    The split can be horizontal (as shown in the figure) or vertical. To change the orientation of the split, choose View > Assistant Layout.

    image: ../art/assistant_layout.png

Customize Keyboard Shortcuts to Determine Where a File’s Contents Are Displayed

Selecting a file in the project navigator or jump bar causes that file to open in the normal editor pane. If Assistant is set to tracking mode, it tracks the change. By default, if you hold down the Option key when selecting a file in the project navigator or jump bar, Xcode displays that file in the Assistant pane rather than the standard pane. Doing so switches Assistant to manual mode.

You can customize the behavior of the single click, Option-click, and double-click keyboard shortcuts in the General pane of Xcode preferences (Figure 5-6).

Figure 5-6  General preferences

To customize the behavior of keyboard shortcuts for opening a file, open General Preferences and choose an option from each navigation pop-up menu. The options include:

  • Primary editor: Opens the file in the primary editor pane in the window and tab already open.

  • Focused editor: Opens the file in whichever editor pane currently has focus.

  • Single assistant editor: When the navigation originates in a navigator pane or the primary editor (using the jump bar or the jump to definition command), if the assistant editor is not open or is not split, opens the file in the assistant editor.

    If the assistant editor is split, displays a navigation chooser dialog (Figure 5-7) showing the current layout of editor panes in the window that has focus, with the option of selecting any open editor pane or adding a new one. Double-click your selected pane, or make your selection and press Return. Press Esc to cancel.

    Figure 5-7  The Single Assistant navigation chooser dialog

    If the file is already open in one of the editor panes, the navigation chooser displays a star to indicate the pane containing the file.

    When the navigation originates in an assistant editor pane, Xcode opens the file in the primary editor.

  • Separate assistant editor: If the assistant editor is closed and is not split, opens the file in the assistant editor.

    If the assistant editor is open, opens the file in a new assistant editor pane.

    If the assistant editor is split but closed, opens the file in the most-recently-opened assistant editor pane, replacing the file that was in that pane.

    If the file is already open in an assistant editor pane, switches the focus to that pane.

  • Separate tab: If the file is not already open in the current window, opens the file in a new tab.

    If the file is already open in another tab in the same window, switches the focus to that tab.

  • Separate window: If the file is not already open in a separate window, opens the file in a new window.

    If the file is already open in a separate window, switches the focus to that window.

The Option-Shift-Click key combination opens a navigation chooser dialog (Figure 5-8) showing the current layout with the options of selecting any open editor pane in any window and any tab, or adding a new editor pane, window, or tab. Double-click your selection, or make your selection and press Return. Press Esc to cancel.

Figure 5-8  The navigation chooser dialog

Jump to a Symbol’s Definition

You can jump to the definition of a symbol and display it in the primary editor window, in a split editor pane, in another tab, or in another window.

bullet
To jump to a symbol’s definition
  1. Hold down the Command key., and command-click the symbol in which you’re interested.

  2. Move the pointer over text to highlight each symbol that can be used as a link to a definition.

    image: ../art/jump_to_definition.pngimage: ../art/jump_to_definition.png
  3. If there is more than one definition for the symbol, Xcode displays a list of possibilities. Click the one you want.

    image: ../art/jump_to_definition_choice.png

Alternatively, select the symbol in which you’re interested and choose Navigate > Jump to Definition or Control-click the symbol and choose Jump to Definition from the shortcut menu.

Find Related Items with the Jump Bar

Use the related items pop-up menu in the jump bar (Figure 1-9) to jump to files and classes related to the file you have open. For example, you can find superclasses and subclasses of the class defined in the open file, headers included in the file, or headers that include the file. For a header file you can jump to the implementation file, and vice versa.

Find Related Content Automatically

When you open an assistant editor pane, you can set Assistant to either of two modes: tracking (or automatic) mode or manual mode. Tracking mode has several criteria from which you can choose, such as counterparts, superclasses, subclasses, or siblings. Assistant selects the file or files that best meet the selected criterion and opens those files in the assistant editor pane. In manual mode, you select the file to display by navigating to it in the jump bar. You can split the assistant editor into as many panes as you wish.

bullet
To set the behavior of the assistant editor
  1. Open an assistant editor pane.

  2. Open the Assistant pop-up menu. The Assistant pop-up menu is the first item to the right of the back and forward arrows in the assistant editor jump bar.

    image: ../art/assistant_setting_behavior.png
  3. Make a selection from the menu.

    image: ../art/genius_submodes.png
bullet
To split the assistant editor
  1. Click the plus sign at the right end of the assistant editor jump bar to split the editor.

  2. Set each Assistant pane to manual or tracking.

  3. Set each tracking pane to a tracking criterion.

    The figure shows one file on the left of the split editor pane, the counterpart file in the upper-right Assistant pane, and another view of the file in the lower-right Assistant pane.

    image: ../art/splits.pngimage: ../art/splits.png

Use Assistant with Interface Builder and Data Models

When you’re using Interface Builder to design a user interface, you can use Assistant to automatically display the code file most relevant to the interface element you’re working with. See “Simultaneously Design and Implement User Interface Objects Using Multiple Editors” for details. Similarly, when you use the Core Data modeling editor, the assistant editor can display model classes related to the entities in your model (Figure 5-9). The Core Data modeling editor is discussed in “Edit Data Model Documents.”

Figure 5-9  The assistant editor used with a data model

Incorporate Other Source Editor Features into Your Workflow

The source editor provides many features to make it easier to write and maintain your code. This section highlights a few of these features not described elsewhere in this document.

Examine the Structure of Your Code with Code Folding

One powerful way to examine the structure of source code is to use the focus ribbon, also called the code folding ribbon.

Focus your attention on a particular method or function in source code by hiding the other parts of the source code.

If you have the option “Focus code blocks on hover” selected in Text Editing preferences, then you can move the pointer over the focus ribbon to examine the various scopes of code blocks in a file. In Figure 5-10, for example, the pointer is over the focus ribbon next to an if statement and three scopes are indicated by degrees of shading in the code: the if statement, the method (showOrHideWindow) containing the if statement, and the class implementation (NSWindowController(SKTConvenience)) containing the method.

Figure 5-10  The focus ribbon in use

View Preprocessor or Assembly Output

You can use commands in the Product > Generate Output menu to process source files and generate the preprocessed output (Figure 5-11) or assembly output.

Figure 5-11  Preprocessor output

The preprocessor evaluates directives in your source code (instructions starting with the pound sign (#) such as includes, defines, and conditional logic) and converts them into C code to be sent to the compiler. You can examine the preprocessed output to make sure that the logic in your source code is being interpreted by the preprocessor as you expect in order to debug compilation problems.

The assembly output is the set of instructions that the compiler generated from the preprocessed output. You can study the assembly output to see how the instructions were formed or ordered, to seek out better optimization patterns, or to look for compiler bugs.

The output type is also a new category in the assistant editor for a selected primary file (Figure 5-12).

Figure 5-12  Generated output in Assistant jump bar

View Documentation for a Symbol Using Quick Help

You use Quick Help in the Symbol inspector to get information about API symbols, user interface objects, and build settings.

Find concise reference documentation for an API symbol without moving away from your source file.

To get information about a symbol when the utility area is closed, you can open a Quick Help window by Option-clicking the symbol (“Find and Display Related Content”).

Figure 5-13  The Quick Help window

Find concise documentation for an object using Quick Help. You can find concise class reference documentation for a single object without taking your focus away from your nib file.

Find concise documentation for a build setting using Quick Help.

Automate Extensive Changes in Your Files

In addition to all the features Xcode provides to make it easier to enter and correct your code, there are features at several scales to help you make changes that apply to more than one line of text. These include Edit All in Scope, Search and Replace, and Refactor.

Simultaneously modify all the occurrences of a symbol within a scope with the Edit All in Scope feature. For example, you can change the name of a local variable or parameter everywhere in a scope at the same time.

To find and change all the instances of a text string in a single file, choose Edit > Find > Find and Replace.

To find and change all the instances of a text string in your project or workspace, use the Replace option of the search navigator (see “Replace Text Strings”).

To refactor code (that is, to change the code without changing its behavior), see “Improve Your Code’s Structure Through Refactoring.”

Incorporate Files and Code from the Xcode Libraries

Xcode provides libraries of file templates and code snippets that you can use in your program. It also has libraries of Interface Builder objects and media files that you can use in your nib files. The library pane is in the lower part of the utility area (see “The Xcode 4 workspace window”). Each of the buttons at the top of this pane selects a category of library objects, as follows:

  • File templates range from templates for applications to subclasses of commonly used Cocoa classes. File templates have subcategories, which you can choose from the pop-up menu below the line of buttons. You can display the templates as icons only or as icons and text. Drag file and project templates to the project navigator.

  • Code snippets are short pieces of source code that you can use in your software. To use one, drag it directly into your source code file. Alternatively, you can select a portion of the code from the code information pop-up window and drag that into your file. When you create a code snippet, you can add a completion shortcut, which you can use when editing source code. Type the shortcut and select the completion shortcut from the completion list to add the code snippet to your file. Note that the new code snippet is flagged with the word “User”.

  • Interface builder objects are organized with subcategories and provide information pop-up windows like those for the file templates and code snippets. Depending on the object, you drag it onto the Interface Builder canvas, into another object on the canvas, or into the Interface Builder dock. See “Edit User Interfaces” for more information on Interface Builder.

  • Media files include all the graphics, icons, sound files, and other media files that you use in your code. When you’re editing an Interface Builder document, the Media library also shows the built-in template images from NSImage and sounds provided by the system. In Interface Builder, you can drag an image from the library and drop it into your user interface. Interface Builder creates an image view to hold the dropped image. Alternatively, you can drag an image into an existing button, image view, or any other object that can contain an image. You can set a sound on an NSButton object.

Add a new file to a project or workspace using the File Template library. This library offers a convenient way to create files in your project or workspace.

When you click a template, an information window pops open with information about the use of the template (Figure 5-14).

Figure 5-14  A file template information pop-up window

Add frequently-used source code to your project by using a snippet from the Code Snippet library.

Extend the scope of the Code Snippet library by creating custom snippets. The Code Snippet library provides a number of useful standard snippets. You can add to this collection by creating your own custom snippets.

Enter source code text with minimum effort by typing a completion shortcut for a code snippet.

Filter the library items displayed in the selected library by entering text into the search field at the bottom of the library pane.

Use Inspectors to View and Enter Data

Inspectors are panes in the utility area that you can use to read or enter data about files, Interface Builder objects, symbols, and data models. Figure 5-15 shows the File inspector.

Figure 5-15  The File inspector

The Symbol inspector is discussed in “View Documentation for a Symbol Using Quick Help.” The File inspector and Symbol inspector are always available. Other inspectors appear when appropriate. For more information about Interface Builder, see “Edit User Interfaces.”


Did this document help you? Yes It's good, but... Not helpful...