While working on development of a utility to speed integration of toolbox calls in MacFortran source code, I found myself looking for a search and replace routine. Perusal of Macintosh Revealed (Vol. 2) quickly led to the toolbox routine Munger (rhymes with plunger). A search of back issues of MacTutor also revealed the lack of a general discussion of Munger and doing find/replace (not even the generic multi-window text editor from the January 1987 issue). Thus, I decided to write a general purpose find/replace unit from a modeless dialog environment.

Basic Program Design

The find/replace unit and the accompanying example program are written in LS Pascal. Conversion to TML, Turbo, or MPW should be relatively straightforward. The find/replace unit is designed as a standalone unit that requires very little modification to the users program to add its capabilities. The modifications required include changing the main event loop to handle modeless dialog events, adding a new menu, and inserting calls to the find/replace unit in your program. When calling the find/replace routines the user passes the current event and a handle for the editText to be searched. The program contains a simple text edit window, a modeless Find dialog, and a modeless Replace Dialog. The program supports desk accessories; cut, copy, and paste within the program (but not with desk accessories); and should be screen and machine size independent. The program requires a 512Ke or later machine. If run on an old 512k machine, the program alerts the user and exits back to the Finder.

Simple Text Editor

The demonstration program uses the ROM85 library enhancements for the textedit window which allowed me to write a barebones editor sufficient for demonstration purposes. The text window can be resized, zoomed, and automatically scrolled. However, there are no scroll bars, thus movement to text outside the visible region must done with the arrow keys. Cut, copy, paste, and clear work properly. The text window contents cannot be loaded from disk, nor saved to disk. Upon startup (Figure 1), the text window contains Lincolns Gettysburg Address retrieved from the resource fork.

Figure 1.

Find/Replace Unit

The Find dialog allows the user to enter text characters and does an exact find. The search process can be initiated by clicking the Find button or pressing the return key. The find routine works from the current selection point and does not wrap past the end of the textedit record. If found, the current selection is set to the string found and highlighted. If not found, the machine beeps. The find routine does not support wildcards nor non-printing characters (e.g., control characters).

The Search dialog allows the user to enter both the search and replace strings. Initially, the Search button is highlighted as the default button. Once the search string has been found (and selected, the search routine is just the find routine), the Replace button is highlighted. If the Replace button is selected then the occurrence of the search string previously found is replaced. The replace string can be null but the find string must contain at least one character. When the replace operation is successfully completed, the Search button returns to the default button. Although I have not included a replace all button (which could easily be integrated), the user can continually press the return key searching and replacing. Dialog cut, copy, and paste from the text edit scrap is supported within both the Find and Replace dialogs.

Handling Modeless Dialogs

To properly handle the modeless find and replace dialogs four major aspects of modeless dialog event handling must be observed carefully: main event loop changes, window events, dialog events, and command keys. Each element is relatively straightforward, but the combination of the four can lead to some confusion and unnecessary coding.

Main Event Loop

When a program contains modeless dialogs, the toolbox routine IsDialogEvent should be called after calling GetNextEvent. Inside Mac (page I-416) warns that the program should call IsDialogEvent even if GetNextEvent returns false. When IsDialogEvent returns true the program should drop into its routine to handle events for the modeless dialog. Thus, the program should call GetNextEvent, then IsDialogEvent, and then start processing on the basis of the booleans returned by the two routines. If the program does a

{1}
if GetNextEvent(myEvent) then
begin
if IsDialogEvent(MyEvent) then
begin
Do_Modeless(MyEvent);
...

structure then null dialog events will not be passed to its modeless dialog routines. The alternative used by the program in the listing does the following:

The structure region of a window is composed of two parts: the content region and the window frame (see Inside Mac, pages I-271,272). In the standard document window, the window frame contains the drag, go-away, and zoom regions (if zoom was desired). These regions do not overlap with the content region in the standard document window, although they could in a custom window definition. Thus, if your modeless dialog uses a standard document window (or a noGrowDocument proc) then you must be careful in handling events. A mouse-down event in the window frame of a modeless dialog will return false for IsDialogEvent. The main event loop must handle mouse-downs in the drag, go-away, and zoom boxes of a modeless dialog when using standard window types. This does not pose a particular problem since handling multiple windows for growing, dragging, and zooming is a standard Mac programming task.

Dialog Handler

When IsDialogEvent returns true, the user should pass control to a routine that handles the modeless dialog event. This routine should call the function

DialogSelect(theEvent,whichDialog,ItemHit):boolean.

DialogSelect will return a result of true with the dialog pointer in whichDialog and the item number in ItemHit when there is

 a mouse-down, key-down, or auto-key event in an enabled editText item. DialogSelect will take appropriate action within the editText item.

 a mouse-down event, then mouse released within an enabled control item. DialogSelect will call TrackControl while the mouse button is down.

 a mouse-down event in any other enabled item.

DialogSelect returns a result of false with the dialog pointer, whichDialog, undefined and ItemHit undefined when there is

 an activate or update event for the dialog window. DialogSelect will handle the redrawing of all items in the window (but will not handle redrawing of the default button).

 a mouse-down, key-down, or auto-key event in a disabled editText item.

 a key-down or auto-key event when no editText item exists.

 a mouse-down event in a control when the mouse is released outside the control.

 a mouse-down event in any other disabled item.

Thus, your modeless routine calls DialogSelect, letting the Dialog Manager handle actions while the user mouses around in the dialog. If the user indicates some action within an enabled dialog item, then the modeless routine takes appropriate action. If DialogSelect returns false then the modeless routine should do nothing. Two exceptions to handling returns of false from DialogSelect exist. First, if the modeless routine needs to take special actions for modeless update or activate events (e.g., redrawing the default button, showing selected text) then the routine must check for these types of events after DialogSelect returns false.

Second, DialogSelect does not check for the command key when handling key-down events. If some key-down events are special cases or if the command key equivalents for menu events (e.g., cut, copy, paste) are to be handled while the modeless dialog is the active window, then the modeless routine must check for key-down events prior to calling DialogSelect. The find/replace unit in the listing checks for edit menu command key equivalents, find/replace menu command key equivalents, and the return key as the default button.

Find/Replace Routines

Implementing a find/replace unit can take many alternative forms. Inside Mac does not specify user-interface guidelines for find/replace actions leading to many different solutions existing. The implementation given in the listing uses a single modeless dialog and follows a simple logic within three routines: Find, Search, and Replace. These routines provide the setup to access the toolbox routine Munger. Munger provides the core find and replace actions on the specified text. Switching between find and replace options alters the appearance and action of the modeless dialog.

Logic Used

When in the Find mode, the user can enter a text string (Figure 2). When the user clicks the find button (or presses the return key) the editText record is searched forward from the current selection. If located, the find string is highlighted in the editText record. If the string is not in the current visible region, a call to TESelView scrolls the string into view (Figure 3). If the string is not found, then the machine beeps.

Figure 2.

Figure 3.

Figure 4.

When in the replace mode, the user must enter a find string while the replace string is optional (Figure 4). When the user clicks the find button (or presses return), starting at the current selection, the find routine tries to locate and highlight the find string. If found, the search routine changes the default button to Replace (Figure 5). When the user clicks the replace button (or presses return) the find text is replaced with the replace text, leaving the current selection after the replacement text, and re-establishing the Search button as the default button (Figure 6).

Figure 5.

Figure 6.

How It Works: Munger

The find, search, and replace routines serve to setup the proper information to send to and retrieve from the toolbox function Munger:

The handle, h, specifies a handle to destination text generated as a relocatable block allocated by the memory manager. Offset refers to the starting location of the operation in the destination text and must be less than the length of the destination text. Ptr1, len1 refers to the target text and ptr2, len2 refers to the replacement text. The function value returned is negative if the operation failed and positive if the specified operation was successful. The behavior of Munger depends on the values passed. The six possible cases are:

Case 1: ptr1<>nil, len1>0; ptr2<>nil, len2>0: the destination text is searched from the offset specified to the end of the text, replacing the first occurrence of the target string found with the replacement text. The function returns the offset of the first byte past the replaced text.

Case 2: ptr1=nil, len1>0; ptr2<>nil, len2>0: the destination text from the specified offset to offset + len1 is replaced by the replacement text. The function returns the offset of the first byte past the replaced text.

Case 3: ptr1=nil, len1<0; ptr2<>nil, len2>0: the destination text from the specified offset to the end of the destination text is replaced by the replacement text. The function returns the offset of the first byte past the replaced text.

Case 4: len1=0; ptr2<>nil, len2>0: the replacement text is inserted into the destination text at the specified offset. The function returns the offset of the first byte past the replaced text.

Case 5: ptr1<>nil, len1>0; ptr2=nil: the destination text is searched for the target string. Munger returns the offset at the beginning of the found string.

Case 6: ptr1<>nil, len1>0; ptr2<>nil, len2=0: the target string is deleted from the destination text instead of replaced. The function returns the offset at the byte where the text was deleted.

The find routine uses Case 5 to perform the search. The find routine retrieves the find string from the dialog, checking for a target string of length greater than zero. The replace pointer is set to nil. If the current selection is not an insertion point, the offset is set to the end of the current selection for the find dialog. The target length is retrieved and the replace length is set to zero. Finally, Munger is called. If the target string is found, the current selection is set to the target and scrolled into view.

The search routine locates the target string using the find routine. If the find was successful, then the default button is set to the replace button and enabled. Once the target string is located, a user action to replace call the replace routine. The replace routine uses Case 1 for positive length replacement text and Case 6 for empty replacement text. The replace routine retrieves the target and replace text from the dialog edit fields, sets the offset to the current selection start of the destination text, and finally calls Munger. If Munger returns a positive value, the first occurrence of the target text was replaced. The editText is then recalibrated, the selection reset, and an invalrect call used to force an update of the editText window. Finally, the default button is set back to the Search button. If Munger returns a negative value, the replace failed and the machine beeps.

Concluding Remarks

The find/replace unit presented is simple in design, takes very little additional memory (approximately 5k), easily integrated into your application, and easily modified to suit your tastes. Most all the programming work is setting up the call to Munger and interpreting the results. The routine could also be changed to a modal dialog quickly. However, the modeless dialog environment seems more natural for a find/replace capability.

Software Updates via MacUpdate

MacFamilyTree 7.3.4 - Create and explore...

MacFamilyTree gives genealogy a facelift: it's modern, interactive, incredibly fast, and easy to use. We're convinced that generations of chroniclers would have loved to trade in their genealogy... Read more

Yummy FTP 1.10.2 - FTP/SFTP/FTPS client...

Yummy FTP is an FTP + SFTP + FTPS file transfer client which focuses on speed, reliability and productivity.
Whether you need to transfer a few files or a few thousand, schedule automatic backups, or... Read more

VueScan 9.5.08 - Scanner software with a...

VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more

Iridient Developer 3.0.1 - Powerful imag...

Iridient Developer (was RAW Developer) is a powerful image conversion application designed specifically for OS X. Iridient Developer gives advanced photographers total control over every aspect of... Read more

Air Video Server HD 2.1.0 - Stream video...

Air Video Server HD streams videos instantly from your computer on your iPhone, iPad, iPod touch or Apple TV. No need to worry about converting or transferring files.
We took everything that was... Read more

Duplicate Annihilator 5.7.5 - Find and d...

Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes.
Duplicate Annihilator... Read more

BusyContacts 1.0.2 - Fast, efficient con...

BusyContacts is a contact manager for OS X that makes creating, finding, and managing contacts faster and more efficient. It brings to contact management the same power, flexibility, and sharing... Read more

Capture One Pro 8.2.0.82 - RAW workflow...

Capture One Pro 8 is a professional RAW converter offering you ultimate image quality with accurate colors and incredible detail from more than 300 high-end cameras -- straight out of the box. It... Read more

Backblaze 4.0.0.872 - Online backup serv...

Backblaze is an online backup service designed from the ground-up for the Mac.With unlimited storage available for $5 per month, as well as a free 15-day trial, peace of mind is within reach with... Read more

Little Snitch 3.5.2 - Alerts you about o...

Little Snitch gives you control over your private outgoing data.
Track background activity As soon as your computer connects to the Internet, applications often have permission to send any... Read more

Pie In The Sky: A Pizza Odyssey 1.0
Device: iOS Universal
Category: Games
Price: $2.99, Version: 1.0 (iTunes)
Description:
A game about delivering pizza. In space.
| Read more »

Chosen Gives Hopeful Singers, Songwriter...

If YouTube videos and reality TV shows like The Voice have taught us one thing, it’s that there are a lot of people out there who are anxious to show the world their talents. And if they’ve taught us a second thing, it’s that there’s an almost... | Read more »

Android's Popular OfficeSuite Now A...

Once only available for Android devices, OfficeSuite has finally landed on the app store. The Mobile Systems app lets you view, edit, create, and share Word, Excel, and PowerPoint documents as well as convert them to/from PDFs. It's touted as being... | Read more »

Warhammer: Arcane Magic is Coming Soon,...

Turbo Tape Games has announced that they're joining forces with Games Workshop to bring the turn-based strategy board game, Warhammer: Arcane Magic, to life on the iOS.
| Read more »

Fast & Furious: Legacy's Creati...

| Read more »

N-Fusion and 505's Ember is Totally...

| Read more »

These are All the Apple Watch Apps and G...

The Apple Watch is less than a month from hitting store shelves, and once you get your hands on it you're probably going to want some apps and games to install. Fear not! We've compiled a list of all the Apple Watch apps and games we've been able to... | Read more »

Appy to Have Known You - Lee Hamlet Look...

Being at 148Apps these past 2 years has been an awesome experience that has taught me a great deal, and working with such a great team has been a privilege. Thank you to Rob Rich, and to both Rob LeFebvre and Jeff Scott before him, for helping me... | Read more »

Hands-On With Allstar Heroes - A Promisi...

Let’s get this out of the way quickly. Allstar Heroes looks a lot like a certain other recent action RPG release, but it turns out that while it’s not yet available here, Allstar Heroes has been around for much longer than that other title. Now that... | Read more »

Macho Man and Steve Austin Join the Rank...

WWE Immortals, by Warner Bros. Interactive Entertainment and WWE, has gotten a superstar update. You'll now have access to Macho Man Randy Savage and Steve Austin. Both characters have two different versions: Macho Man Randy Savage Renegade or Macho... | Read more »

Price Scanner via MacPrices.net

Adobe Brings Powerful Layout-Design Capabilit...

Adobe today announced the availability of Adobe Comp CC, a free iPad app that enables rapid creation of layout concepts for mobile, Web and print projects. With Comp CC, designers can rough out and... Read more

Apple offering refurbished 27-inch 5K iMacs f...

The Apple Store is offering Apple Certified Refurbished 27″ 3.5GHz 5K iMacs for $2119 including free shipping. Their price is $380 off the price of new models, and it’s the lowest price available for... Read more

16GB iPad mini on sale for $199, save $50

Walmart has 16GB iPad minis (1st generation) available for $199.99 on their online store, including free shipping. Their price is $50 off MSRP. Online orders only.
Read more

The Apple Store has Apple Certified Refurbished 13″ 2.6GHz/128GB Retina MacBook Pros available for $979 including free shipping. Original MSRP for this model was $1299.
Read more

Save up to $600 with Apple refurbished Mac Pr...

The Apple Store is offering Apple Certified Refurbished Mac Pros for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more

Samsung Galaxy S 6 and Galaxy S 6 edge U.S. P...

Samsung Electronics America, Inc. has announced the Galaxy S 6 and Galaxy S 6 edge will be available in the U.S. beginning April 10, with pre-orders being accepted now.
“We have completely reimagined... Read more

13-inch 2.5GHz MacBook Pro (refurbished) avai...

The Apple Store has Apple Certified Refurbished 13″ 2.5GHz MacBook Pros available for $829, or $270 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free:
- 13″ 2.... Read more

MacTech is a registered trademark of Xplain Corporation. Xplain, "The journal of Apple technology", Apple Expo, Explain It, MacDev, MacDev-1, THINK Reference, NetProfessional, Apple Expo, MacTech Central, MacTech Domains, MacNews, MacForge, and the MacTutorMan are trademarks or service marks of Xplain Corporation. Sprocket is a registered trademark of eSprocket Corporation. Other trademarks and copyrights appearing in this printing or software remain the property of their respective holders. Not responsible for typographical errors.

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.