There are two independent "layers" here, which are often confusingly lumped together.
First, we have the routines EditProg and CloseProg. These routines are documented in the SDK guide. EditProg allocates all free RAM into a given variable; CloseProg reverses the effect. In order for this to work, the iMathPtrs are used to remember which variable is "open" for editing. You shouldn't ever modify iMathPtr1, iMathPtr3, or iMathPtr4; you'll presumably need to modify iMathPtr2 in order to change the size of the variable.
Second, we have the "edit buffer" layer. An edit buffer is a region of RAM that stores text for the user to edit. The buffer might be allocated using EditProg (which is what the OS often does, e.g. when editing a program or equation), or it might be a static buffer that you create in safe RAM somewhere. Or it might be allocated in some other way; it's up to you. The edit buffer routines have nothing to do with the iMathPtrs; they use only the pointers (editTop), (editCursor), (editTail), and (editBtm).
An edit buffer consists of three parts: "head", "gap", and "tail". The head contains the tokens that come before the insertion point, the tail contains the tokens that come after the insertion point, and the gap contains all of the free space. These three areas are defined by the four pointers I mentioned above:
tokens free space more tokens
|***************|.....................|*****************|
^ ^ ^ ^
(editTop) (editCursor) (editTail) (editBtm)
This arrangement means that all of the usual editing operations take constant time. Moving the insertion point "right", for instance, means copying a byte from (editTail) to (editCursor), then incrementing both pointers. Inserting a token means writing it to (editCursor) and incrementing (editCursor). Deleting a token means simply incrementing (editTail). (Of course, if you're dealing with BASIC tokens, you also need to consider the possibility of 2-byte tokens, but you get the idea.) On the other hand, it's not random access: you can't just start editing at an arbitrary place in the buffer; you first need to "move" the insertion point to that location.
You can see from the above diagram that:
- (editTop) ≤ (editCursor) ≤ (editTail) ≤ (editBtm); all of the system routines will assume this is true, and will most likely crash if it's violated.
- If (editCursor) = (editTop), the insertion point is at the "beginning" of the buffer.
- If (editTail) = (editBtm), the insertion point is at the "end" of the buffer.
- If (editCursor) = (editTail), the buffer is "full".