TweetFollow Us on Twitter

TextEdit in Forth
Volume Number:1
Issue Number:7
Column Tag:Forth Forum


By Jörg Langowski

Through the set of routines called TextEdit, the toolbox provides the basic functions necessary for editing and formatting text: cutting, pasting, copying, inserting, deleting and scrolling within windows.

You are already familiar with all of the functions supported by TextEdit, since almost every application makes use of them, and selecting text with the mouse is one of the basic principles of the Macintosh user interface.

In this column we shall set up a simple TextEdit (TE) record in a window under MacForth and learn about some principles of TE.

TE basically forms an interface between an ASCII text and a GrafPort, the drawing environment of QuickDraw. Given the port in which to display the text and some other parameters, which I’ll soon explain, it will automatically draw the visible part of the text on the screen. TE then also responds to mouse action like clicking and dragging by moving the ‘insertion point’ (the blinking vertical line) and by highlighting the selected text correspondingly.

The GrafPort that we are drawing in generally is part of a window. Fig.1 reviews the structure of a window record as it is given in the Window Manager part of IM. As you can see, the GrafPort comprises the first and largest part of the window record. Most of the parameters important for drawing text and pictures are given there; however, a reference to an ASCII text record cannot be seen anywhere. This is correct; the standard convention is rather that the TE record contains a pointer to the GrafPort in which the text is to appear.

Fig. 2 shows the complete arrangement of a TE record.The text to be edited is referred to by the handle hText.TE displays this text in the destination rectangle; the drawing is clipped to the view rectangle. Both rectangles are specified in the TE record and given in the coordinates of the grafPort. The text is displayed in word wrap mode, so that words are not split when new lines are started. The start positions of new lines are kept in the array lineStarts and are automatically adjusted when the text is redrawn in a different destination rectangle.

The standard way to use a TE record is first to obtain a handle to a new record from the system. The toolbox trap that does this is TENew, which needs the destination and view rectangles on the stack (two 8-byte items) and returns a handle to a TE record within the current grafPort. MacForth calls this trap through the built-in compiling word TEXT.FIELD, which creates a dictionary entry that contains the TE handle as well as the current window that this particular TE record resides in. TEXT.FIELD is defined as follows:

: text.field  ( destRect\viewRect\windowPtr -- )
       create  get.window >r  window 
                   tenew  ,   get.window  ,   r>  window  ;

Now take a look at the sample program (Listing 1). Here we define a window at the very beginning with the additional attribute TEXT.RECORD, which sets a flag indicating that there is a TE record in this window. The actual setup of the TE record happens close to the end of the program text, where we get the address of the content area rectangle (+WCBOUNDS) and use it both as destination and view rectangle (since we want to see everything we are typing into the window).

The new variable TEST.TEXT can now be used to store the TE record handle in the refCon field of the window record; this field is kept free for use by the application, and MacForth expects the current TE handle here.

TextEdit Procedures

The important toolbox procedures that process TE records are TEClick, TEKey, TECut, TECopy, TEPaste, and some others (which are also described in IM).

Calling these procedures is somewhat simpler under MacForth than described in IM. The toolbox traps normally expect a TE handle on top of the stack. MacForth assumes that you want to edit text in the currently active window and therefore gets the TE handle that was stored in the refCon field. TE requests under MacForth are handled through the F line trap dispatcher (see V1,No.3; Fig.1 on p.24). The TE trap handler jumps to a self-modifying piece of code (similar to the OS trap handler) that gets the TE handle first and puts it on top of the stack, then executes the trap. Fig. 3 shows this piece of code.

MOVE.L  (SP),A1  ;trap word -> A1
MOVE.L  (A5),A0  ;QD globals ptr -> A0
MOVE.L  (A0),A0  ;active port ptr -> A0
MOVE.L  $98(A0),(SP) ;put TE handle-> stk  
MOVE  (A1),$32FE(A4) ;put trap word
AXXX  <--------------   ;right here !
JMP(A4) ;and jump to NEXT

Fig.3: Trap Handler for TE Routines

The activate routine of the example window first calls TEACTIVATE, which highlights the selection range in the TE record or displays the caret (vertical line) at the text insertion point. Then the routine drops into the usual event loop. Three kinds of events are handled explicitly: mouse down, window resizing and keyboard events. Furthermore, the event loop periodically calls the routine TEIDLE, which blinks the caret. If a key down event is recognized, TEKEY is called, which inserts the character on top of the stack into the TE record at the insertion point. A mouse down event inside the editing window calls the Forth word TEXT.CLICK, which is an interface to the TEClick trap and automatically handles selecting and highlighting a piece of text.

Resizing The Window - TEUpdate

When the window is resized, we want to change the appearance of the edited text so that all of it is still visible. Therefore, we have to reset the view and destination rectangles in the TE record, using the resized window’s new content area. RECALC in our example does this; it first moves the rectangle data from the window to the TE record and then calls TECALTEXT, which recalculates the line beginnings. The whole content area of the new window is then erased and marked invalid (requiring an update) so that TEXT.UPDATE, when called, will redraw the text correctly. (You may try and see what happens if you don’t erase the window before updating or if you do not set the content area invalid).

Scrolling Text Inside The Window

Just with the routines described so far, any text that is bigger than what the window can hold will disappear beyond the bottom of the window. Of course, we want to be able to scroll within our text so that we can see it all. I have added a vertical scroll bar to our window, and the event loop contains the necessary procedures to handle scrolling. The range of the scroll bar is fixed to 0 1000, corresponding to a display range of 1000 pixels. If you ever want to make a full-fledged editor out of this example, you will probably want to adjust the control range to reflect the actual size of the text. Up and down buttons scroll by 10 pixels, page areas by 100 pixels each. The scrolling is done by TESCROLL, which scrolls the text horizontally and vertically by a relative amount, and the application itself has to keep track of the absolute position within the text. After resizing, the text starts at the beginning again, and the scroll bar is reset to zero.

Cutting, Copying, Pasting

The menu TE.MENU handles cut/paste within our text record. It does not cut/paste correctly to and from other applications, since I did not add anything to handle the scrap. The MacForth handbook gives a short description of the scrap handling words, and I’ll explain the scrap in a later column. Nevertheless, cutting and pasting within the example window can be done in a very simple way by calls to the TE routines TECUT, TECOPY, and TEPASTE, which do exactly what you expect from their names.

You see that the example program really forms a ‘mini-editor’; if you add a routine to save/read a disk file, you have a complete small editor program.

Vectored Execution: The DOER/MAKE Pair

Those of you who read the excellent book Thinking FORTH by Leo Brodie, might have noticed the DOER/MAKE routines for vectored execution near the end of the book. They might also have noticed that none of them work under MacForth (I know of at least one reader who has).

DOER is a defining word that creates a dictionary entry with a vector address in its parameter field. When a word defined by DOER is executed, it will place this address on the return stack, then call EXIT and thus jump to the routine that the vector points to.

The word that changes the vector of a DOER word is called MAKE. Suppose you define:

   DOER TEST                 and
 : CHANGE  MAKE TEST .” Hi!” ;

then TEST will do nothing after the first definition, and will printout “Hi!” after CHANGE was executed. DOER/MAKE can therefore be used to dynamically change the execution behavior of FORTH code (something like a jump table in other languages).

The reason why Brodie’s examples do not work with MacForth is that MacForth does not store addresses of Forth routines in the threaded code, but tokens, which are addresses offset from a base pointer (register A4).

Therefore the only thing one has to do to make DOER/MAKE work correctly, is to insert a TOKEN>ADDR into the definition of (MAKE) given by Brodie, so that the address and not the token of the DOER word appears on the stack. Listing 2 gives the complete set of routines, modified so that they work on the Mac.

Remarks on MacModula-2

Shortly after I had sent off my first review of Modula-2 across the ocean, I received the new official release of the MacModula-2 system by Modula Corp. Enough has been changed (and improved) that another short comment is appropriate.

The first big surprise to me was the handbook. This manual is a master example in understatement; on every other page you can read that a detailed explanation of the toolbox is ‘beyond the scope of a 90 dollar product’, only to find out that almost everything is explained rather concisely a couple of pages later. The existing interfaces to the toolbox routines are collected into a set of modules that can be directly used on a 512K machine, or pasted into your program on a 128K system. Of course, some module names, the module numbers for external calling and the routine numbers within the modules have changed, so our example from the last issue won’t work as it is. However, it still works if you do the necessary changes.

All in all one can say that the MacModula-2 documentation almost is a mini-’Inside Macintosh’. When I work with Modula, I still have IM at hand, but I get most of the information about the routines (i.e. mainly how to call them) out of the Modula manual. Very convenient.

The benchmarks that I ran on the new version gave the same results as on the beta release; the speed of the interpreter does not seem to be changed. So you still can go get some coffee while a longer program is compiled, and since it is so easy to make errors in Modula, program development is still a rather lengthy process.

Rumor has it that the company that distributes MacModula-2 in Germany is working on a native code compiler for this system. Wouldn’t that be nice! I only hope that they don’t forget to re-compile the Compiler and Linker from M-code to native code to speed up things a little. The annual Hannover fair starts in a few weeks, and I hope they will show up there so that I can give you some more information.

International ‘Compatibility’

One of the important features of the Mac is international compatibility, or at least that’s what Apple says. You are supposed to be able to modify applications to work under different languages, change keyboard configurations, to metri or non-metric, formatting on dates, etc. Well, in principle, yes After having worked with different Macs here in Germany, I have my objections.

Of course, I have a U.S. Mac and a U.S. keyboard. I also have some disks with the U.S. System and Finder files on them. Now, if you try to start up a system with a German (or other ‘international’) keyboard with the US disk, it will work fine at first. Try to type something, and you’ll find that 1) not only have the keys changed which are different on that particular keyboard (such as y and z on the German board, or ; and ö, [ and ü etc.), but 2) that the whole lower row of keys is shifted one position. Anytime you hit a ‘b’, the Mac will present you with an ‘n’ and so on. When you hit the return key, you get the backslash, to get return, you have to press the ‘#’ key. There are probably still more surprises, but this was already rather frustrating.

The next ‘feature’ (i.e. planned bug) that struck me as a little strange was that the designers of the Mac wanted to be 100% international and even changed the name of the Desktop file (which is invisible anyway) to the appropriate language. So it’s ‘Schreibtisch’ in German, and probably (I didn’t have the chance to find out) ‘bureau’ in French or ‘scrivania’ in Italian. Very cute. So what happens when you stick a U.S. disk into a system that has a German startup disk in it? Nothing, for a very long time up to several minutes. This is because the system looks for the ‘Schreibtisch’ but there is only a ‘Desktop’. So it assumes the ‘Schreibtisch’ has been destroyed and proceeds by pulling all the files out of their folders and organizing a new ‘Schreibtisch’. So if you had some 70-odd files on your disk, you have to straighten out the mess before you can continue working. Not mentioning that the keyboard gets messed up again as soon as you start an application from your U.S. disk. So much for the touted ‘international compatibility’ of the Mac. Apple probably hasn’t realized that people also exchange programs across country borders. Still I am very happy that I can type my ä-s, ö-s, ü-s and ß-s (and åæøçñã as well) without changing character ROMs.

Listing 1
( TE Test Window )
( © 032985 MacTutor by J. Langowski )
new.window te.window 
“ TETest Window “ te.window w.title
   50 50  300 400   te.window  w.bounds
   sys.window te.window w.behind  scroll.up/down  +  text.record + +   
   te.window w.attributes          te.window add.window

: text.update get.window terecord +tvisrect teupdate ;
: set.inval get.window +wcbounds dup
                                                    invalid.rect erase.rect 
: recalc get.window +wcbounds  get.window terecord
         over over 2  lmove  8+ 2  lmove
         tecaltext set.inval text.update
  get.window dup  +vbar @ 0 set.control  show.controls ;

( init display pointer ) variable textval  0 textval ! 

( redisplay after scroll ) : redisplay get.window dup
  show.controls  +vbar @ get.control dup 
  textval @ swap - 0 swap tescroll textval ! ;

( controls ) : do.control   @mouse.dn get.window
  find.control ?dup if case
      in.thumb of this.control @ @mouse track.control 
                        drop ( flag ) redisplay endof
      up.button of this.control @ dup get.control
               10 - set.control redisplay  endof
      down.button  of this.control @ dup get.control
               10 + set.control redisplay  endof
      page.up  of this.control @ dup get.control
               100 - set.control redisplay  endof
      page.down of this.control @ dup get.control
               100 + set.control redisplay  endof
             drop endcase  then   ;

( mouse handler ) : do.mouse  @mouse  get.window
  +wcbounds  ptinrect  if  else do.control  then  ;

: adjust.cursor  @mouse get.window +wcbounds ptinrect
       if  ibeam set.cursor   else  init.cursor then  ;

( main event loop ) : t.edit    teactivate
    begin  adjust.cursor  teidle
     case  mouse.down  of do.mouse endof
  of wait.mouse.up drop recalc  endof
           ?keystroke if tekey then
     endcase  again   ;

( activate / deactivate window ) : text.activate
    if    te.window show.window  t.edit
    else  tedeactivate  then  ;

( setup edit field ) : text.edit  ( edit field -- )
    dup @ swap 4+ @ swap over +wrefcon !
    dup on.activate text.activate  dup on.update  text.update
    dup  terecord   0 over 72 + W!    1 swap 74 + W!
         ( auto new line & Geneva font )  ;

( set control range ) : set.scroll.range 
  te.window +vbar @ 0 1000 set.control.range ;

( create TE record in window ) 
te.window +wcbounds dup te.window  text.field  test.text
test.text  text.edit    set.scroll.range

( TextEdit menu definitions)  5 constant
    0  “ TextEdit”
    “ Cut;Copy;Paste” append.items
: te.function menu.selection:  0
    case 1 of  tecut   endof   2 of  tecopy  endof
         3 of  tepaste endof  endcase  ;


Listing 2

( DOER/MAKE MacForth © MacTutor by J. Langowski ) 
: nothing  ;                                                    
: doer  create  ‘ nothing , does>  @  >r ;                      
variable marker                                                 
: (make)  r> dup 2+ dup 2+ swap w@ token>addr 2+ !                   
 w@ ?dup if >r then ;                                        
: make  state @ if ( compiling)                                 
     compile (make)  here marker !  0 w,                        
     else here  [compile] ‘ !                                   
     smudge [compile] ]  then ;  immediate                      
: ;and  compile exit  here marker @ w! ;  immediate             
: undo  ‘ nothing  [compile] ‘ ! ;


Community Search:
MacTech Search:

Software Updates via MacUpdate

DiskCatalogMaker 7.1.3 - Catalog your di...
DiskCatalogMaker is a simple disk management tool which catalogs disks. Simple, light-weight, and fast Finder-like intuitive look and feel Super-fast search algorithm Can compress catalog data for... Read more
Together 3.8.7 - Store and organize all...
Together helps you organize your Mac, giving you the ability to store, edit and preview your files in a single clean, uncluttered interface. Together Features Smart storage. With simple drag-and-... Read more
Little Snitch 4.0.1 - Alerts you about o...
Little Snitch gives you control over your private outgoing data. Track background activity As soon as your computer connects to the Internet, applications often have permission to send any... Read more
Sparkle Pro 2.2.1 - $79.99
Sparkle Pro will change your mind if you thought building websites wasn't for you. Sparkle is the intuitive site builder that lets you create sites for your online portfolio, team or band pages, or... Read more
iWatermark Pro 2.0.0fc4 - Easily add wat...
iWatermark Pro is the essential watermarking app for professional, business, and personal use. Easily secure and protect your photos with text, a graphic, a signature, or a QR watermark. Once added... Read more
Amadeus Pro 2.4 - Multitrack sound recor...
Amadeus Pro lets you use your Mac for any audio-related task, such as live audio recording, digitizing tapes and records, converting between a variety of sound formats, etc. Thanks to its outstanding... Read more
iFFmpeg 6.4.2 - Convert multimedia files...
iFFmpeg is a comprehensive media tool to convert movie, audio and media files between formats. The FFmpeg command line instructions can be very hard to master/understand, so iFFmpeg does all the hard... Read more
EtreCheck 3.4.2 - For troubleshooting yo...
EtreCheck is an app that displays the important details of your system configuration and allow you to copy that information to the Clipboard. It is meant to be used with Apple Support Communities to... Read more
Carbon Copy Cloner 4.1.17 - Easy-to-use...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
VueScan 9.5.81 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more

Latest Forum Discussions

See All

Eden: Renaissance (Games)
Eden: Renaissance 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Eden: Renaissance is a thrilling turn-based puzzle adventure set in a luxurious world, offering a deep and moving... | Read more »
Glyph Quest Chronicles guide - how to ma...
Glyph Quest returns with a new free-to-play game, Glyph Quest Chronicles. Chronicles offers up more of the light-hearted, good humored fantasy fun that previous games featured, but with a few more refined tricks up its sleeve. It's a clever mix of... | Read more »
Catch yourself a Lugia and Articuno in P...
Pokémon Go Fest may have been a bit of a disaster, with Niantic offering fans full refunds and $100 worth of in-game curency to apologize for the failed event, but that hasn't ruined trainers' chances of catching new legendary Pokémon. Lugia nad... | Read more »
The best deals on the App Store this wee...
There are quite a few truly superb games on sale on the App Store this week. If you haven't played some of these, many of which are true classics, now's the time to jump on the bandwagon. Here are the deals you need to know about. [Read more] | Read more »
Realpolitiks Mobile (Games)
Realpolitiks Mobile 1.0 Device: iOS Universal Category: Games Price: $5.99, Version: 1.0 (iTunes) Description: PLEASE NOTE: The game might not work properly on discontinued 1GB of RAM devices (iPhone 5s, iPhone 6, iPhone 6 Plus, iPad... | Read more »
Layton’s Mystery Journey (Games)
Layton’s Mystery Journey 1.0.0 Device: iOS Universal Category: Games Price: $15.99, Version: 1.0.0 (iTunes) Description: THE MUCH-LOVED LAYTON SERIES IS BACK WITH A 10TH ANNIVERSARY INSTALLMENT! Developed by LEVEL-5, LAYTON’S... | Read more »
Full Throttle Remastered (Games)
Full Throttle Remastered 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Originally released by LucasArts in 1995, Full Throttle is a classic graphic adventure game from industry legend Tim... | Read more »
Stunning shooter Morphite gets a new tra...
Morphite is officially landing on iOS in September. The game looks like the space shooter we've been needing on mobile, and we're going to see if it fits the bill quite shortly. The game's a collaborative effort between Blowfish Studios, We're Five... | Read more »
Layton's Mystery Journey arrives to...
As you might recall, Layton's Mystery Journey is headed to iOS and Android -- tomorrow! To celebrate the impending launch, Level-5's released a new trailer, complete with an adorable hamster. [Read more] | Read more »
Sidewords (Games)
Sidewords 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Grab a cup of coffee and relax with Sidewords. Sidewords is part logic puzzle, part word game, all original. No timers. No... | Read more »

Price Scanner via

PHOOZY World’s First Thermal Capsules to Summ...
Summer days spent soaking up the sun can be tough on smartphones, causing higher battery consumption and overheating. To solve this problem, eXclaim IP, LLC has introduced the PHOOZY Thermal Capsule... Read more
2018 Honda Ridgeline with Android Auto and Ap...
The 2018 Honda Ridgeline is arriving in dealerships nationwide with a Manufacturer’s Suggested Retail Price (MSRP1) starting at $29,630. The 2017 Honda Ridgeline was named North American Truck of the... Read more
comScore Ranks Top 15 U.S. Smartphone Apps fo...
comScore, Inc. recently released data from comScore Mobile Metrix, reporting the top smartphone apps in the U.S. by audience reach for June 2017. * “Apple Music,” as it appears in comScore’s monthly... Read more
13-inch 3.1GHz MacBook Pros on sale for $100...
B&H Photo has the new 2017 13″ 3.1GHz Space Gray MacBook Pros in stock today and on sale for $100 off MSRP including free shipping. B&H charges sales tax in NY and NJ only: – 13″ 3.1GHz/256GB... Read more
Apple refurbished Mac minis available startin...
Apple has Certified Refurbished Mac minis available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: – 1.4GHz Mac mini: $419 $80 off MSRP – 2.6GHz Mac... Read more
Apple’s 2017 Back to School Promotion: Free B...
Purchase a new Mac using Apple’s Education discount, and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free. As part... Read more
Clearance 2016 13-inch MacBook Pros available...
B&H Photo has clearance 2016 13″ MacBook Pros in stock today for up to $220 off original MSRP. Shipping is free, and B&H charges NY & NJ sales tax only: – 13″ 2.9GHz/512GB Touch Bar... Read more
Apple Move Away from White Label Event Apps C...
DoubleDutch, Inc., a global provider of Live Engagement Marketing (LEM) solutions, has made a statement in the light of a game-changing announcement from Apple at this year’s WWDC conference.... Read more
70 Year Old Artist Creates Art Tools for the...
New Hampshire-based developer Pirate’s Moon has announced MyArtTools 1.1.3, the update to their precision drawing app, designed by artist Richard Hoeper exclusively for use with the 12.9-inch iPad... Read more
Sale! New 2017 13-inch 2.3GHz MacBook Pros fo...
Amazon has new 2017 13″ 2.3GHz/128GB MacBook Pros on sale today for $150 off MSRP including free shipping. Their prices are the lowest available for these models from any reseller: – 13″ 2.3GHz/128GB... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Poole -...
Job Summary The people here at Apple don't just create products - they create the kind of wonder that's revolutionised entire industries. It's the diversity of those Read more
SW Engineer *Apple* TV - Apple Inc. (United...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more Read more
Frameworks Engineering Manager, *Apple* Wat...
Frameworks Engineering Manager, Apple Watch Job Number: 41632321 Santa Clara Valley, California, United States Posted: Jun. 15, 2017 Weekly Hours: 40.00 Job Summary Read more
Product Manager - *Apple* Pay on the *Appl...
Job Summary Apple is looking for a talented product manager to drive the expansion of Apple Pay on the Apple Online Store. This position includes a unique Read more
*Apple* Retail - Multiple Positions - Apple...
SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.