TweetFollow Us on Twitter

Undo
Volume Number:3
Issue Number:5
Column Tag:Programmer's Workshop

Implementing Undo For Text Edit

By Melvyn D. Magree, (M)agreeable software, inc.

Undo (Cmd-Z) It!

Honored more in the breech than not is the standard Edit Menu Apple published in Inside Macintosh (page I-58). Even if a program does contain an Edit Menu with the recommended items, Undo might not really be available.

An Undo command is a very helpful feature, especially if you just did Clear when you meant to do Cut or if you backspaced one word too many or whatever! It is remarkable that Undo is not included in all editing type programs because it is not that difficult to program. I designed and coded a text-file version for my own development system in less that two weeks. I modeled my Undo by observing the behavior of MacWrite.

We want to give the user the following Undo capabilities:

Undo Cut:

• Reinsert the cut text from the clipboard.

• Restore the previous contents of the clipboard.

Undo Copy:

• Restore the previous contents of the clipboard.

Undo Paste:

• Remove pasted text.

• Reinsert the text overlaid by Paste.

Undo Clear:

• Reinsert the text removed by Clear.

Undo Typing:

• Remove all characters typed since the user made the last selection.

• Reinsert the selection overlaid by the typing including any removed by backspacing.

For each Undo operation except copy, we also must reset the selection as it was before the user requested the "undid" operation.

Redo Cut, Copy, Paste, and Clear are straightforward. We merely perform a Cut, Copy, Paste, or Clear. However, for Redo Typing, we must:

• Remove the current selection.

• Remove any characters that the user had backspaced over.

• Reinsert the "effective" typing sequence that the user Undid.

The effective typing sequence is the string of characters remaining after the user backspaced. That is, if the text and selection had been as follows:

and the user had typed:

 {backspace}{backspace}the most  user-
dis{backspace}{backspace}{backspace}un

resulting in

then the effective typing sequence is

 the most user-un

If the user requested Undo Typing, the text and selection would revert to

and if the user followed the request with Redo Typing, the text and selection would once again become:

To make sure that we can undo an operation, we have to save any information that the operation destroys. So, our edit operations are:

Cut

• Save current contents of clipboard.

• Cut current selection to clipboard.

• Set menu to Undo Cut.

Copy

• Save current contents of clipboard,

• Copy current selection to clipboard, and

• Set menu to Undo Copy.

Paste

• Save current selection,

• Paste clipboard to current selection, and

• Set menu to Undo Paste.

Clear

• Save current selection,

• Delete current selection, and

• Set menu to Undo Clear.

Typing

• If first character for selection:

Save current selection.

• If backspace over previously unsaved character:

Insert unsaved character at beginning of saved selection.

• Insert character in text at insertion point.

• Set menu to Undo Typing.

Note that I use the term clipboard to refer to the TextEdit scrap, not the clipboard file. To actually put the TextEdit scrap in the clipboard file (also called the desk scrap) you must call TEtoScrap. To read the clipboard to the TextEdit scrap you must call TEfromScrap.

The key design elements for undo (and redo) are a state variable for the next possible undo operation and a second Text Edit record. We use the state variable to reset the Undo item of the Edit Menu and to call the proper procedure when the user requests Undo. We use the second Text Edit record as a private scrap area to save the text removed by the user's last editing operation. We can then use the various TextEdit procedures to move text from the clipboard to the private scrap or vice versa.

To try out some simple versions of these undoable editing routines, we will write a very simple editing program. The program allows the user to select a file, opens a window, reads the contents of the file into the window, and then allows the user to change the contents of the window by typing, by using the mouse, and by selecting from the Edit menu. The program allows the user to close the window and open another from the File menu. The program's File menu also contains a Quit entry.

If you are familiar with writing Macintosh stand-alone applications, you might want to skip over the next section to Editing Functions.

To keep the program simple, we will ignore many expected Macintosh features such as desk accessories, moving the window on the screen, scrolling the text, and making the program easily translatable from English. We will not check for many possible error situations.

Thus, our main program is:

Initialize tool box,

Initialize program's global variables,

Initialize menus, and

Start the main event loop.

Our main event loop checks only for four events:

activate:

If window open calls TEActivate.

mouse down:

If in menu, calls menu selector

Else if window open calls TE selector.

key down and auto key:

If window open calls typing routine

Our main event loop continues to look for these events until the menu selector sets the global variable Quit to TRUE. When Quit is TRUE, the main event loop returns to our main program which terminates.

Our menu selector:

Determines which menu item was selected,

If Apple menu, ignores it,

If File Menu, calls File Manager with item, or

If Edit Menu, calls Edit Manager with the item.

Removes highlighting from menu bar.

Our File Manager calls FileOpen or FileClose according to the item selected. That is,

If Open, calls Open_File,

If Close, calls Close_File, and

If Quit, then

If a file is open, calls Close_File,

Sets QuitFlag to TRUE.

Open_File

Asks the user to select a file from a list;

Opens the requested file;

Opens a window to display the text of the file;

Opens a TextEdit record to control display of the text;

Opens a TextEdit record for the scrap;

Reads text of the file into TextEdit record;

Disables the Open item and enables Close item;

The only error condition that we will check is if the user clicked the cancel button in the file dialog box. Note that if the file contains more than 32,767 characters, then our program may hang. TEInsert does not check for this limit and may never return. [The 32K limit is notorious throughout Text Edit, especially in TEScroll. This has not been changed in the SE & Mac II ROMS unfortunately. -Ed]

Close_File does almost the reverse of Open_File. It:

Closes the display TextEdit record,

Closes the scrap TextEdit record,

Closes the window,

Closes the file, and

Enables the Open item and disables Close item.

If we allowed the user to actually change the file, then we would have to rewrite the text and flush the volume also. Without considering the editing portion of our program, we need the following global variables:

Pointer for the window,

Handle for the TextEdit record,

Handle for the scrap TextEdit record,

Integer for the file reference number, and

Boolean for the Quit flag.

Our first program in TML Pascal is then shown in listing one.

PROGRAM UndoIt;

{Program to test Edit menu including Undo/Redo of previous operation}

{$L UndoIt/Rsrc}


{$I Memtypes.Ipas }
{$I QuickDraw.Ipas}
{$I OSIntf.Ipas   }
{$I ToolIntf.Ipas }
{$I PackIntf.Ipas }

CONST MenuBarID = 200;
      FileMenu  = 200;
      OpenItem  =   1;
      CloseItem =   2;
      QuitItem  =   4;
      EditMenu  = 201;
      UndoItem  =   1;
      CutItem   =   3;
      CopyItem  =   4;
      PasteItem =   5;
      ClearItem =   6;
      WindowID  = 200;

{Global variables}

VAR theWindow  : WindowPtr; {Main window}
    DisplayTE  : TEHandle;  {TextEdit record for display}
    ScrapTE    : TEHandle;  {TextEdit record for scrap}
    fNum       : integer;   {Ref number for current file}
    QuitFlag   : Boolean;   {Main event loop exits when TRUE}
    FileHandle : MenuHandle;
    EditHandle : MenuHandle;

PROCEDURE Init_MyGlobals;

 BEGIN
  QuitFlag:=FALSE;
  theWindow:=NIL; {=NIL if no window opened}
 END; {Init_MyGlobals}

PROCEDURE Open_File;
 
 CONST hCorner   =    90;
       vCorner   =    90;
       MaxTEText = 32767;  {Should be smaller for 128K Mac}
       
 VAR OpenReply  : SFReply;
     GetWhere   : Point;
     fTypes     : SFTypeList;
     OpenErr    : OSErr;
     TextRect   : Rect;
     TextLength : LongInt;
     TextDest   : Ptr;
 
 BEGIN
  GetWhere.h:=hCorner;
  GetWhere.v:=vCorner;
  fTypes[0]:='TEXT';
  OpenErr:=-1;           {Set to other than noErr}
  SFGetFile(GetWhere,'',NIL,1,fTypes,NIL,OpenReply);
  WITH OpenReply DO
   IF Good THEN
    OpenErr:=FSOpen(fName,vRefNum,fNum);
  IF OpenErr=noErr THEN
   BEGIN
    theWindow:=GetNewWindow(windowID,NIL,WindowPtr(-1));
    SetPort(theWindow);
    TextRect:=theWindow^.portRect;
    DisplayTE:=TENew(TextRect,TextRect);
    WITH TextRect DO    {Make ScrapTE "invisible"}
     BEGIN
      top:=-bottom;
      left:=-right;
      bottom:=0;
      right:=0;
     END;
    ScrapTE:=TENew(TextRect,TextRect);
    OpenErr:=GetEof(fNum,TextLength);
    IF TextLength>MaxTEText THEN  {Ensure "not too much"}
     TextLength:=MaxTEText;
    TextDest:=NewPtr(TextLength);
    OpenErr:=SetFPos(fNum,fsFromStart,0); {read text}
    OpenErr:=FSRead(fNum,TextLength,TextDest);
    TEInsert(TextDest,TextLength,DisplayTE);
    DisposPtr(TextDest);
    EnableItem(FileHandle,CloseItem);
    DisableItem(FileHandle,OpenItem);
   END; {IF OpenErr=noErr}
 END; {Open_File}

PROCEDURE Close_File;
 
 VAR CloseErr   : OSErr;
 
 BEGIN
  HideWindow(theWindow);
  TEDispose(DisplayTE);
  TEDispose(ScrapTE);
  DisposeWindow(theWindow);
  theWindow:=NIL;
  CloseErr:=FSClose(fNum);
  EnableItem(FileHandle,OpenItem);
  DisableItem(FileHandle,CloseItem);
 END; {Close_File}

PROCEDURE File_Manager(MenuItem:integer;VAR QuitFlag:Boolean);

 BEGIN
  CASE MenuItem OF
   OpenItem:Open_File;
   CloseItem:Close_File;
   QuitItem:
    BEGIN
     IF theWindow<>NIL THEN
      Close_File;
     QuitFlag:=TRUE;
    END;
  OTHERWISE
  END; {CASE MenuItem}
 END; {File_Manager}

PROCEDURE Cut;
 
 BEGIN
 END; {Cut}

PROCEDURE Copy;
 
 BEGIN
 END; {Copy}

PROCEDURE Paste;
 
 BEGIN
 END; {Paste}

PROCEDURE Clear;
 
 BEGIN
 END; {Clear}

PROCEDURE Undo;
 
 BEGIN
 END; {Undo}

PROCEDURE Edit_Manager (MenuItem:integer);

 BEGIN
  CASE MenuItem OF
   UndoItem:
    Undo;
   CutItem:
    Cut;
   CopyItem:
    Copy;
   PasteItem:
    Paste;
  END; {CASE MenuItem}
 END; {Edit_Manager}

PROCEDURE Menu_Selector(where:Point;VAR QuitFlag:boolean);
 
 VAR theCode          : LongInt;
     MenuNum,MenuItem : integer;

 BEGIN
  theCode:=MenuSelect(where);
  MenuNum:=HiWord(theCode);
  MenuItem:=LoWord(theCode);
  Case MenuNum OF
   FileMenu:File_Manager(MenuItem,QuitFlag);
   EditMenu:Edit_Manager(MenuItem);
   OTHERWISE
  END; {CASE OF MenuNum}
  HiliteMenu(0);
 END; {Menu_Selector}

PROCEDURE TE_Selector(where:Point;extend:Boolean);

 BEGIN
 END; {TE_Selector}

PROCEDURE Typist(EventMessage:LongInt);

 BEGIN
 END; {Typist}

PROCEDURE MainEventLoop;
 
 MainEvent : EventRecord;
     theCode   : integer;
     extend    : Boolean;
     anyWindow : WindowPtr;

 BEGIN {MainEventLoop}
  REPEAT
   IF GetNextEvent(everyEvent,MainEvent) THEN
    CASE MainEvent.what OF
     activateEvt:
      IF theWindow<>NIL THEN
       TEActivate(DisplayTE);
     mouseDown:
      BEGIN
       theCode:=FindWindow(MainEvent.where,anyWindow);
       CASE theCode OF
        inMenuBar:
         Menu_Selector(MainEvent.where,QuitFlag);
        inContent:         {Assume only one window}
         BEGIN
          extend:=(BitAnd(MainEvent.modifiers,ShiftKey)<>0);
                  {If user holding shift key, then extended
                   selection}
          TE_Selector(MainEvent.where,extend);
         END;
        OTHERWISE           {Ignore}
       END; {CASE theCode}
      END; {mouseDown}
   keyDown,autoKey:  {ignores command key}
      IF theWindow<>NIL THEN
       Typist(MainEvent.message);
     OTHERWISE
    END; {IF GetNextEvent, CASE MainEvent.what}
  UNTIL QuitFlag;
 END; {MainEventLoop}

FUNCTION Init_MyMenus:Boolean;
 
 CONST MenuBarId = 200;

 VAR theMenuBar : Handle; {MBAR resource points to menus}

 BEGIN
  Init_MyMenus:=FALSE;     {Assume menus not initialized}
  theMenuBar:=GetNewMBar(MenuBarId);
  IF theMenuBar<>NIL THEN
   BEGIN
    SetMenuBar(theMenuBar);
    DrawMenuBar;
    FileHandle:=GetMHandle(FileMenu);
    EditHandle:=GetMHandle(EditMenu);
    Init_MyMenus:=TRUE;
   END;
 END; {Init_MyMenus}

BEGIN {Main Program}
 InitGraf(@thePort);
 InitFonts;
 InitWindows;
 InitMenus;
 TEInit;
 InitDialogs(NIL);
 InitCursor;
 Init_MyGlobals;
 FlushEvents(EveryEvent,0);
 IF Init_MyMenus THEN
  MainEventLoop;
END. {Main Program}

The resource file for this program is shown in listing two.

*  UndoIt/Rsrc.R - Resource definition of UndoIt

UndoIt/Rsrc.rel

TYPE MBAR=GNRL
,200    ;; Resource ID
.I ;; Integers follow
3;; Three menu items;
1;; Apple Menu
200;; File Menu
201;; Edit Menu

TYPE MENU
  ,1    ;; Apple Menu
\14

 ,200 ;; File Menu
File
 Open
 (Close ;; Initially disabled
 (-
 Quit

 ,201   ;; Edit Menu
Edit
 (Can't Undo   ;; Disable at beginning
 (-
 (Cut
 (Copy
 (Paste
 (Clear ;; Full standard edit menu should also include
 ;; Select All and Show Clipboard

TYPE WINDOW
   ,200
No Title;; If title is only blanks, RMaker can crash
   40 20 300 480
   Visible NoGoAway
   2                 ;; Plain Box
   0

Editing Functions

We now continue by doing the traditional editing functions: Cut, Copy, Paste, and Clear. We need a state variable to let us know what the next possible Undo or Redo operation is. For this we define:

TYPE EditType = (CantUndo,UndoTyping,UndoCut,UndoCopy,
 UndoPaste,UndoClear,
 RedoTyping,RedoCut,RedoCopy,
 RedoPaste,RedoClear);

and add the variable EditStatus of EditType.

To switch the text of the menu according to the current value of EditStatus, we need several string constants. These really should be in the resource file, but for brevity we put them directly in the program. These strings are:

CONST CantUndoStr= 'Can''t Undo'; {Note double apostrophe}
 UndoStr= 'Undo';
 RedoStr= 'Redo';
 TypingStr= 'Typing';

The remainder, Cut, Copy, Paste, and Clear we can take from the menu itself.

We need two global variables to save the start and end of the selection to be redone. Because the user can backspace over text in front of the previous selection, we also need a global variable to save the farthest point which the user backspaced to. These variables are:

VAR
 UndoStart  : integer;  {Start previous/current selection}
 UndoEnd: integer; {End previous/current selection}
 CurrentStart  : integer; {Backspace point before previous 
 selection}

With these variables defined, we can write our TE_Selector procedure for when the user clicks the mouse in the window.

TE_Selector

Calls TEClick to set the selection in the TextEdit record, and
Calls Reset_EditMenu to set Undo to Can't Undo.
Reset_EditMenu is called with an EditType parameter and
 If the Clipboard contains text then
 Enables the Paste item
 Else
 Disables the Paste item;
 If the selection is more than the insertion point,
 Enables the Cut, Copy, and Clear items
 Else
 Disables the Cut, Copy, and Clear items;
 Sets the Edit status to the value of the parameter;
 If the parameter is CantUndo
 Sets Undo item to Can't Undo
   Else if Undo Typing or Redo Typing
 Sets Undo item appropriately,
 Else
 Get the text of the corresponding menu item, and
 Sets Undo item appropriately;
If the paramter is CantUndo
 Disable Undo item
Else
 Enable Undo item;

So, we fill out TE_Selector in our program above as:

PROCEDURE TE_Selector(where:Point;extend:Boolean);

 BEGIN
  SetPort(theWindow);      {Ensure port is text window}
  GlobaltoLocal(where);    {Make mouse local to window}
  TEClick(where,extend,DisplayTE);
  Reset_EditMenu(CantUndo);
 END; {TE_Selector}

and we add Reset_EditMenu, placing it before Cut.

PROCEDURE Reset_EditMenu(UndoState:EditType);
 
 VAR theStr     : Str255;
     theItem    : integer;

 BEGIN
  IF TEGetScrapLen>0 THEN    {Set Paste according to scrap}
   Enable(EditHandle,PasteItem)
  ELSE
   Disable(EditHandle,PasteItem);
  WITH DisplayTE^^ DO
   IF SelStart<SelEnd THEN   {Set Cut,Copy,Clear according}
    BEGIN                    {to selection size     }
     Enable(EditHandle,CutItem);
     Enable(EditHandle,CopyItem);
     Enable(EditHandle,ClearItem);
    END
   ELSE
    BEGIN
     Disable(EditHandle,CutItem);
     Disable(EditHandle,CopyItem);
     Disable(EditHandle,ClearItem);
    END;
  EditStatus:=UndoState;
  IF EditStatus=CantUndo THEN
   theStr:=CantUndoStr
  ELSE IF EditStatus IN [UndoTyping,RedoTyping] THEN
   theStr:=TypingStr
  ELSE
   BEGIN
    CASE EditStatus OF     {Get item number to Undo/Redo}
     UndoCut,RedoCut:
      theItem:=CutItem;
     UndoCopy,RedoCopy:
      theItem:=CopyItem;
     UndoPaste,RedoPaste:
      theItem:=PasteItem;
     UndoClear,RedoClear:
      theItem:=ClearItem;
     OTHERWISE
    END; {CASE EditStatus}
    GetItem(EditHandle,theItem,theStr;
   END; {IF EditStatus}
  IF EditStatus IN [UndoTyping..UndoClear] THEN
   theStr:=Concat(UndoStr,' ',theStr)
  ELSE IF EditStatus IN [RedoTyping..RedoClear] THEN
   theStr:=Concat(RedoStr,' ',theStr);
  SetItem(EditHandle,UndoItem,theStr);   {Reset Undo item}
  IF EditStatus=CantUndo THEN
   Disable(EditHandle,UndoItem)      {Disable Can't Undo or}
  ELSE
   Enable(EditHandle,UndoItem);      {Enable Undo/Redo  }
 END; {Reset_EditMenu}

Have you often thought that "These writers dash off programs so easily, how do they do it?" Well, in many cases they don't. They just don't bother telling you all their struggles to find the typo or the minus sign that should have been a plus sign. In this particular case, I spent an hour trying to figure out why no caret appeared and why clicking on the mouse highlighted a new area, but did not unhighlight the old area.

I read and reread about TEClick in both Inside Macintosh and Macintosh Revealed. I could not understand what I was doing wrong. Then I remembered a similar problem from long ago; to make the TextEdit procedure I was using work, I had to call TEActivate. For this program, I could have called TEActivate right after the call to TENew and that would have been sufficient, but I went back and added a new event test in MainEventLoop. So what you see now as the first try at the program was really the n-th try. Most programs don't have this problem because, whenever a window is activated, the program also activates any associated TextEdit record.

After I fixed the program, I saw the note on the middle of page I-383 of Inside Macintosh. [This is a common frustration; you spend hours finally fixing the problem, only to discover it later in Inside Macintosh, AFTER you know what to look for! -Ed]

Other problems that I encountered while writing this program are summarized at the end of this article under "What Can Go Wrong".

Continuing, we now write write the procedures Cut, Copy, Paste, and Clear. These are:

Cut

Save selection points,

If selection greater than an insertion point

• Paste Clipboard to ScrapTE,

• Cut current selection to Clipboard,

• Set Undo item to Undo Cut,

• Enable Undo and Paste items, and

• Disable Cut item.

Copy

Save selection points,

If selection greater than an insertion point

• Paste Clipboard to ScrapTE,

• Copy current selection to Clipboard,

• Set Undo item to Undo Copy, and

• Enable Undo item.

Paste

• Save selection points,

• Delete ScrapTE text,

• Copy current selection to ScrapTE,

• Paste Clipboard to current selection,

• Set Undo item to Undo Paste, and

• Enable Undo item.

Clear

Save selection points,

If selection greater than an insertion point

• Delete ScrapTE text,

• Copy current selection to ScrapTE,

• Delete current selection,

• Set Undo item to Undo Copy, and

• Enable Undo item.

Writing these in Pascal, we add before Cut:

PROCEDURE Save_EndPoints;  {Save selection points}

 BEGIN
  WITH DisplayTE^^ DO
   BEGIN
    UndoStart:=SelStart;
    UndoEnd:=SelEnd;
    CurrentStart:=UndoStart;
   END;
 END {Save_Selection}

PROCEDURE Save_Clipboard;

 BEGIN
  TESetSelect(0,ScrapTE^^.TELength,ScrapTE);
  TEPaste(ScrapTE);
 END; {Save_Clipboard}

PROCEDURE Delete_ScrapTE;

 BEGIN
  TESetSelect(0,ScrapTE^^.TELength,ScrapTE);
  TEDelete(ScrapTE);
 END; {Delete_ScrapTE}

PROCEDURE Save_Selection(theStart,theEnd);

 BEGIN
  IF theStart<theEnd THEN
   BEGIN
    HLock(Handle(DisplayTE));
    WITH DisplayTE^^ DO
     BEGIN
      HLock(hText);
     TEInsert(Ptr(Ord4(hText^)+theStart,                 theEnd-theStart,ScrapTE);
      HUnlock(hText);
     END;
    HUnlock(Handle(DisplayTE));
   END;
 END; {Save_Selection}

and replace Cut, Copy, Paste, and Clear with:

PROCEDURE Cut;

 BEGIN
  Save_EndPoints;
  Save_Clipboard;        {Save old clipboard}
  TECut(DisplayTE);      {Cut selection to clipboard}
  Reset_EditMenu(UndoCut);
 END; {Cut}

PROCEDURE Copy;

 BEGIN
  Save_EndPoints;
  Save_Clipboard;        {Save old clipboard}
  TECopy(DisplayTE);     {Copy selection to clipboard}
  Reset_EditMenu(UndoCopy);
 END; {Copy}

PROCEDURE Paste;

 BEGIN
  Save_EndPoints;
  Delete_ScrapTE;
  Save_Selection(UndoStart,UndoEnd);
  TEPaste(DisplayTE);     {Paste selection from clipboard}
  Reset_EditMenu(UndoPaste);
 END; {Paste}

PROCEDURE Clear;

 BEGIN
  Save_EndPoints;
  Delete_ScrapTE;
  Save_Selection(UndoStart,UndoEnd);
  TEDelete(DisplayTE);            {Delete current selection}
  Reset_EditMenu(UndoClear);
 END; {Clear}

Undo Operations

Now we have most of the tools in place to undo cut, copy, paste, or clear. With Undo we can now restore both the text and the clipboard as they were before the user requested the operation to be undone. For the undo operations except Undo Typing, we need to:

Undo Cut:

• Paste clipboard to insertion point,

• Reset selection,

• Copy ScrapTE to clipboard,

• Set Undo item to Redo Cut, and

• Enable all edit items.

Undo Copy:

• Cut ScrapTE to clipboard,

• Set Undo item to Redo Copy, and

• Enable all edit items.

Undo Paste:

• Reset selection to pasted text,

• Delete selection,

• Copy ScrapTE to selection

• Reset selection to previous text,

• Set Undo item to Redo Paste, and

• If selection greater than insertion point

Enable all edit items

Else

Enable Undo and Paste items.

Undo Clear:

• Copy ScrapTE to selection

• Reset selection,

• Set Undo item to Redo Clear, and

• Enable all edit items.

For common subroutines for undo operations, we add to the group of Save Procedures:

PROCEDURE Restore_Clipboard;

 BEGIN
  TESetSelect(0,ScrapTE^^.TELength,ScrapTE);
  TECut(ScrapTE);              {Also clears ScrapTE}
 END; {Restore_Clipboard}
 
PROCEDURE Restore_Selection(theLength:integer);

 BEGIN
  IF theLength>0 THEN
   BEGIN
    HLock(Handle(ScrapTE));
    WITH ScrapTE^^ DO
     BEGIN
      HLock(hText);            {ScrapTE to insertion point}
      TEInsert(Ptr(Ord4(hText^)),theLength,DisplayTE);
      HUnlock(hText);
     END;
    HUnlock(Handle(ScrapTE));
 END; {Restore_Selection}

and replace Undo with all of the following:

PROCEDURE Undo_Cut;
 
 BEGIN
  TEPaste(DisplayTE);                        {Restore text}
  TESetSelect(UndoStart,UndoEnd,DisplayTE);  {Reset selection}
  Restore_Clipboard;
  Reset_EditMenu(RedoCut);
 END; {Undo_Cut}
 
PROCEDURE Undo_Copy;
 
 BEGIN
  Restore_Clipboard;
  Reset_EditMenu(RedoCopy);
 END; {Undo_Copy}
 
PROCEDURE Undo_Paste;
 
 BEGIN
  TESetSelect(UndoStart,DisplayTE^^.SelEnd,DisplayTE);
  {Delete pasted text}
  {UndoStart is also beginning of pasted text}
  TEDelete(DisplayTE);
  Restore_Selection(ScrapTE^^.TELength);
  TESetSelect(UndoStart,UndoEnd,DisplayTE);  {Reset selection}
  Delete_ScrapTE;
  Reset_EditMenu(RedoPaste);
 END; {Undo_Paste}
 
PROCEDURE Undo_Clear;
 
 BEGIN
  Restore_Selection(ScrapTE^^.TELength);
  TESetSelect(UndoStart,UndoEnd,DisplayTE);  {Reset selection}
  Delete_ScrapTE;
  Reset_EditMenu(RedoClear);
 END; {Undo_Clear}
 
PROCEDURE Undo_Typing;
 
 BEGIN
 END; {Undo_Typing}
 
PROCEDURE Redo_Typing;
 
 BEGIN
 END; {Redo_Typing}
 
PROCEDURE Undo;

 BEGIN
  CASE EditStatus OF
   UndoCut:
    Undo_Cut;
   UndoCopy:
    Undo_Copy;
   UndoPaste:
    Undo_Paste;
   UndoClear:
    Undo_Clear;
   UndoTyping:
    Undo_Typing;
   RedoCut:
    Cut;
   RedoCopy:
    Copy;
   RedoPaste:
    Paste;
   RedoClear:
    Clear;
   RedoTyping:
    Redo_Typing;
   OTHERWISE
  END; {CASE EditStatus}
 END; {Undo}

Typing

Finally, we get to the most difficult, handling typing so that it is undoable. One would think that it is no more difficult than undoing any of the other editing operations. However, the backspace key causes a problem. If the user backs over newly entered text, we have no problem. But when the user backs over previous text we must save the newly deleted character and the new beginning point.

See the example at the beginning of the article for an example of backspacing over the previous text.

For typing, we need to:

• Check if user entered a meaningful character;

• If EditStatus is not UndoTyping, then

Save selection points;

Delete ScrapTE text;

Copy selection to ScrapTE;

• If user entered backspace, then

If not beginning of text and

If all newly typed characters deleted, then

Copy character preceding insertion point to beginning of ScrapTE;

Decrement "current insertion point";

• Insert character entered by user in text;

• If EditStatus is not UndoTyping, then

Set Undo item to Undo Typing;

Enable Undo item.

Note that we cannot set Undo Typing under the first test of EditStatus because Reset_EditMenu enables or disables the other item according to the size of the selection. If the selection is more than the insertion point, the first character inserted with TEKey into the text will delete the selection.

Thus, we rewrite Typist as:

PROCEDURE Typist;
 
 CONST Return    = $0D;
       Enter     = $03;
       Backspace = $08;
       Tab       = $09;
  
  TYPE Codes = 0..255;

  VAR KeyCode      : integer;
      CharIn       : Char;
      CharH        : CharsHandle;
      AllowedCodes : SET OF Codes;

 BEGIN
  KeyCode:=BitAnd(EventMessage,charCodeMask);
  AllowedCodes:=[$20..$7F,Return,Enter,Backspace,Tab];
  {May be erroneous if used directly in TML Pascal 1.11}
  {See letter from Christopher Dunn in July 1986 MacTutor}
  IF KeyCode IN AllowedCodes THEN
   CharIn:=chr(KeyCode)
  ELSE
   KeyCode:=0;  {Use KeyCode=0} as test to bypass sections}
  IF EditStatus<>UndoTyping THEN
   IF KeyCode<>0 THEN
    BEGIN
     Save_EndPoints;
     Delete_ScrapTE;
  Save_Selection(UndoStart,UndoEnd);
    END; {IF EditStatus<>UndoTyping,IF KeyCode<>0}
  IF KeyCode=Backspace THEN
   WITH DisplayTE^^ DO
    IF SelStart>0 THEN
     IF SelEnd<=CurrentStart THEN
      BEGIN
       CharH:=TEGetText(DisplayTE);
    {Get the text as a character array}
       CurrentStart:=CurrentStart-1;
       TESetSelect(0,0,ScrapTE);
       TEKey(CharH^^[SelStart-1],ScrapTE);
      END;
    IF KeyCode<>0 THEN
     BEGIN
     TEKey(CharIn,DisplayTE);
  IF EditStatus<>UndoTyping THEN
   Reset_EditMenu(UndoTyping);
     END;
 END; {Typist}

We now have the pieces in place to Undo or Redo any typing by the user. For Undo Typing we neeed to:

• Move new typing to end of ScrapTE,

• Delete new typing from DisplayTE,

• Move previous selection to DisplayTE,

• Set selection points to previous selection,

• Delete previous selection from ScrapTE, and

• Set Undo item to Undo Typing.

For Redo Typing we need to:

• Move previous selection to end of ScrapTE,

• Delete previous selection from DisplayTE,

• Move new typing to DisplayTE,

• Delete new typing from ScrapTE, and

• Set Undo item to Redo Typing.

Hmm! Undo Typing and Redo Typing look very similar! They are, and in fact, we could merge them into one procedure. For clarity, we won't but will leave that as an exercise for . . .

Our final piece of code is to expand these by replacing Undo_Typing and Redo_Typing. For Undo_Typing we have:

PROCEDURE Undo_Typing;

 VAR scrapLength : integer;
  TypingEnd   : integer;
  theText     : Handle;

 BEGIN
  scrapLength:=ScrapTE^^.TELength;{Put new type at scrap end}
  TESetSelect(scrapLength,scrapLength,ScrapTE);
  TypingEnd:=DisplayTE^^.selEnd;
  IF CurrentStart<TypingEnd THEN
   BEGIN
    Save_Selection(CurrentStart,TypingEnd);
    TESetSelect(CurrentStart,TypingEnd,DisplayTE);
    TEDelete(DisplayTE);       {Delete new typing}
   END; {IF CurrentStart<TypingEnd}
  Restore_Selection(scrapLength); {Put orig selection back}
  TESetSelect(UndoStart,UndoEnd,DisplayTE);
  TESetSelect(0,scrapLength,ScrapTE); {Delete prev from scrap}
  TEDelete(ScrapTE);
  Reset_EditMenu(RedoTyping);
 END; {Undo_Typing}

For Redo_Typing we have:

PROCEDURE Redo_Typing;

 VAR scrapLength : integer;
  TypingEnd   : integer;
  theText     : Handle;

 BEGIN
  scrapLength:=ScrapTE^^.TELength; {Put old select at end of}  
  TESetSelect(scrapLength,scrapLength,ScrapTE);  {ScrapTE}
  TypingEnd:= DisplayTE^^.selEnd;
  IF CurrentStart<TypingEnd THEN
   BEGIN
    Save_Selection(CurrentStart,TypingEnd);
    TESetSelect(CurrentStart,TypingEnd,DisplayTE);
    TEDelete(DisplayTE);       {Delete old selection}
   END; {IF CurrentStart<TypingEnd}
  Restore_Selection(scrapLength); {Move new typing to          
                           DisplayTE}
  TESetSelect(0,scrapLength,ScrapTE);
  TEDelete(ScrapTE);     {Delete new typing from ScrapTE}
  Reset_EditMenu(RedoTyping);
 END; {Redo_Typing}

That's it! Now you have an editor for very small files that allows the user to Undo each editing operation immediately after requesting the operation. But this is only the beginning of your work for an editor. Now you have to add:

• Scrolling,

• Window resizing,

• Multiple windows,

• Search and replace commands,

• Additional error checking, and

• Much more.

[Note: Some of this capability was published in the first article in this series on Text Edit in the January 1987 issue of MacTutor. -Ed]

What Can Go Wrong

This article is a bit deceptive. Because, I wrote it as a step-by-step approach, programming this small editor seems easy. However, I should admit that what you see is the third attempt. My first editor was the text editing support in DevHELPER®. My second editor was the first draft of this article, and I did it pretty much in the order given. My third editor is the program of this article with all the bugs out (or most obvious bugs), with little reorganizations to improve readability, and with common code put into separate procedures.

When you write your editor, you may make some of the same mistakes that I did. To save you some of the grief of figuring out what went wrong, here are some mistakes that I recorded in my notes.

• Immediate termination of program

Did not call Init_MyGlobals, thus did not set QuitFlag.

• System Error 01,02

Used theWindow in MainEventLoop as local variable, but did not declare it so.

• Watch cursor shown before first menu selection

Did not call InitCursor before or at beginning of MainEventLoop.

• Selection is "checkerboard" of highlighting

Did not call GlobaltoLocal for mousepoint.

• No blinking caret

Did not call TEActivate after TENew.

• Hang on Cut

viewRect and destRect for ScrapTE were "illegal" rectangles, that is, top>bottom or right>left.

• Undo Paste using wrong text:

ScrapTE not cleared by earlier operation

• Undo Paste not undoing:

Scrap TE not cleared by earlier operation.

• Slow typing

Slow typoing can happen on a MacXL or a Mac with 128K. TEKey on these systems is too slow if it has to move several thousand characters which would happen at the beginning of large documents. TEKey on a Mac+ was not a problem on the same document in the same place. If you plan to write your editor for earlier machines, you may need to work with only a portion of the text. Now that we've begun to understand Text Edit, we get to start all over again, with the new text edit on the SE and Macintosh II! Look for more articles in this series in the coming months.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »

Price Scanner via MacPrices.net

Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
Nurse Anesthetist - *Apple* Hill Surgery Ce...
Nurse Anesthetist - Apple Hill Surgery Center Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Apr 20, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.