1. Customizing
    1. Customizing NEdit
    2. Preferences
      1. Preferences Menu
      2. Preferences -> Default Settings Menu
      3. Changing Font(s)
      4. Customizing Menus
      5. Sharing Customizations with Other NEdit Users
    3. X Resources
      1. The .nedit File
      2. Selected X Resource Names
    4. Key Binding
      1. Key Binding in General
      2. Key Binding Via Translations
      3. Changing Menu Accelerator Keys
    5. Highlighting Patterns
      1. WRITING SYNTAX HIGHLIGHTING PATTERNS
      2. Coloring Sub-Expressions
      3. Hierarchical Patterns
      4. Deferred (Pass-2) Parsing
      5. Pattern Context Requirements
    6. Smart Indent Macros

Customizing

Customizing NEdit

NEdit can be customized many different ways. The most important user-settable options are presented in the Preferences menu, including all options that users might need to change during an editing session. Options set in the Default Settings sub-menu of the Preferences menu can be preserved between sessions by selecting Save Defaults, which writes a file called .nedit in the user's home directory. See the section titled "Preferences" for more details.

User defined commands can be added to NEdit's Shell, Macro, and window background menus. Dialogs for creating items in these menus can be found under Customize Menus in the Default Settings sub menu of the Preferences menu.

For users who depend on NEdit every day and want to tune every excruciating detail, there are also X resources for tuning a vast number of such details, down to the color of each individual button. See the section "X Resources" for more information, as well as a list of selected resources.

The most common reason customizing your X resources for NEdit, however, is key binding. While limited key binding can be done through Preferences settings (Preferences -> Default Settings -> Customize Menus), you can really only add keys this way, and each key must have a corresponding menu item. Any significant changes to key binding should be made via the Translations resource and menu accelerator resources. The sections titled "Key Binding" and "X Resources" have more information.


Preferences

The Preferences menu allows you to set options for both the current editing window, and default values for newly created windows and future NEdit sessions. Options in the Preferences menu itself (not in the Default Settings sub-menu) take effect immediately and refer to the current window only. Options in the Default Settings sub-menu have no effect on the current window, but instead provide initial settings for future windows created using the New or Open commands. Preferences set in the Default Settings sub-menu can also be saved in a file that is automatically read by NEdit at startup time, by selecting Save Defaults.

Preferences Menu

Default Settings
Menu of initial settings for future windows. Generally the same as the options in the main part of the menu, but apply as defaults for future windows created during this NEdit session. These settings can be saved using the Save Defaults command below, to be loaded automatically each time NEdit is started.
Save Defaults
Save the default options as set under Default Settings for future NEdit sessions.
Statistics Line
Show the full file name, line number, and length of the file being edited.
Language Mode
Tells NEdit what language (if any) to assume, for selecting language-specific features such as highlight patterns and smart indent macros, and setting language specific preferences like word delimiters, tab emulation, and auto-indent. See Features for Programming -> Programming With NEdit for more information.
Auto Indent
Setting Auto Indent "on" maintains a running indent (pressing the return key will line up the cursor with the indent level of the previous line). If smart indent macros are available for the current language mode, smart indent can be selected and NEdit will attempt to guess proper language indentation for each new line. See Help -> Features for Programming -> Automatic Indent for more information.
Wrap
Choose between two styles of automatic wrapping or none. Auto Newline wrap, wraps text at word boundaries when the cursor reaches the right margin, by replacing the space or tab at the last word boundary with a newline character. Continuous Wrap wraps long lines which extend past the right margin. Continuous Wrap mode is typically used to produce files where newlines are ommitted within paragraphs, to make text filling automatic (a kind of poor-man's word processor). Text of this style is common on Macs and PCs but is not necessarily supported very well under Unix (except in programs which deal with e-mail, for which it is often the format of choice).

Wrap Margin
Set margin for Auto Newline Wrap, Continuous Wrap, and Fill Paragraph. Lines may, be wrapped at the right margin of the window, or the margin can be set at a specific column.
Tabs
Set the tab distance (number of characters between tab stops) for tab characters, and control tab emulation and use of tab characters in padding and emulated tabs.
Text Font ...
Change the font(s) used to display text (fonts for menus and dialogs must be set using X resources for the text area of the window). See below for more information.
Highlight Syntax
If NEdit recognizes the language being edited, and highlighting patterns are available for that language, use fonts and colors to enhance viewing of the file. (See Help -> Features for Programming -> Syntax Highlighting for more information.
Make Backup Copy
On Save, write a backup copy of the file as it existed before the Save command with the extension .bck (Unix only).
Incremental Backup
Periodically make a backup copy of the file being edited under the name ~filename on Unix or _filename on VMS (see Crash Recovery).
Show Matching (..)
Momentarily highlight matching parenthesis, brackets, and braces when one of these characters is typed, or when the insertion cursor is positioned after it.
Overtype
In overtype mode, new characters entered replace the characters in front of the insertion cursor, rather than being inserted before them.
Read Only
Lock the file against accidental modification. This temporarily prevents the file from being modified in this NEdit session. Note that this is diferent from setting the file protection.

Preferences -> Default Settings Menu

Options in the Preferences -> Default Settings menu have the same meaning as those in the top-level Preferences menu, except that they apply to future NEdit windows and future NEdit sessions if saved with the Save Defaults command. Additional options which appear in this menu are:

Language Modes
Define language recognition information (for determining language mode from file name or content) and set language specific preferences.
Customize Menus
Add/remove items from the Shell, Macro, and window background menus (see below).
Searching
Options for controlling the behavior of Find and Replace commands:
Verbose
Presents search results in dialog form, asks before wrapping a search back around the beginning (or end) of the file.
Keep Dialogs Up
Don't pop down Replace and Find boxes after searching.
Default Search Style
Initial setting for search type in Find and Replace dialogs.
Syntax Highlighting
Program and configure enhanced text display for new or supported languages (See Features for Programming -> Syntax Highlighting).
Initial Window Size
Default size for new windows.

Changing Font(s)

The font used to display text in NEdit is set under Preferences -> Text Font (for the current window), or Preferences -> Default Settings Text Font (for future windows). These dialogs also allow you to set fonts for syntax highlighting. If you don't intend to use syntax highlighting, you can ignore most of the dialog, and just set the field labeled Primary Font.

Unless you are absolutely certain about the types of files that you will be editing with NEdit, you should choose a fixed-spacing font. Many, if not most, plain-text files are written expecting to be viewed with fixed character spacing, and will look wrong with proportional spacing. NEdit's filling, wrapping, and rectangular operations will also work strangely if you choose a proportional font.

Note that in the font browser (the dialog brought up by the Browse... button), the subset of fonts which are shown is narrowed depending on the characteristics already selected. It is therefore important to know that you can unselect characteristics from the lists by clicking on the selected items a second time.

Fonts for syntax highlighting should ideally match the primary font in both height and spacing. A mismatch in spacing will result in similar distortions as choosing a proportional font: column alignment will sometimes look wrong, and rectangular operations, wrapping, and filling will behave strangely. A mismatch in height will cause windows to re-size themselves slightly when syntax highlighting is turned on or off, and increase the inter- line spacing of the text. Unfortunately, on some systems it is hard to find sets of fonts which match exactly in height.

Customizing Menus

You can add or change items in the Shell, Macro, and window background menus under Preferences -> Default Settings -> Customize Menus. When you choose one of these, you will see a dialog with a list of the current user-configurable items from the menu on the left. To change an existing item, select it from the list, and its properties will appear in the remaining fields of the dialog, where you may change them. Selecting the item "New" from the list allows you to enter new items in the menu.

Hopefully most of the characteristics are self explanatory, but here are a few things to note:

Accelerator keys are keyboard shortcuts which appear on the right hand side of the menus, and allow you avoid pulling down the menu and activate the command with a single keystroke. Enter accelerators by typing the keys exactly as you would to activate the command.

Mnemonics are a single letter which should be part of the menu item name, which allow users to traverse and activate menu items by typing keys when the menu is pulled down.

In the Shell Command field of the Shell Commands dialog, the % character expands to the name (including directory path) of the file in the window. To include a % character in the command, use %%.

The Menu Entry field can contain special characters for constructing hierarchical sub-menus, and for making items which appear only in certain language modes. The right angle bracket character ">" creates a sub-menu. The name of the item itself should be the last element of the path formed from successive sub-menu names joined with ">". Menu panes are called in to existence simply by naming them as part of a Menu Entry name. To put several items in the same sub-menu, repeat the same hierarchical sequence for each. For example, in the Macro Commands dialog, two items with menu entries: a>b>c and a>b>d would create a single sub menu under the macro menu called "a", which would contain a single sub-menu, b, holding the actual items, c and d:

    +---++---++---+
    |a >||b >||c  |
    +---++---+|d  |
    	      +---+

To qualify a menu entry with a language mode, simply add an at-sign "@" at the end of the menu command, followed (no space) by a language mode name. To make a menu item which appears in several language modes, append additional @s and language mode names. For example, an item with the menu entry:

Make C Prototypes@C@C++

would appear only in C and C++ language modes, and:

Make Class Template@C++

would appear only in C++ mode.

Menu items with no qualification appear in all language modes.

Sharing Customizations with Other NEdit Users

If you have written macro or shell menu commands, highlight patterns, or smart-indent macros that you want to share with other NEdit users, you can make a file which they can load into their nedit environment.

To load such a file, start nedit with the command:

nedit -import <file>

In the new nedit session, verify that the imported patterns or macros do what you want, then select Preferences -> Save Defaults. Saving incorporates the changes into your own .nedit file, so the next time you run nedit, you will not have to import the distribution file.
Loading a customization file is automated, but creating one is not. To produce a file to be imported by other users, you must make a copy of your own .nedit file, and edit it, by hand, to remove everything but the few items of interest to the recipient. Leave only the individual resource(s), and within those resources, only the particular macro, pattern, style, etc, that you wish to exchange. For example, to share a highlighting pattern set, you would include the patterns, any new styles you added, and language mode information only if the patterns are intended to support a new language rather than updating an existing one.

For example:
   nedit.highlightPatterns:\
	My Language:1:0{\n\
		Comment:"#":"$"::Comment::\n\
		Loop Header:"^[ \\t]*loop:":::Loop::\n\
	}
   nedit.languageModes: My Language:.my::::::
   nedit.styles: Loop:blue:Bold

Resources are in the format of X resource files, but the format of text within multiple-item resources like highlight patterns, language modes, macros, styles, etc., are private to NEdit. Each resource is a string which ends at the first newline character not escaped with \, so you must be careful about how you treat ends of lines. While you can generally just cut and paste indented sections, if something which was originally in the middle of a resource string is now at the end, you must remove the \ line continuation character(s) so it will not join the next line into the resource. Conversely, if something which was originally at the end of a resource is now in the middle, you'll have to add continuation character(s) to make sure that the resource string is properly continued from beginning to end, and possibly newline character(s) (\n) to make sure that it is properly separated from the next item.


X Resources

NEdit has additional options to those provided in the Preferences menu which are set using X resources. Like most other X programs, NEdit can be customized to vastly unnecessary proportions, from initial window positions down to the font and shadow colors of each individual button (A complete discussion of how to do this is left to books on the X Windows System). Key binding (see "Key Binding" is one of the most useful of these resource settable options.

X resources are usually specified in a file called .Xdefaults or .Xresources in your home directory (on VMS this is sys$login:decw$xdefaults.dat). On some systems, this file is read and its information attached to the X server (your screen) when you start X. On other systems, the .Xdefaults file is read each time you run an X program. When X resource values are attached to the X server, changes to the resource file are not available to application programs until you either run the xrdb program with the appropriate file as input, or re-start the X server.

The .nedit File

The .nedit (saved preferences) file is in the same format as an X resource file, and its contents can be moved into your X resource file. One reason for doing so would be to attach server specific preferences, such as a default font to a particular X server. Another reason for moving preferences into the X resource file would be to keep preferences menu options and resource settable options together in one place. Though the files are the same format, additional resources should not be added to the .nedit file, they will not be read, and NEdit modifies this file by overwriting it completely. Note also that the contents of the .nedit file take precedence over the values of X resources. Using Save Defaults after moving the contents of your .nedit file to your .Xdefaults file will re-create the .nedit file, interfering with the options that you have moved.

Selected X Resource Names

The following are selected NEdit resource names and default values for NEdit options not settable via the Preferences menu (for preference resource names, see your .nedit file):

nedit.tagFile: (not defined)
The name of a file of the type produced by the Unix ctags command which NEdit will load at startup time (see Features for Programmers). The tag file provides a database from which NEdit can automatically open files containing the definition of a particular subroutine or data type.
nedit.shell: /bin/csh
(Unix systems only) The Unix shell (command interpreter) to use for executing commands from the Shell menu
nedit.wordDelimiters: .,/\\`'!@#%^&*()-=+{}[]":;<>?
The characters, in addition to blanks and tabs, which mark the boundaries between words for the move-by-word (Ctrl+Arrow) and select-word (double click) commands. Note that this default value may be overridden by the setting in Preferences -> Default Settings -> Language Modes....
nedit.remapDeleteKey: True
Setting this resource to False restores the original Motif binding of the delete key to forward-delete. This binding causes problems when X servers with one delete/ backspace configuration are connected with X clients of the other. Users with a backspace key in the backspace/delete position and who use only machines with that style of keyboard can set this resource to False to get back the forward-delete function of the delete key.
nedit.stdOpenDialog: False
Setting this resource to True restores the standard Motif style of Open dialog. NEdit file open dialogs are missing a text field at the bottom of the dialog, where the file name can be entered as a string. The field is removed in NEdit to encourage users to type file names in the list, a non-standard, but much faster method for finding files.
nedit.bgMenuButton: ~Shift~Ctrl~Meta~Alt<Btn3Down>
Specification for mouse button / key combination to post the background menu (in the form of an X translation table event specification). The event specification should be as specific as possible, since it will override less specific translation table entries.
nedit.maxPrevOpenFiles: 30
Number of files listed in the Open Previous sub-menu of the File menu. Setting this to zero disables the Open Previous menu item and maintenance of the .neditdb file.
nedit.printCommand: (system specific)
Command used by the print dialog to print a file, i.e. lp, lpr, etc.. The command must be capable of accepting input via stdin (standard input).
nedit.printCopiesOption: (system specific)
Option name used to specify multiple copies to the print command. If the option should be separated from its argument by a space, leave a trailing space. If blank, no "Number of Copies" item will appear in the print dialog.
nedit.printQueueOption: (system specific)
Option name used to specify a print queue to the print command. If the option should be separated from its argument by a space, leave a trailing space. If blank, no "Queue" item will appear in the print dialog.
nedit.printNameOption: (system specific)
Option name used to specify a job name to the print command. If the option should be separated from its argument by a space, leave a trailing space. If blank, no job or file name will be attached to the print job or banner page.
nedit.printHostOption: (system specific)
Option name used to specify a host name to the print command. If the option should be separated from its argument by a space, leave a trailing space. If blank, no "Host" item will appear in the print dialog.
nedit.printDefaultQueue: (system specific)
The name of the default print queue. Used only to display in the print dialog, and has no effect on printing.
nedit.printDefaultHost: (system specific)
The node name of the default print host. Used only to display in the print dialog, and has no effect on printing.
nedit.multiClickTime: (system specific)
Maximum time in milliseconds allowed between mouse clicks within double and triple click actions.
nedit*scrollBarPlacement: BOTTOM_LEFT
How scroll bars are placed in NEdit windows, as well as various lists and text fields in the program. Other choices are: BOTTOM_RIGHT, TOP_LEFT, or TOP_RIGHT.
nedit*text.autoWrapPastedText: False
When Auto- Newline Wrap is turned on, apply automatic wrapping (which normally only applies to typed text) to pasted text as well.
nedit*text.heavyCursor: False
For monitors with poor resolution or users who have difficulty seeing the cursor, makes the cursor in the text editing area of the window heavier and darker.
nedit*text.foreground: black
Foreground color of the text editing area of the NEdit window.
nedit*text.background: white
Background color of the text editing area of the NEdit window.
nedit*text.selectForeground: black
Foreground (text) color for selections in the text editing area of the NEdit window.
nedit*text.selectBackground: gray80
Color for selections in the text editing area of the NEdit window.
nedit*text.highlightForeground: white
Foreground (text) color for highlights (parenthesis flashing) in the text editing area of the NEdit window.
nedit*text.highlightBackground: red
Color for highlights (parenthesis flashing) in the text editing area of the NEdit window.
nedit*text.cursorForeground: black
Color for text cursor in the text editing area of the NEdit window.
nedit*text.blinkRate: 600
Blink rate of the text insertion cursor in milliseconds. Set to zero to stop blinking.
nedit*text.Translations:
Modifies key bindings (see below).
nedit*statsLine.foreground: black
Foreground color of the statistics line area of the NEdit window.
nedit*statsLine.background: gray70
Background color of the statistics line area of the NEdit window.
nc.autoStart: False
Whether the nc program should automatically start an NEdit server (without prompting the user) if an appropriate server is not found.
nc.serverCommand: nedit -server
Command used by the nc program to start an NEdit server.

Key Binding

There are several ways to change key bindings in NEdit. The easiest way to add a new key binding in NEdit is to define a macro in Preferences -> Default Settings -> Customize Menus -> Macro Menu. However, if you want to change existing bindings or add a significant number of new key bindings you will need to do so via X resources.

Before reading this section, you must understand how to set X resources (see the help section "X Resources"). Since setting X resources is tricky, it is also helpful when working on key-binding, to set some easier-to-verify resource at the same time, as a simple check that the NEdit program is actually seeing your changes. The appres program is also very helpful in checking that the resource settings that you make, actually reach the program for which they are intended in the correct form.

Key Binding in General

Keyboard commands are associated with editor action routines through two separate mechanisms in NEdit. Commands which appear in pull-down menus have individual resources designating a keyboard equivalent to the menu command, called an accelerator key. Commands which do not have an associated menu item are bound to keys via the X toolkit translation mechanism. The methods for changing these two kinds of bindings are quite different.

Key Binding Via Translations

The most general way to bind actions to keys in NEdit is to use the translation table associated with the text widget. To add a binding to Alt+Y to insert the string "Hi!", for example, add lines similar to the following to your X resource file:

NEdit*text.Translations: #override \n\
  Alt<Key>y: insert_string("Hi!") \n

The Help topic "Action Routines" lists the actions available to be bound.

Translation tables map key and mouse presses, window operations, and other kinds of events, to actions. The syntax for translation tables is simplified here, and you. may need to refer to a book on the X window system for more detailed information.

Note that accelerator resources (discussed below) override translations, and that most Ctrl+letter and Alt+letter combinations are already bound to an accelerator key. To use one of these combinations from a translation table, therefore, you must first un-bind the original menu accelerator.

A resource for changing a translation table consists of a keyword; #override, #augment, or #replace; followed by lines (separated by newline characters) pairing events with actions. Events begin with modifiers, like Ctrl, Shift, or Alt, followed by the event type in <>. BtnDown, Btn1Down, Btn2Down, Btn1Up, Key, KeyUp are valid event types. For key presses, the event type is followed by the name of the key. You can specify a combination of events, such as a sequence of key presses, by separating them with commas. The other half of the event/action pair is a set of actions. These are separated from the event specification by a colon and from each other by spaces. Actions are names followed by parentheses, optionally containing one or more parameters separated by comas.

Changing Menu Accelerator Keys

The menu shortcut keys shown at the right of NEdit menu items can also be changed via X resources. Each menu item has two resources associated with it, accelerator, the event to trigger the menu item; and acceleratorText, the string shown in the menu. The form of the accelerator resource is the same as events for translation table entries discussed above, though multiple keys and other subtleties are not allowed. The resource name for a menu is the title in lower case, followed by "Menu", the resource name of menu item is the name in lower case, run together, with words separated by caps, and all punctuation removed. For example, to change Cut to Ctrl+X, you would add the following to your .Xdefaults file:

nedit*editMenu.cut.accelerator: Ctrl<Key>x
nedit*editMenu.cut.acceleratorText: Ctrl+X

Accelerator keys with optional shift key modifiers, like Find..., have an additional accelerator resource with Shift appended to the name. For example:

nedit*searchMenu.find.acceleratorText: [Shift]Alt+F
nedit*searchMenu.find.accelerator: Alt<Key>f
nedit*searchMenu.findShift.accelerator: Shift Alt<Key>f

Highlighting Patterns

WRITING SYNTAX HIGHLIGHTING PATTERNS

Patterns are the mechanism by which syntax highlighting (see Syntax Highlighting under the heading of Features for Programming) is programmed in NEdit, that is, how it decides what to highlight in a given language. To create syntax highlighting patterns for a new language, or to modify existing patterns, select "Patterns for Highlighting" from "Syntax Highlighting" sub-section of the "Default Settings" sub-menu of the "Preferences" menu.

First, a word of caution. As with regular expression matching in general, it is quite possible to write patterns which are so inefficient that they essentially lock up the editor as they recursively re-examine the entire contents of the file thousands of times. With the multiplicity of patterns, the possibility of a lock-up is significantly increased in syntax highlighting. When working on highlighting patterns, be sure to save your work frequently.

NEdit's syntax highlighting is unusual in that it works in real-time (as you type), and yet is completely programmable using standard regular expression notation. Other syntax highlighting editors usually fall either into the category of fully programmable but unable to keep up in real-time, or real-time but limited programmability. The additional burden that NEdit places on pattern writers in order to achieve this speed/flexibility mix, is to force them to state self-imposed limitations on the amount of context that patterns may examine when re-parsing after a change. While the "Pattern Context Requirements" heading is near the end of this section, it is not optional, and must be understood before making any any serious effort at pattern writing.

In its simplest form, a highlight pattern consists of a regular expression to match, along with a style representing the font an color for displaying any text which matches that expression. To bold the word, "highlight", wherever it appears the text, the regular expression simply would be the word "highlight". The style (selected from the menu under the heading of "Highlight Style") determines how the text will be drawn. To bold the text, either select an existing style, such as "Keyword", which bolds text, or create a new style and select it under Highlight Style.

The full range of regular expression capabilities can be applied in such a pattern, with the single caveat that the expression must conclusively match or not match, within the pre-defined context distance (as discussed below under Pattern Context Requirements).

To match longer ranges of text, particularly any constructs which exceed the requested context, you must use a pattern which highlights text between a starting and ending regular expression match. To do so, select "Highlight text between starting and ending REs" under "Matching", and enter both a starting and ending regular expression. For example, to highlight everything between double quotes, you would enter a double quote character in both the starting and ending regular expression fields. Patterns with both a beginning and ending expression span all characters between the two expressions, including newlines.

Again, the limitation for automatic parsing to operate properly is that both expressions must match within the context distance stated for the pattern set.

With the ability to span large distances, comes the responsibility to recover when things go wrong. Remember that syntax highlighting is called upon to parse incorrect or incomplete syntax as often as correct syntax. To stop a pattern short of matching its end expression, you can specify an error expression, which stops the pattern from gobbling up more than it should. For example, if the text between double quotes shouldn't contain newlines, the error expression might be "$". As with both starting and ending expressions, error expressions must also match within the requested context distance.

Coloring Sub-Expressions

It is also possible to color areas of text within a regular expression match. A pattern of this type associates a style with sub-expressions references of the parent pattern (as used in regular expression substitution patterns, see the NEdit Help menu item on Regular Expressions). Sub-expressions of both the starting and ending patterns may be colored. For example, if the parent pattern has a starting expression "\<", and end expression "\>", (for highlighting all of the text contained within angle brackets), a sub-pattern using "\0" in both the starting and ending expression fields could color the brackets differently from the intervening text. A quick shortcut to typing in pattern names in the Parent Pattern field is to use the middle mouse button to drag them from the Patterns list.

Hierarchical Patterns

A hierarchical sub-pattern, is identical to a top level pattern, but is invoked only between the beginning and ending expression matches of its parent pattern. Like the sub-expression coloring patterns discussed above, it is associated with a parent pattern using the Parent Pattern field in the pattern specification. Pattern names can be dragged from the pattern list with the middle mouse button to the Parent Pattern field.

After the start expression of the parent pattern matches, the syntax highlighting parser searches for either the parent's end pattern or a matching sub-pattern. When a sub-pattern matches, control is not returned to the parent pattern until the entire sub-pattern has been parsed, regardless of whether the parent's end pattern appears in the text matched by the sub-pattern.

The most common use for this capability is for coloring sub-structure of language constructs (smaller patterns embedded in larger patterns). Hierarchical patterns can also simplify parsing by having sub-patterns "hide" special syntax from parent patterns, such as special escape sequences or internal comments.

There is no depth limit in nesting hierarchical sub-patterns, but beyond the third level of nesting, automatic re-parsing will sometimes have to re-parse more than the requested context distance to guaranty a correct parse (which can slow down the maximum rate at which the user can type if large sections of text are matched only by deeply nested patterns).

While this is obviously not a complete hierarchical language parser it is still useful in many text coloring situations. As a pattern writer, your goal is not to completely cover the language syntax, but to generate colorings that are useful to the programmer. Simpler patterns are usually more efficient and also more robust when applied to incorrect code.

Deferred (Pass-2) Parsing

NEdit does pattern matching for syntax highlighting in two passes. The first pass is applied to the entire file when syntax highlighting is first turned on, and to new ranges of text when they are initially read or pasted in. The second pass is applied only as needed when text is exposed (scrolled in to view).

If you have a particularly complex set of patterns, and parsing is beginning to add a noticeable delay to opening files or operations which change large regions of text, you can defer some of that parsing from startup time, to when it is actually needed for viewing the text. Deferred parsing can only be used with single expression patterns, or begin/end patterns which match entirely within the requested context distance. To defer the parsing of a pattern to when the text is exposed, click on the Pass-2 pattern type button in the highlight patterns dialog.

Sometimes a pattern can't be deferred, not because of context requirements, but because it must run concurrently with pass-1 (non-deferred) patterns. If they didn't run concurrently, a pass-1 pattern might incorrectly match some of the characters which would normally be hidden inside of a sequence matched by the deferred pattern. For example, C has character constants enclosed in single quotes. These typically do not cross line boundaries, meaning they can be parsed entirely within the context distance of the C pattern set and should be good candidates for deferred parsing. However, they can't be deferred because they can contain sequences of characters which can trigger pass-one patterns. Specifically, the sequence, '\"', contains a double quote character, which would be matched by the string pattern and interpreted as introducing a string.

Pattern Context Requirements

The context requirements of a pattern set state how much additional text around any change must be examined to guaranty that the patterns will match what they are intended to match. Context requirements are a promise by NEdit to the pattern writer, that the regular expressions in his/her patterns will be matched against at least <line context> lines and <character context> characters, around any modified text. Combining line and character requirements guaranty that both will be met.

Automatic re-parsing happens on EVERY KEYSTROKE, so the amount of context which must be examined is very critical to typing efficiency. The more complicated your patterns, the more critical the context becomes. To cover all of the keywords in a typical language, without affecting the maximum rate at which users can enter text, you may be limited to just a few lines and/or a few hundred characters of context.

The default context distance is 1 line, with no minimum character requirement. There are several benefits to sticking with this default. One is simply that it is easy to understand and to comply with. Regular expression notation is designed around single line matching. To span lines in a regular expression, you must explicitly mention the newline character "\n", and matches which are restricted to a single line are virtually immune to lock-ups. Also, if you can code your patterns to work within a single line of context, without an additional character-range context requirement, the parser can take advantage the fact that patterns don't cross line boundaries, and nearly double its efficiency over a one-line and 1-character context requirement. (In a single line context, you are allowed to match newlines, but only as the first and/or last character.)


Smart Indent Macros

Smart indent macros can be written for any language, but are usually more difficult to write than highlighting patterns. A good place to start, of course, is to look at the existing macros for C and C++.

Smart indent macros for a language mode consist of standard NEdit macro language code attached to any or all of the following three activation conditions:

  1. When smart indent is first turned on for a text window containing code of the language,
  2. When a newline is typed and smart indent is expected,
  3. after any character is typed. To attach macro code to any of these code "hooks", enter it in the appropriate section in the Preferences -> Default Settings -> Auto Indent -> Program Smart Indent dialog.

Typically most of the code should go in the initialization section, because that is the appropriate place for subroutine definitions, and smart indent macros are complicated enough that you are not likely to want to write them as one monolithic run of code. You may also put code in the Common/Shared Initialization section (accessible through the button in the upper left corner of the dialog). Unfortunately, since the C/C++ macros also reside in the common/shared section, when you add code there, you run some risk of missing out on future upgrades to these macros, because your changes will override the built-in defaults.

The newline macro is invoked after the user types a newline, but before the newline is entered in the buffer. It takes a single argument ($1) which is the position at which the newline will be inserted. It must return the number of characters of indentation the line should have, or -1. A return value of -1 means to do a standard auto-indent. You must supply a newline macro, but the code: "return -1" (auto-indent), or "return 0" (no indent) is sufficient.

The type-in macro takes two arguments. $1 is the insert position, and $2 is the character just inserted, and does not return a value. You can do just about anything here, but keep in mind that this macro is executed for every keystroke typed, so if you try to get too fancy, you may degrade performance.


Send questions and comments to: nedit_support@fnal.gov.