TweetFollow Us on Twitter

Forth Q and A
Volume Number:1
Issue Number:6
Column Tag:TECH NOTES

FORTH Q&A

By Jörg Langowski

Q: How can I write text and numbers to a window and have automatic wrap- around?

A: For one thing, Forth does not define the simple “.” or type words so as to provide an automatic CR when the end of the window is reached. This makes sense in some applications, such as printing out tables, when the window size is not known beforehand. On the other hand, it is rather annoying if one wants to test a simple definition to see half of the printout disappear off the right edge.

You might have noticed that the built-in Forth word, WORDS, does an automatic word wrap. So it almost looks like there is some hidden word in MacForth that tests for the end of the ‘screen’ and prints out a CR when it is reached. Lets look at the definition of WORDS, using the decompiler from an earlier issue of this journal. (I converted the BRANCHes to IFs etc. to make the code more readable). Please refer to figure 1.

: words
  context @ ?dup 
   if @ ?dup
     if dup @ + ( stack now contains address of latest definition )
        begin dup dup 1+ c@ swap c@ or while ( token <> 0 )
            2+ count 31 and 2dup 16 {2c7c} ( aha! hidden definition )
            dup {2c58} ( another one ) type 2 spaces
            + ( add name length, get next token )
        repeat
     drop then
   then;

Figure 1

The code is pretty sraightforward: The address of the CONTEXT vocabulary is put on the stack and the offset to the LATEST definition added to it. Then, after making sure it is not at the end of the list (token = 0), WORDS gets the name string of the definition and, after some manipulations, types it. The manipulations are done by two of those strange tokens that have no name associated with them, {2C7C} and {2C58}. They are defined as follows:

: {2c7c} col @ over wmod 1+ -
         dup {2c58} col @ if spaces else drop then ;

: {2c58} col @ +
         get.window +wbounds 6+ w@
         get.window +wline.height @ 7-
         w/ > if cr then ;

The first one, {2C7C} tabs to the next integer multiple of n, where n is the number on top of the stack, and wraps around if it would go beyond the limit of the window. The actual wraparound is done by {2C58}, which expects the number of characters to be output on top of the stack. It then compares the final cursor position to (right window edge)/(line height - 7), which is approximately the last column position in the window. If the string would print beyond this last position, a carriage return is output first. The ‘approximately’, by the way, is the reason why WORDS sometimes prints off the screen with non-standard text sizes. The remedy is to increase LINE.HEIGHT.

So you can very easily achieve automatic wrap when outputting text. For string output (with COUNT TYPE) you may redefine:

: wraptype dup 2c58 execute type ;

and any string you output using this word will automatically be confined to the window boundaries (more or less; in case of trouble change LINE.HEIGHT). For number output, you either have to know beforehand how many digits your number will have, or you write your number to string conversion routine and then use WRAPTYPE.

In the near future, we will solve the text output problem (and also the Cut/Paste problem) in a more elegant way by using the TextEdit functions. Stay tuned for an article on that.

Q: How can I get access to the toolbox routines that are not predefined in MacForth?

A: I hope your question has already been answered in one of my recent columns (there is this 3 months’ delay between writing the letter to us and getting the answer), but I’ll repeat that important point here.

MacForth provides defining words that support most of the toolbox routines. They are the following:

OS.TRAP - the address on top of stack (TOS) is an operating system trap, which is compiled into the definition of the following word. On execution, this word takes the 32-bit number on TOS, puts it into register A0 and executes the trap. The result is returned in the variable IO-RESULT.

MT - the address on TOS is a Pascal procedure type trap. All parameters to this procedure are 32-bit items. On execution, the trap is called with all the parameters passed through the stack. They have to be set up in the order given in the trap definition (in Inside Macintosh).

W>MT - the Pascal definition expects one 16-bit item on TOS. Therefore, the (32-bit) item on TOS is converted to a 16-bit item before the trap is called.

2W>MT - same as W>MT, the two topmost items on the stack are converted to 16 bits.

The third type of traps are Pascal function type traps. This means that you have to allocate space, either 16 or 32 bits, by pushing a zero before you push the arguments on the stack. This way, function type traps can be called through MT. For simple functions, MacForth provides four defining words that do this space allocation automatically:

FUNC>W - no argument, 16 bit result (converted to 32 bits)
FUNC>L - no argument, 32 bit result
W>FUNC>L - 16 bit argument, 32 bit result
L>FUNC>L - 32 bit argument, 32 bit result. 

For all other trap calls you have to write your custom stack set-up procedure, which is not too hard. The definition of NEW.CONTROL in the March issue gives an example for that. One important tool in writing such a toolbox trap definition is the routine PUSHW that changes TOS and the stack pointer in such a way that TOS is a 16-bit item:

: pushw s0 @ >r sp@ 2- s0 ! sp! r> s0 ! drop ;

Be cautious in using PUSHW; 16-bit pushes and calls that pull 16 bits have to match, otherwise the stack pointer may be 2 bytes out of frame.

Q: How do I use resources from MacForth?

A: The BLKS files contain no resources (as you might check using a resource editor - some of them are around now - or even a simple disk editor program). If you want to use the resource fork of a file, you have to generate the resources first with Rmaker (this program can also be found on several public domain disks). Rmaker, however, has the annoying habit of deleting the data fork of a file that is presented to him. Therefore, the correct procedure is to create a new file of the correct type and creator with Rmaker and put in the resources that you want. For example, the input to Rmaker might look like:

MyFile
BLKSM4TH

TYPE MENU
   ,1
\14

   ,2
Test
Item1
Item2
(-
Item4
Item5

This will create the file MyFile with the correct type (BLKS) and creator (M4TH) and put the Apple menu (ID=1) and a test menu (ID=2) into the resource fork. Of course, this file does not contain a data fork yet, so you have to add some blocks to it by executing

 “ MyFile” 1 assign
1 open
1 10 append.blocks

and you can put your Forth program text into those blocks. MacForth provides the word OPEN.RSRC for opening the resource fork of a file; you will have to read the resources through the appropriate toolbox routines, since there are no predefined words for getting resources from a file.

Since Forth programs are usually distributed in source form, however, I do not consider resources as critical as in other applications. However, if you develop stand-alone applications in Forth (I have not used Level 3 yet, but any comments are welcome), you might want to add the resources with Rmaker. I will deal with using resources in one of my next columns.

 
AAPL
$111.78
Apple Inc.
-0.87
MSFT
$47.66
Microsoft Corpora
+0.14
GOOG
$516.35
Google Inc.
+5.25

MacTech Search:
Community Search:

Software Updates via MacUpdate

LibreOffice 4.3.5.2 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
CleanApp 5.0.0 Beta 5 - Application dein...
CleanApp is an application deinstaller and archiver.... Your hard drive gets fuller day by day, but do you know why? CleanApp 5 provides you with insights how to reclaim disk space. There are... Read more
Monolingual 1.6.2 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
NetShade 6.1 - Browse privately using an...
NetShade is an Internet security tool that conceals your IP address on the web. NetShade routes your Web connection through either a public anonymous proxy server, or one of NetShade's own dedicated... Read more
calibre 2.13 - 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 librarian... Read more
Mellel 3.3.7 - Powerful word processor w...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
ScreenFlow 5.0.1 - Create screen recordi...
Save 10% with the exclusive MacUpdate coupon code: AFMacUpdate10 Buy now! ScreenFlow is powerful, easy-to-use screencasting software for the Mac. With ScreenFlow you can record the contents of your... Read more
Simon 4.0 - Monitor changes and crashes...
Simon monitors websites and alerts you of crashes and changes. Select pages to monitor, choose your alert options, and customize your settings. Simon does the rest. Keep a watchful eye on your... Read more
BBEdit 11.0.2 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
ExpanDrive 4.2.1 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more

Latest Forum Discussions

See All

Make your own Tribez Figures (and More)...
Make your own Tribez Figures (and More) with Toyze Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
So Many Holiday iOS Sales Oh My Goodness...
The holiday season is in full-swing, which means a whole lot of iOS apps and games are going on sale. A bunch already have, in fact. Naturally this means we’re putting together a hand-picked list of the best discounts and sales we can find in order... | Read more »
It’s Bird vs. Bird in the New PvP Mode f...
It’s Bird vs. Bird in the New PvP Mode for Angry Birds Epic Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Telltale Games and Mojang Announce Minec...
Telltale Games and Mojang Announce Minecraft: Story Mode – A Telltale Games Series Posted by Jessica Fisher on December 19th, 2014 [ permalink ] | Read more »
WarChest and Splash Damage Annouce Their...
WarChest and Splash Damage Annouce Their New Game: Tempo Posted by Jessica Fisher on December 19th, 2014 [ permalink ] WarChest Ltd and Splash Damage Ltd are teaming up again to work | Read more »
BulkyPix Celebrates its 6th Anniversary...
BulkyPix Celebrates its 6th Anniversary with a Bunch of Free Games Posted by Jessica Fisher on December 19th, 2014 [ permalink ] BulkyPix has | Read more »
Indulge in Japanese cuisine in Cooking F...
Indulge in Japanese cuisine in Cooking Fever’s new sushi-themed update Posted by Simon Reed on December 19th, 2014 [ permalink ] Lithuanian developer Nordcurrent has yet again updated its restaurant simulat | Read more »
Badland Daydream Level Pack Arrives to C...
Badland Daydream Level Pack Arrives to Celebrate 20 Million Downloads Posted by Ellis Spice on December 19th, 2014 [ permalink ] | Read more »
Far Cry 4, Assassin’s Creed Unity, Desti...
Far Cry 4, Assassin’s Creed Unity, Destiny, and Beyond – AppSpy Takes a Look at AAA Companion Apps Posted by Rob Rich on December 19th, 2014 [ permalink ] These day | Read more »
A Bunch of Halfbrick Games Are Going Fre...
A Bunch of Halfbrick Games Are Going Free for the Holidays Posted by Ellis Spice on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »

Price Scanner via MacPrices.net

The Apple Store offering free next-day shippi...
The Apple Store is now offering free next-day shipping on all in stock items if ordered before 12/23/14 at 10:00am PT. Local store pickup is also available within an hour of ordering for any in stock... Read more
It’s 1992 Again At Sony Pictures, Except For...
Techcrunch’s John Biggs interviewed a Sony Pictures Entertainment (SPE) employee, who quite understandably wished to remain anonymous, regarding post-hack conditions in SPE’s L.A office, explaining “... Read more
Holiday sales this weekend: MacBook Pros for...
 B&H Photo has new MacBook Pros on sale for up to $300 off MSRP as part of their Holiday pricing. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699... Read more
Holiday sales this weekend: MacBook Airs for...
B&H Photo has 2014 MacBook Airs on sale for up to $120 off MSRP, for a limited time, for the Thanksgiving/Christmas Holiday shopping season. Shipping is free, and B&H charges NY sales tax... Read more
Holiday sales this weekend: iMacs for up to $...
B&H Photo has 21″ and 27″ iMacs on sale for up to $200 off MSRP including free shipping plus NY sales tax only. B&H will also include a free copy of Parallels Desktop software: - 21″ 1.4GHz... Read more
Holiday sales this weekend: Mac minis availab...
B&H Photo has new 2014 Mac minis on sale for up to $80 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 1.4GHz Mac mini: $459 $40 off MSRP - 2.6GHz Mac mini: $629 $70 off MSRP... Read more
Holiday sales this weekend: Mac Pros for up t...
B&H Photo has Mac Pros on sale for up to $500 off MSRP. Shipping is free, and B&H charges sales tax in NY only: - 3.7GHz 4-core Mac Pro: $2599, $400 off MSRP - 3.5GHz 6-core Mac Pro: $3499, $... Read more
Save up to $400 on MacBooks with Apple Certif...
The Apple Store has Apple Certified Refurbished 2014 MacBook Pros and MacBook Airs available for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
Save up to $300 on Macs, $30 on iPads with Ap...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
iOS and Android OS Targeted by Man-in-the-Mid...
Cloud services security provider Akamai Technologies, Inc. has released, through the company’s Prolexic Security Engineering & Research Team (PLXsert), a new cybersecurity threat advisory. The... Read more

Jobs Board

*Apple* Store Leader Program (US) - Apple, I...
…Summary Learn and grow as you explore the art of leadership at the Apple Store. You'll master our retail business inside and out through training, hands-on experience, 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* 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
*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
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.