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:

TEACTIVATE

Syntax: TEACTIVATE WINDOW(6)

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.

TECALTEXT

Syntax: TECALTEXT WINDOW(6)

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.

TEDEACTIVATE

Syntax: TEDEACTIVATE WINDOW(6)

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.

TEDELETE

Syntax: TEDELETE WINDOW(6)

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.

TEINSERT

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.

TEKEY

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.

TESCROLL

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.

TESETSELECT

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.

TESETTEXT

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.

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.”
endofstring=LEN(OriginalEditString$)
‘ Set up rectangle for TEUPDATE call
rect%(0)=20:rect%(1)=10:rect%(2)=200:rect%(3)=460

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  ”
LOCATE 15,1
PRINT “The Text Edit field has been created. (EDIT FIELD statement)”
LOCATE 17,1:PRINT “TextEdit Buffer:”
oldkey$=””
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) 
ERASERECT VARPTR(rect%(0))
TEUPDATE VARPTR(rect%(0)),WINDOW(6)
LOCATE 15,1
PRINT “The Text Edit field has been set to a new string (TESETTEXT call).”
GOSUB eventloop

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

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

‘De-activate the edit field 
TEDEACTIVATE WINDOW(6)
LOCATE 15,1
PRINT “The text has been deactivated (TEDEACTIVATE call)”
GOSUB eventloop

‘Re-activate the edit field...
TEACTIVATE WINDOW(6)
LOCATE 15,1
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)
LOCATE 15,1
PRINT “Text has been inserted at the insertion point. (TEINSERT call)”;STRING$(20,” 
“)
GOSUB eventloop

quit:
EDIT FIELD CLOSE 1
CLS: END

eventloop:
WHILE MOUSE(0)<>1
GOSUB TextEdit
key$=EDIT$(1)
IF key$<>oldkey$ THEN GOSUB processtext
oldkey$=key$
WEND
RETURN

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

TextEdit:
myHandle#=WINDOW(6)
LOCATE 17,24:PRINT myHandle#
ptr1=PEEK(myHandle#+3)
ptr2=PEEK(myHandle#+2)
ptr3=PEEK(myHandle#+1)
ptr4=PEEK(myHandle#+0)
ptr#=(ptr3*(65536!)) + (ptr2*256) + ptr1
telength1 = PEEK(ptr#+61)
teLength2=PEEK(ptr#+60)
teLength = teLength2*256+telength1
LOCATE 17,35:PRINT ptr#
LOCATE 17,45:PRINT teLength
RETURN

wrap:
GOSUB TextEdit : REM get teRec address
REM poke new values in teRec
crOnlyAdd#=ptr#+72
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
NEXT i
TECALTEXT WINDOW(6): REM re-do line endings
RETURN

Fig. 3 Set new text

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.