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.

 
AAPL
$116.47
Apple Inc.
+0.16
MSFT
$47.98
Microsoft Corpora
-0.72
GOOG
$537.50
Google Inc.
+2.67

MacTech Search:
Community Search:

Software Updates via MacUpdate

Cobook 3.0.7 - Intelligent address book....
Cobook Contacts is an intuitive, engaging address book. Solve the problem of contact management with Cobook Contacts and its simple interface and powerful syncing and integration possibilities.... Read more
StatsBar 1.9 - Monitor system processes...
StatsBar gives you a comprehensive and detailed analysis of the following areas of your Mac: CPU usage Memory usage Disk usage Network and bandwidth usage Battery power and health (MacBooks only)... Read more
Cyberduck 4.6 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Evernote 6.0.1 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
calibre 2.11 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital... Read more
Herald 5.0.1 - Notification plugin for M...
Note: Versions 2.1.3 (for OS X 10.7), 3.0.6 (for OS X 10.8), and 4.0.8 (for OS X 10.9) are no longer supported by the developer. Herald is a notification plugin for Mail.app, Apple's Mac OS X email... Read more
Firetask 3.7 - Innovative task managemen...
Firetask uniquely combines the advantages of classical priority-and-due-date-based task management with GTD. Stay focused and on top of your commitments - Firetask's "Today" view shows all relevant... Read more
TechTool Pro 7.0.6 - Hard drive and syst...
TechTool Pro is now 7, and this is the most advanced version of the acclaimed Macintosh troubleshooting utility created in its 20-year history. Micromat has redeveloped TechTool Pro 7 to be fully 64... Read more
PhotoDesk 3.0.1 - Instagram client for p...
PhotoDesk lets you view, like, comment, and download Instagram pictures/videos! (NO Uploads! / Image Posting! Instagram forbids that! AND you *need* an *existing* Instagram account). But you can do... Read more

Latest Forum Discussions

See All

Ubisoft Gives Everyone Two New Ways to E...
Ubisoft Gives Everyone Two New Ways to Earn In-Game Stuff for Far Cry 4 Posted by Jessica Fisher on November 21st, 2014 [ permalink ] | Read more »
Golfinity – Tips, Tricks, Strategies, an...
Dig this: Would you like to know what we thought of being an infinite golfer? Check out our Golfinity review! Golfinity offers unlimited ways to test your skills at golf. Here are a few ways to make sure your score doesn’t get too high and your... | Read more »
Dark Hearts, The Sequel to Haunting Meli...
Dark Hearts, The Sequel to Haunting Melissa, is Available Now Posted by Jessica Fisher on November 21st, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Meowza! Toyze Brings Talking Tom to Life...
Meowza! | Read more »
Square Enix Announces New Tactical RPG f...
Square Enix Announces New Tactical RPG for Mobile, Heavenstrike Rivals. Posted by Jessica Fisher on November 21st, 2014 [ permalink ] With their epic stories and gorgeous graphics, | Read more »
Quest for Revenge (Games)
Quest for Revenge 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: The great Kingdom of the west has fallen. The gods ignore the prayers of the desperate. A dark warlord has extinguished... | Read more »
Threadz is a New Writing Adventure for Y...
Threadz is a New Writing Adventure for You and Your Friends Posted by Jessica Fisher on November 21st, 2014 [ permalink ] In the tradition of round-robin storytelling, | Read more »
SteelSeries Stratus XL Hardware Review
Made by: SteelSeries Price: $59.99 Hardware/iOS Integration Rating: 4 out of 5 stars Usability Rating: 4.5 out of 5 stars Reuse Value Rating: 4.25 out of 5 stars Build Quality Rating: 4.5 out of 5 stars Overall Rating: 4.31 out of 5 stars | Read more »
ACDSee (Photography)
ACDSee 1.0.0 Device: iOS iPhone Category: Photography Price: $1.99, Version: 1.0.0 (iTunes) Description: Capture, perfect, and share your photos with ACDSee. The ACDSee iPhone app combines an innovative camera, a powerful photo... | Read more »
ProTube for YouTube (Entertainment)
ProTube for YouTube 2.0.2 Device: iOS Universal Category: Entertainment Price: $1.99, Version: 2.0.2 (iTunes) Description: ProTube is the ultimate, fully featured YouTube app. With it's highly polished design, ProTube offers ad-free... | Read more »

Price Scanner via MacPrices.net

Save up to $400 with Apple refurbished 2014 1...
The Apple Store has restocked Apple Certified Refurbished 2014 15″ Retina MacBook Pros for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and shipping... Read more
New 13-inch 1.4GHz MacBook Air on sale for $8...
 Adorama has the 2014 13″ 1.4GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY & NJ tax only. Their price is $100 off MSRP. B&H Photo has the 13″ 1.4GHz/128GB MacBook... Read more
Apple Expected to Reverse Nine-Month Tablet S...
Apple and Samsung combined accounted for 62 percent of the nearly 36 million branded tablets shipped in 3Q 2014, according to early vendor shipment share estimates from market intelligence firm ABI... Read more
Stratos: 30 Percent of US Smartphone Owners t...
Stratos, Inc., creator of the Bluetooth Connected Card Platform, has announced results from its 2014 Holiday Mobile Payments Survey. The consumer survey found that nearly one out of three (30 percent... Read more
2014 1.4GHz Mac mini on sale for $449, save $...
 B&H Photo has lowered their price on the new 1.4GHz Mac mini to $449.99 including free shipping plus NY tax only. Their price is $50 off MSRP, and it’s the lowest price available for this new... Read more
Check Apple prices on any device with the iTr...
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
64GB iPod touch on sale for $249, save $50
Best Buy has the 64GB iPod touch on sale for $249 on their online store for a limited time. Their price is $50 off MSRP. Choose free shipping or free local store pickup (if available). Sale price for... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale for $1799.99 for a limited time. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of... Read more
New Logitech AnyAngle Case/Stand Brings Flexi...
Logitec has announced the newest addition to its suite of tablet products — the Logitech AnyAngle. A protective case with an any-angle stand for iPad Air 2 and all iPad mini models, AnyAngle is the... Read more
Notebook PC Shipments Rise Year-Over-Year as...
According to preliminary results from the upcoming DisplaySearch Quarterly Mobile PC Shipment and Forecast Report, the global notebook PC market grew 10 percent year-over-year in Q3’14 to 49.4... Read more

Jobs Board

*Apple* Solutions Consultant (ASC)- Retail S...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Store Leader Program - College Gradu...
Job Description: Job Summary As an Apple Store Leader Program agent, you can continue your education as you major in the art of leadership at the Apple Store. You'll Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.