Chapter 7. Syntax-Aware Editing

WHAT'S IN THIS CHAPTER?

  • Using and customizing syntax coloring

  • Folding code blocks

  • Accepting code completion suggestions

  • Inserting text macros

In Chapter 6, you learned a lot of editing features specifically designed to make writing source code easier, but most of these features are just textual aides that know little or nothing about your code and symbols.

Xcode's syntax-aware features pick up where the basic text editing aides leave off — with some overlap between them. Syntax-aware editing means that the editor analyzes your source code and uses that knowledge to highlight your code's structure and symbols, offer suggestions, and make intelligent changes.

You've already encountered a few syntax-aware features. The Balance command, which finds a matching brace or bracket, understands the block structure, string format, comment syntax, and other details of your programming language.

This chapter describes the various syntax-aware editing features and tools available in Xcode. Xcode can know a lot about your code's structure, and its vocabulary is quite broad; it understands languages from ADA to XML. The code analysis is performed continuously and in the background. It won't get in the way of your development, and it's almost always up-to-date.

CODE SENSE

Code Sense is the technology that analyzes your code continuously while you write it. It assembles and maintains a database, called the Code Sense index, of the classes, variables, methods, functions, structures, types, data models, and constants defined in your application. It also tracks class inheritance and file references. Many of the syntax-aware features described in this chapter rely on Code Sense.

Code sense updates its index incrementally, analyzing only the function or method that you're editing and the source files that have been saved recently. Updates are typically quite fast — on the order of a few seconds. This means that Code Sense recognizes local variables in the method you're editing almost instantly, and changes to classes, methods, functions, and types as soon as you save the file.

Note

If a symbol doesn't appear to be in the Code Sense index (that is, you can't jump to its definition, or it doesn't appear in the auto-completion list), save all of your source files to disk (File

CODE SENSE

Enabling Code Sense

You enable Code Sense globally for all projects in the Code Sense panel of the Xcode preferences, as shown in Figure 7-1.

FIGURE 7-1

Figure 7-1. FIGURE 7-1

The Enable for All Projects option turns all Code Sense–dependent features on or off. This includes some syntax coloring, code completion, jump to definition, the Included Files and Class Hierarchy navigation menus, the Symbols smart group, and the Class Browser. The only real motivation for disabling Code Sense is to avoid the CPU, memory, and disk space required to maintain it, but these seem like small prices to pay for the enormous benefits that Code Sense provides. I would recommend disabling it only if absolutely necessary.

Code Sense works by interacting intimately with the compiler. This also requires that all the source items are members of a "native" target. Native targets are targets that Xcode knows how to build (see Chapter 16), and by extension it knows what compilers will be used to compile each source file. External (non-native) targets defer the actual build process to some external program, such as Make or Ant. Items in external targets cannot use Code Sense.

Because Code Sense works silently in the background, it's sometimes hard to tell whether a symbol isn't in the Code Sense index or whether Code Sense just hasn't reindexed it yet. The Window

TIP TO REMEMBER

Reindexing a Project

If you suspect that the Code Sense index has gotten out of synchronization with your project, open the Info widow for the project (Project

Reindexing a Project

The Code Sense index is stored in your account's ~/Library/Caches folder. If the Code Sense index is ever deleted or is not in synchronization, Xcode automatically rebuilds it.

FIGURE 7-2

Figure 7-2. FIGURE 7-2

SYNTAX COLORING

The most visible and passive of the syntax-aware editing features is syntax coloring. It uses a basic knowledge of a language's syntax to colorize the text of source code so that keywords, comments, literals, symbols, and other language elements are displayed in distinctive colors, fonts, or styles. The intent is to make it easier to read the code by highlighting the functionality of elements in the source.

Customizing Syntax Coloring

You control the colors that syntax coloring uses, or whether syntax coloring is done at all, in the Fonts & Colors tab of the Xcode Preferences, shown in Figure 7-3.

FIGURE 7-3

Figure 7-3. FIGURE 7-3

Each entry in the table controls the color, and possibly the font, used to display a category of editor element. The entire collection is collectively referred to as a theme. Xcode provides several themes that you can choose from, and you can create your own. The major categories are described in the following table.

You can control syntax-aware coloring globally with the Use Syntax-Based Formatting and Color Indexed Symbols options. Turning the first option off disables all syntax coloring. With syntax coloring enabled, the second option determines whether only basic language elements are colorized, or whether project symbols in the Code Sense index are also colorized.

In addition to the syntax coloring, this preference pane also establishes the font and color scheme used in all editing panes. This includes the background color of the pane and the color used to highlight selected text. The list is broadly organized into three groups of entries:

  • The Background, Selection, Insertion Point, and Plain Text categories apply globally to all text editor panes.

  • The categories Comments through Attributes affect recognized language elements when the Use Syntax-Based Formatting option is enabled.

  • The remaining categories change the color of recognized symbols when the Color Indexed Symbols option is enabled.

Text that isn't colorized — either because it's not one of the recognized categories or you've turned off the Use Syntax-Based Formatting or Color Index Symbols options — is displayed using the Plain Text color and font.

CATEGORY

DESCRIPTION

Background

The background color for all editor panes. Make sure that it contrasts well with the colors chosen for text selections, the insertion point, and text. Any element that's the same color as the background will be invisible.

Selection, Insertion Point

The colors used to indicate the current text selection and insertion point.

Plain Text

The color, font, and size for all text that's not colorized using one of the other categories.

Comments

Comments in the source code. For C, Java, and similar languages this means text enclosed by /* and */ character sequences, and the text following a //. For property lists and shell scripts, comments are lines that begin with #. AppleScript denotes comments between pairs of (* and *) and after --.

Documentation Comments

Java's JavaDoc and Darwin's HeaderDoc tools scan source code files and generate documentation for a program or library. Both rely on specially formatted comments that begin with /** or /*! and contain annotations and keywords.

Documentation Comments Keywords

JavaDoc and HeaderDoc comments can also include any number of keywords that identify the different parts of the comment. For instance, the @param keyword is used to document a single parameter of a function call.

Strings

String literals contained between pairs of double quotes. Xcode interprets escape characters; it won't be confused by strings such as "North Carolina (the "Tar Heel" State)".

Characters

Character literals contained between single quotes.

Numbers

Numeric constants. Xcode recognizes decimal, octal, and hexadecimal numbers that begin with 0x. It does not recognize numeric Unicode constants.

Keywords

The standard keywords for the language. Obviously, this will vary wildly from one language to the next. For C-like languages, words such as for, if, else, and then are keywords. The word register is a keyword in a C++ source file, but not in a Java file. For shell scripts, the keywords are the bash built-in commands.

Preprocessor Statements

Preprocessor directives used by C-based languages, such as #include or #define. Xcode understands multi-line preprocessor statements.

URLs

Any valid URL.

Font & Color themes provided by Xcode are not editable. To create a customized theme, begin by clicking the Duplicate button to make a copy of any existing theme. To delete a custom theme, select it as the current theme and click the Delete button. If you attempt to edit a built-in theme, Xcode alerts you and gives you the opportunity to duplicate it.

To customize an element, select the category (or categories) in the list and apply any of the text styling commands found in the Edit

FIGURE 7-3

Changing Syntax Coloring for a Single File

Syntax coloring is naturally dependent on Xcode knowing in what language your source file is written. By default, Xcode uses the file's type (see the "Source Item Attributes" section in Chapter 5) to determine this. The vast majority of time this is correct. If, for any reason, Xcode guesses wrong, you can manually specify that it use a different language when interpreting the file by selecting the correct language (or None) from the View

Changing Syntax Coloring for a Single File
FIGURE 7-4

Figure 7-4. FIGURE 7-4

When Default is selected, the language Xcode has chosen is displayed as a dash in the menu of available languages.

For files that belong to a project, this setting is stored in the project document and is persistent. Otherwise, the selection is lost when the editor pane is closed.

CODE FOLDING

Code folding highlights blocks of structured text and allows them to be collapsed — or "folded" — so that you can concentrate on the higher-level structure of your code. Code folding is supported in all C-like languages (C++, Objective-C, Java) and XML, as shown in Figure 7-5. To see and use code folding, you must have the Show Code Folding Ribbon option turned on in the Text Editing pane of the Xcode Preferences.

FIGURE 7-5

Figure 7-5. FIGURE 7-5

The code folding ribbon appears between the gutter and the text. The depth of the blocks in your text is graphed using gradations of grey; the darker the ribbon, the deeper the text in that line is nested. Hovering your cursor over the ribbon presents collapse controls for the block of text that begins on that line.

Code Focus

Code focus highlights a block of text in the editor, making it easier to see what the block encompasses, as shown in the bottom window in Figure 7-5. Code focus appears when you hover your cursor over the code folding ribbon. Uncheck the Code Focus option in the preferences to disable this behavior.

If you find code focus really useful, even temporarily, and are tired of moving your cursor over the code folding ribbon, you can have code focus follow your current text selection by choosing View

Code Focus

Folding Code

You have four ways to fold a block of code, listed in the following table.

ACTION OR COMMAND

EFFECT

Collapse button in ribbon

Collapses highlighted block

View

Folding Code

Collapses block containing the current selection

View

Folding Code

Collapses the outmost block of every method or function

View

Folding Code

Collapses all multi-line comments

Folded code is collapsed and replaced with an ellipsis placeholder, as shown in Figure 7-6.

FIGURE 7-6

Figure 7-6. FIGURE 7-6

The Fold command folds the block containing the current text selection or insertion point, and is the only fold action that uses the current selection. The Collapse button folds the highlighted block in the ribbon, and the other two commands apply globally to the entire file.

Folding comment blocks only applies to multi-line comments (like /* ... */). The command does not recognize, or fold, successive lines of single-line comments (//).

Have no fear; the text in the folded region is still there. Including a folded block placeholder in a text selection includes all of the text in that block, just as if it weren't folded.

Unfolding Code

You have six ways to unfold code, listed in the following table.

ACTION OR COMMAND

EFFECT

Expand button in ribbon

Expands collapsed block

View

Unfolding Code

Expands blocks contained in the selected text or in the selected block

View

Unfolding Code

Expands the outmost block of every method or function

View

Unfolding Code

Expands all multi-line comments

View

Unfolding Code

Expands all collapsed blocks

Display any text in a collapsed block

Expands the block containing the text

The first four actions are symmetric complements to the code folding actions in the previous section. In addition, the Unfold All command unfolds all collapsed blocks of code. Finally, any action that you take that causes some text to be selected or revealed — searching for text or jumping to a symbol definition — automatically expands the block so that the text is visible.

INDENTING TEXT

Over the years, programmers have developed coding styles that visually reflect the structured nature of the languages in which they are programming. One of these conventions is indenting. These conventions have become so common and consistent, that many can be automated.

Indenting is accomplished by starting a line with tab or space characters. Using spaces to indent lines is the most predictable method, but creates unnecessarily large files. Tab characters are more efficient, but are problematic because there is no standard that dictates how many column positions a tab character represents. If you decide that tab stops should be every four columns and you open a text file from a programmer who thought tabs should be every eight columns, the text won't line up correctly. You'll achieve the greatest compatibility by adopting four-column tab stops, which seems to be the most common setting these days. You can also alter the tab width for individual files. The default tab settings for files are configured in the Indentation tab of the Xcode Preferences.

Xcode's tab width, indenting, and auto-formatting behaviors are all set globally in the preference's Indenting pane, shown in Figure 7-7. The tab widths are default for files, but individual files can override these global settings. The remaining options in this preferences pane are global and apply to all source files.

FIGURE 7-7

Figure 7-7. FIGURE 7-7

Setting Tab Width and Indent Width

Xcode makes a distinction between the width of the tab stops and the amount by which each line of code is indented. The two numbers do not have to be the same. The Tab Width setting, shown in Figure 7-7, determines the width of the tab stops in characters. The Indent Width setting is the number of columns' worth of white space added to the beginning of a line to indent it one level. Xcode uses the most efficient combination of spaces and tabs that it can. If the indent width is an integer multiple of the tab width, only tab characters are used to indent lines. If not, a combination of tabs and spaces is used to achieve the desired indentation. Say you have a tab width of 8 and an indent width of 4. To indent a line one level requires four space characters. Indenting two levels would cause these spaces to be replaced by a single tab.

The global tab and indent width settings can be overridden for an individual file either in the Info window for the file, or by choosing the View

Setting Tab Width and Indent Width
FIGURE 7-8

Figure 7-8. FIGURE 7-8

The Editor Uses Tabs option permits the use of tab characters to indent lines. Turning it off forces Xcode to use spaces for all indenting. This is the safest option when you're sharing code with other programmers who might not be using the same tab width, but it also makes your files substantially larger. I also think it makes deleting the white space in lines awkward, and also makes it easier to inadvertently align text at odd indentations.

The Reset to Text Editing Defaults button returns the file to using the global settings in the Indentation preferences panel. File-specific editor settings are maintained for the file in its project document. The settings will not be remembered for files that are not assets of a project, and the settings are independent of other projects.

Automatic Indentation

Automatic indenting occurs whenever you start a new line by pressing the Return key. The editor inserts the same amount of indentation on the new line as was present on the line above it. This feature is always active. To circumvent it for a single line, type Option+Return at the end of the line. Option+Return starts a new line with no indentation. There is no simple option to turn off auto-indentation globally, but it can be defeated by changing the key binding for the Return key, as explained in Chapter 23.

Syntax-Aware Indentation

Enabling Syntax-Aware Indenting in the Indentation pane of the Xcode Preferences turns on a number of additional features that will aid you in indenting source code and forming code blocks. You can have Xcode do any of the following:

  • Automatically indent lines when you press the Tab key

  • Automatically indent code blocks

  • Automatically create a balanced code block when you type a { character

  • Automatically re-indent a line when you type one of several punctuation characters

  • Automatically indent C-style comments

Each feature can be independently configured or disabled, as desired.

Syntax-Aware Tab Indenting

The Tab Indents option determines what action occurs when you press the Tab key. It has three settings, as described in the following table.

TAB INDENTS SETTING

TAB KEY ACTION

In Leading White Space

When the text cursor is at the beginning, in, or immediately to the right of any white space at the beginning of the line, pressing the Tab key causes the entire line to be indented one level. When not in this leading non–white space portion of the line, the Tab key inserts a single tab character.

Always

Regardless of where the cursor position is within the line, pressing the Tab key causes the line to be re-indented.

Never

Tab key inserts a tab character.

The In Leading White Space setting is the most useful when you're programming in block-structured languages. At the beginning of the line, pressing the Tab key indents the line. Within the line, typically at the end of a statement where you want to begin a comment, the Tab key simply inserts a tab character.

Note

"White space" refers to the non-graphic, printable characters in the Unicode character set. Practically, that means the tab, space, and end-of-line characters, but, technically, it also includes characters like the non-breaking space (Unicode 0x00A0). White space characters get their name from the fact that they cause subsequent characters in the file to be shifted to new lines or column positions, but are not themselves visible. In other words, they just leave a white space on the page.

Note that the first two settings are not variations on one another. Xcode has two indentation functions: indent and re-indent. Indent increases the indentation level of a line by inserting more white space. Re-indention looks at the indention of the line with respect to the indentation of the line that precedes it, and uses syntax-aware rules to determine what its indentation level should be. Repeatedly indenting a line continues to shift the line further and further to the right. Repeatedly re-indenting a line does nothing. Until you change the contents of the line, or the preceding line, Xcode repeatedly reformats the text to the same indentation level.

You can circumvent the settings for the Tab key at any time by using Option+Tab or Control+I. Option+Tab always inserts a tab character, regardless of the syntax-aware tab settings. Control+I always performs a re-indent of the currently selected line, or lines, and is the same as the Edit

Syntax-Aware Tab Indenting

Indenting Solitary "{"

Returning to the Indentations tab of the Xcode Preferences (see Figure 7-7), the Indent Solo "{" option determines what happens when an opening brace is the first non–white space character of a line. The option determines how much the line will be indented relative to the previous line. This is independent of the Indent Width setting, but if non-zero it's typically the same value — the Horstmann style illustrates an exception. The following table illustrates some popular coding styles that can benefit from this option. The table assumes an indent width of 4.

STYLE

INDENT SOLO "{"

EXAMPLE

Allman

0

if (a==b)
{
    foo();
}

Whitesmiths

4

if (a==b)
    {
    foo();
    }

GNU

2

if (a==b)
  {
    foo();
  }

Horstmann

0

if (a==b)
{   foo();
}

The indentation amount is always relative to the indentation of the previous line, not the indentation level of the line containing the leading { character. In other words, if the Indent Solo "{" setting is 4 characters and the line was already indented four characters more than the previous line, a leading { changes nothing. In fact, the indentation level could decrease if the Indent Solo "{" setting is lower than the nominal indentation amount for the line.

Automatically Close { ... } Blocks

The Automatically Insert Closing "}" option does two things when you type a { character: it inserts a line with a matching } ahead of the cursor, and then it advances to the next line as if the Return key had been pressed. The effect is simple: typing a { creates a balanced block with the cursor positioned at the first line of the block. Figure 7-9 shows an if statement before and after a single { character was typed.

FIGURE 7-9

Figure 7-9. FIGURE 7-9

Controlling When Automatic Indentation Occurs

The Automatically Indented Characters setting selects the characters that trigger an automatic re-indentation of the current line. When a character in the set is checked, typing one of those characters is the same as invoking the Edit

Controlling When Automatic Indentation Occurs

Indenting Comments

The two // Comments options apply to C/C++-style comments when a line is re-indented. They are not applied when comments are being typed. The Indent // Comments option treats // comments like any other program statement and indents them to the same level as the surrounding code. If off, // comments are left at whatever indentation level the programmer typed them. The Align Consecutive // Comments option indents a // comment that appears alone on a line to the same indentation level as the // comment in the previous line. This is most significant when // comments are started to the right of a program statement and continued in another // comment on the next line.

The following three listings illustrate the effects of the two comment formatting options:

No // Comment Formatting
   int main (int argc, char * const argv[])

   {

   // Check the environment

       char * server_addr = getenv("SERVER");

       if (server_addr==NULL)

           exit(3);        // terminate immediately

                  // returning a status of 3

Indent // Comments Only

   int main (int argc, char * const argv[])

   {

       // Check the environment

       char * server_addr = getenv("SERVER");

       if (server_addr==NULL)

           exit(3);        // terminate immediately

       // returning a status of 3

Indent // Comments and Align Consecutive // Comments

   int main (int argc, char * const argv[])

   {

       // Check the environment

       char * server_addr = getenv("SERVER");

       if (server_addr==NULL)
exit(3);        // terminate immediately

                          // returning a status of 3

When you use both comment formatting options, you should get in the habit of inserting a blank line before starting a new C/C++-style comment on its own line. Otherwise, it may get indented to the level of the comment on the previous line.

Re-indenting Text

As mentioned earlier, re-indenting text uses the language-specific rules to determine the appropriate indentation level for each line. This can happen automatically as you type, depending on which syntax-aware indentation options you have enabled, or manually when you use Control+I or the Edit

Re-indenting Text

You can always manually alter the indentation level of a line, or lines, using the Edit

Re-indenting Text

CODE COMPLETION

The most sophisticated feature of syntax-aware editing is Code Completion, Xcode's auto-completion technology. Code completion analyzes the context of the code you are typing and interactively offers suggestions for completing the statement. Code completion supports the C, C++, Objective-C, Objective-C++, Java, and AppleScript languages. It works by assembling a list of symbol names from the Code Sense index that would be appropriate at that point in your code. If you are starting a new statement, the appropriate symbols will include any global variable, function, class name, or language keyword, but if you typed a class or structure name, the appropriate symbols would be only the member functions or instance variables in that class or structure. Figure 7-10 shows the available completions for the CGSize structure nested inside a CGRect structure.

FIGURE 7-10

Figure 7-10. FIGURE 7-10

Code completion uses the context, scope, and type of variables found in the Code Sense index. Consequently, code completion is very accurate and is not easily fooled by namespace, scope, or preprocessor macros.

Accepting Suggestions

Code completion appears in two forms: suggestions and completion lists. Suggestions appear ahead of your typing, as shown in Figure 7-11. In this example I typed the text NSDic and code completion suggested the rest.

FIGURE 7-11

Figure 7-11. FIGURE 7-11

The portion of grey text to the right of the insertion point is the suggestion. You can accept a suggestion by pressing the Tab key. To ignore a suggestion, just keep typing.

The highlighted portion of the suggestion is what will be inserted if you press the Tab key. Xcode recognizes that many symbol names are very similar. In the code in Figure 7-11, you might want to type NSDictionary or NSDictionaryController. If you wanted NSDictionary, press Tab once (to accept the NSDictionary portion) and continue typing. If you wanted NSDictionaryController instead, start by pressing the Tab key once to accept the tionary suggestion. Code completion immediately returns with all of the suggestions that begin with NSDictionary, which include NSDictionaryController, as shown in Figure 7-12. Pressing Tab a second time accepts the Controller suggestion and the classname is complete.

FIGURE 7-12

Figure 7-12. FIGURE 7-12

This successive refinement of suggestions permits you to narrow down your choice quickly from huge families of class and constant names that share common prefixes.

Note

Symbol completion is case-insensitive and retroactively corrects the case of what you've already typed. In the example in Figure 7-11, I could have just as easily typed nsdic instead of NSDic. If I accepted Xcode's suggestion of NSDictionary, the case of the letters I had already typed would have been changed to agree with the symbol. If I ignored the suggestion, the text would have reverted to its original lowercase form.

Suggestion Display Settings

The appearance of suggestions is controlled by the Automatically Suggest option in the Code Sense panel of the preferences, as was shown in Figure 7-1. The possible settings are:

  • Never

  • Immediately

  • With Delay

Never means suggestions never appear while you're typing, but those suggestions and the completion lists are still available. Immediately and With Delay automatically present suggestions either all the time, or only after you've stopped typing for a moment. Suggestions never appear unless Xcode thinks it can make a reasonably accurate guess about what you're typing. For example, thousands of symbols begin with NS in the Cocoa framework. Typing NS will not present any suggestions. Neither will typing NSFile — almost 100 symbols begin with NSFile. But typing NSFileW will suggest either NSFileWrite or NSFileWrapper, followed by the two dozen or so symbols that begin with those prefixes.

Getting Another Suggestion

At any time — even when a suggestion isn't being presented in your text — you can prompt Xcode to offer the next suggestion in its list of candidates by choosing Edit

Getting Another Suggestion
FIGURE 7-13

Figure 7-13. FIGURE 7-13

If you like the suggestion, just keep typing — the suggestion is already part of your text. If you don't, choose Edit

FIGURE 7-13

Using Completion Lists

Choose Edit

Using Completion Lists
FIGURE 7-14

Figure 7-14. FIGURE 7-14

The list can be extensive. In this example, it includes every method of NSNotification, every method of its NSObject superclass, and every category of NSObject. The list can be navigated using the mouse or keyboard (up arrow, down arrow, home, end, page up, page down). You can also continue to type; the completion list will refine itself as you do. Press Tab or Return to accept the currently selected suggestion from the list, or Esc again to close the list.

Note

Code completion requires some practice. Don't get discouraged at first. Once you become used to the "rhythm" of suggestions and the keyboard shortcuts to accept, pick, and reject suggestions, coding even the longest symbol names becomes rapid and accurate.

The typical technique is to use the completion list as a guide to what symbols exist. Type enough of the first portion of the symbol you want, until the list becomes short enough to use the keyboard arrows to select the desired symbol from the list. Then press Tab or Return to insert the suggestion.

Completion Arguments

When Xcode completes a function or method name, it inserts placeholders for its arguments, as shown in Figure 7-15.

FIGURE 7-15

Figure 7-15. FIGURE 7-15

After the completion, the first placeholder is selected automatically. To provide a value for the first placeholder just begin typing — with code completion, of course. The special Edit

FIGURE 7-15

The Show Arguments in Pop-Up List option of the Code Sense Preferences pane (see Figure 7-1) controls whether argument placeholders appear in suggestion or the completion list. C, C++, and Java programmers should turn this option on. These languages use method overloading and without the argument placeholders it's impossible to distinguish between multiple functions that differ only in their argument types. Objective-C programmers, on the other hand, will probably want to turn this off because Objective-C method names are unique and tend to be descriptive of their argument types.

TEXT MACROS

Text macros are another kind of auto-completion. These are text fragments that can be inserted whenever you need them. The text macros supplied by Xcode include a variety of common control structures and programming conventions, the kind that programmers tend to reuse repeatedly. This section discusses how to use text macros.

Text macros are organized by language in the Edit

TEXT MACROS

Text macros can contain placeholders, just like code completions for methods and functions. They may also contain a special placeholder that is replaced by the current selection in the editor. For instance, on the left in Figure 7-16 the statement free(byteArray); is selected. After you select Edit

TEXT MACROS
FIGURE 7-16

Figure 7-16. FIGURE 7-16

Like function arguments inserted by code completion, the first placeholder in the macro is automatically selected. Use the same Select Next Placeholder (Control+/) command to jump to any additional placeholders.

Code completion can also insert text macros. Each text macro has a name property. These names appear in the completion list alongside other top-level function and symbol names. The following table lists a few of the text macros — accessible via code completion — that will save you a lot of typing.

CODE COMPLETION NAME

INSERTS

init

Skeleton Objective-C -(id)init method

dealloc

Skeleton Objective-C -(void)dealloc method

if/for/while/do/switch/case

C control blocks

@try

Objective-C @try/@catch/@finally block

Unlike the menu, only those macros appropriate to your file's language appear. Selecting one inserts the entire text macro. Because you have to be typing the name of the macro to invoke code completion, you cannot simultaneously select text to replace the statements placeholder. If you want to use this feature, you have to invoke the macro by using the menu.

Macros can have several variations. Inserting the C

FIGURE 7-16
First Use of Edit 
FIGURE 7-16
Insert Text Macro
FIGURE 7-16
C
FIGURE 7-16
If Block int foo( int bar ) { if (<#condition#>) { <#statements#> } } Immediately Selecting Edit
FIGURE 7-16
Insert Text Macro
FIGURE 7-16
C
FIGURE 7-16
If Block Again
int foo( int bar ) { if (<#condition#>) { <#statements#> } else { <#statements#> } }

When inserting macros from code completion, use the Edit

FIGURE 7-16

Note

The text <#statements#> in these listings appears as a single statements placeholder in the Xcode editor. If you save the file, it will contain the text "<#statements#>" where the placeholder is. If you add text to your file using this form (that is, <#name#>), it won't appear as a placeholder, but the Edit

FIGURE 7-16

EDITING SYMBOL NAMES

The editor provides a small, eclectic set of shortcuts for finding and editing symbol names. These are referred to collectively as the "Edit All in Scope" feature, although that's just one of its functions. This feature is enabled in the Code Sense pane (see Figure 7-1 again) of the preferences and can be set to Never, Immediate, or With Delay. When enabled, hovering your cursor over a symbol name that's selected or is at the current insertion point presents a pop-up menu button, as shown in Figure 7-17.

FIGURE 7-17

Figure 7-17. FIGURE 7-17

Clicking this button presents three commands. The Edit All in Scope command is a quick means of renaming all occurrences of that symbol within the block of code that contains it. To use it, choose Edit All in Scope and type a replacement name. The editor highlights all occurrences of the symbol so you can see what is about to be changed, and then simultaneously replaces all occurrences as you type. The results are shown in Figure 7-18.

FIGURE 7-18

Figure 7-18. FIGURE 7-18

Alternatively, you can also select a symbol name and choose the Edit

FIGURE 7-18

The Find in Project command makes the current symbol the search text and opens the Find in Project window. Learn more about searching projects in Chapter 8. The Jump to Definition command is the same one described in the "Jumping to a Definition" section in Chapter 6.

SUMMARY

Xcode's editor provides powerful, language-specific tools that help you write code quickly and accurately. Code coloring and folding make visualizing the structure and meaning of your code much easier. Code completion helps you choose the right name in the right place, and text macros save you from many repetitive coding tasks.

You probably won't absorb all of Xcode's editing features in a single day. As you use Xcode to edit files, revisit these two chapters from time to time to reacquaint yourself with some of the more esoteric features.

Though the editor provides a number of navigation features that will jump to predetermined or saved locations, sometimes you just need to go looking for something, or replace occurrences of one thing with something else. The next chapter explains how.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset