TweetFollow Us on Twitter

TextEdit from BASIC
Volume Number:3
Issue Number:6
Column Tag:BASIC School

TextEdit from MS BASIC

By Dave Kelly, MacTutor Editorial Board

As you may recall from previous discussions about MS Basic, there are several statements in version 3.0 of the interpreter and version 1.0 of the compiler which have not yet been documented. Well, at least these statements have not been documented by Microsoft. In fact, they are documented in Inside Macintosh (and books like Macintosh Revealed ). The statements I refer to are all calls to the Macintosh Toolbox text-editing routines. Before this version of Basic text-editing was limited to whatever you could do with the Edit Field statement. The Macintosh text-edit routines provide basic text editing, with no added features. Some basic text edit capabilities include cut, paste, copy, insert, delete, and scrolling are provided. Word wrap, double-clicking to select words, inverse highlighting is supported. It allows you to edit a single font, style, and size (display only one at a time). It provides the basics of what full blown word processors provide. Text Edit does NOT support the use of more than one font or style, fully justified text, tabs and adjustment of spaces between words in the current system file. However, under the new system file for the Mac II and SE, multiple fonts and style are supported, but tabs and 32K limitations remain a problem. The new system file is scheduled to ship in May and should bring these new features to Mac Plus systems as well. A good review of text edit’s capabilities is given in the Pascal multi-window example in the January issue of MacTutor.

The Inside Macintosh Edit Records are automatically prepared by MS Basic when the EDIT FIELD statement is first defined. The Edit Record contains information which defines the complete Editing environment. You don’t have to know or worry about what goes on with the Edit Records to use the new calls. Each Edit Field has a handle (teHandle) which refers to the Edit Record. Microsoft has beefed up the EDIT FIELD statement so that when the Text Edit field is defined the text string no longer defaults to a selected state. Otherwise, your program may not have quite the appearance that you desire, especially if you are creating a text editor.

In the text edit field, a character position is an index into the text. Position zero corresponds to the first character of the edit field. The selection range is indicated by a starting and ending index into the text. The text that will be highlighted when selected by the mouse is indicated by the start and end indexes. If the starting and ending position is the same then the position is indicated by the insertion point. The insertion point is the position where the characters will be inserted.

Fig. 1 Edit Field Text Wraps!

There are 10 new calls which are already built into Basic. These 10 are only about half of the total number of routines given in Inside Macintosh . The routines which are not implemented are already provided for by using the EDIT FIELD statement in Basic. The statements NOT available are:

TEClick TECopy TECut

TEDispose TEGetText TEIdle

TEInit TENew TEPaste

TESetJust TextBox

First a few words about some of the syntax used. The WINDOW(6) function is used to return the handle (same as teHandle) for the active edit field in the current output window. WINDOW(6) returns zero if the window has no active edit field. The SADD(<string-expression>) function returns the address of the first byte of data in <string-expression>. Note that this value is only valid until another string allocation of a new variable assignment takes place, since string allocations and variable assignments can cause existing strings to move in memory. The selection range referred to in some of the statements is the range of text which is selected in an edit field. Here are the new commands with a quick description of their use and syntax:



Description: TEACTIVATE displays the insertion point and highlights the selected text (unless the selection is the insertion point) in the text edit field specified by the WINDOW(6) function. Macintosh User Interface Guidelines indicate that when a window is inactive, the text selected in a text field should be inactive and the insertion point should be hidden. Use this call when your window is activated. Remember that text edit always works on the currently active grafPort; ie the SetPort result. See TEDEACTIVATE also.



Description: TECALTEXT recalculates each line of text in the edit field indicated by the WINDOW(6) function. This call should be used whenever the number of characters per line of the edit field has been changed.



Description: TEDEACTIVATE hides the insertion point and unhighlights the selected text in the text edit field specified by the WINDOW(6) function. Macintosh User Interface Guidelines indicate that when a window is inactive, the text selected in a text field should be inactive and the insertion point should be hidden. Use this call when your window is deactivated. See TEACTIVATE also.



Description: TEDELETE removes the text which has previously been selected in the edit field indicated by the WINDOW(6) function. The text which is deleted is not recoverable.


Syntax: TEINSERT SADD(string ), LEN (string ), WINDOW(6)

Description: TEINSERT takes the specified string and inserts it at the insertion point of the edit field indicated by the WINDOW(6) function. Any selected text is not replaced by the newly inserted text. Use TEDELETE to delete selected text.


Syntax: TEKEY key , WINDOW(6)

Description: TEKEY replaces the selection range with the character key typed at the keyboard. If the selection range is an insertion point then the character is inserted. All types of characters (normal and control characters) are inserted so your routine should filter out any unwanted characters. TEKEY re-draws the text as necessary. It is not clear if this can be used with an Edit field in Basic, since the Edit field statement prevents INKEY$ from allowing you to get single keystrokes from the keyboard. The only apparent way to get text typed by the user during an active Edit field statement is to use EDIT$, which returns the entire string contents of the text edit record.


Syntax: TESCROLL horiz, vert, WINDOW(6)

Description: TESCROLL scrolls the text within the edit field specified by WINDOW(6) by the number of pixels specified by horiz and vert parameters. Positive parameters move the text to the right and down. Negative parameters move the text to the left and up. See Inside Macintosh for more information.


Syntax: TESETSELECT selStart, selEnd, WINDOW(6)

Description: TESETSELECT sets the selection range of the edit field text indicated by the WINDOW(6) function. The old text selection is unhighlighted and the text between selstart and selend is highlighted. Selstart and Selend can range from 0 to 32767. If Selend is beyond the last character of text, the position just past the last character is used.


Syntax: TESETTEXT SADD(string), LEN (string), WINDOW(6)

Description: TESETTEXT changes the text string of the edit field pointed to by the WINDOW(6) function. The edit field will now point to the string set by the new string parameter. The selection point is set to the end of the new text. However, the text is not re-drawn. Follow this with an ERASERECT and the next function below, TEUPDATE.


Syntax: TEUPDATE VARPTR(rect%(0)), WINDOW(6)

Description: TEUPDATE draws the text of the edit field specified by the WINDOW(6) function within the rectangle rect%.

The call descriptions are somewhat brief. It will be useful to look at a few examples. Some of the new calls will probably only be used occasionally since the Basic Edit Field routines automatically provide some of the functions. The text edit demo program I have prepared will show some working examples of some of the text edit calls. The TEKEY, and TESCROLL, calls will be saved for a later column. Now you can write your text editor in BASIC (well, sort of)!! The DOUBLE-CLICK ME programs that come with the Basic interpreter use a few of the calls, the QnD (Quick-N-Dirty) editor demo (included with Basic) uses a few more of the calls. The problem with these examples is that they don’t make use of the ToolLib routines for creating scroll bars. Instead, they draw and manipulate their own set of scroll bars and window bars by drawing rectangles in a blank window and keeping track of them all. This seems to make things a lot more confusing than it has to be. This might be an indication that these demos were actually written before it was decided that the ToolLib routines would be included. If so, then it seems to me that Microsoft would have had plenty of time to document the text edit routines by now. As of this time, no one at Microsoft has sent me any information about the text edit calls which I had requested. If the QnD edit was written after ToolLib was slated to be included in MS Basic then it appears that the authors of QnD didn’t yet know how to use the ToolLib Libraries. At any rate, QnD will give you some ideas of ways to implement a text editor.

The Text Edit Demo will show you the effects of each call as you click through each step by pressing the mouse button outside of the Edit Field. If you click inside the Edit Field (which is controlled automatically by Basic) you will be changing the insertion point or selecting and highlighting text, if you drag the mouse. If you type, characters will be inserted at the insertion point, and the text will wrap when it gets to the end of the line. More on this later. The demo will first create an edit field and put default text in it. Next you click the mouse button and the default text is replaced by a new string (set with the TESETTEXT call). The TEUPDATE call re-draws the edit field with the new string. Click the mouse again and the selection range is set up by the TESETSELECT call such that the text is selected from the 1st up to the 6th character. Another click of the mouse and the TEDELETE call deletes the selected text. The next clicks deactivate and activate the edit field followed by text inserted by the TEINSERT call. Most uses of these calls are demonstrated by this demo.

Word Wrapping Edit Fields

by David E. Smith

Normally, Basic sets up an Edit Field with a very large destination rectangle and with the text edit field crOnly set to FF00, a negative value. This indicates that lines will only break at a carriage return. Hence when you type in the Edit Field, the text never wraps at the end of the line as you would expect from normal use of text edit functions in other languages. Many people have been frustrated at trying to get text to word wrap in Edit Fields (see letters column this month for a few such frustrations!). In order to get text to wrap, the destination rectangle must be the same size or smaller than the view rectangle, which Basic sets equal to the Edit Field rectangle. Also the crOnly field must be positive. In our demo program, we call a subroutine called Wrap, which pokes the proper values into the text edit record so the destination rectangle is changed and the crOnly field is changed. Hence, if you type in the demo program, you’ll see that when you get to the edge of the Edit Field box, the text does word wrap properly. However, there is a penalty for this.

With word wrapping enabled, Basic no longer processes or returns carriage returns in the Edit Field, even when you set the type parameter to indicate that it should process carriage returns. Whatever mechanism Basic uses to intercept and process control characters in an active Edit Field apparently will not process carriage returns if the crOnly field is positive. You can try this with the demo. As you type (assuming you type at the end of the text), each character will be displayed on the Edit Buffer line. If a carriage return is received, then the program will print “CR” there. But with the subroutine call to Wrap, you’ll never see a CR. Now if you remark out the Wrap subroutine call, then carriage returns will be returned properly, but of course then the Edit Field won‘t wrap text to the view rectangle! This seems like a design bug in Basic as there is no obvious correlation between the text edit record set-up and whether or not carriage returns get filtered from the Edit Field.

Peeking at the text edit record and changing it’s fields can be a very interesting pursuit. To do this, you need to get the handle to the text edit record. This is returned with the WINDOW(6) function. You can store this in a double precision variable as shown in the program listing under the TextEdit subroutine.

myHandle# = WINDOW(6)

On our Text Buffer line, we’ve printed some important debugging information. The first large number is the teHandle to the text edit record. The next number is the address of the text edit record itself. The final small number is one of the text edit record fields, ie the length of text in the buffer. As you type, you’ll see this number increment. To dereference the handle, we use the PEEK function:

ptr1 = PEEK(myHandle#+3)
ptr2 = PEEK(myHandle#+2)
ptr3 = PEEK(myHandle#+1)
ptr4 = PEEK(myHandle#+0)

This returns the four individual bytes at the handle. They now have to be re-constructed into the master pointer:

ptr# = (ptr3*65536!)) + (ptr2*256) + ptr1

Now we have the address of the text edit record itself. This address is valid as long as we don’t do anything that would move things in memory, like call a toolbox routine. Now we can peek at individual text edit record items, like the length:

telength1 = PEEK(ptr#+61)
telength2 = PEEK(ptr#+60)
telength = telength2 * 256 + telength1

Once we’ve identified the text edit record, then our Wrap routine can poke new values into the destination rectangle and the crOnly field. The address of the crOnly field will be ptr#+72. The address of the destination rectangle is ptr# since it is the first field in the record. The address of the view rectangle, which is the second item in the field is ptr#+8. Rectangles are eight bytes, so if we poke the destination rectangle field with the view rectangle field, then the two will be the same, and the text will wrap. A little for next loop does this for us in the Wrap subroutine. To find the address of other items in the text edit record, just add up the size of each field. A rectangle is 8 bytes; a point is 4 bytes, as are pointers and handles; an integer is two bytes. Starting at zero, it is easy to determine the offset of each field in the record from the definition in Inside Macintosh.

Can you really make a text editor? It doesn’t look too good, even with these new routines. The problem is, you don’t really have an honest event loop, so how do you get keystrokes. The only events Basic lets you have are menu events and dialog type events. Key events are intercepted by Basic. For example, if you have an active Edit Field as we do in this example, how do you get the actual single character last pressed? INKEY$ is ignored when the Edit Field is active. The only option seems to be the EDIT$ statement, which returns the entire edit field contents. So you don’t really have a text editor if you can’t process keystrokes. Remember, TEKey only inserts characters into a text edit record, it doesn’t poll the keyboard. That is supposed to happen during an event loop, but Basic only lets you see certain events. If you find some more information on this subject of using MS Basic 3.0 with text edit, share it with our MacTutor audience.

Fig. 2 Making a selection

‘Text Edit Demo
‘By Dave Kelly
‘teRec Wrap by Dave Smith
‘©MacTutor 1987

OriginalEditString$=”This is the first string.”
‘ Set up rectangle for TEUPDATE call

WINDOW 1,”Text Edit Demo”,(15,40)-(495,330),2
EDIT FIELD 1,OriginalEditString$,(10,20)-(460,200),6,1
PRINT “Click mouse button outside of edit field or type  ”
PRINT “The Text Edit field has been created. (EDIT FIELD statement)”
LOCATE 17,1:PRINT “TextEdit Buffer:”
GOSUB wrap: REM make textedit wrap to view rectangle
TESETSELECT endofstring+1,endofstring+1,WINDOW(6)
GOSUB eventloop

‘Set the edit field text to a new string
NewEditString$=”This the second string. (replaced old string)”
TESETTEXT SADD(NewEditString$), LEN(NewEditString$), WINDOW(6)

‘Re-draw the edit field (needs to be re-drawn after setting new text) 
PRINT “The Text Edit field has been set to a new string (TESETTEXT call).”
GOSUB eventloop

‘Set the selection range 
PRINT “The text has been selected  selection range”; STRING$(50,” “)
PRINT “is from before character 1 until before character 6. (TESETSELECT 
GOSUB eventloop

‘Delete the selected text 
PRINT “The selected text has been deleted. (TEDELETE call)”;STRING$(30,” 
PRINT STRING$(150,” “)
GOSUB eventloop

‘De-activate the edit field 
PRINT “The text has been deactivated (TEDEACTIVATE call)”
GOSUB eventloop

‘Re-activate the edit field...
PRINT “The text has been activated (TEACTIVATE call)”; STRING$(10,” “)
GOSUB eventloop

‘Insert new text at the insertion point 
TextToInsert$=”-This text was inserted-”
TEINSERT SADD(TextToInsert$), LEN(TextToInsert$), WINDOW(6)
PRINT “Text has been inserted at the insertion point. (TEINSERT call)”;STRING$(20,” 
GOSUB eventloop


GOSUB TextEdit
IF key$<>oldkey$ THEN GOSUB processtext

chartyped$=RIGHT$(key$,1) :REM how do you get last char typed?
LOCATE 17,18
LOCATE 17,18
IF chartyped$<>CHR$(13) THEN PRINT chartyped$ ELSE PRINT “CR”

LOCATE 17,24:PRINT myHandle#
ptr#=(ptr3*(65536!)) + (ptr2*256) + ptr1
telength1 = PEEK(ptr#+61)
teLength = teLength2*256+telength1
LOCATE 17,35:PRINT ptr#
LOCATE 17,45:PRINT teLength

GOSUB TextEdit : REM get teRec address
REM poke new values in teRec
cronly%=0:POKE crOnlyAdd#,0 :REM turn OFF cronly
FOR i=0 TO 7
POKE ptr#+8+i,PEEK(ptr#+i): REM dest rect = view rect
TECALTEXT WINDOW(6): REM re-do line endings

Fig. 3 Set new text


Community Search:
MacTech Search:

Software Updates via MacUpdate

Kodi 15.0.beta1 - Powerful media center...
Kodi (was XBMC) is an award-winning free and open-source (GPL) software media player and entertainment hub that can be installed on Linux, OS X, Windows, iOS, and Android, featuring a 10-foot user... Read more
DiskCatalogMaker 6.4.12 - Catalog your d...
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... Read more
Macs Fan Control - Monitor and c...
Macs Fan Control allows you to monitor and control almost any aspect of your computer's fans, with support for controlling fan speed, temperature sensors pane, menu-bar icon, and autostart with... Read more
Lyn 1.5.11 - Lightweight image browser a...
Lyn is a lightweight and fast image browser and viewer designed for photographers, graphic artists and Web designers. Featuring an extremely versatile and aesthetically pleasing interface, it... Read more
NeoOffice 2014.11 - Mac-tailored, OpenOf...
NeoOffice is a complete office suite for OS X. With NeoOffice, users can view, edit, and save OpenOffice documents, PDF files, and most Microsoft Word, Excel, and PowerPoint documents. NeoOffice 3.x... Read more
LaunchBar 6.4 - Powerful file/URL/email...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
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
Microsoft Remote Desktop 8.0.18 - Connec...
With Microsoft Remote Desktop, you can connect to a remote PC and your work resources from almost anywhere. Experience the power of Windows with RemoteFX in a Remote Desktop client designed to help... Read more

Biz Builder Delux (Games)
Biz Builder Delux 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: Ah, there's nothing like the rhythmic bustle of a burgeoning business burg... especially when you're the one building it... | Read more »
Auroch Digital is Bringing Back Games Wo...
| 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 »
Draggy Dead (Games)
Draggy Dead 1.1 Device: iOS Universal Category: Games Price: $.99, Version: 1.1 (iTunes) Description: Ditch your dead end job and take up a rewarding career in Grave Robbing today!Guide the recently deceased to a fun filled life of... | Read more »
Bad Dinos (Games)
Bad Dinos 1.0.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.0 (iTunes) Description: | Read more »
The Apple Watch isn't Great as a Fi...
| Read more »
Show the World What You See With
Live broadcasting is getting popular on mobile devices, which is why you can now get, 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 »

Price Scanner via

Memorial Day Weekend Sale: New 27-inch 3.3GHz...
Best Buy has the new 27″ 3.3GHz 5K iMac on sale for $1899.99 this weekend. Choose free shipping or free local store pickup (if available). Sale price for online orders only, in-store prices may vary... Read more
OtterBox Maximizes Portability, Productivity...
From the kitchen recipe book to the boarsroom presentation, the OtterBox Agility Tablet System turns tablets into one of the most versatile pieces of handheld technology available. Available now, the... Read more
Launch of New Car App Gallery and Open Develo...
Automatic, a company on a mission to bring the power of the Internet into every car, has announced the launch of the Automatic App Gallery, an app store for nearly every car or truck on the road... Read more
Memorial Day Weekend Sale: 13-inch 1.6GHz Mac...
Best Buy has the new 13″ 1.6GHz/128GB MacBook Air on sale for $849 on their online store this weekend. Choose free shipping or free local store pickup (if available). Sale price for online orders... Read more
Memorial Day Weekend Sale: 27-inch 3.5GHz 5K...
Best Buy has the 27″ 3.5GHz 5K iMac on sale for $2099.99 this weekend. Choose free shipping or free local store pickup (if available). Sale price for online orders only, in-store prices may vary.... Read more
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
With a Mission to Make Mobile Free, Scratch W...
Scratch Wireless, claiming to be the world’s first truly free mobile service, has announced the availability of a new Scratch-enabled Android smartphone, the Coolpad Arise. The smartphone is equipped... Read more
First-Ever Titanium Alloy Curved iPhone 6 Scr...
One of the most common problems with mobile phones is damage to the screens. The slightest drop can cause a dreaded spider web of gashes and cracks in the glass panel surface that can cost $hundreds... Read more
Preorder new 12-inch MacBook, $10 off, save o...
Adorama has new 12″ Retina MacBooks available for preorder for $10 off MSRP including free shipping plus NY & NJ sales tax only. For a limited time, Adorama will include a free Apple USB-C to USB... Read more

Jobs Board

*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* TV Live Streaming Frameworks Test En...
**Job Summary** Work and contribute towards the engineering of Apple 's state-of-the-art products involving video, audio, and graphics in Interactive Media Group (IMG) at 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
Partner Marketing Manager, Merchant- *Apple*...
**Job Summary** The Apple Pay partner marketing team is looking for a marketing manager to develop and drive US marketing programs with our merchant partners. The right Read more
Technical Project Manager - *Apple* Pay - A...
**Job Summary** Apple Pay is seeking an experienced technical PM to…manage the on boarding of new merchants for the Apple Pay platform in the US Within this role you Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.