Chapter 33. Writing Code in Dreamweaver

CONTENTS

graphics/01icon01.gif

 

  •  Using Dreamweaver as a Text Editor
  •  Linking to External Text Editors
  •  Tag Libraries and the Tag Library Editor
  •  Advanced Search and Replace
  •  Editing Non-HTML Markup with Dreamweaver
  •  Writing JavaScript in Dreamweaver
  •  Summary

Dreamweaver is a lot of things to a lot of people, but at heart it's a code-editing tool. This chapter examines the various code-writing features that make it a favorite program among the hand-coding and scripting crowd. This chapter reviews the Dreamweaver built-in text editor and covers how to make the most of it; how to facilitate working with Dreamweaver and external text editors, such as HomeSite and BBEdit; and how you can use Dreamweaver with more than just HTML, embracing various markup and scripting languages such as XML and JavaScript.

Using Dreamweaver as a Text Editor

The power of Dreamweaver has always been its close integration between visual and text-based editing. The program's built-in text editor, accessible through the Document window's Code view or the separate Code inspector panel, offers many features generally found only in dedicated text-editing programs. These include line numbers, word wrap control, syntax-based color coding, complex text searches utilizing regular expressions and, new to Dreamweaver MX, several features adopted from HomeSite, such as code hints and tag completion. In addition, because the Dreamweaver text editor also is responsible for writing the code created when you work in Design view, it includes built-in source formatting and error-correction functions.

Accessing the Text Editor

You can access the Dreamweaver text editor from the main Document window by choosing Code view or Code and Design view. (For a full discussion of the Document window, see Chapter 2, "Setting Up the Dreamweaver Workspace.") Alternatively, you can open the text editor in its own tabbed panel window by accessing the Code inspector (go to Window > Others > Code inspector). All text-editing features work the same in both Code view and the Code inspector. If you're short on screen space, you'll probably want to use Code view (or Code and Design view) in the Document window. If you have a dual monitor setup at your workstation, you may prefer to display the Document window, set to Design view, on one monitor and the Code inspector, along with any other open panels, on the other monitor. Figure 33.1 shows Code view and the Code inspector, side-by-side for comparison.

Figure 33.1. The Dreamweaver built-in text editor as it appears in Code view in the main Document window (left) and in the separate Code inspector tabbed panel (right).

graphics/33fig01.gif

Code View Options

Options for setting up the text editor's workspace can be found in the Code View Options submenu (accessible from the View menu or from the Document window toolbar), and in the Preferences dialog box (Edit > Preferences). Figure 33.2 shows the Code View Options submenu for Code view. Note that choices made in the View > Code View Options submenu (left) will affect only the Document window's Code view, not the Code inspector.

Figure 33.2. The Code View Options submenu accessible from the toolbar in either the Code window or from the Document window's View menu.

graphics/33fig02.gif

Setting Text Size and Font

By default, all text in the code editor is displayed in 10-point Courier New (Windows) or 10-point Monaco (Macintosh). Because this text is used only for displaying code in Dreamweaver, you can change the size/font to anything that suits you without affecting your files at all.

Like some, you might prefer your code in the "large-print" format for easy onscreen reading without squinting. Or you might prefer to look at fonts other than Courier or Monaco. One bit of advice, however: Certain text-editing tasks, such as counting characters, are much easier to perform on monospaced fonts (such as Courier and Monaco) than on proportionally spaced fonts. One nice alternative you might have installed on your system is Microsoft's Andale Mono.

To change the text size or font of the code display, in the Preferences dialog box select the Fonts category (see Figure 33.3). Changes made here will affect both Code view and the Code inspector.

Figure 33.3. Setting the text size and font in the Preferences dialog box, Fonts/Encoding category.

graphics/33fig03.gif

Syntax Coloring

One of the most useful visual aids in text processing is syntax-based color coding. By setting certain code elements to certain colors, you can tell at a glance how a document is structured. Dreamweaver goes a step further than coloring, allowing you to set other styling attributes like bold, italic, and underlining to differentiate different syntax elements. You also can specify different formatting options for different document types (HTML, PHP, JS, and so forth).

To turn syntax coloring (and styling) on or off, go to the Code View Options menu (accessible in the toolbar or under the View menu) and select or deselect Syntax Coloring. Note that the Reference panel's context-based features will work only if syntax coloring is on. (See Chapter 3, "Creating and Working with Documents," for a full discussion of the Reference panel.) Also, keep in mind that the Code View Options menu command is only accessible when you are in the Code and Design view or in Code view.

To customize which elements are assigned which color and styling, open the Preferences dialog box and select the Code Coloring category (see Figure 33.4). Choose the document type whose styling you want to change, and click the Edit Coloring Scheme button. In the new dialog box that opens, choose any element from the list in the upper left; choose color and styling options from the options in the upper right; and check to see how your changes will look, in the preview area at the bottom of the panel (see Figure 33.4).

Figure 33.4. Customizing the code coloring and styling in the Preferences > Code Coloring dialog box and Edit Coloring Scheme dialog box.

graphics/33fig04.gif

Line Numbers

Line numbers are handy for finding exactly where something is happening in the code. They're mostly useful for web pages that involve scripting, as an aid to debugging (see "Scripting in Dreamweaver," later in this chapter, for more on this). Dreamweaver reports and invalid code warnings also use line numbers for identification.

To show or hide line numbers, go to the Code View Options menu (accessible in the toolbar or under the View menu) and select or deselect Line Numbers.

Word Wrap (Soft Wrapping)

Wrapping means sending text to a new line. In text processing terms, soft wrapping is something the text editor does on-the-fly to make the text fit in the window. The Dreamweaver code editor enables you to view your code with or without soft wrapping. Viewing code that has no wrapping often involves a lot of sideways scrolling to read long lines. Not being able to see an entire line at a time can make it more difficult to understand what's happening in the code. On the other hand, code displayed without wrapping more accurately conveys the overall structure of a document. Figure 33.5 shows the differences between code with and without soft wrapping.

Figure 33.5. HTML code fragment shown with (top) and without (bottom) soft wrapping.

graphics/33fig05.gif

To turn soft-wrapping on or off, go to the Code View Options menu and select or deselect Word Wrap. Note that if you work with line numbers showing, soft-wrap will not affect the numbering of lines, because the wrapping is a temporary visual convenience only. If you save a file created with soft wrapping on, and open it in another editor, no soft wraps will have been saved as part of the file.

Auto-Indenting

Indenting lines of code to indicate nested elements is another way to make the code more easily readable. Lines are indented by adding tabs or spaces. When you manually enter code into the Dreamweaver text editor, you indent your lines as you see fit. As you're typing, the Dreamweaver Auto-Indent feature automatically indents each new line to match the indent of the previous line. This is a handy timesaver if you're coding nested tags, where each tag's indent is based on the indent of previous tag.

To automatically indent each new line based on current indents, go to the Code View Options menu and select Auto-Indent.

Code Formatting Options

Although the Dreamweaver built-in code editor is in many ways comparable to other text-editing software, in one way it is unique. When you author in Design view, Dreamweaver is writing and formatting the source code for you. When you author in Code view, you are in charge of formatting your own source code. When (the most common scenario) you move freely between Code and Design view, or are using Code and Design view, you may write code that Dreamweaver will later edit and reformat. This is called applying source formatting. It's rather like having Mom looking over your shoulder as you work, tidying up after you, making sure you've indented properly, wrapped your text nicely, and so forth.

Dreamweaver will never rewrite your code but will reformat it, if you allow. Dreamweaver automatically applies source formatting to a page element whenever that item is edited from within Design view. You can force the program to apply source formatting to an entire document by going to Commands > Apply Source Formatting.

Like Mom, this source formatting may be intrusive or helpful, depending on your point of view. You can turn the different aspects of source formatting on or off, and you can customize what kind of formatting is applied. Most of this customizing can be done in the Preferences dialog box, under the Code Format category (see Figure 33.6).

Figure 33.6. The Preferences dialog box showing the Code Format category.

graphics/33fig06.gif

Automatic Text Wrap (Hard Wrapping)

Hard wraps are returns coded into the text, using a carriage return (CR), line feed (LF), or both. As you're coding, every time you press the Return key you're hard wrapping. Just as you might use soft wrapping to make your code more readable, some web authors like to insert manual (hard) returns into the code to force line breaks for easier readability. When Dreamweaver is writing code (that is, when you're working in Design view), it will by default add hard wraps to avoid long lines of code. When you type your own code, you control the hard wraps by deciding when to type a Return. Even though you entered the code yourself, however, as soon as you edit it in Design view, or choose Commands > Apply Source Formatting, Dreamweaver will take over and add its own hard wraps wherever it finds excessively long lines.

Note

graphics/01icon07.gif

Hard wrap or soft wrap? If you rely on soft wrapping to display more readable code, switching between wrapped and unwrapped views is as simple as turning Word Wrap on and off. If you rely on hard wrapping, your code's line breaks are fixed unless you manually remove them. In addition, although hard wraps will not affect how a document will display on the web, CRs and LFs are characters and take up file space. Long documents can, therefore, take slightly longer to download if their coding contains many hard wraps.

To control automatic hard wrapping, open the Preferences > Code Format dialog box (see Figure 33.6). If the Automatic Wrapping option is disabled, no hard wraps will be added within a tag or text element, no matter how long the line becomes. If the option is enabled, you can specify how many characters Dreamweaver should allow in a line before it adds a hard wrap. Note that if you work with line numbers showing, hard wrapping will affect the line numbers because it is adding lines to the code. If you save a file created with hard wrapping on, and open it in another editor, the hard wraps will still be there. They are part of the file.

To determine how hard wraps are encoded, open the Preferences > Code Format dialog box and choose one of the Line Break options from the pop-up menu. This is important because different operating systems expect hard returns to be coded differently. Obviously, you want the web server where your pages will reside to recognize your hard wraps for what they are. If you will be uploading your pages using FTP set to ASCII Transfer mode, Dreamweaver takes care of this for you, coding each return character as needed based on the OS of the server. If you will be uploading your HTML documents using FTP set to Binary mode, you must set the correct return character yourself, before uploading.

Indenting

Do you like your code indented? How large an indent do you prefer? Do you want your indents made from tab or space characters? The controls in the Preferences > Code Format dialog box determine how and when Dreamweaver will indent your code during source formatting, as follows:

  • Indent or don't indent. To turn indenting off completely, so all new lines are flush left, deselect the Use option. Selecting the Use option will enable all other choices controlling indentation.

  • Tabs/spaces. You can specify whether indents should be created from tab characters or multiple spaces. Generally, spaces are preferable unless you plan to import your text to a word processing program for eventual printing.

  • Indent size. Determines how many spaces or tabs each indent will be.

  • Tab size. Determines, in characters, how big each tab will be. (If you tell Dreamweaver to calculate your indents in tabs, and set the indent size to 2 and the tab size to 3, each indent will be 6 characters wide.)

Case Control

Standard HTML browsers aren't case-sensitive when interpreting HTML. But any browser or other device that uses XML or XHTML validation is case-sensitive. In addition, many web authors prefer their code to be written consistently in one case (upper or lower).

To specify a case for code that Dreamweaver writes, in the Preferences > Code Format dialog box set the Default Tag Case and Default Attribute Case (refer back to Figure 33.6).

To have Dreamweaver change the case of existing code during source formatting, choose one or both of the Override Case Of options.

Code Rewriting

Dreamweaver promises never ever, ever to rewrite your code. However, it will warn you about, and optionally try to fix, invalid code. Invalid code consists mainly of incorrectly nested or closed tags, such as the following:

<b><i>This is bad nesting! </b></i>  <h1>I have too many tags!</h1></h1>  <h6>I'm missing something...
How Error Checking Works

To display or hide warnings for invalid code, go to the View > Code View Options menu and select or deselect Highlight Invalid HTML. (Note that this option governs only the various Code views. Dreamweaver always highlights invalid HTML in Design view.)

To allow Dreamweaver to fix invalid code, open the Preferences > Code Rewriting dialog box and set options as desired there (see Figure 33.7).

Figure 33.7. The Preferences > Code Rewriting dialog box.

graphics/33fig07.gif

To exclude file types from error checking, go to the Preferences > Code Rewriting dialog box and add the file extension to the Never Rewrite Code options list. Each new file extension must be separated from others in the list by spaces on either side.

Strategies for Using Error Checking

Dreamweaver performs its error checking, and optional error fixing, whenever a document is opened. If you have set your preferences to Warn When Fixing or Removing Tags, at this point Dreamweaver will open an alert window specifying any invalid code found and how it has been fixed. If you haven't turned the warning feature on, you won't even be aware that code is being rewritten.

Why would you want to turn warnings on? Although fixing invalid code is, in theory, a good thing, Dreamweaver isn't always perfect in determining what the desired valid code should look like. For instance, here's a segment of code with a missing </h1> tag:

<html>  <head>  <title>My Page</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <h1>My Home Page  <p>Welcome to my wonderful website.</p>  </body>  </html>

Where should the closing tag be inserted? Directly in front of the <p> tag, probably. Here's where Dreamweaver inserts it:

<html>  <head>  <title>My Page</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <h1>My Home Page  <p>Welcome to my wonderful website.</p>  </h1></body>  </html>

This is definitely an occasion when author intervention is needed to correct the Dreamweaver error correction. Figure 33.8 shows the warning message that will appear when Dreamweaver opens a document containing this code.

Figure 33.8. The Dreamweaver alert window listing invalid code that has been fixed in a document.

graphics/33fig08.gif

Note that the Dreamweaver alert window doesn't give you the opportunity to cancel the code rewriting. If you don't like any of the changes that have been made to your code, you can isolate them (by turning on line numbering in the code editor and using the line references from the alert message) and fix them; or you can just close the document without saving and all changes will be ignored. From there, either open the document in another text editor or open the Preferences > Code Rewriting dialog box and temporarily disable the rewriting features.

Code Writing and Editing

In addition to helping you format your code for readability and display, the Dreamweaver text editor offers a variety of tools to make working with the code easier.

Editing Commands and Shortcuts

If you like working with code, presumably you like typing. A few commands under the Edit menu, each with its own keyboard shortcut, can keep you typing instead of reaching for the mouse while you work. Table 33.1 shows these commands.

Table 33.1. Code-Editing Commands

Command

Keystroke

Description

 

Windows

Macintosh

 

Select parent tag

Ctrl+Shift+<

Cmd+Shift+<

Select any tag completely nesting the current selection.

Select child

Ctrl+Shift+>

Cmd+Shift+>

Select the first tag nested within the currently selected tag.

Indent code

Ctrl+]

Cmd+]

Increase the indent level of a selected line by one.

Outset code

Ctrl+[

Cmd+[

Reduce the indent level of a selected line by one.

Code Hints and Auto Tag Completion

graphics/01icon05.gif

If you like working with code, but don't think doing all that typing is very efficient, Dreamweaver offers a variety of time- and keystroke-saving tools, including the brand-new Code Hints and Auto Tag Completion features.

Auto Tag Completion engages every time you type the opening tag of a pair, causing Dreamweaver to automatically type the closing tag, leaving the insertion point between the two tags. Type <p> and get </p>, and your cursor is correctly positioned to type the text you want between the two tags (see Figure 33.9). If you've ever forgotten to type that closing tag, then wondered why your page wouldn't preview properly, this is the feature for you!

Figure 33.9. Auto Tag Completion at work creating an italic section of a page heading.

graphics/33fig09.gif

Code Hints is a more wide-ranging and configurable feature. It engages every time you type the opening characters of a tag, offering drop-down menus of possible tags, attributes, and even attribute values (see Figure 33.10). The hints aren't just for reference, either. You can navigate through and choose from any menu without moving your hands from the keyboard, for maximum efficiency. The main techniques for navigating the hint menus are as follows:

Figure 33.10. Code Hints at work presenting a menu of possible attributes for the <table> tag.

graphics/33fig10.gif

  • By default, the first item in the hint menu is selected. To move down or up in the list, use the arrow keys on your keyboard.

  • Menus containing lists of text items are arranged alphabetically. To jump to a particular place in the list, type the first letter of the item you want to select. Keep typing more letters to get closer to your desired selection.

  • Depending on the values expected for an attribute, different hint menus will appear. If the expected value is a color, the color palette will appear (use the arrow keys to navigate through the swatches). If the expected value is a relative file path, a menu containing only a browse option will appear (press Return/Enter to open a browse dialog box). If the expected value is unspecified text or a number, no code hint will appear. Figure 33.11 shows the color palette code hint menu.

    Figure 33.11. Using Code Hints to choose a color value for the bgcolor attribute.

    graphics/33fig11.gif

  • To choose a selected item, and have Dreamweaver enter it in your code for you, hit Return or Enter. The item will be inserted, and your insertion point positioned to continue typing.

To configure Auto Tag Completion and Code Hints, open the Preferences > Code Hints dialog box (see Figure 33.12). From here, you can enable or disable either feature. You also can configure the following aspects of Code Hints:

Figure 33.12. The Preferences dialog box showing the Code Hints category, which governs Code Hints and Auto Tag Completion.

graphics/33fig12.gif

  • The Delay slider determines how quickly after you type the menus of code hints will appear. With a delay of 0, each hint menu will appear immediately. With a longer delay, the menus won't appear unless you stop typing for the specified number of seconds. If you don't like those hint menus popping up all over the place, but still want to take advantage of them the next time you get stuck or feel lazy, set the delay to a few seconds, and see how you like it.

  • The list of Menus determines which code hint menus will appear. Do you want Dreamweaver to finish typing tag names for you, or just to suggest attributes? Do you want suggestions for each attribute's value, where appropriate? (To edit the contents of the hint menus, you can click the link to the Tag Library Editor. Read all about this wonderful new MX feature later in this chapter.)

Inserting Objects in Code View

graphics/01icon05.gif

Even though you're working in Code view, don't forget that you can use the Insert bar (and its partner, the Insert menu) while in Code view. In fact, new to Dreamweaver MX are a variety of objects and tabs in the Insert bar that especially appropriate to working in Code view. Though all of these objects are also available from within Design view, choosing them either inserts code that doesn't show up in Design view or switches the focus to Code view for further editing. Table 33.2 lists these items and their functionality.

Table 33.2. Useful Objects for Working in Code View

Tab

Object

Description/Result of Insertion

Common

Tag Chooser

Opens the Tag Chooser dialog box, from which any tag in the Tag Library can be inserted into the document. Switches focus to Code view.

Text

Font tag editor

Opens the Font tag editor dialog box for inserting and configuring the <font> tag. Inserts a tag pair around the current selection.

 

<b>, <i>, <strong>, <em>

Various objects for inserting character formatting (bold, italic, strong, emphasis). Inserts a tag pair around the current selection.

 

<p>, <blockquote>, <pre>

Objects for inserting block-level formatting (paragraph, block quote, pre-formatted text). Inserts a tag pair around the current selection.

 

<h1>, <h2>, <h3>

Objects for inserting the most commonly used heading levels. Inserts a tag pair around the current selection.

 

<ul>, <ol>, <li>

Objects for inserting lists (unordered list, ordered list, list item). Inserts a tag pair around the current selection.

 

<dl>, <dt>, <dd>

Objects for inserting definitions (definition list, definition term, definition description). Inserts a tag pair around the current selection.

 

<abbr>, <acronym>

Objects for inserting abbreviations and acronyms. Inserts a tag pair around the current selection.

Tables

Table

The standard Table object, found also in the Common tab. Same as using Common Table object, inserts table code framework.

 

<table>, <tr>, <th>, <td>, <cap>

Objects for inserting specific tag pairs that go into the construction of a table. Switches focus to Code view, inserts a tag pair wrapping current selection. Each object by itself inserts an incomplete piece of table code.

Forms

Label

Inserts the <label></label> tag pair around the current selection.

 

Fieldset

Inserts the <fieldset><legend> </legend></fieldset> nested tag set around the current selection.

Media

<param>

Inserts a generic parameters tag, suitable for use with the <object> or <applet> tag, with this syntax: <param name="name" value="value">.Switches focus to Code view.

Script

<noscript>

Opens the tag editor dialog box for the <noscript> tag. Switches focus to Code view.

These various Code view objects imply a different working strategy than the editing commands and code hints described above. While it is possible to assign shortcut keys to objects, for the most part, inserting objects means using the mouse to choose from the Insert bar or menu. The other tools described in this section are aimed mainly at keeping your fingers on the keyboard away from the mouse. If you like working with dialog boxes and mouse clicks, even while you're working in Code view, don't forget that you can access the tag editor from within Code view by putting the cursor within a tag and choosing Modify > Edit Tag. (See Chapter 3 for a full discussion of the tag editor.)

If you like using objects, but would still rather type than use the mouse, you can use shortcuts and keyboard navigation techniques to get back to the keyboard. Do it like this:

  • Use the Edit > Keyboard Shortcuts command to assign shortcuts to any commonly used items in the Insert menu. (See Chapter 34, "Customizing Dreamweaver," for a full discussion of customizing keyboard shortcuts.)

  • Use keyboard commands (Tab, arrow, Return) to navigate through any dialog boxes.

  • Use the pre-assigned Ctrl/Cmd+F5 keyboard shortcut to access the tag editor dialog box as needed.

This level of keyboard access is part of Macromedia's commitment to accessibility in the Dreamweaver MX interface. For more on accessibility issues relevant to the end-user and web design, see Chapter 3.

Code Snippets

graphics/01icon05.gif

Snippets, a new feature in Dreamweaver MX, allow you to save frequently needed chunks of code and insert them into a document with a few mouse clicks. Snippets can be used to store anything from comments to formatting wrapped around a selection to entire tables and page layouts.

Using the Snippets Panel

Snippets are created, organized, and inserted using the Snippets panel, which is part of the Code panel group. Access this panel by going to Window > Snippets, or by expanding the docked panel interface to view the Code panels and bringing the Snippets tab to the front. Figure 33.13 shows the Snippets panel in all its glory. Dreamweaver ships with a wide selection of snippets ready for you to use.

Figure 33.13. The Snippets panel, part of the Code panel group.

graphics/33fig13.gif

Inserting Snippets

You can insert a snippet into a document by drag-and-drop or by selecting the snippet and clicking the Insert button at the bottom of the panel. You will, however, want to investigate what code the snippet contains and how it will be inserted, before trying to use it.

Inserting in Code Versus Design View

Because a snippet can contain any portion of code, including incomplete tags and tags that must be nested inside other tags, not all snippets can be inserted everywhere. Some snippets can be inserted into Design view; others may require that you be in Code view before inserting. Some can be inserted as nested content inside tables, or other tags; others may not. The Meta > No-Cache snippet, for instance, can only be inserted while Code view is active; if Code view is active, it will insert at the current insertion point, wherever that is regardless of whether the insertion point is in the <head> or the <body> section, or even in the middle of another tag. Obviously, you need to know where <meta> tags can and cannot go, before using this snippet.

Inserting Block Versus Wrapped Snippets

Most snippets insert a single block of code a table, a set of form elements, a <meta> tag. Some snippets insert two blocks of code, wrapped around whatever you currently have selected when you insert them. The various Comments snippets, for instance, can be used to "comment out" any selected page element by wrapping it in <!-- --> comment tags. If you have nothing selected when you insert a comment snippet, Dreamweaver will insert an empty pair of comment tags into your document.

Editing Snippets

Snippets are easy to edit. In the Snippets panel, either select a snippet and click the Edit button, or double-click the snippet itself, to open the Snippet dialog box (shown in Figure 33.14). You can change any snippet's name, description, type (block or wrapped), as well as editing the code the snippet will insert. You can also determine how the snippet will be previewed within the Snippets panel.

Figure 33.14. The Snippet dialog box, for creating and editing snippets.

graphics/33fig14.gif

Warning

graphics/01icon07.gif

There's nothing stopping you from entering invalid code into a snippet. If you break one of the Dreamweaver default snippets by fiddling with its code, the only way to restore the undamaged snippet is by re-installing Dreamweaver or tinkering around inside the Dreamweaver Configuration folder (another inherently dangerous activity).

Snippet Housekeeping

Snippets are organized in folders, some of which are nested inside other folders. You can rearrange this hierarchy as you like by dragging and dropping snippets and folders. You can rename snippets by editing them. You can rename folders by double-clicking them. You can even delete snippets or folders by selecting them and clicking the trash icon at the bottom of the panel (see Figure 33.13).

Creating Your Own Snippets

The best feature of snippets is that you can easily create your own snippets, and even your own folders to store them in.

To create a new snippet folder, do this:

  1. If you want your folder to appear at the root level of the Snippets panel, start by deselecting any other folders in the Snippets panel. If you want your folder to be nested inside an existing folder, select that folder.

  2. Click the Folder icon at the bottom of the panel (see Figure 33.13). Your new folder will appear.

  3. Name your folder! It's ready for action.

To create a new snippet, do this:

  1. Optional: If you already have the chunk of code that the snippet should contain, open the document containing that code and select it in Code view.

  2. In the Snippets panel, select the folder that you want to contain the new snippet.

  3. Click the new Snippet icon at the bottom of the panel (see Figure 33.13). This will create a new, untitled snippet and will automatically open the Snippet dialog box. If you had code selected, it will appear in the Content field otherwise, type it in now. (You can't create an empty snippet!)

  4. If you're creating a wrapped snippet (a snippet that inserts code before and after any selection), make sure the proper portions of code are in the Before and After fields.

  5. Fill in all the other options of the dialog box, and click OK. Your snippet will now appear in the Snippets panel and will behave just like any other snippet. You can insert it, edit it, delete it, move it around whatever you like.

Exercise 33.1 Creating a Simple Page Layout Using Code Tools Only

In this exercise, you'll create a fairly simple document using only the coding tools in Dreamweaver. While you're at it, you'll customize your working environment for working efficiently with code and you'll see how Code view and its tools can help you learn more about HTML, even if you've always designed more visually in the past.

  1. Create a new document. Save it as generic_order.html. To take full advantage of Code view for coding and Design view for previewing, do one of the following (depending on your available screen real estate): In the Document window, go to Split Code and Design view; or set the Document window to Design view and open the Code inspector. Either way, you want to see your design happening as you code it.

    Before starting work, you'll set some preferences. In the Code View Options menu, turn off Word Wrap. Turn on Line Numbering, Highlight Invalid HTML, Syntax Coloring, and Auto-Indent. In the Preferences dialog box, go to the Fonts category and choose whatever font and size you would like for viewing your code. Finally, make sure code hints and auto tag completion are enabled (Preferences > Code Hints).

    Figure 33.15 shows the document layout you're trying to create, as it will appear in Design view. This will require you to create a form containing a table with three rows and two columns, with the cells in the bottom row set to span two columns. Working on the code only, but using Design view for a preview, you'll create this.

    Figure 33.15. The desired layout for generic_order.html, as it will look in Design view.

    graphics/33fig15.gif

  2. With Code view active, start by entering a pair of form tags in the body of the document. Type <form> and Dreamweaver will insert the closing tag for you. So now you have a pair of tags, with the cursor in between them, ready to continue.

  3. Now you'll start building the table that goes in the form, using the various objects in the Tables tab of the Insert bar.

    From the Insert bar, select the Tables Tab and click the tabl button. Now your code should look like this, with the cursor right in the middle:

    <form><table></table></form>

    From the Insert bar, click the <tr> object. That adds a row within your table. Press Return to create a new line between the <tr></tr> tags. You'll do the rest using hand coding and hints.

  4. Start creating the <td> tag, by typing <td followed by a space. As soon as you type a space following the tag name, the Code Hints menu will appear, showing a list of attributes for this tag. Using the down arrow key on your keyboard, select the align attribute and press Return/Enter.

    Now a Code Hints menu appears, listing the possible values for the attribute. Use the arrow keys to select right, and press Return/Enter. Your code should now look like this:

    <form><table><tr>  <td align="right"  </tr></table></form>

    Continue typing and choosing from hints until your code looks like this:

    <form><table><tr>  <td align="right" valign="baseline" nowrap>Lorem ipsum:</td>  </tr></table></form>

     

  5. Continue the above process, using the Table objects, hand coding and hints, until your code contains all of the following elements (don't worry about where the line breaks occur, for now just get the tags and attributes in place):

    <form>  <table>  <tr>  <td align="right" valign="baseline" nowrap>Lorem ipsum:</td>  <td align="left" valign="baseline"><input type="text"  name="text"></td>  </tr>  <tr>  <td></td>  <td align="left" valign="baseline" nowrap>  <input type="checkbox" name="check"></td>  </tr>  <tr>  <td align="right" colspan="2"><input type="submit" value="Submit"></td>  </tr>  </table>  </form>
  6. When you've got your code completed, the line breaks and indents probably make it a little bit hard to read. Go to Commands > Apply Source Formatting. Everything is now lined up and arranged, in readable format! (See Figure 33.16.) Save your file, and pat yourself on the back.

    Figure 33.16. Final form code for generic_order.html with source formatting applied.

    graphics/33fig16.gif

Exercise 33.2 Creating and Inserting Snippets

In this exercise, you'll turn elements of the generic_order.html document into snippets, so you can easily use them to construct other documents.

  1. Open the generic_order.html file you created in the previous exercise. Work in Code and Design view, or in Design view with the Code inspector visible, so you can see code and design at once.

  2. Open the Snippets panel (expand the Code panel group, or go to Window > Snippets). You want to create a new folder to hold your practice snippets. Select the Content_Tables folder, and click the New Folder icon at the bottom of the panel. Name your new folder Practice (see Figure 33.17).

    Figure 33.17. Creating a Practice snippets folder, in the Snippets panel.

    graphics/33fig17.gif

  3. You're going to create a snippet for each type of table row in the layout, complete with its form element contents. If you create a lot of similar form layouts, this can be a terrific time-saver.

    First, you'll create a snippet from the row containing your right-aligned label and left-aligned text field. In Design view, using the tag selector, or in Code View, select the code for the top row of the table:

    <tr>  <td align="right" valign="baseline" nowrap>Lorem ipsum:</td>  <td align="left" valign="baseline"><input type="text" name="text"></td>  </tr>

    With that code selected, go to the Snippets panel and select the Practice folder. Then click the New Snippet icon at the bottom of the panel (see Figure 33.18).

    Figure 33.18. Creating a new snippet from selected code.

    graphics/33fig18.gif

    The Snippets dialog opens. Your code should already be in place. (If it's not, you'll have to type it in by hand.) Set the dialog box options to match those shown in Figure 33.19. This will create a block type snippet called TextFieldRow. When you're done, click OK. There's your snippet in the Practice folder!

    Figure 33.19. The Edit Snippet dialog box for the new TextFieldRow snippet.

    graphics/33fig19.gif

  4. Repeat the above process to make snippets for the row containing the checkbox and the row containing the submit button. Call them CheckboxRow and SubmitRow.

  5. The final snippet you'll make contains the <form> and <table> tags that should enclose the other tags. Because this is a simple snippet, you can create it entirely in the Edit Snippets dialog box.

    With no code selected, create a new snippet. Set the options to match those shown in Figure 33.20. This will create a wrapped snippet called FormTable, which will contain selected text in a <form> and <table> tag.

    Figure 33.20. The Edit Snippet dialog box for the FormTable snippet.

    graphics/33fig20.gif

  6. It's time to try those snippets out! Create a new HTML document, and have your snippets panel open and ready. You'll start by inserting the various cell snippets. Then you'll wrap the whole lot in the TableForm snippet.

    To start, go to Design view in the new Document. Select the TextFieldRow snippet, and click the Insert button in the Snippets panel. Nothing happens! That's because Dreamweaver won't let you insert incomplete code into Design view, and a <td> tag on its own is definitely incomplete code.

    Now go to Code view, and put the insertion point between the <body></body> tags. Select the LabelCell snippet, and click Insert. There's your code!

    The goal of this part of the exercise is to use snippets to create a slightly fancier version of the generic_order.html form. Examine the layout shown in Figure 33.21. Can insert snippets to create that layout? Start by inserting the row snippets, in order. Then select all the code for all table rows, and insert the FormTable snippet.

    Figure 33.21. A more complex layout assembled from the snippets created from generic_order.html.

    graphics/33fig21.gif

Linking to External Text Editors

So, you like working with code, and you like Dreamweaver, but you prefer your favorite text editor to the Dreamweaver Code view. You can set up a link between Dreamweaver and your external text editor and have the best of both worlds. For both Windows and Macintosh, you have the choice of standard integration with any text editor you choose, or the special options of an integrated HTML editor (HomeSite+ for Windows, or BBEdit for Mac OS 9/X).

Setting Up an External Text Editor (Non-Integrated)

The procedure for linking to and working with an external text editor other than HomeSite or BBEdit is simple and is basically the same across platforms.

To set up integration with an external editor, follow these steps:

  1. In the Preferences dialog box, access the File Types/Editors category (see Figure 33.22).

    Figure 33.22. The Preferences > File Types/Editors dialog box showing options for enabling an external text editor.

    graphics/33fig22.gif

  2. (Mac only) Find and deselect the Enable BBEdit Integration option.

  3. Browse to select the text editor of your choice.

    The Reload Modified Files option determines what will happen when you have edited a document in an external editor and are then returning to Dreamweaver. For more seamless integration, choose Always Reload; the changes will be incorporated automatically. For more control over possible discrepancies that might occur between programs, choose Prompt; Dreamweaver will warn you that changes have been made.

    The Save on Launch option determines whether Dreamweaver will save a document before launching an external text editor. Again, for more seamless integration, choose Always. If you want to be given the chance to review document changes before saving, choose Prompt.

Your chosen editor will appear in the Edit menu, as part of the Edit with application menu command (see Figure 33.23). Choose this option to open your current document in the new editor.

Figure 33.23. The Edit menu ready for integration with the TextPad text editor.

graphics/33fig23.gif

Text Editors, Beyond HomeSite and BBEdit

graphics/01icon07.gif

Many people already have a favorite text editor. No matter what your platform, if you're in the market for a newer, better, more intuitive editor, you have all sorts of choices from freeware to commercial.

Windows

If you're using Dreamweaver/Windows, you're probably using HomeSite+, because it comes bundled with Dreamweaver MX. But plenty of other choices exist, if you prefer. Some web authors like the no-frills familiarity of Notepad. Others prefer more powerful shareware alternatives like UltraText, TextPad, or CuteHTML. A search through www.download.com will present a dozen more alternatives.

Macintosh

BBEdit is definitely the king of Mac text editors, but if you're not ready to pay for this commercial software, you still have several good choices. BBEdit Lite, the freeware little brother to BBEdit, is a great alternative for OS 9 users. Pepper, the popular UNIX-based text editor, is now available as shareware for OS X. And, of course, there's always SimpleText for the true minimalists among us.

Integrating HomeSite+ and Dreamweaver (Windows)

As its name indicates, Macromedia's HomeSite+ for Dreamweaver MX integrates easily and tightly with Dreamweaver.

To set up HomeSite integration in Dreamweaver, follow the steps outlined earlier for linking to an external editor.

You also can set up Dreamweaver integration in HomeSite. By default, HomeSite should have integration enabled. In HomeSite, go to Options > Settings and choose the Dreamweaver category to check this and to configure how HomeSite will treat modified files' other options.

To edit a Dreamweaver document in HomeSite, open a document in Dreamweaver and go to Edit > Edit with HomeSite. That program will launch, if it's not already running, and your document will open for editing.

To edit a HomeSite document in Dreamweaver, open a document in HomeSite and on the Editing toolbar click the Dreamweaver icon (see Figure 33.24).

Figure 33.24. The HomeSite interface with Dreamweaver integration features highlighted.

graphics/33fig24.gif

If you have enabled both programs to automatically reload modified files and save before launching, and if you have a large monitor or dual-monitor setup at your workstation, you can leave the same document open in both programs and work back and forth fairly seamlessly, almost like working with the Code inspector.

Integrating BBEdit and Dreamweaver (Macintosh)

Dreamweaver/Mac includes very tight integration with BBEdit, unlike anything available for any other editor on either platform. If both of these applications are present on your system, integration between the two is automatically enabled; no setup is necessary.

To edit a Dreamweaver document in BBEdit, open a document in Dreamweaver, and go to Edit > Edit with BBEdit. That program will launch, if it's not already running, and come to the front, and your document will open for editing.

To edit a BBEdit document in Dreamweaver, open a document in BBEdit, and go to Markup > HTML Tools Palette to open the palette. From the palette, find and click the Dreamweaver button (see Figure 33.25).

Figure 33.25. The BBEdit interface with Dreamweaver integration features highlighted.

graphics/33fig25.gif

Any code you have selected in Dreamweaver will be selected in BBEdit, and vice versa. Any changes made on a document in one program will be immediately visible in the other, as soon as that program is activated. If you have a large monitor or dual-monitor setup at your workstation, you can leave the same document open in both programs, and work back and forth seamlessly, almost like working with the Code inspector.

Tag Libraries and the Tag Library Editor

graphics/01icon05.gif

Tag libraries are at the heart of Dreamweaver functionality. A tag library is a database of information about a set of tags HTML tags, ASP tags, ColdFusion tags, and so on. In that database is the information that Dreamweaver uses to perform most of its tag-related tasks, from populating code hint menus, to applying source formatting, to generating the information presented in the Tag Chooser and Edit tag editor boxes.

The Tag Library Editor is your window to the tag libraries, and your tool for editing and adding to the information stored there. Has the latest version of Internet Explorer started supporting a tag or attribute that Dreamweaver doesn't know about? Add it to the library! Do you just hate the way Dreamweaver indents table code, or where it inserts line breaks between tabs? Change the library! And it's all done with the Tag Library Editor.

Using the Tag Library Editor Dialog Box

Before you can start tinkering with tag libraries, you need to know what information and options are available to you through the Tag Library Editor dialog box. To open the Tag Library Editor, choose Edit > Tag Libraries. As Figures 33.26 and 33.27 show, the interface contains a wealth of nested information.

Figure 33.26. The Tag Library Editor dialog box showing all the tag libraries in the Dreamweaver database.

graphics/33fig26.gif

Figure 33.27. The Tag Library Editor dialog box showing settings for individual tags within a library.

graphics/33fig27.gif

The Tags List

The upper half of the dialog box is taken up by the tags list, an expandable tree structure showing all tag libraries, the tags they contain, and the attributes of those tags. The tag libraries (see Figure 33.26) are shown in the order in which Dreamweaver searches them for tag information. In other words, when Dreamweaver is determining how to handle a certain tag, only if that tag does not exist in the HTML library does Dreamweaver search for it in the ColdFusion and other libraries. Within each library (see Figure 33.27), the individual tags and attributes are listed in alphabetical order.

Tag Library Options

If you have a tag library selected in the tags list, the bottom half of the dialog box displays a list of document types that might contain tags in that library (see Figure 33.26). This doesn't mean that Dreamweaver will only allow certain tags in certain document types but it does mean that tags in a certain library will only be meaningful to Dreamweaver within those document types. For instance, within a JavaScript document, HTML tags like <a> or <table> are meaningless. Dreamweaver won't provide code hints or other code editing help to those tags in that context.

Tag Options

When a tag is selected in the tags list, the bottom half of the dialog box displays Tag Format options for that tag (see Figure 33.27). These options include:

  • Line Breaks. Should Dreamweaver insert a hard return in the code before and/or after the tag, or between a tag pair and its nested contents? The options in this pop-up menu determine that.

  • Contents. Should any contents nested within a tag pair be indented beyond the tag's indentation, and should the contents be formatted? Choose from this menu to determine that.

  • Case. Should the tag be uppercase, lowercase, or mixed case? Or should it follow an application-wide default? (Click the Default link to establish the default case for all tags.)

The Preview area, at the bottom of the dialog box, shows the results of whatever formatting options have been chosen for the current tag.

Attribute Options

When a tag attribute is selected in the tags list, the bottom half of the dialog box displays formatting options for that attribute (see Figure 33.28). These options include:

Figure 33.28. The Tag Library Editor dialog box showing settings for an individual tag attribute.

graphics/33fig28.gif

  • Attribute Case. As with tags, case can be set to upper case, lower case, or mixed case for each individual attribute, or the attribute can use an application-wide default for all attributes. (Click the Default link to establish the default case.)

  • Attribute Type. The option selected from this pop-up menu determines what kind of help will be available to users in the form of code hints and Tag Inspector options, for instance when working with this attribute. If Dreamweaver is expecting a text value, for instance, no code hint will be given; if a color value is expected, the color palette will appear; if an enumerated value is expected, a list of possible choices will appear in the Code Hint menu. Table 33.3 lists the attribute types, and their results for how the attribute will be treated in the Dreamweaver interface.

    Table 33.3. Possible Attribute Types for Entries in a Tag Library

    Attribute Type

    Description

    Code Hints

    Text

    Any text can be entered

    (none)

    Enumerated

    Select values only are acceptable

    Menu populated with comma-separated list entered in the Attribute Value field

    Color

    Color name or hexadecimal color value

    Color palette

    Directory

    Absolute URL for a directory

    Menu of protocols: ftp://, http://, and so forth

    File Name

    Absolute URL for a file

    Menu of protocols: ftp://, http://, and so forth

    File Path

    Absolute URL for a file

    Menu of protocols: ftp://, http://, and so forth

    Flag

    No value at all; the mere presence of the attribute is the flag (for example, the nowrap attribute for table cells)

    (none)

    Font

    One or more fonts

    Menu of defined font lists

    Relative Path

    Relative URL

    Browse option

    Style

    CSS or other style name

    (none)

     

  • Attribute Value. If the attribute type is set to Enumerated, this input area should hold a comma-delimited list of possible values. These will become the entries in the Code Hint menu.

Editing Tag Library Entries

As you have probably figured out by now, you can change any setting for any library, tag, or attribute, simply by selecting the desired item in the tags list and changing the settings that appear. A few tips on making changes:

  • You can't do too much serious damage to Dreamweaver, just by changing the line break or capitalization settings for tags; but you can make features like code hints unusable for certain attributes if you aren't careful with your settings. Proceed with caution.

  • Don't override the default case of tags and attributes unless you have good reason to. The application-wide default becomes meaningless when most of the elements involved override it.

  • Try your changes out, to see how you like them! After you've changed a formatting option, try creating and editing some samples of the changed tags in Code view. How do the code hints work? What happens when you apply source formatting? If you don't like it, go back to the Tag Library Editor and change things back.

Note

graphics/01icon07.gif

Tag Library information is stored in the Dreamweaver application folder, in various files within the Configuration/Tag Libraries folder. To make absolutely sure you don't do any lasting damage to your copy of Dreamweaver, take a moment to make a backup copy of the Tag Libraries folder before doing any serious tinkering. That way, if disaster strikes and you make a change that impairs your Dreamweaver, you can simple delete the damaged Tag Library folder and replace it with your backup copy.

Adding (and Removing) Entries

Adding and removing attributes, tags, and even entire libraries is a little bit more complex (and can be a lot more dangerous!) than editing existing entries. But it's also where the true customizable power of Dreamweaver tag libraries comes to your aid. All adding and removing can be done with the plus (+) and minus (-) buttons at the top of the Tag Library Editor dialog box.

Adding a Tag Library

To create a new, empty tag library, do this:

  1. Click the plus (+) button at the top of the tags list, and choose New Tag Library from the pop-up menu.

  2. In the dialog box that appears, give your new library a name. (This name is for your benefit only, so be descriptive and concise.)

  3. Click OK to close the dialog box, and you'll see your new library at the bottom of the tags list. (New libraries are like the new kids at school they have to go to the end of the line.)

  4. With your new library selected in the tags list, select what document types should support the tags in this library.

Your new library is ready to rock and roll! The next step is to add tags to the library, so it will have some functionality.

Adding a Tag

To add a new tag to a library, do this:

  1. Click the plus (+) button at the top of the tags list, and choose New Tags from the pop-up menu.

  2. The New Tags dialog box will appear (see Figure 33.29). Specify what library the tag should be added to, and enter the tag's name. (The name is what will appear between the opening and closing < > symbols don't include the symbols themselves.)

    Figure 33.29. The New Tags dialog box, part of the Tag Library Editor.

    graphics/33fig29.gif

  3. If the tag will consist of an opening and closing pair, select the Have Matching End Tags option. If the tag will be a single tag only (like <img> or <hr>), deselect this option.

  4. When you're finished, click OK. Check out the tags list your tag will appear as an entry in the library you specified. Select the tag in the list, and edit its formatting options as desired.

After you've done this, you can try it out! Open a document of a type that will support the library containing your tag, go to Code view, and type the first few characters of your new tag. If you have code hints enabled, a hint menu should appear, with your tag as one of the entries.

Adding an Attribute

To add a new attribute to a tag, do this:

  1. Click the plus (+) button at the top of the tags list, and choose New Attributes from the pop-up menu.

  2. The New Attributes dialog box will appear (see Figure 33.30). Specify the library and tag the new attribute will belong to, and enter the attribute's name.

    Figure 33.30. The New Attributes dialog box, part of the Tag Library Editor.

    graphics/33fig30.gif

  3. When you're finished, click OK. Check out the tags list your attribute will appear as an entry for the tag you specified. Select the attribute in the list, and edit its formatting options as desired.

Exercise 33.3 Adding a Custom Tag Library and Elements

You want to get some practice working with tag library elements, but you probably don't want to risk upsetting the program's built-in functionality. So, in this exercise, you'll create a new tag library, populate it with a new tag, and assign various attributes to that tag. When you're finished, you'll remove the whole lot.

  1. Start by choosing Edit > Edit Tag Libraries, to open the Tag Library Editor.

  2. In the tags list, contract all categories so you're seeing a list of libraries like that shown in Figure 33.26.

  3. Create the new library by clicking the plus (+) button and choosing New Library from the pop-up menu. Call the library Practice Tags.

  4. In the tags list, select the Practice Tags library and make sure HTML documents are selected as one of the document types where these tags may be found (see Figure 33.31).

    Figure 33.31. The Practice Tags library set up so its tags will be recognized when found in HTML documents.

    graphics/33fig31.gif

  5. Next, the Practice Tags library needs a tag of its very own. With Practice Tags selected in the tags list, click the plus (+) button and choose New Tags from the pop-up menu. In the dialog box that appears, make sure the tag will be added to the Practice Tags library. Call the tag grin. This imaginary tag has no closing tag, so deselect the Have Matching End Tags option (see Figure 33.32). Click OK to close the New Tags dialog box.

    Figure 33.32. Adding the <grin> tag to the Practice Tags library.

    graphics/33fig32.gif

  6. Back in the Tag Library Editor, select <grin> in the tags list, and set its options. Choose whatever formatting options you like use the Preview area to see how your choices will affect the code structure (see Figure 33.32).

  7. Try out your new tag! Click OK to close the Tag Library Editor, and open a new HTML document. Make sure code hints are enabled (Edit > Preferences > Code Hints).

    Go to Code view, and in between the <body> </body> tags, type <g. Pause a moment before continuing. The code hint menu appears, taking you right to your new tag! Press Enter/Return, to insert the rest of the tag: <grin>. Congratulations!

  8. Now, add a few attributes to your tag. Go to Edit > Edit Tag Libraries, to open the Tag Library Editor. From the tags list, find and select your <grin> tag. Click the plus (+) button and choose New Attributes from the pop-up menu.

  9. In the New Attributes dialog box, make sure your Practice Tags library and <grin> tag are selected. Call your attribute kind . Click OK, and go back to the Tag Library Editor.

  10. In the editor, select the new kind attribute. Set its Attribute Type to Enumerated, and enter a comma-separated list of possible grins in the Attribute Value field (sly, sneaky, crooked ). Figure 33.33 shows this happening.

    Figure 33.33. Adding the kind attribute to the <grin> tag.

    graphics/33fig33.gif

    Tip

    graphics/01icon07.gif

    When defining an enumerated list in the Tag Library Editor, be sure not to put any spaces between your commas or the list won't work.

  11. Set whatever other attribute formatting you like, and click OK to close the Tag Library Editor. Try your attribute out! In your open document, still in Code view, try entering a new <grin> tag. This time, type this much: <grin.

    Pause for a moment. A code hint menu showing your grin types appears! Choose one, and let Dreamweaver finish coding your <grin> tag for you. Figure 33.34 shows this happening.

    Figure 33.34. The <grin> tag in action, in Code.

    graphics/33fig34.gif

  12. Now, see how the new tag behaves in the Tag Inspector. Open the Tag Inspector (Window > Tag Inspector, or expand the Code panel group).

    In the tree structure view at the top of the panel, find your grin tag and select it. Now look at the attribute list, in the lower half of the panel. There's your kind attribute and its value! Select the value note that the inspector shows a pop-up triangle icon, indicating that there's a pop-up list of values for that attribute. If you click on the icon, you'll be presented with your list of attributes (see Figure 33.34).

Advanced Search and Replace

Although the Dreamweaver Find and Replace command doesn't necessarily have to be used in Code view, sophisticated searching is a feature usually associated with code editing. Back in Chapter 3, you learned the basics of using Find and Replace for HTML tags and text elements, within single documents or across folders or entire sites. In this chapter, you'll see how you can limit page text searches to text only within specific HTML tags, perform advanced searches for HTML tags and attributes using a simple pop-up menu interface, use regular expressions to construct complex search and replace patterns, and even save complex search criteria for future reuse.

Advanced Text Searches

With a basic text search, Dreamweaver enables you to search the text elements in an HTML document (that is, the text that is actually visible on the page, distinguished from HTML tags). With advanced text searching, you can limit the search to only those text elements within, or outside of, specific tags. You can specify that the text element be within one tag or multiple tags; you can even require that the enclosing tags have certain attributes. The Advanced Text search option is available through the Search and Replace window. With the window open, from the Search For pop-up menu, select Text (Advanced).

Advanced text searches are useful any time you're working with complex documents and want to refine your searches as much as possible, the advanced text search is a great aid. Maybe you want to change all instances of Minnesota to MN, except not in titles, for instance. Do a search for the state name but only when it's not in an <h1> or other title tag. Especially if you're doing sitewide changes, this sort of refinement can make it possible to complete a Replace All search in five minutes, rather than an item-by-item Replace search that might take an hour.

Figure 33.35 shows the Find and Replace dialog box set up to perform a complex advanced text search. Table 33.4 explains the various search criteria available in the popup menus. Use the plus (+) and minus (-) buttons to add or remove search criteria.

Figure 33.35. The Find and Replace dialog box set up to perform an advanced text search.

graphics/33fig35.gif

Table 33.4. Criteria for Advanced Text and Specific Tag Searches

Criterion

Description

Inside tag

Not inside tag

Limit the search to text elements contained (or not contained) within a certain pair of tags. Note that only tags that occur in pairs, such as <p>...</p>, will produce valid search results.

With attribute

Without attribute

Limit the search to tags that have (or don't have) a certain attribute set to a certain value; to search based only on the presence or absence of the attribute, regardless of value, leave the Value field blank.

Containing

Not containing

Limit the search to tags that contain (or don't contain) a specified nested tag or text element.

Specific Tag Searches

This type of search enables you to find and modify the attributes of different HTML tags, as well as add, change, and even remove specific tags. This is powerful code-editing functionality, although not something you normally associate with searching and replacing.

After you've tried it a few times, you'll be amazed at how handy this kind of search is. What if you use the company logo throughout your site and then discover you forgot to give it an alt label? A sitewide search for every <img> tag with the attribute src="logo.gif", setting the alt attribute to "Your Logo", will fix the problem in no time flat. Or maybe you need to find all 100-percent width tables across an entire site and change them to 90-percent width; one easy search will do it.

Figure 33.36 shows the Find and Replace dialog box set up to perform a specific tag search with several criteria. Note that instead of replacing you can choose an action to perform on any found tags. The (slightly less than intuitive) procedure for this type of search is to click the Find button to search for instances of the specified tag, and then click the Replace button to perform the specified action on any found tags. Table 33.5 explains the choices available in the Action pop-up menu.

Figure 33.36. The Find and Replace dialog box set up to perform a specific tag search.

graphics/33fig36.gif

Table 33.5. Actions for Specific Tag Searches

Action

Description

Replace tag and contents

Completely replaces opening and closing tags and any nested tags or other contents with specified text. To remove the tag and its contents entirely, leave the specified text field blank.

Replace contents only

Replaces everything within the opening and closing tags with specified text, but leaves the tags in place. To remove the contents, leave the specified text field blank.

Strip tag

Removes opening and closing tags, but leaves any contents in place. Note that this action will not be executed if it would result in invalid code (such as stripping a single <td> from within a table while leaving the table contents in place).

Change tag

Replaces the opening and closing tags with another specified pair of opening and closing tags, leaving any contents intact. Note that if an unclosed or self-closing tag (such as <img> or <img/>) is specified as the replacement for a tag pair (such as <p></p>), all contents of the original tag pair will be lost.

Set attribute

Sets a specified attribute of the tag to a specified value.

Remove attribute

Removes a specified attribute of the tag.

Add before start tag

Adds specified text immediately before the opening tag.

Add after end tag

Adds specified text immediately following the closing tag.

Add after start tag

Adds specified text immediately following the opening tag. This can be used to add a new row to the top of certain tables, for instance.

Add before end tag

Adds specified text immediately preceding the closing tag. This can be used to add a new row to the end of certain tables, for instance.

Using Regular Expressions

Regular expressions aren't a kind of search, and they aren't unique to Dreamweaver. Regular expressions offer a powerful way to search code for patterns rather than specific character-by-character matches. If you're searching for all the phone numbers in a group of web pages, but you don't want to search for each phone number individually, for instance, you can use a regular expression to search for a pattern of numbers, dashes, and parentheses that all the phone numbers follow. Regular expressions are a part of Perl, JavaScript, and other scripting and programming languages. They can be remarkable simple or very sophisticated and complex, depending on what you're trying to accomplish.

If you are technically minded, be aware that the Dreamweaver searching capabilities are built from JavaScript. Therefore, all the features of regular expressions supported by JavaScript will work in defining criteria for the Find and Replace command.

Writing Regular Expressions

A regular expression is a description of a text string that contains certain characters in certain positions or patterns. The simplest regular expressions just consist of the letters or numbers you want to search for, and they find only instances of those specific characters. For instance, the following three search strings are all regular expressions that will find exactly the text strings specified, wherever they occur in a document:

Fred Flintstone  87125  laura@rocketlaura.com

However, regular expressions also can include various "metacharacters," which are used to describe and count characters in a document. Tables 33.6 and 33.7 list the most commonly used metacharacters. Built from metacharacters shown there, a search for phone numbers might be encoded into a regular expression like one of these, for instance:

(\d\d\d) \d\d\d-\d\d\d\d  (*\d{3})*[\s-]\d{3}-\d{4}

The second of these is fancier but more flexible, finding any of these phone numbers:

(800) 123-4567  (800)123-4567  800 123-4567  800-123-4567
Table 33.6. Regular Expression Metacharacters (Character-Matching)

Expression

Kind of Character to Match

Example

\d

Numeral (0 9)

\d matches the 2s in R2D2, but nothing in Skywalker.

\D

Not a numeral

\D matches any character in Skywalker and the R and D in R2D2.

\w

Any alphanumeric character, including underscore

\w matches every character except the spaces and period in "R2D2 ran down the road."

\W

Not any alphanumeric character, or underscore

\W matches only the spaces and the period in "R2D2 ran down the road."

.

Any character except newline rain or region.

r.n matches ran and run, but not

[xyz]

Any character in the brackets (specify a range of characters with a hyphen)

[a-f] is equivalent to [abcdef], and either will match the f and a in favor, and the e, a, and f in leaf.

[^xyz]

Any character not in the brackets (specify a range of characters with a hyphen)

[l-p] is equivalent to [lmnop], and either will match any character in Chewbacca but none in moon or pool.

\b

Word boundary

\bh matches hello but not bother.

\B

Not a word boundary

\h matches "bother" but not "hello"

\s

Single white space character (space, tab, form feed, line feed)

\sone matches one in "is he the one?" but nothing in "someone's there!"

\S

Single nonwhite space

\Sone matches one in "someone's there!" but nothing in "is he the one?"

^

The beginning of a string or line

^ a matches the a in "all for one," but nothing in "one for all."

$

The end of a string or other selection

s$ matches the second s in biscuits, but not the first.

\t

Tab

 

\f

Form feed

 

\r

Carriage return

 

\n

Line feed

 

\x

The literal value of x (used to search for occurrences of special characters that would otherwise be interpreted as metacharacters)

hi. matches hit, hid, and so forth; hi\. matches hi.

Table 33.7. Regular Expression Metacharacters (Character-Counting)

Expression

How Many Characters

Examples

*

The preceding character, zero or more times

om* matches om in mom, omm in mommy, and o in son.

+

The preceding character, one or more times

om+ matches om in mom, omm in mommy, but nothing in son.

?

The preceding character, zero or one time

so?e?n matches son in Anderson, sn in snack, but nothing in soon.

{n}

The preceding character, exactly n times

c{2} matches cc in Chewbacca but nothing in charcoal.

{n.}

The preceding character, n or more times

6{1.} matches the 6s in 976 and 97662, but not in 666.

{n,m}

The preceding character, at least n, at most m times

F{1,3} matches the Fs in #F204CA and #FFCCCC, but nothing in #FFFFFF.

To learn more about regular expressions, check out Mastering Regular Expressions (published by O'Reilly). Many JavaScript and Perl books also have in-depth discussions of this topic.

Finding and Replacing with Regular Expressions

To use regular expressions in Dreamweaver, just enable the Use Regular Expressions option in the Find and Replace dialog box and enter characters and metacharacters in any of the dialog box's Find text fields. (It makes no sense to use regular expressions as replacement strings.)

Figure 33.37 shows examples of three search types using regular expressions. The top example shows a basic Text search that finds variant spellings of labeled and makes them consistent. The center example shows an Advanced Text search that finds all occurrences of the word and in headers only (h? will return h1, h2, h3, and so on) and replaces them with &. The bottom example shows a Specific Tag search that finds all tables with percent-based widths (\d*% finds numbers with any number of digits that end in a percent sign) and removes the width attribute.

Figure 33.37. Find and Replace dialog boxes showing different search types utilizing regular expressions: basic Text search (top), Advanced Text search (middle), Specific Tag search (bottom).

graphics/33fig37.gif

The Use Regular Expressions and Ignore White Space options can't both be enabled at the same time, because white space cannot be ignored within regular expressions.

The most powerful feature of the Dreamweaver Find and Replace command is its capability to save search criteria for later reuse. Any setup you create in the Find and Replace dialog box can be saved. This feature really makes it worthwhile spending time and thought to create flexible, complex searches. A good set of search criteria is like your very own utility program, ready to run on any document with a few mouse clicks.

After you've filled in all the Find and Replace options as desired, you can save any set of criteria by clicking the Save button (the one with the disk icon). You'll be presented with a standard Save dialog box. Choose a location and choose a name. After you have finished, your criteria will be saved to a file with the.dwr extension. Figure 33.38 shows this happening.

Figure 33.38. Saving the settings from a Find and Replace dialog box.

graphics/33fig38.gif

To load a saved criteria file, open the Find and Replace dialog box and click the Load Query button (the one with the file icon). A dialog box will appear asking you what file to load. Choose your DWR file and open it. The Find and Replace interface will be set to your saved settings.

You also can modify the saved criteria file. After all, DWR files are just XML files storing the various search parameters as attributes of custom tags. If you love working with code, you can always open the DWR file in a text editor (Dreamweaver, even!) and modify the criteria there. The code for the search shown in Figure 33.37, for instance, looks like this:

<?xml version="1.0"?>  <dwquery>      <queryparams matchcase="false" ignorewhitespace="false"  useregexp="true"/>           <find>           <qtag qname="table">               <qattribute qname="width" qcompare="=" qvalue="\d*%"></qat tribute>           </qtag>           </find>      <replace action="removeAttribute" param1="width" param2=""/>  </dwquery>

Exercise 33.4 Finding and Replacing for Maximum Efficiency

In this exercise, you use various kinds of searches to efficiently edit a document that would otherwise be a nightmare of boring, repetitive tasks.

  1. From the chapter_33 folder on the CD, find and open states.html and examine its contents (see Figure 33.39). You can see that it consists of two types of tables: a layout table for the overall page structure, and lots of colored data tables. Your job is to make sweeping changes to those data tables.

    Figure 33.39. The states.html file with multicolored data tables.

    graphics/33fig39.gif

  2. First, you want to add a row of header cells to each data table (with the headings State, Capital, and Pop.). You can do this with a Specific Tag search; but what tag do you search for? You can't search for all <table> tags, or the layout table will be included. You can't search by background color, because each table's color is different. If you look at the code for this document, however, you'll see that each data table has a class of state assigned to it. You can search by class. For each data table, you want to add a <tr> with specific contents. Therefore, when you find each appropriate <table> tag, you'll add the following code after the start tag:

    <tr><th bgcolor="#FFFF00" align="left">State</th><th  bgcolor="#FFFF00" align="left">Capital</th><th bgcolor="#FFFF00"  align="left">Pop.</th></tr>

    Open the Find and Replace dialog box, and set it up as shown in Figure 33.40.

    Figure 33.40. The Find and Replace dialog box, ready to add a header row to each data table in states.html.

    graphics/33fig40.gif

  3. You've seen how a class assignment can help identify items for mass changes. You can use custom classes along with CSS to more easily format your table cells. Open the CSS Inspector and you'll see that two custom classes have been defined for this document: statetitle and statedata. You want to apply those to the cells of your data tables. Can you see how a Specific Tag search can help with this? The statetitle class is easy; it should be assigned to all <th> tags. The statedata class is harder; you need to find some combination of characteristics that is unique for all data cells. For this document, examination of the code shows that the data cells have no attributes at all, whereas the layout cells have either height, width, or both. Figure 33.41 shows the Find and Replace dialog boxes to perform the searches required here. Perform those searches and examine your code to make sure you get the results you wanted.

    Figure 33.41. Find and Replace dialog boxes for the searches that will add statetitle and statedata classes to the data tables.

    graphics/33fig41.gif

    Here's an extra: Now that you have a class providing color for the <th> tags, you don't need the bgcolor attribute in those tags. Can you use a Specific Tag search to remove that attribute?

  4. One of our headers has the text Pop., but you've changed your mind and want it to say Population. This might be a simple Text search, but what if some text somewhere else in the document says Pop.? You want an Advanced Text search that finds only this text when it's in a statetitle<th> tag. Can you perform this search? The setup for this one isn't shown here.

  5. The boss says he wants the cells with population numbers in them to have a white background so that they stand out. You need to do a tag search for all <td> tags with a class of statedata, but only those that contain numbers. Time for a regular expression! Can you think this one through? Figure 33.42 shows a setup that will work.

    Figure 33.42. Find and Replace dialog box to search for all <td> tags with a class of statedata and containing numbers.

    graphics/33fig42.gif

  6. Last big challenge: If you examine the code for the style sheet in this document's <head>, you'll see that all styles refer to a group of sans-serif fonts, but each font list differs slightly. You want all font lists for sans-serif fonts to be identical. You want them to read like this: Verdana, Arial, Helvetica, Geneva, Swiss, sans-serif. This requires a Source search with a regular expression; you want to replace every font list that contains the word sans-serif with your font list. In regular expression terms, you want to find the following:

    font-family:[^;]*sans-serif;

    And replace it with the following:

    font-family: Verdana, Arial, Helvetica, Geneva, Swiss, sans-serif;

Can you see how the regular expression works? Try it out. Perform the search; then examine your document code to make sure the changes were made successfully. If they weren't, Edit > Undo as many times as necessary and try again.

That was a pretty handy search. Maybe it wouldn't have been so difficult making a manual code change for just this one document, but what if you want to change internal style sheets across an entire site? More than that, you might find yourself needing a similar search again in the future. Do you want to have to figure out that regular expression every time? Of course not! This is a good set of search criteria to save. Open the Find and Replace dialog box again. Your preceding settings should still be in place. Save the search criteria as Set Sans-Serif Font List, in whatever centralized location you like. You now have a handy tool for future use.

Editing Non-HTML Markup with Dreamweaver

The Dreamweaver code editor can be used to edit other kinds of code other than the default markup languages (HTML, XML, XHTML, ASP, CFM, and so on), although you won't be able to display those files in Design view or use the Preview in Browser feature to view them.

Macintosh users should be aware that unlike many other Mac programs, Dreamweaver/Mac uses filename extensions to determine file types. A file created in Dreamweaver may even display on your desktop with the DW icon, and the program still won't be able to open or preview it if it doesn't include the proper extension.

To enable Dreamweaver to open and edit different file types, go to Edit > Preferences and choose the File Types/Editors category. Find the Open in Code View option, and add the new file extension to the text field (see Figure 33.43). Note that each extension must be separated from others in the list by spaces on either side. Don't forget to include the period (.).

Figure 33.43. Configuring Dreamweaver to open additional file types in the Preferences > File Types/Editors category.

graphics/33fig43.gif

To make sure Dreamweaver doesn't rewrite the code for this file type, go to Edit > Preferences and choose the Code Rewriting category. Find the Never Rewrite Code options list and add the new extension. Each new file extension must be separated from others in the list by spaces on either side. (See the section on "Code Rewriting" for more on this.)

Writing JavaScript in Dreamweaver

In addition to other code-writing chores, Dreamweaver has several features specifically to help you hand code JavaScript.

The Reference Panel

In previous chapters, you have seen how the Reference panel can give you context-sensitive help for HTML and CSS. For scripting help, the Reference panel also provides JavaScript help. To access the JavaScript help in the Reference panel, click the <?> button on the Document toolbar and choose O'Reilly JavaScript Reference from the panel's Book pop-up menu. Figure 33.44 shows the JavaScript section of the Reference panel with all of its parts labeled for easy browsing. It's organized by object, as most JavaScript dictionaries are, so you'll need to know your object structure to take full advantage of it.

Figure 33.44. The JavaScript section of the Reference Panel, a handy source of information for scripters.

graphics/33fig44.gif

Scripting Without Using Code View

If you want to be able to add your own scripts to your page without having to navigate through one of the code editor views, you have two choices: the Call JavaScript behavior, or the Script object. The Script Property Inspector also enables you to edit existing <script> tags.

Call JavaScript Behavior

You apply and edit this behavior the same way you would any other item in the Behaviors panel. Instead of inserting some prewritten JavaScript action, however, the behavior adds only an event handler and whatever JavaScript statement(s) you specifically tell it to add. Any time you want to add a simple one- or two-line script statement to a page using an event handler, this is a nice, quick option. (For a full discussion on using Dreamweaver behaviors, see Chapter 16, "Getting Interactive with Behaviors.") To add the Call JavaScript behavior to a document, follow these steps:

  1. Open a document and select whichever page element you want to attach the behavior to. (Be sure to select an element that can have a behavior attached to it, such as a text link, image, or image link.)

  2. Open the Behaviors panel (Window > Behaviors). Double-check the panel's title bar to make sure the correct page element is selected.

  3. From the plus (+) menu, choose Call JavaScript.

  4. In the dialog box that appears, type in whatever JavaScript statement(s) you want to execute. (Separate multiple statements with semicolons.) After you have finished, click OK.

    The MM_CallJS() function will be added to your document, like this:

    function MM_callJS(jsStr) { //v2.0    return eval(jsStr)  }

    Your script statement will be passed as a parameter in the function call, like this:

    <a href="#" onClick="MM_callJS('window.alert(\'Hello  world\');')">Click here!</a>

Figure 33.45 shows the Call JavaScript behavior being assigned.

Figure 33.45. Using the Call JavaScript behavior to attach a simple script statement to a page link.

graphics/33fig45.gif

As the preceding code shows, whatever statement you enter in this behavior will be passed as part of an event handler in double and single quotes. Always use single quotes within your script statement; otherwise the behavior will generate errors in the browser. To make sure Dreamweaver doesn't try to URL-encode your quotes (turning " into %22, for instance), go to Edit > Preferences > Code Rewriting (Mac OS X: Dreamweaver > Preferences > Code Rewriting) and disable both Special Characters options Encode Special Characters in URLs and Encode <,>,&, and " in Attribute Values Using &. With these options deselected, Dreamweaver will escape all quotes with \ and leave all other characters alone.

The dialog box text field has no maximum character restrictions, so you can enter as long a chunk of code as you like; although longer statements will, of course, require some scrolling to view in the text field. If you're frustrated by the viewing restrictions, you can customize the behavior to present a text area rather than a text field in its dialog box by editing the calljavascript.htm file (located in the Dreamweaver application folder, in Configuration/Behaviors/Actions). Open this file in a text editor or in Dreamweaver itself, if you like and change the <input> tag from a text field to the following:

<textarea name="message" cols="50" wrap="virtual" rows="5"></textarea>

You can set the columns and rows to any values you like. Set the wrap to "virtual" for best viewing in the dialog box. Obviously, don't change the name from "message", or the behavior will not function properly. (For more on working with the Dreamweaver configuration files, see Chapter 33, "Writing Code in Dreamweaver.") The next time you launch Dreamweaver, the new dialog box with expanded text area should appear (see Figure 33.46).

Figure 33.46. The Call JavaScript behavior with expanded text area for better viewing.

graphics/33fig46.gif

The Script Object

The Dreamweaver Script object is a quick way to insert a complete <script> tag into a document without going to Code view. Scripts entered this way aren't limited to JavaScript. They can include anything a <script> tag normally contains, including links to separate JS files.

To insert a script block into a document using the Script object, follow these steps (see Figure 33.47):

Figure 33.47. Using the Script object to insert a <script> tag into the document head. Note that the head content bar is visible and active.

graphics/33fig47.gif

  1. Open a document.

  2. To insert the script into the <body> section, position the insertion point where the tag should be added. To insert the script to the <head> section, use the View Options menu to turn Head Content on, and click in the head content bar (along the top of the Document window) to activate it.

  3. In the Insert bar, choose the Script Tab. Find and click the Script object icon.

  4. In the dialog box that appears, choose a scripting language. JavaScript and VBScript appear in the pop-up menu. To add version information, or to choose another language, enter the information directly into the text field.

  5. Enter the complete script contents you want to enter, minus only the opening and closing <script> tags (and the script-hiding comment tags).

Dreamweaver will insert your script, inside <script> tags and with the proper language specified. It also will include comment tags to hide the script from noncompliant browsers.

To edit a script block using the Script inspector, follow these steps (see Figure 33.48):

Figure 33.48. The Property inspector for Script objects.

graphics/33fig48.gif

  1. Open a document containing <script> tags.

  2. In the View menu, be sure Visual Aids: Invisibles is enabled. Each <script> tag in the document should now show in Design view as a script icon.

  3. Select the script icon representing the code you want to edit.

  4. Use the Property inspector to change any script parameters. Click the Edit button to access and edit the code.

When you insert a Script object, you're not given the choice to add a script link. The dialog box assumes you're going to type your own script in. However, you can subvert the process (although it's easier just to use the Assets panel, as discussed later).

To insert a link to a client-side or server-side JS file, using the Script object, follow these steps:

  1. Open a document and insert a Script object, as described earlier.

  2. In the Script object dialog box, leave the code field blank and click OK. This inserts an empty <script> into your document.

  3. Enable viewing of invisible items, find the script icon, and select it.

  4. In the Script Object Property inspector, choose the file to which you want to attach.

Scripts in the Assets Panel

If you're working within a defined site and want to add links to JS files to your documents, the easiest way is to use the Assets panel. Every JS file within your local site folder will appear in the Scripts section of the Assets panel (see Figure 33.49). To add a script link to a document this way, follow these steps:

Figure 33.49. Linking an HTML document to a JS file by dragging from the Assets panel.

graphics/33fig49.gif

  1. Open the document to which you want to add the link.

  2. Use View > Head Content, if necessary, to show the head content bar.

  3. Open the Assets panel and click the script icon to show the site's script files.

  4. Find the file you want to link to and drag its icon from the Assets panel to the head content bar of your document. Figure 33.49 shows this happening.

JavaScript Tools in Code View

If you're editing your scripts in Code view or the Code inspector, you can take advantage of colored syntax, function navigation, auto-balancing, and various debugging tools.

Syntax Coloring for Scripts

You have already seen how syntax coloring works in Dreamweaver how to enable it and customize text colors and styling. The Preferences > Code Coloring dialog box includes special settings for coloring text within scripts, including reserved keywords, other keywords, and strings (refer back to Figure 33.7). This coloring will apply to any code between a pair of <script> tags. It won't affect any code that is part of an event handler in the HTML, because that code is not within a <script> tag.

When working with colored script syntax, remember that if you're typing a new <script> tag into the code editor, as soon as you type the word <script>, the coloring for everything in the entire document from that point on will be determined by script syntax colors. This means that if you're entering a script into an already existing HTML page, the color coding for the rest of the HTML code will be overridden. This can be distracting as you work. The solution is to immediately enter both the opening and closing <script> tags and then come back to type in your script's code. The closing </script> tag tells Dreamweaver to stop applying script-based syntax coloring.

JavaScript Snippets

Snippets, discussed earlier in this chapter, can also be used to store frequently used JavaScript code fragments. In fact, Dreamweaver ships with a variety of handy JavaScript snippets that you might want to explore.

Code Navigation Menu

Whether you're working on an HTML document containing functions in its <head>, or a JS document, Dreamweaver enables you easily jump to different JavaScript functions with the Code Navigation menu. You can access this menu from the document or Code inspector toolbar by clicking the double curly braces icon (see Figure 33.50). The menu lists any JavaScript functions. Choosing a function will move the cursor to the first line of that function and will scroll the display if necessary to show it.

Figure 33.50. Accessing the Code Navigation menu (available only from Code view).

graphics/33fig50.gif

Auto-Balancing Braces

Losing track of opening and closing curly braces, parentheses, and quotation marks is a common problem in scripting. In Dreamweaver, you're on your own determining whether all your open quotes close properly, but the program will help you with your braces (curly braces, square brackets, parentheses). To test whether your punctuation marks are correctly paired, follow these steps:

  1. In Code view or the Code inspector, select an opening brace (curly brace, square bracket, or parenthesis).

  2. Go to Edit > Balance Braces. Dreamweaver will select all code between that brace and the corresponding closing brace.

If you're used to how auto-balancing is implemented in some text editors (such as BBEdit, for instance), the Dreamweaver Balance Braces command may take some getting used to. As mentioned earlier, you can't use it to balance anything but braces. Also, it works only when selecting an opening brace, not a closing brace. However, it will respond with an error beep if you have incorrectly balanced braces (for instance, more openers than closers or vice versa). For example, selecting the first opening brace in the following code will generate an error sound, because the braces don't balance:

function helloWorld() { if (a==0) {        window.alert("Hello, world");  }

Selecting the second opening brace, however, will not result in an error; Dreamweaver will just select the code inside the if statement braces.

Debugging Tools

Any time you get into serious script writing, you're going to be doing some debugging. Debugging is the process of finding (and fixing) errors in scripts. This involves checking the code for syntax errors. It also involves running the script a step at a time, while keeping track of variable values, to identify logical errors.

The Dreamweaver code editor offers the ability to set breakpoints and debug through various browsers. When you debug a document in Dreamweaver, the program adds two files to the folder containing the file: mm_debug.js and the Java applet mm_nsapplet.class. Using these two files, Dreamweaver first checks for syntax errors. Then it launches a browser and loads the Java applet, which checks for logic errors.

Breakpoints are stopping places in a script. When checking for logical errors, you tell the script to stop running periodically so that you can check the variables and determine whether everything is progressing as it should.

To set breakpoints for debugging, follow these steps (see Figure 33.51):

Figure 33.51. Setting a breakpoint in a Dreamweaver script, preparatory to debugging.

graphics/33fig51.gif

  1. Open a document with one or more scripts you want to debug, and view it in Code view or the Code inspector.

  2. Examine your script, deciding which variables you want to keep track of and where in the script you want to check their values. In the following code, for instance, it would be nice to know the value of this URL before performing any more actions on it:

    function collectName() { var thisURL=document.url;  var nameString=thisURL.substring(thisURL.indexOf("=")+1,  thisURL.length);  window.alert("Welcome, "+nameString);  }

     

  3. Each breakpoint is attached to a particular line of the script. The breakpoint will stop the script before execution of the line where it's set. Determine which line you want the breakpoint attached to and position the cursor in that line.

  4. From the {} menu on the toolbar, select Set Breakpoint. A large dot will appear to the left of the line you've chosen (see Figure 33.51).

  5. Repeat steps 3 and 4 for every additional breakpoint you want to set. (You can stop as many times as you like, in the debugging process, and check as many variables as you need to check.)

Dreamweaver will remember your breakpoints even after you close the document. They will be forgotten (removed) when you quit Dreamweaver.

To remove a breakpoint, follow these steps:

  1. Position the cursor in a line that currently has a breakpoint set for it.

  2. From the {} menu, select Remove Breakpoint.

To remove all breakpoints, go to the {} menu and select Remove All Breakpoints.

As mentioned earlier, debugging launches a browser and runs a Java applet, through the browser. Debugging in Dreamweaver/Windows can be done in Internet Explorer or Netscape; debugging in Dreamweaver/Mac can only be done in Netscape.

To debug a document, follow these steps:

  1. Save the document you want to debug (or Dreamweaver will ask whether you want to do so).

  2. Choose File > Debug in Browser, and select your browser (see Figure 33.52).

    Figure 33.52. The Preview/Debug in Browser menu for Windows (top) and Mac.

    graphics/33fig52.gif

  3. If your script contains any syntax errors, Dreamweaver will open an error window detailing the problem(s), and the debugging process will stop. Read the error message, and then click the Go to Line button to find the error. Figure 33.53 shows this happening.

    Figure 33.53. The syntax error message window showing an unterminated string literal in line 12 of the script.

    graphics/33fig53.gif

  4. If there are no errors, the browser will launch. A prompt window will appear, asking whether you want to start debugging. Click OK to proceed.

  5. A security alert may appear, warning you that running the Java applet is a risk and asking whether you want to continue. To continue, click the Grant button. (Warning: This whole process may take a while, especially if your computer is connected to a large network.)

  6. With the browser still active, the debugger window will then open (refer back to Figure 33.47). It shows the source code for your document, with breakpoints, and gives you the opportunity to set or change your breakpoints before you proceed. (It's your choice whether you want to set your breakpoints ahead of time, in Dreamweaver, or wait until now to do it.)

  7. At this point, you need to create a list of watched variables. Do that in the bottom portion of the debugger window. Click the plus (+) button to get a variable name field to appear. Type the name of the variable you want to track here (see Figure 33.54). Repeat this process to add as many variables as you want to track.

    Figure 33.54. The Dreamweaver debugging window showing a debug session in progress.

    graphics/33fig54.gif

  8. At the top of the debugger window, click the Run button to start debugging (see Figure 33.54). This will open your document in the browser window. If your script is set to run automatically onLoad, it also will begin running the script. If your script needs to be triggered, the browser and debugger will wait for you to trigger the script. After the script has been triggered, it will run until it reaches the first breakpoint. Then it will stop, and the debugger window will come to the front.

  9. The debugger's list of watched variables will show the current values of all variables you specified. Check them. When you're ready to continue, click the Run button again. The browser window will come to the front again, and the script will continue running until it finishes, or until it reaches another breakpoint.

  10. After you have finished all your debugging, close the debugger window and go back to Dreamweaver. If your script needs adjusting based on what you found out, make those changes and go through the whole process again!

Exercise 33.5 Inserting and Debugging a JavaScript

This exercise is more of a challenge. Can you use Dreamweaver to successfully debug a (not very complicated) JavaScript in an HTML document? Figure 33.55 shows what the final page should look like in the browser, when the script is functioning properly. The exercise file contains various scripting errors that prevent the page from displaying properly.

Figure 33.55. Proper browser display of script_debug.html.

graphics/33fig55.gif

  1. From the chapter_33 folder on the CD, find and open script_debug.html. Examine its contents. You can see that the entire <body> section is created from one JavaScript contained in a <script> tag. If you view the document in Design view, with invisible objects showing, you'll see a single script icon (pretty exciting, eh?).

  2. To view the script from Design view, you can select the script icon and, in the Property inspector, click the Edit button. The code-viewing options are limited in the editing window, however no colored syntax, no line numbers, and so forth so you'll want to do your debugging and editing from Code view or the Code inspector.

  3. Here's the challenge: The script contains various syntax and logical errors. Can you find them using the debugger with breakpoints? If you're an old hand at scripting, you may not need those tools, but give them a try to get used to working with them. Be sure to enable line numbers in the code editor before proceeding, for easier reference.

Summary

In this chapter, you have seen how the Dreamweaver coding environment works, and how to make the most of integrating it into your authoring workflow. You can use Dreamweaver for coding tasks from markup to scripting, and can configure it to handle whatever file types you need to edit. You can use the Document window's Code view or the separate Code inspector panel to do this. And you have a great deal of control over how the code editor formats, rewrites, and displays your code. Finally, if you don't want to use the internal code editor, you can configure Dreamweaver to link to an external text editor. If you use HomeSite (Windows) or BBEdit (Mac) for this task, special integration features are available; but you can use any text editor you choose. From a coder's point of view, who needs Design view?

CONTENTS


Inside Dreamweaver MX
Inside Dreamweaver MX (Inside (New Riders))
ISBN: 073571181X
EAN: 2147483647
Year: 2005
Pages: 49

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net