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

Remotix 3.1.4 - Access all your computer...
Remotix is a fast and powerful application to easily access multiple Macs (and PCs) from your own Mac. Features Complete Apple Screen Sharing support - including Mac OS X login, clipboard... Read more
DesktopLyrics 2.6.6 - Displays current i...
DesktopLyrics is an application that displays the lyrics of the song currently playing in "iTunes" right on your desktop. The lyrics for the song have to be set in iTunes; DesktopLyrics does nothing... Read more
VOX 2.5.1 - Music player that supports m...
VOX is a beautiful music player that supports many filetypes. The beauty is in its simplicity, yet behind the minimal exterior lies a powerful music player with a ton of features and support for all... Read more
NetNewsWire 4.0.0 - RSS and Atom news re...
NetNewsWire is the best way to keep up with the sites and authors you read most regularly. Let NetNewsWire pull down the latest articles, and read them in a distraction-free and Mac-like way. Native... Read more
MacUpdate Desktop 6.0.6 - Search and ins...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more
ForkLift 2.6.5 - Powerful file manager:...
ForkLift is a powerful file manager and ferociously fast FTP client clothed in a clean and versatile UI that offers the combination of absolute simplicity and raw power expected from a well-executed... Read more
Drive Genius 4.1.0 - Powerful system uti...
Drive Genius 4 gives you faster performance from your Mac while also protecting it. The award-winning and improved DrivePulse feature alerts you to hard drive issues before they become major problems... Read more
OnyX 2.9.7 - Maintenance and optimizatio...
OnyX is a multifunctional utility for OS X. It allows you to verify the startup disk and the structure of its System files, to run miscellaneous tasks of system maintenance, to configure the hidden... Read more
DEVONthink Pro 2.8.5 - Knowledge base, i...
DEVONthink Pro is your essential assistant for today's world, where almost everything is digital. From shopping receipts to important research papers, your life often fills your hard drive in the... Read more
Backblaze 4.0.1.878 - 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

Carbo - Handwriting in the Digital Age...
Carbo - Handwriting in the Digital Age 1.0 Device: iOS Universal Category: Productivity Price: $3.99, Version: 1.0 (iTunes) Description: | Read more »
The Apple Watch isn't Great as a Fi...
| Read more »
Show the World What You See With Stre.am...
Live broadcasting is getting popular on mobile devices, which is why you can now get Stre.am, by Infinite Takes. [Read more] | Read more »
PhotoTime's 2.1 Update Adds Apple W...
The latest PhotoTime update is adding even more functionality to the handy photo organizing app. Yep, including Apple Watch support. [Read more] | Read more »
Oh My Glob! Adventure Time Puzzle Quest...
Finn and Jake are taking over D3 Go!'s popular puzzle game series in the upcoming Adventure Time Puzzle Quest. [Read more] | Read more »
Earthcore: Shattered Elements - Tips, Tr...
At first glance, Earthcore: Shattered Elements seems like a rather simple card-battling game. Once you’re introduced to skills that will change quite a bit. Even more so once you start to acquire hero cards. But it’s not so complicated that we... | Read more »
Dungeon999F (Games)
Dungeon999F 1.33 Device: iOS Universal Category: Games Price: $.99, Version: 1.33 (iTunes) Description: "The game you must play at least once in your life!" "The game with potential of million downloads globally!" ...is what the... | Read more »
Mixels Rush - Use Mixes, Maxes and Murps...
Mixels Rush - Use Mixes, Maxes and Murps to Outrun the Nixels 1.0.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.0 (iTunes) Description: Use awesome new Mixels and make crazy combinations to beat the annoying... | Read more »
Battles of the Ancient World II (Games)
Battles of the Ancient World II 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: | Read more »
Sword Of Xolan (Games)
Sword Of Xolan 1.0.4 Device: iOS Universal Category: Games Price: $.99, Version: 1.0.4 (iTunes) Description: Sword of Xolan is an action platformer game that includes the juice of pixel art style. Xolan is a young and brave man who... | Read more »

Price Scanner via MacPrices.net

Sale! 16GB iPad mini 3 for $349, save $50
B&H Photo has the 16GB iPad mini 3 WiFi on sale for $349 including free shipping plus NY sales tax only. Their price is $50 off MSRP, and it’s the lowest price available for this model. Read more
Price drop on 2014 15-inch Retina MacBook Pro...
B&H Photo has dropped prices on 2014 15″ Retina MacBook Pros by $200. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1799.99 save $200 - 15″ 2.5GHz... Read more
Will iOS 9 Finally Bring Productivity Friendl...
Ah, the irony. From its original announcement in 2010, Apple has doggedly insisted that the iPad remain “simple,” thus arbitrarily limiting its considerable potential as a content creation and... 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
Mac Pros on sale for up to $260 off MSRP
B&H Photo has Mac Pros on sale for up to $260 off MSRP. Shipping is free, and B&H charges sales tax in NY only: - 3.7GHz 4-core Mac Pro: $2799, $200 off MSRP - 3.5GHz 6-core Mac Pro: $3719.99... Read more
Save up to $600 with Apple refurbished Mac Pr...
The Apple Store has Apple Certified Refurbished Mac Pros available 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
Apple drops price on refurbished 15-inch 2.2G...
The Apple Store has dropped their price on the Apple Certified Refurbished 2014 15″ 2.2GHz Retina MacBook Pro to $1609, $390 off original MSRP. Apple’s one-year warranty is included, and shipping is... Read more
Apple restocks refurbished Mac minis for up t...
The Apple Store has restocked Apple Certified Refurbished 2014 Mac minis, with models available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: - 1.4GHz... Read more
Cover For iPhone Helps You Create Beautiful P...
Taking photos, editing and sharing them is one of the things most of people do on their iPhones for fun, especially if they’re users of social media. Unfortunately, many iOS photo-editing solutions... Read more
Password Keyboard 1.0 For iOS Handles Logins...
Pfaeffikon, Switzerland based Power APP has introduced Password Keyboard 1.0.0, their new password utility developed for iPhone, iPad and iPod touch devices. Password Keyboard is designed to simplify... Read more

Jobs Board

Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
Visual Merchandise Manager %u2013 Accessories...
…to be part of an incredible team. Imagine what you could do here. At Apple , great ideas have a way of becoming reality very quickly. Our Accessories assortment makes Read more
*Apple* Solutions Consultant - Retail Sales...
**Job Summary** As an Apple Solutions Consultant (ASC) you are the link between our customers and our products. Your role is to drive the Apple business in a retail Read more
*Apple* Solutions Consultant - Retail Sales...
**Job Summary** The ASC is an Apple employee who serves as the Apple business manager and influencer in a hyper-business critical Reseller's store which delivers Read more
Technical Project Manager - *Apple* Pay - A...
**Job Summary** Apple Pay is seeking an experienced technical PM…manage the rollout of features to merchants for the Apple Pay platform in the US Within this role Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.