ON ERROR PROCerr:END
vsn$="2.79":date$="24 Nov 2026"
RISCOS311%=TRUE
ROM%=TRUE

REM Need to fettle places where comments say !HACK! [case sens]

IF ROM% THEN RISCOS311%=TRUE : REM DA code isn't ROM safe
extra$=" "
fnm$="LineEditor"
debug%=0
trace%=0
countclientbuf%=0:REM quick fix to stop quitting while client buffers exist
oldrecall%=0:REM old recall list all buffers ; new just the current one
unison_area_max_size=1024<<10: REM 1M
IF RIGHT$(vsn$,1)<"0" OR RIGHT$(vsn$,1)>"9" OR debug% THEN extra$+=" [test version - don't distribute without permission]"
IF debug% THEN extra$+=" [with debug code]"
IF extra$=" " THEN extra$=""
fkeybuff_len=256: REM buffer for fnkey expansion (RO uses 255, so this'll do)
REM fkey workspc [ptr to next char][chars left][buffer - fkeybuff_len bytes]
maxpathlen%=256:REM Maximum path length
maxlen%=maxpathlen%
REM =16:REM Word-rounded max leaf len inc. terminator eg "AUTOEXEC/BAT"
bufsize%=1024:REM Buffer for leafnames in a directory (77*11 for ADFS)
REM Code will read more leafnames if buffer is too small

REM Ensure bufsize% can be loaded by MOV R0,#bufsize% (it can by default)
REPEAT T%=bufsize%:WHILE(T%AND3)=0:T%=T%>>2:ENDWHILE:IF T%>=256 bufsize%+=4
UNTIL T%<256

bl$=CHR$0:cr$=CHR$13:lfcr$=CHR$10+cr$:tab$=CHR$9:esc$=CHR$27:hspc$=CHR$31
codesize=&10000:DIM org codesize:L%=org+codesize
swichunk=&83880:REM As allocated by Acorn
CMD_alias=1
CMD_command=2
CMD_fileobj=3
PROCinitdict

P%=0:O%=org
[OPT12
.head&0
; NB order of these 5, and offset from start of block, are relied upon...
.bufsize & 0:.flags & 0:.minlen & 0:.maxlen & 0:.cursors & 0
.upcasetable & 0
.kbdtype & 0
FNassert("bufsize=4")
FNassert("flags=8")
FNassert("minlen=12")
FNassert("maxlen=16")
FNassert("cursors=20")
.pKernel & 0
]
IF countclientbuf% THEN
[OPT12
.clbufcnt & 0
]
ENDIF
[OPT12
.morebufs & 0 ; Buffers managed for other folks
.tmp256 & 0 ; Scratch block
.lastth & 0:.osver & 0:.sizeofheader]
P%=0:O%=org:[OPT12; Instance -
.cur     & 0 ; Current ptr into history buf (0 => inactive, -1 => bottom)
.buf     & 0 ; pointer to start of history buffer
.end     & 0 ; Current pointer to end of buffer
.limit   & 0 ; pointer to end of history buffer ie maximum value of end
.next    & 0 ; pointer to next instance in linked list
.taskh   & 0 ; task handle (0 for not taskwindow) (-1 for client buffer)
.cltaskh & 0 ; task handle tied to client buffer (0 or -1 means none)
                ; only set for client buffer, so check taskh first
.fkeybuf & 0 ; ptr to fnkey expansion (0 if none active)
.match   & 0 ; length of initial segment to match for PageUp/PageDown
.compcontext & 0 ; completion context structure
.gbpbbuf & 0 ; -> buffer for OS_GBPB (0=>none allocated)
.mtchbuf & 0 ; -> buffer for leaf match so far during filename completion
.yankbuf & 0 ; -> buffer for yank-able text
.r6      & 0 ; r6 for thingy
.r7      & 0 ; r7 for thingy
.pchar   & 0 ; password char
.root    & 0 ; root for command completion tree
; note should have buf <= cur <= end <= limit
FNassert("buf=4")
FNassert("end=8")
FNassert("limit=12")
FNassert("cur=0")
.sizeofinst:]
P%=0:O%=org:[OPT12; completion context
.type    & 0
.dirname & 0 ; -> buffer for path during filename completion
.wildfnm & 0 ; -> buffer for wildcarded leaf we're trying to complete
.context & 0 ; last R4 for OS_GBPB call (-ve => not in one)
.match_s & 0
.match_e & 0
.sizeofcontext:]
typeFile=0
typeSysvar=1
typeFS=2
typeCmd=3
REM Buffer Structure:
REM
REM   #####]\rLine 1\rLine 2\rLine n\0           [#####
REM    buf->     cur->           end->    limit->
REM
REM   mincur->              maxcur->
REM
REM For an empty buffer:
REM
REM  #####]\0                                   [#####
REM   buf->                              limit->
REM   cur->
REM     end->
prog$="Line Editor"
XOS_WriteC=&20000:XOS_WriteS=&20001:XOS_Write0=&20002:XOS_NewLine=&20003
XOS_ReadC=&20004:XOS_Byte=&20006:XOS_GBPB=&2000C:XOS_WriteN=&20046
XOS_WriteI=&20100
XWimp_ReadSysInfo=&600F2:XWimp_SendMessage=&600E7
ReadLineV=14:REM OS_ReadLine vector number
C_bit=1<<29:V_bit=1<<28
REM flags in bits 8-23 of R8
fEchoBuf=1<<20
fPasswd=1<<19
fKeep4D=1<<18:REM Modified leaves compcontext alone
fShowComp=1<<17:REM Set iff show list of completions (fTcsh set => comp 1st)
fCompRev=1<<16:REM Set if it was Shift-Ctrl-Tab rather than Shift-Tab
fTcsh=1<<15:REM Set/clear before calling completefnm
fTaskwndw%=1<<14:REM TRUE iff in taskwindow
fCopying=1<<13
fAbbrev%=1<<12:REM used by filename completion to flag to try *Acc.Fred case
fEsc%=1<<11:fEdit%=1<<10:fOver%=1<<9:fCopy%=1<<8
dfltsize=4:REM EdSize default = 4K
fAll%=fAbbrev% OR fEsc% OR fEdit% OR fOver% OR fCopy% OR fCopying
REM These are in [R12,#flags]
f_LocalHist = %1
f_TrailDots = %10
f_DfltOver  = %100
f_KeepDupl  = %1000
f_NoTildes  = %10000
f_NoEvents  = %100000
f_NoHatRepl = %1000000
f_NoLeadSpc = %10000000
FOR A%=%1100 TO %1110 STEP %0010
P%=0:O%=org
[OPT A%
;label          OP      args              ; Comment
                & 0
                & init              ; Initialisation entry
                & finalise          ; Finalisation entry
                & servicecall       ; Service call entry
                & titlestring       ; -> Title string
                & helpstring        ; -> Help string
                & keywordtable      ; -> Help/Command keyword table
                & swichunk          ; And now SWIs...
                & swihandler
                & switab
                & 0
                & 0
                & modflags
.erasehisthelp  ADR     R0,szerasehisthelp
                ADR     R2,szerasehistory
.pprinthelpsyn  MOV     R5,R14
                BL      pprinthelp
                ADR     R0,syntax0args
                BL      pprinthelp
                MOV     PC,R5
.recallhelp     ADR     R0,szrecallhelp
                ADR     R2,szrecall
                B       pprinthelpsyn
.edstatushelp   ADR     R0,szedstatushelp
                ADR     R2,szedstatus
                B       pprinthelpsyn
.modflags       & 1
.ukswitok       & &1E6
                = "BadSWI"+bl$
.helpstring    := prog$+tab$+vsn$+" ("+date$+")"+extra$+bl$
.syntax0args   := esc$+CHR$1+bl$    ; "Syntax; *<...>"
ALIGN ; so syntax1fnm can be reached by ADRs
.syntax1fnm    := esc$+CHR$27+bl$   ; "Syntax; *<...> <filename>"
.szerasehisthelp
="*":DCB 27:DCB 0
FNpp(" erases the contents of the history buffer."+cr$+bl$)
.szrecallhelp
="*":DCB 27:DCB 0
FNpp(" displays the current contents of the history buffer."+cr$+bl$)
.szedstatushelp
="*":DCB 27:DCB 0
FNpp(" displays details of the current history buffer usage."+cr$+bl$)
.szloadhisthelp
="*":DCB 27:DCB 0
FNpp(" loads a saved history file."+cr$+bl$)
.szsavehisthelp
="*":DCB 27:DCB 0
FNpp(" saves the current history into a file."+cr$+bl$)
.switab
.titlestring   := "LineEditor"+bl$
                = "SetOptions"+bl$
                = "GetOptions"+bl$
                = "CreateBuffer"+bl$
                = "DeleteBuffer"+bl$
                = "SetPos"+bl$
                = "GetPos"+bl$
                = "GetLine"+bl$
                = "AppendLine"+bl$
                = "DeleteLine"+bl$
                = "ReadInfo"+bl$
                = "ReadLine"+bl$
]
IF debug% [OPTA%:="X"+bl$:]:REM Debugging SWI - does *Recall on buffer
[OPTA%
                = 0
ALIGN
.loadhisthelp   ADR     R0,szloadhisthelp
                ADR     R2,szloadhist
                B       pprinthelpsyn1
.savehisthelp   ADR     R0,szsavehisthelp
                ADR     R2,szsavehist
.pprinthelpsyn1 MOV     R5,R14
                BL      pprinthelp
                ADR     R0,syntax1fnm
                MOV     R1,#0
                SWI     "XOS_PrettyPrint"
                SUBS    R0,R0,R0
                MOV     PC,R5
.ukswi          ADR     R0,ukswitok
                MOV     R1,#0
                MOV     R2,#0
                ADR     R4,titlestring
                MOV     R10,R14              ; Bug-fix to code in PRM
                SWI     "XMessageTrans_ErrorLookup"
                MOV     PC,R10
.keywordtable
.szedstatus    := "EdStatus"+bl$:ALIGN
                & edstatus
                & &20000000 ; help printed by code
                & syntax0args
                & edstatushelp
.szerasehistory:= "EraseHistory"+bl$:ALIGN
                & erasehistory
                & &20000000 ; help printed by code
                & syntax0args
                & erasehisthelp
.szrecall      := "Recall"+bl$:ALIGN
                & recall
                & &20000000 ; help printed by code
                & syntax0args
                & recallhelp
.szloadhist    := "LoadHistory"+bl$:ALIGN
                & loadhistory
                & &20010001 ; help printed by code
                & syntax1fnm
                & loadhisthelp
.szsavehist    := "SaveHistory"+bl$:ALIGN
                & savehistory
                & &20010001 ; help printed by code
                & syntax1fnm
                & savehisthelp
                & 0

.swihandler     LDR     R12,[R12,#0]
                CMP     R11,#(swijmptabend-swijmptab)/4
                ADDLO   PC,PC,R11,LSL#2
                B       ukswi
.swijmptab      B       le_setopts
                B       le_getopts
                B       CreateBuffer
                B       DeleteBuffer
                B       SetPos
                B       GetPos
                B       GetLine
                B       AppendLine
                B       DeleteLine
                B       ReadInfo
                B       ReadLine
]
IF debug% THEN
[OPTA%
                B       X
]
ENDIF
[OPTA%
.swijmptabend
; /E
; R0 = buffer size (0 for default)
; R1 = flags
; R2 = min len to record (0=>no min)
; R3 = max len to record (0=>no max)
; R4 = cursors
.le_setopts     TEQ     R0,#0
                MOVEQ   R0,#dfltsize
                TEQ     R2,#0
                MOVEQ   R2,#1
                TEQ     R3,#0
                MOVEQ   R3,#1<<30 ; was (1<<31)-1
                STMIB   R12,{R0-R4}          ; Store values (no writeback)
                MOV     PC,R14
; /X
; R0 = buffer size
; R1 = flags
; R2 = min len to record
; R3 = max len to record
; R4 = cursors
.le_getopts     LDMIB   R12,{R0-R4}          ; Load values (no writeback)
                MOV     PC,R14
; /E R0=size (0 for default)
;    R1=0 (for expansion, later used to point to more info)
; or to pass a taskhandle -
;    R0=size (0 for default)
;    R1=taskhandle to tie buffer to for autodelete (-1 for none)
;    R2=0 (for expansion, later used to point to more info)
;
; (optionally min and max length to buffer, flags)
; /X R0=handle or 0 for can't create (0 won't be returned as a valid handle,
;               so may be used to flag "no handle" in your code)
; Returns error if can't create (due to lack of memory probably)
.CreateBuffer   MOV     R10,R1
                MOV     R11,R14
]
IF countclientbuf% THEN
[OPTA%
                LDR     R14,[R12,#clbufcnt]
                ADD     R14,R14,#1
                STR     R14,[R12,#clbufcnt]
]
ENDIF
[OPTA%
                MOV     R1,R0
                MVN     R0,#NOT(-1)
                BL      newinst
                MOV     R1,R10
                TEQ     R0,#0
                LDRNE   R10,[R0,#buf]
                STRNE   R10,[R0,#cur]     ; Set cur pointer to top of buffer
                STRNE   R1,[R0,#cltaskh]
                MOVNE   PC,R11
                MOV     R14,R11
                B       noroomerror
; /E R0=handle
.DeleteBuffer   STMFD   R13!,{R14}
                ADD     R10,R12,#morebufs-next ; Nasty, eh?
.DBlp           MOV     R11,R10
                LDR     R10,[R11,#next]
                TEQ     R10,#0
                BEQ     DBbad
                TEQ     R10,R0
                BNE     DBlp
                LDR     R14,[R0,#next]    ; R0 points to instance to kill
                STR     R14,[R11,#next]   ; Unlink instance
                BL      freeinstance
                LDMFD   R13!,{PC}
.DBbad          BL      invalid_id
                LDMFD   R13!,{PC}
; /E R0=handle, R1=line no. (use R1=&7fffffff for end)
; -ve R1 means from end of buffer
; R1 = &80000001 for prev line
; R1 = &80000002 for next line
; R1 = &80000000 for prev line (wrap)
; R1 = &80000003 for next line (wrap)
.SetPos         STMFD   R13!,{R9,R14}
                MOV     R9,R0
                BL      validate_id
                LDMFD   R13!,{R9,R14}
                MOVVS   PC,R14
                BIC     R10,R1,#3
                TEQ     R10,#&80000000
                LDMIA   R0,{R10,R11,R12}  ; cur, buf, end
                ADDEQ   PC,PC,r1,LSL#2    ; MSB is lost...
                B       foo
                B       SetPos_decwr      ; Special case for prev line (wrap)
                B       SetPos_dec        ; Special case for prev line
                B       SetPos_inc        ; Special case for next line
                B       SetPos_incwr      ; Special case for next line (wrap)
.foo            CMN     R1,#-&7fffffff    ; Special case to save scanning
                BEQ     SetPos_end        ; whole buffer to find end
                MOVS    R10,R1
                BMI     SetPosneg
                ADD     R10,R1,#1
.SetPoslp
.SetPoslp2      LDRB    R12,[R11],#1
                CMP     R12,#13
                BGT     SetPoslp2         ; Skip a line
                SUBLT   R11,R11,#1
                BLT     SetPosDone
                SUBS    R10,R10,#1        ; EQ means zero means end of buffer
                BNE     SetPoslp          ; Otherwise decrement count
.SetPosDone     STR     R11,[R0,#cur]     ; And set cur
                MOV     PC,R14
;
.SetPosneg      STMFD   R13!,{r14}
                SUB     R12,R12,#1
.SetPosneglp    CMP     R12,R11           ; Check not start of buf
                BEQ     SetPosnegDone
.SetPosneglp2   LDRB    R14,[R12,#-1]!
                CMP     R14,#13
                BGT     SetPosneglp2      ; Skip a line
                ADDS    R10,R10,#1        ; EQ means zero means end of buffer
                BNE     SetPosneglp       ; Otherwise decrement count
                ADD     R12,R12,#1
.SetPosnegDone  STR     R12,[R0,#cur]     ; And set cur
                LDMFD   R13!,{PC}
;
; Set current position to end of buffer
.SetPos_end     SUB     R12,R12,#1
                STR     R12,[R0,#cur]     ; cur = end-1
                MOV     PC,R14
;
.SetPos_decwr   SUB     R10,R10,#1
                CMP     R10,R11           ; Check if already at start of buf
                SUBLS   R10,R12,#1        ; and wrap if we are
                STRLS   R10,[R0,#cur]     ; And set cur
                MOVLS   PC,R14
                ADD     R10,R10,#1
;
.SetPos_dec     SUB     R10,R10,#1        ; Check not already at start of buf
                CMP     R10,R11           ; If empty LO - EQ otherwise
                MOVLS   PC,R14
.SetPos_declp   LDRB    R12,[R10,#-1]!
                CMP     R12,#13
                BGT     SetPos_declp      ; Skip a line backwards
                ADD     R10,R10,#1
                STR     R10,[R0,#cur]     ; And set cur
                MOV     PC,R14
;
.SetPos_incwr   LDRB    R12,[R11]         ; Look at first byte
                TEQ     R12,#0            ; Give up if buffer empty
                MOVEQ   PC,R14
                LDRB    R12,[R10],#1
                TEQ     R12,#0
                ADDEQ   R10,R11,#1
                STREQ   R10,[R0,#cur]     ; And set cur
                MOVEQ   PC,R14
;
.SetPos_inc
.SetPos_inclp   LDRB    R12,[R10],#1
                CMP     R12,#13
                BGT     SetPos_inclp      ; Skip a line
                SUBLT   R10,R10,#1
                STR     R10,[R0,#cur]     ; And set cur
                MOV     PC,R14
]
IF debug% THEN
[OPTA%
; Do a recall on this buffer
.X              MOV     R11,R14
                MOV     R10,R9
                MOV     R9,R0
                BL      recallbuffer
                MOV     R9,R10
                MOV     PC,R11
]
ENDIF
[OPTA%
; /E R0=handle
; /X R1=line no.
.GetPos         STMFD   R13!,{R9,R14}
                MOV     R9,R0
                BL      validate_id
                LDMFD   R13!,{R9,R14}
                MOVVS   PC,R14
                MOV     R1,#0
                LDR     R12,[R0,#cur]
                LDR     R11,[R0,#buf]
                ADD     R11,R11,#1
                CMP     R11,R12
                MOVHS   PC,R14            ; Top of buffer - line 0
.GetPoslp
.GetPoslp2      LDRB    R10,[R11],#1
                CMP     R10,#32
                BGE     GetPoslp2         ; Skip a line
                ADD     R1,R1,#1          ; Increase count
                CMP     R11,R12
                BLO     GetPoslp          ; Loop if not there yet
                MOV     PC,R14
; /E R0=handle, R1->buffer, R2=buffer len
; /X R2=actual length
.GetLine        STMFD   R13!,{R9,R14}
                MOV     R9,R0
                BL      validate_id
                LDMFD   R13!,{R9,R14}
                MOVVS   PC,R14
                LDR     R11,[R0,#cur]
                MOV     R12,R1
.GetLinelp      SUBS    R2,R2,#1
                LDRGEB  R10,[R11],#1
                STRGEB  R10,[R12],#1
                CMPGE   R10,#32
                BGE     GetLinelp
                MOV     R2,#0
                STRB    R2,[R12,#-1]
                CMP     R10,#32
.GetLinelp2     LDRGEB  R10,[R11],#1
                CMPGE   R10,#32
                BGE     GetLinelp2
                LDR     R12,[R0,#cur]
                SUB     R2,R11,R12
                SUB     R2,R2,#1          ; Return actual length
                MOV     PC,R14
; /E R0=handle, R1->line (ctrl terminated)
.AppendLine     STMFD   R13!,{R6,R7,R9,R14}
                MOV     R9,R0             ; Fake up variables
                BL      validate_id
                MOVVC   R7,R1
                MOVVC   R6,#0
                BLVC    addnewhist
                LDMFD   R13!,{R6,R7,R9,PC}
; /E R0=handle
.DeleteLine     STMFD   R13!,{R9,R14}
                MOV     R9,R0             ; Fake up variables
                BL      validate_id
                LDRVC   R0,[R9,#cur]
                BLVC    delhistent
                LDMFD   R13!,{R9,PC}
; /E R0=task handle to read info for
; /X R0=length of line (or -1 for inactive ; -2 for taskwindow never seen)
;    R1=cursor posn in line
.ReadInfo       STMFD   R13!,{R2,R14}
;BL showregs
                SUB     R1,R12,#next-head ; Nasty, eh?
.richeckinstlp                            ; Check R0 against taskh of
                LDR     R1,[R1,#next]     ; each instance
                TEQ     R1,#0
                BEQ     richeckinstskip   ; Not one of my taskwindows
                LDR     R14,[R1,#taskh]
                TEQ     R0,R14
                BNE     richeckinstlp
                LDR     R0,[R1,#r7]
                TEQ     R0,#0
                MVNEQ   R0,#NOT(-1)
                LDMEQFD R13!,{R2,PC}
;BL showregs
                SUB     R2,R0,#1
.ristrlenlp     LDRB    R14,[R2,#1]!
                CMP     R14,#32
                BGE     ristrlenlp
;BL showregs
                SUB     R0,R2,R0
                LDR     R1,[R1,#r6]
                LDMFD   R13!,{R2,PC}
; not a valid task handle
.richeckinstskip
                MVN     R0,#NOT(-2)
                LDMFD   R13!,{R2,PC}
; /E R9=buffer ID
; /X Error if invalid
.validate_id    STMFD   R13!,{R14}
                ADD     R14,R12,#morebufs-next ; Nasty, eh?
._L1            LDR     R14,[R14,#next]
                CMP     R14,R9
                LDMEQFD R13!,{PC}
                TEQ     R14,#0
                BNE     _L1
                LDMFD   R13!,{R14}        ; fall through
.invalid_id     STMFD   R13!,{R14}
                ADR     R0,invalid_id_msg
                SWI     "XOS_GenerateError"
                LDMFD   R13!,{PC}
.invalid_id_msg & swichunk
                = "Invalid history buffer ID"+bl$
                ALIGN
; /E R1 = Free value, R2 = Total value
.docolumns      STMFD   R13!,{R0-R2,R14}
                SUB     R0,R2,R1          ; Used value
                MOV     R1,#8             ; Field width
                BL      outpadval
                SUB     R0,R2,R0          ; Free value (r1 on entry)
                BL      outpadval
                MOV     R0,R2             ; Total value
                BL      outpadval
                SWI     XOS_NewLine
                LDMFD   R13!,{R0-R2,PC}

; Module initialisation
.init           STMFD   R13!,{R10,R14}
                MOV     r0,r10
]
IF NOT ROM% THEN
[OPT A%
                BL      start
                STMFD   R13!,{R0-R4}
]
ENDIF
[OPT A%
                MOV     R5,R12
                LDR     R12,[R12,#0]
]
IF NOT RISCOS311% THEN
[OPT A%
                BL      alloc_init        ; Attempt to set up a dynamic area
]
ENDIF
[OPT A%
                BL      claimspace
]
IF ROM% THEN
[OPT A%
                BVS     initfail2
]
ELSE
[OPT A%
                ADDVS   R13,R13,#20
                LDMVSFD R13!,{R10,PC}
]
ENDIF
[OPT A%
                BL      claimreadlinev
                BVS     initfail
                BL      findkmod ; for command completion
                MOV     R0,#1
                SWI     "XOS_InstallKeyHandler"
                CMP     R0,#1
                MOVNE   R0,#2
                STR     R0,[R12,#kbdtype]
]
IF ROM% THEN
[OPT A%
                MOV     R0, #0
                MOV     R1, #0
                MOV     R2, #0
                MOV     R3, #0
                MOV     R4, #&100
]
ELSE
[OPT A%
                LDMIA   R13!,{r0-r4}
]
ENDIF
[OPT A%
                BL      le_setopts
                LDMFD   R13!,{R10,PC}
.initfail
]
IF ROM% THEN
[OPT A%
                MOV     R10,#1
                BL      finalise
.initfail2
                SUBS    R0, R0, R0      ; clear V
                LDMFD   R13!,{R10,PC}
]
ELSE
[OPT A%
                STR     R0,[R13,#16]!
                MOV     R10,#1
                BL      finalise
                LDMFD   R13!,{R0}
                SWI     "XOS_GenerateError"
                LDMFD   R13!,{R10,PC}
; /E R0 -> command line (*¬* incl. modulename?)
.start          STMFD   R13!,{r0-r4,r14}
                MOV     r1,#0
                MOV     r2,#0
                MOV     r3,#0
                MOV     r4,#0
                MOV     r14,#&100 ;ins flash/under; over flash/block
                STMIA   R13,{r1-r4,r14}
                SUB     R1,R0,#1
.startlp        LDRB    R2,[R1,#1]!
                CMP     R2,#32
                BEQ     startlp
                LDMLTFD R13!,{r0-r4,pc}
                MOV     R0,#1<<31          ; Check terminated by spc or ctrl
                SWI     "XOS_ReadUnsigned"
                STRVC   r2,[R13]
                SWIVC   "XOS_ReadUnsigned"
                STRVC   r2,[R13,#4]
                SWIVC   "XOS_ReadUnsigned"
                STRVC   r2,[R13,#8]
                SWIVC   "XOS_ReadUnsigned"
                STRVC   r2,[R13,#12]
                SWIVC   "XOS_ReadUnsigned"
                STRVC   r2,[R13,#16]
                LDMFD   R13!,{r0-r4,pc}
]
ENDIF
[OPT A%
; Free buffers of instance and then instance block itself
; NB note down the next pointer *before calling* this routine!
; /E R0->instance ; HACKHACKHACK
.freeinstance   STMFD   R13!,{R0-R1,R14}
                MOV     R1,R0
                LDR     R0,[R1,#fkeybuf]
                BL      free              ; Free fkey buffer (if any)
                LDR     R0,[R1,#yankbuf]
                BL      free              ; Free yank buffer (if any)
                LDR     R14,[R1,#taskh]
                CMN     R14,#-(-1)        ; Client buffer, so *do* free
]
IF countclientbuf% THEN
[OPTA%
                LDREQ   R14,[R12,#clbufcnt]
                SUBEQ   R14,R14,#1
                STREQ   R14,[R12,#clbufcnt]
]
ENDIF
[OPTA%
                LDRNE   R14,[R12,#flags]
                EORNE   R14,R14,#f_LocalHist ; !HACK! !HACK! !HACK!
                TSTNE   R14,#f_LocalHist  ; NE => Global history
                LDRNE   R14,[R12,#head]
                TEQNE   R14,#0            ; NE => Global history & more inst
                LDREQ   R0,[R1,#buf]
                BLEQ    free
                MOV     R0,R1
                BL      free              ; Free instance
                LDMFD   R13!,{R0-R1,PC}
; Module finalisation - relase workspace & vector and restore cursor
; /E R10 = 0 => non-fatal, 1 => fatal, R12 -> priv word, sp(R13) -> SVC stack
; /X May corrupt R0-R6, R12, R14, flags
.finalise       MOV     R6,R14
                MOV     R5,R12
                LDR     R12,[R12,#0]
                TEQ     R10,#0
                BEQ     finalnonfatal
                LDR     R14,[R12,#morebufs]
                TEQ     R14,#0            ; Refuse to die if my clients
                BNE     dontdie           ; still need me
]
IF countclientbuf% THEN
[OPTA%
                LDR     R14,[R12,#clbufcnt]
                TEQ     R14,#0
                BNE     dontdie
]
ENDIF
[OPTA%
                LDR     R0,[R12,#head]    ; Fatal finalisation
                MOVS    R2,R0
                BEQ     freechainend      ; If no instances!
; !HACK! (not really) (cur==0)
.checkchainlp   LDR     R14,[R2,#cur]     ; Check - no active instances?
                TEQ     R14,#0
                BNE     dontdie
                LDR     R2,[R2,#next]
                TEQ     R2,#0
                BNE     checkchainlp
.freechainlp    LDR     R2,[R0,#next]
                STR     R2,[R12,#head]    ; Unlink next instance
                BL      freeinstance
                MOVS    R0,R2
                BNE     freechainlp
.freechainend   MOV     R0,R12            ; R12 = [privword]
                BL      free              ; Free all workspace
                STR     R0,[R5]           ; R5 = R12 on entry
]
IF NOT RISCOS311% THEN
[OPT A%
                BL      alloc_final
]
ENDIF
[OPT A%
.finalnonfatal  BL      relreadlinev
                MOV     PC,R6

.dontdie        ADR     R0,dontdiemsg
                SWI     "XOS_GenerateError"
                MOV     PC,R6

.dontdiemsg     & 0
                = prog$+" in use"+bl$
                ALIGN

.freetaskh      STMFD   R13!,{R0,R2-R3,R14}
                LDR     R2,[R12,#head]
                SUB     R3,R12,#next-head
.freethchainlp  MOVS    R0,R2             ; End of list?
                LDMEQFD R13!,{R0,R2-R3,PC}
                LDR     R2,[R0,#next]
                LDR     R14,[R0,#taskh]
                TEQ     R14,#0            ; Don't free the command line one
                MOVEQ   R3,R0
                STRNE   R2,[R3,#next]     ; If taskwindow, unlink instance
                BLNE    freeinstance      ; and free it
                B       freethchainlp
.servicetable   & 0                 ; RO4-format service call table
                & serviceaccept
                & &27               ; Service_Reset
                & &53               ; Service_WimpCloseDown
                & 0
                & servicetable
; /E R1 = Service call number
.servicecall    MOV     R0,R0
                TEQ     R1,#&53           ; Service_WimpCloseDown
                TEQNE   R1,#&27           ; Service_Reset
                MOVNE   PC,R14
.serviceaccept  STMFD   R13!,{R0-R1,R5,R14}
                MOV     R5,R12
                LDR     R12,[R12,#0]
                TEQ     R1,#&53           ; Service_WimpCloseDown
                BEQ     service_wimpclosedown
                TEQ     R12,#0            ; Must be Service_Reset
                BEQ     serviceaccept_claimspace
                BL      freetaskh
                BL      claimreadlinev
                LDMFD   R13!,{R0-R1,R5,PC}
.serviceaccept_claimspace
                BL      claimspace
                BL      claimreadlinev
                LDMFD   R13!,{R0-R1,R5,PC}
                ;
.service_wimpclosedown
; /E R0=0 for Wimp_CloseDown, >0 for Wimp_Init. in domain, R2 = taskhandle
; NB if R0<>0, then Wimp_Init may get blocked (eg *StartTask in taskwindow)
; (Is this right? I think Taskwindow should block Wimp_Init... !HACK!)
                TEQ     R0,#0
                LDMNEFD R13!,{R0-R1,R5,PC}
                SUB     R0,R12,#next-head ; Nasty, eh?
.checkinstlp    MOV     R1,R0             ; Check R2 against taskh of
                LDR     R0,[R1,#next]     ; each instance
                TEQ     R0,#0
                BEQ     checkinstskip     ; Not one of my taskwindows
                LDR     R14,[R0,#taskh]
                TEQ     R2,R14
                BNE     checkinstlp
                LDR     R14,[R0,#next]    ; R0 now points to instance to kill
                STR     R14,[R1,#next]    ; Unlink instance
                BL      freeinstance
                ;                         ; Now check client buffers
.checkinstskip  ADD     R0,R12,#morebufs-next ; Nasty, eh?
.checkinstlp2   MOV     R1,R0             ; Check R2 against taskhandle of
.checkinstmore  LDR     R0,[R1,#next]     ; each client
                TEQ     R0,#0
                LDMEQFD R13!,{R0-R1,R5,PC} ; Nope
                LDR     R14,[R0,#cltaskh]
                TEQ     R2,R14
                BNE     checkinstlp2
                LDR     R14,[R0,#next]    ; R0 now points to instance to kill
                STR     R14,[R1,#next]    ; Unlink instance
                BL      freeinstance
                B       checkinstmore     ; Keep going in case there's more
; /E R0 = char
.writec         STMFD   R13!,{R14}
                TST     R8,#fPasswd
                LDRNE   R0,[R9,#pchar]
                SWI     XOS_WriteC
                LDMFD   R13!,{pc}
; /E R0 -> history entry
; Contents of linebuffer are cleared, history entry is copied into
; linebuffer, redisplayed and the cursor put at the end
.fetchhist      STMFD   R13!,{R0,R1,R14}
                STR     R0,[R9,#cur]      ; Set current history pointer
                BL      clearline
                MOV     R6,#0
                MOV     R1,R0
.fetchhistlp    TEQ     R6,R10            ; Truncate if recalled line
                LDRNEB  R0,[R1],#1        ; would overfill buffer
                TEQNE   R0,#0             ; and change zero to CR
                MOVEQ   R0,#13
                STRB    R0,[R7,R6]
                TEQ     R0,#13
                ADDNE   R6,R6,#1
                LDMEQFD R13!,{R0-R1,PC}
                BL      writec
                B       fetchhistlp

.updatecursor   STMFD   R13!,{R0,R14}
                LDR     R0,[R12,#cursors]
                TST     r8,#fOver%
                MOVNE   R0,R0,LSR #8
                AND     R0,R0,#3
                BL      setcursorshape
                LDMFD   R13!,{R0,PC}
; Erase entire line and leave cursor at start
; /X R6 = 0, R11 = 0, modified flag cleared

.clearline      STMFD   R13!,{R0,R14}
                BL      gotoend
.clearlinelp    BL      del
                BNE     clearlinelp
                MOV     R11,#0            ; Put mark at start too
                MOV     R14,#13
                STRB    R14,[R7]
                BIC     r8,r8,#fEdit%     ; Clear modified flag
                LDMFD   R13!,{R0,PC}
; Load R0 with character at current cursor position and
; check if it is a character marking a break between words
; /X R0 = char, Eq => break, Gt => non-break char, Lt => End of line
.ldrr0testbreak LDRB    R0,[R7,R6]
;
; Check if R0 is a character marking a break between words
; /E R0 = char; /X Eq => break, Gt => non-break char, Lt => End of line
.testbreak      CMP     R0,#ASC" "
                TEQGT   R0,#ASC"("
                TEQGT   R0,#ASC")"
                MOV     PC,R14
; /E R7->linebuffer
;    R8=(minchar<<24)+maxchar+flags in bits 8-23 (only fCopy% on entry)
;    R9->current instance pointer
;    R10=maxlength
; Additionally, in routine
;    R6=current cursor posn
;    R11=position of mark
;    R5 is unused
; /X R6=length of line, R8 contains updated flags
.dolineedit     STMFD   R13!,{R0-R4,R11,R14}
                BIC     r8,r8,#(fAll%ANDNOTfCopy%); clear all flgs bar fCopy
                LDR     R14,[R12,#flags]  ; Set fOver if overtype mode on
                TST     R14,#f_DfltOver   ; by default
                ORRNE   r8,r8,#fOver%
                MVN     R14,#NOT(-1)      ; Set current ptr for this instance
                STR     R14,[r9,#cur]     ; to the bottom
                STR     R14,[R9,#match]   ; No page-up active
                TEQ     R4,#0
                MOVEQ   R4,#256           ; null printout if password bit set
                CMP     R4,#127
                CMPNE   R4,#32
                MOVLS   R4,#ASC"-"
                STR     R4,[R9,#pchar]
                BL      updatecursor      ; Sort out cursor shape
                MOV     R6,#0             ; Current cursor posn
                STR     R6,[R9,#compcontext]; Not completing filename
                BL      free_cmdtree      ; Or command
                MOV     R11,#0            ; Current mark posn
                MOV     R0,#13            ; Buffer empty initially
                STRB    R0,[R7]
.nextchar       BIC     R8,R8,#fShowComp OR fCompRev OR fTcsh
                LDR     R1,[R9,#fkeybuf]  ; Are we in the middle of expanding
                TEQ     R1,#0             ; a function key?
                BNE     fnkeyexpand
                STR     R6,[R9,#r6]
                STR     R7,[R9,#r7]
                MOV     R0,#216
                MOV     R1,#0
                MOV     R2,#&FF           ; See if the OS is doing an Fkey
                SWI     XOS_Byte          ; expansion and if so, don't try
                SWI     XOS_ReadC         ; and work out a Zap keycode
                BCS     badreadc
                TEQ     R1,#0
                BNE     vanilla
                MOV     R4,R0
                MOV     R0,#198
                MOV     R1,#0
                MOV     R2,#&FF           ; See if the OS is reading from a
                SWI     XOS_Byte          ; *Exec file and if so, don't try
                TEQ     R1,#0             ; and work out a Zap keycode
                MOV     R0,R4             ; NB for some reason this test
                BNE     vanilla           ; doesn't work in a TaskWindow (on
                                          ; a Risc PC anyway)
                BL      checkmodkeys
                MOVEQ   R3,#%1000         ; lowest 4 bits are ~s~csc
                MOVNE   R3,#%0010
                ORRCC   R3,R3,#%0100
                ORRCS   R3,R3,#%0001
                MOV     R0,#122
                SWI     XOS_Byte          ; /X R1 = intl. key # or &FF
                MOVS    R0,R4             ; Extended key code ?
                BEQ     extended
                CMP     R0,#32
                BGT     gt32
                TSTEQ   R3,#%0100
                MOVEQ   R0,#0             ; cSpace -> &000
                BEQ     doshift           ; scSpace -> &100
                TEQ     R1,#47            ; '<-|'
                MOVEQ   R0,#&1C
                CMP     R0,#10
                BGE     gt9
.le9            ADR     R14,ntab
                LDRB    R14,[R14,R0]
                TEQ     R14,R1
                ADDEQ   R0,R0,#&100+ASC"0"
                BEQ     widget
.gt9            CMP     R0,#13
                BEQ     cr
                CMP     R0,#27
                BLT     skippy
                LDR     R14,[R12,#kbdtype]
                TEQ     R14,#1
                ADREQ   R14,ctab_arc-27
                ADRNE   R14,ctab_rpc-27
                LDRB    R14,[R14,R0]
                TEQ     R14,R1
                BNE     skippy
.unskippy       TEQ     R0,#30
                ADDNE   R0,R0,#&2B-27
                MOVEQ   R0,#&36
.skippy         TEQ     R0,#0             ; &132 is Zap code for c2 (ctrl @)
                MOVEQ   R0,#&32           ; NB c0 returns &00 too
.backin         CMP     R0,#32            ; Orr &100 if >32
                BGT     orrinstr
.doshift        TST     R3,#2             ; Orr &100 if Shifted
                BEQ     decoded
.orrinstr       ORR     R0,R0,#&100
                CMP     R0,#&120
                RSBGTS  R14,R0,#&140
                BLE     decoded
.widget         TST     R3,#2
                ADDNE   R0,R0,#&020
                B       decoded
.cr             TEQ     R1,#73            ; 'Return'
                MOVEQ   R0,#&1D
                TEQ     R1,#60            ; 'kEnter'
                BNE     doshift
                MOV     R2,#&66
                B       kpadenter
.stab          := 91 ; k*
                = 58 ; k+
                =  0 ; dummy to allow for ,
                = 59 ; k-
                = 76 ; k.
                = 74 ; k/
.stab2         := &62
                = &65
                = 0
                = &64
                = &67
                = &61
                ALIGN
.kpadsym
                ADR     R2,stab2-42
                SUB     R14,R2,#stab2-stab
                LDRB    R14,[R14,R0]
                LDRB    R2,[R2,R0]
.kpadnotnum     TEQ     R14,R1
                BNE     decoded
.kpadenter      ADD     R0,R2,#&100
                TEQ     R3,#%1001         ; c
                SUBEQ   R0,R0,#&040
                TEQ     R3,#%0110         ; s
                ADDEQ   R0,R0,#&010
                TEQ     R3,#%0011         ; sc
                SUBEQ   R0,R0,#&020
                B       decoded
.deletekey      TST     R3,#1             ; Ctrl-Delete
                MOVNE   R0,#&1F
                B       doshift
.gt32           CMP     R0,#&7F
                BEQ     deletekey
                TEQ     R0,#ASC","
                BEQ     decoded
                TEQ     R0,#ASC"#"
                MOVEQ   R14,#90
                MOVEQ   R2,#&63
                BEQ     kpadnotnum
                CMP     R0,#42            ; "*"
                RSBGES  R14,R0,#47        ; "/"
                BGE     kpadsym
.number         CMP     R0,#ASC"0"
                RSBGES  R14,R0,#ASC"9"
                BLT     notdigit
                ADR     R14,ktab-ASC"0"
                LDRB    R14,[R14,R0]
                TEQ     R14,R1
                BEQ     kpadnum
                LDR     R14,[R12,#osver]
                CMP     R14,#&A3          ; What does 3.00 do? !HACK!
                BGE     notdigit
                TST     R3,#1             ; Catch RISC OS 2 Ctrl-<digit>
                ADDNE   R0,R0,#&130-ASC"0"
                TSTNE   R3,#%10           ; Shift? !HACK! Test me!
                ADDNE   R0,R0,#&20
                B       notdigit
;
.kpadnum        ADD     R0,R0,#&1C0-ASC"0"
                TST     R3,#1
                ADDNE   R0,R0,#&20        ; Add &20 for control
                TST     R3,#%10
                ADDNE   R0,R0,#&10        ; Add &10 for shift
.notdigit       TEQ     R1,#89            ; 'Delete'
                MOVEQ   R0,#&1C
                BNE     decoded
                TST     R3,#1
                MOVNE   R0,#&1F
                TSTNE   R3,#3
                MOVNE   R0,#&7F
                B       decoded
.ntab          :=  39 ; 0
                =  48 ; 1
                =  49 ; 2
                =  17 ; 3
                =  18 ; 4
                =  19 ; 5
                =  52 ; 6
                =  36 ; 7
                =  21 ; 8
                =  38 ; 9
.ktab          := 106 ; k0
                = 107 ; k1
                = 124 ; k2
                = 108 ; k3
                = 122 ; k4
                = 123 ; k5
                =  26 ; k6
                =  27 ; k7
                =  42 ; k8
                =  43 ; k9
= "PAD" ; so ctab-27 is a multiple of four!
.ctab_arc      :=  56 ; '['
                = 120 ; '\'
                =  88 ; ']'
                =  24 ; '^'
                =  23 ; '_'
= "PAD" ; so ctab-27 is a multiple of four!
.ctab_rpc      :=  56 ; '['
                =  94 ; '\'
                =  88 ; ']'
                =  24 ; '^'
                =  23 ; '_'
                ALIGN
.extended
                SWI     XOS_ReadC
                BCS     badreadc
                MOVS    R4,R0
                BEQ     le9
                ORR     R0,R0,#&100
                BIC     R14,R0,#&130
                TEQ     R14,#&8E
                TEQEQ   R1,#78
                EOREQ   R0,R0,#&50        ; Page Down
                TEQ     R14,#&8F
                TEQEQ   R1,#63
                EOREQ   R0,R0,#&50        ; Page Up
                BIC     R14,R0,#&30
                SUB     R14,R14,#&1C0
                CMP     R14,#2            ; Logo or Menu keys?
                BHS     decoded           ; ... no
                TST     R0,#&10           ; convert to internal key number
                ORRNE   R0,R0,#4
                TST     R0,#&20
                BIC     R0,R0,#&F0
                ORRNE   R0,R0,#&10
                ORR     R0,R0,#&68
                TEQ     R1,#126           ; Is it the right-hand Logo key?
                ADDEQ   R0,R0,#2          ; If so, tweak the key code
.decoded
                FNADRL(14,jmptab)
                LDRB    R1,[R14,R0]
                MOV     R0,R4             ; For vanilla, etc
                ADR     R14,nextchar      ; Setup return address in SVC mode
                ADD     PC,PC,R1,ASL#2
.keyvar        := "key$"            ; Padding word needed anyway
.base
.fileropen      TST     R8,#fPasswd
                BEQ     canon
                MOV     PC,R14
; /X EQ iff already at start of line
.left           TST     R8,#fPasswd
                MOVNE   PC,R14
                STMFD   R13!,{R14}
                TEQ     R6,#0             ; At start of line ?
                BLNE     _left            ; If not, move cursor left
                LDMFD   R13!,{PC}
; /X EQ iff already at end of line
.right          TST     R8,#fPasswd
                MOVNE   PC,R14
                STMFD   R13!,{R0,R14}
                LDRB    R0,[R7,R6]
                TEQ     R0,#13            ; At end of line ?
                BLNE    _right            ; If not, move cursor right
                LDMFD   R13!,{R0,PC}
; Move cursor to the end of the line
; /X R6 = length of line
.cright
.gotoend        TST     R8,#fPasswd
                MOVNE   PC,R14
                STMFD   R13!,{R14}
.gotoendlp      BL      right             ; Returns EQ iff already at end
                BNE     gotoendlp
                LDMFD   R13!,{PC}
; Move cursor to start of the line
; /X R6 = 0
.cleft
.gotostart      TST     R8,#fPasswd
                MOVNE   PC,R14
                STMFD   R13!,{R14}
.gotostartlp    BL      left
                BNE     gotostartlp
                LDMFD   R13!,{PC}
; Goto to the start of the next word (spaces separate words)
; /X R6 changed
.sright
.nextword       TST     R8,#fPasswd
                MOVNE   PC,R14
                STMFD   R13!,{R0,R14}
.nextwordlp     BL      ldrr0testbreak    ; Find first break to the right
                BLLE    nextwordlp2
                BL      _right
                B       nextwordlp
.nextwordlp2    BLEQ    ldrr0testbreak    ; Find first non-space to right
                LDMNEFD R13!,{R0,PC}
                BL      _right            ; or end of line
                B       nextwordlp2
; Goto to the space after end of the previous word (spaces separate words)
; /X R6 changed
.sleft
.prevword       TST     R8,#fPasswd
                MOVNE   PC,R14
                STMFD   R13!,{R0,R14}
.prevwordlp     BL      left              ; Find first space to the left
                LDRNEB  R0,[R7,R6]        ; or start of line if no spaces
                BLNE    testbreak
                BNE     prevwordlp
.prevwordlp2    TEQ     R6,#0             ; Find first non-space to left
                LDMEQFD R13!,{R0,PC}      ; or start of line if all spaces
                ADD     R1,R7,R6
                LDRB    R0,[R1,#-1]       ; Check char to cursor left
                BL      testbreak
                LDMNEFD R13!,{R0,PC}
                BL      _left             ; If it's a space, move left and
                B       prevwordlp2       ; try again
.toggleinsert   TST     R8,#fPasswd
                EOREQ   r8,r8,#fOver%     ; Toggle overtype flag
                BEQ     updatecursor      ; R14 is set to nextchar
                MOV     PC,R14
; Remove current line from history (if not at end)
.removeline     TST     R8,#fPasswd
                MOVNE   PC,R14
                LDR     R0,[r9,#cur]
                CMN     R0,#-(-1)
                BLNE    delhistent        ; r0 points to line to delete
;
.delline        BL      clearline         ; Ctrl-U means clear displayed line
                BL      modified
;
.ignore         B       nextchar
.showcomp       TST     R8,#fPasswd
                ORREQ   R8,R8,#fShowComp
                BEQ     completefnm       ; R14 is set to nextchar
                MOV     PC,R14
.completeshow
.dotcshcompshow ORR     R8,R8,#fTcsh OR fShowComp
.complete
.dotcshcomp     ORR     R8,R8,#fTcsh
.completenext
.docompletion   B       completefnm       ; R14 is set to nextchar
.completeprev   TST     R8,#fPasswd
                ORREQ   R8,R8,#fCompRev   ; (4DOS &) backwards
                BEQ     completefnm       ; R14 is set to nextchar
                MOV     PC,R14
.setmark        TST     R8,#fPasswd
                MOVNE   PC,R14
                MOV     R11,R6
.beepignore     B       beep              ; R14 is set to nextchar
; Allowing COPYing is probably bad news in a Taskwindow, so only allow this
; if cursor key state was *FX4,0 on entry. NB Zap takes over COPYing in its
; Taskwindows, so it works fine and we never get here.
.copy           TST     r8,#fCopy%        ; Allow screen COPYing iff entered
                BEQ     nextchar          ; with *FX4,0
                EOR     r8,r8,#fCopying   ; Toggle fCopying and *FX4 state
.copyjoin       TST     r8,#fCopying
                MOVNE   R1,#0             ; *FX4,0 for copying
                MOVEQ   R1,#2             ; *FX4,2 for not copying
                MOV     R0,#4
                SWI     XOS_Byte          ; Do *FX4,x (corrupts r1,r2)
                BNE     nextchar
                BL      joincopycursors
                BL      updatecursor      ; If we stopped, reset cursor shape
                B       nextchar
; Exchange mark with cursor
.swapmark
.swapmarkcursor TST     R8,#fPasswd
                MOVNE   PC,R14
                STMFD   R13!,{R1,R14}
                MOV     R1,R6
.swapmarklp     CMP     R6,R11            ; Which way do we go?
                MOVEQ   R11,R1
                LDMEQFD R13!,{R1,PC}
                BLT     swapmark_right
                BL      _left
                B       swapmarklp
.swapmark_right BL      _right
                B       swapmarklp
.deltoend
.killeol        B       killeolind
; Delete region between mark and cursor
.cut
.wipe           B       __wipe
; Corrupts r0-r2
.delword        TST     R8,#fPasswd
                MOVNE   PC,R14
                MOV     R2,R6
.delwordlp      BL      ldrr0testbreak
                ADDEQ   R6,R6,#1
                BEQ     delwordlp         ; Delete until non-break reached
.delwordlp2     BL      ldrr0testbreak
                ADDGT   R6,R6,#1
                BGT     delwordlp2        ; Delete until break or eol found
                SUBS    R1,R6,R2
                MOV     R6,R2
                B       jointstuff
; Suck the tail of the line one char to the left
.deletenext
.deleteright
.suckuptail     TST     R8,#fPasswd
                MOVNE   PC,R14
                STMFD   R13!,{R0,R14}
                LDRB    R14,[R7,R6]
                TEQ     R14,#13
                LDMEQFD R13!,{R0,PC}
                CMP     R6,R11
                SUBLT   R11,R11,#1        ; Adjust posn of mark
                ADD     R0,R7,R6
.suckuptaillp   LDRB    R14,[R0,#1]!      ; Move any chars to the right of
                STRB    R14,[R0,#-1]      ; cursor down one byte in memory
                TEQ     R14,#13
                BNE     suckuptaillp
; R0 must be non-zero here
                BL      redrawtail
                LDMFD   R13!,{R0,PC}
.delete
.deleteleft     LDRB    R0,[R7,R6]
                BL      del
                BEQ     nextchar          ; Ignore if at start of line
                BL      modified
                TEQ     R0,#13            ; Put in new CR if the cursor was
                STREQB  R0,[R7,R6]        ; at the end of the line
                BEQ     nextchar          ; and exit
                TST     r8,#fOver%        ; Overtype mode ?
                MOVNE   R0,#ASC" "        ; Store a space, unlike RKL
                STRNEB  R0,[R7,R6]
                BLEQ    suckuptail        ; Insert mode is pretty simple
                B       nextchar
.wipehistory    BL      erasethisbuf
.erasebufjoin   BL      clearline         ; Clear line
                B       nextchar
.wipeallhistory BL      eraseallbufs
                B       erasebufjoin
.paste
.yank           TST     R8,#fPasswd
                MOVNE   PC,R14
                LDR     R1,[R9,#yankbuf]
                TEQ     R1,#0             ; See if there's anyting to yank
.yanklp         LDRNEB  R0,[R1],#1
                CMPNE   R0,#31
                BLE     nextchar
                BL      printins
                B       yanklp
;!HACK! what about the mark?  This works like Zap does...
.swapchars
.transpose      B       __transpose
.quote          SWI     XOS_ReadC
                BCS     badreadc
                TEQ     R0,#0
                BNE     vanilla
                SWI     XOS_ReadC
                BCS     badreadc
                TEQ     R0,#0
                BNE     nextchar          ; Ignore extended key codes
; Treat key press as old OS_ReadLine would
.vanilla        CMP     R0,#13            ; Ctrl-M ?
                BEQ     enter             ; Put in history
                CMP     R0,#10            ; Ctrl-J ?
                BEQ     return            ; Don't put in history
                CMP     R0,#ASC"U"-64     ; Ctrl-U ?
                BEQ     delline
                CMP     R0,#&1B           ; ESCAPE hit ?
                BEQ     escape
                TEQ     R0,#8             ; Ctrl-H or Ǒ?
                TEQNE   R0,#127
                BEQ     deleteleft
                CMP     R0,#ASC" "        ; Don't put ctrl-chars in buffer -
                BLO     outctrlchar       ; just echo them (like OS_ReadLine)
                BL      printable
                B       nextchar
; /X corrupts R0
.cup
.oldesthist     B       __cup
; CTRL-Down Cursor hit - retrieve most recent history line; corrupts r0,r1
.cdown
.latesthist     B       __cdown
;corrupts r0,r1
.up
.uphistreq      TST     R8,#fPasswd
                MOVNE   PC,R14
                BL      addnewhistifmod   ; Retrieve next oldest history line
                LDR     R0,[R9,#cur]
                CMN     R0,#-(-1)
                LDREQ   R0,[R9,#end]      ; cur=-1 => at end
                SUB     R0,R0,#1
                LDR     R1,[R9,#buf]
                CMP     R0,R1             ; Patched in 2.53a
                BLS     go_blankgap
.uphistreqlp    LDRB    R14,[R0,#-1]!
                TEQ     R14,#13
                BNE     uphistreqlp
                ADD     R0,R0,#1
                BL      fetchhist
                B       nextchar
.go_blankgap    BL      dispblankgap      ; Patched in 2.53a
                B       nextchar          ; Patched in 2.53a
; /X corrupts R0
.down
.downhistreq    TST     R8,#fPasswd
                MOVNE   PC,R14
                BL      addnewhistifmod   ; Retrive next most recent history
                LDR     R0,[R9,#cur]      ; line
                CMN     R0,#-(-1)         ; If we're displaying a blank line,
                BEQ     oldesthist        ; then wrap around
.downhistreqlp  LDRB    R14,[R0],#1       ; Scan to end of current
                CMP     R14,#13           ; history line
                BGT     downhistreqlp
                BLT     go_blankgap       ; If last entry then display blank
                BL      fetchhist         ; Retrieve the entry
                B       nextchar
.sup
.uphistmatch    TST     R8,#fPasswd
                BEQ     uphistmatchsub
                MOV     PC,R14
.sdown
.dnhistmatch    TST     R8,#fPasswd
                BEQ     dnhistmatchsub
                MOV     PC,R14
.badreadc                                 ; Here for now...
.escape         TST     r8,#fCopying
                ORREQ   r8,r8,#fEsc%      ; Set ESCAPE flag
                BEQ     esc_gotoend
                MOV     R0,#124
                SWI     XOS_Byte
.uncopy         BIC     r8,r8,#fCopying
                B       copyjoin
.esc_gotoend    BL      gotoend
                B       leaveedit
.enter          TST     R8,#fPasswd
                BNE     common
                BL      checkevents
                BL      striptildes
                BL      addnewhist
                B       common
.return         TST     R8,#fPasswd
                BNE     common
                BL      checkevents
                BL      striptildes
.common         BL      gotoend           ; Goto end of line
                SWI     XOS_NewLine       ; Print a newline
.leaveedit      LDR     R14,[R9,#taskh]   ; Copy taskh to flag the "current"
                STR     R14,[R12,#lastth] ; buffer in *Recall and *EdStatus
                LDMFD   R13!,{R0-R4,R11,PC}
; f0 ... f9 or f10 ... f12 - lower nybble is assumed to be fkey number
.fnkey          AND     R0,R0,#&0F        ; Only want bottom nybble
                CMP     R0,#10
                ADDLT   R2,R0,#ASC"0"     ; R2 = -"n" for F<n> (n a digit)
                ADDGE   R2,R0,#ASC"0"-10  ; R2 = -"n" for F1<n> (n a digit)
                MOVGE   R2,R2,ASL #8      ; then R2 = (R1<<8)+-"1"
                ADDGE   R2,R2,#ASC"1"
; !HACK! what if expansion already in progress??? Possible?
; abandon it is the current approach
                LDR     R0,[R9,#fkeybuf]
                TEQ     R0,#0
                MOVEQ   R0,#(fkeybuff_len+8)
                BLEQ    malloc
                TEQ     R0,#0
                BEQ     beep_nextchar     ; If malloc failed, beep & ignore
                STR     R0,[R9,#fkeybuf]
                ADD     R1,R0,#8
                LDR     R0,keyvar
                STMFD   R13!,{R0,R2}      ; Stick Key$<number> on the stack
                MOV     R0,R13
                MOV     R2,#fkeybuff_len
                MOV     R3,#0
                MOV     R4,#3             ; Return expanded as string
                SWI     "XOS_ReadVarVal"  ; Read fnkey defn
                ADD     R13,R13,#8          ; Restore stack pointer
                MOVVS   R2,#0             ; If error, fake 0 bytes read
                TEQ     R2,#0
                ADDNE   R3,R1,R2
                SUBNE   R3,R3,#1
                STRNE   R3,[R1,#-8]       ; Ptr to last char
                STRNE   R2,[R1,#-4]       ; Characters left in buffer
                BNE     nextchar
                SUB     R0,R1,#8          ; If no fnkey defn, free the buffer
                BL      free              ; and bail out
                STR     R0,[R9,#fkeybuf]
                B       nextchar
.beep_nextchar  BL      beep
                B       nextchar

.__transpose    TST     R8,#fPasswd
                MOVNE   PC,R14
                LDRB    R0,[R7,R6]
                TEQ     R0,#13            ; Check not on last char
                BEQ     nextchar
                BLNE    left              ; Check not on first char
                LDRB    R1,[R7,R6]
                STRB    R0,[R7,R6]
                BL      writec
                MOV     R0,R1
                BL      writec
                ADD     R6,R6,#2
                BL      _left
                STRB    R1,[R7,R6]
                B       nextchar
.__wipe         TST     R8,#fPasswd
                MOVNE   PC,R14
                CMP     R6,R11            ; If cursor to right of mark, swap
                BLGT    swapmark          ; them
                SUBS    R1,R11,R6         ; Amount to delete
.jointstuff     BEQ     nextchar          ; If none, give up
                BL      mallocyank        ; malloc R1+1 and return ptr in R0
.wipelp         LDRB    R14,[R7,R6]       ; Copy into yank buffer
                STRB    R14,[R0],#1
                BL      suckuptail
                SUBS    R1,R1,#1
                BNE     wipelp
                STRB    R1,[R0]           ; Terminate with zero byte
                B       nextchar
.__cup          TST     R8,#fPasswd
                MOVNE   PC,R14
                BL      addnewhistifmod   ; Ctrl-Up Cursor hit
                LDR     R0,[R9,#buf]
                LDRB    R14,[R0],#1
                TEQ     R14,#0            ; Check history not empty
                LDRNE   R14,[R9,#cur]
                TEQNE   R0,R14
                STRNE   R0,[R9,#cur]      ; Move to top
                BLNE    fetchhist         ; Only display if different
                B       nextchar
.__cdown        TST     R8,#fPasswd
                MOVNE   PC,R14
                LDR     R0,[R9,#cur]      ; Start from current posn, checking
                LDR     R14,[R9,#end]     ; we're not already at the bottom
                SUB     R14,R14,#2        ; CDOWN on typed line should be nop
                CMP     R14,R0
                BLO     nextchar          ; NB Unsigned compare to -1 is LO
                MOV     R1,R0
.latesthistlp   LDRB    R14,[R0],#1       ; Hammer thru' to buffer end
                TEQ     R14,#0
                BNE     latesthistlp
.latesthistlp2  LDRB    R14,[R0,#-1]!     ; Now retreat to beginning of
                TEQ     R14,#13           ; last entry
                BNE     latesthistlp2
                ADD     R0,R0,#1
                CMP     R0,R1
                BLNE    fetchhist         ; Retrieve if changed
                B       nextchar
;---------------------------------------------------------------------------
; corrupts R0-R3
.killeolind     MOV     R2,R6             ; Note current position
                BL      gotoend           ; Goto end of line
                SUBS    R1,R6,R2          ; See how far it was
                BEQ     nextchar          ; If at end of line, do nothing
                BL      mallocyank        ; malloc R1+1 and return ptr in R0
                MOV     R3,R0
                MOV     R6,R2
                ADD     R2,R6,R7          ; Point R2 at current position
.killeollp      LDRB    R14,[R2,R1]
                STRB    R14,[R3,R1]
                SUBS    R1,R1,#1
                SWIGE   XOS_WriteI+127    ; Delete back to r6
                BGE     killeollp
                MOV     R0,#13
                STRB    R0,[R7,R6]        ; Truncate line
                CMP     R11,R6            ; Adjust posn of mark if it was
                MOVGT   R11,R6            ; in the deleted bit
                B       nextchar
.mallocyank     STMFD   R13!,{R14}
                LDR     R0,[R9,#yankbuf]
                BL      free
                ADD     R0,R1,#1
                BL      malloc
                STR     R0,[R9,#yankbuf]
                LDMFD   R13!,{PC}
; Primitive right
._right         STMFD   R13!,{R0,R14}
                SWI     XOS_WriteI+9
                ADD     R6,R6,#1
                LDMFD   R13!,{R0,PC}
; Primitive left
._left          STMFD   R13!,{R0,R14}
                SWI     XOS_WriteI+8
                SUB     R6,R6,#1
                LDMFD   R13!,{R0,PC}
; /X EQ iff already at start of line
.del            STMFD   R13!,{R0,R14}
                TEQ     R6,#0             ; At start of line ?
                SUBNE   R6,R6,#1          ; If not, decrement R6 and delete
                SWINE   XOS_WriteI+127    ; left
                LDMFD   R13!,{R0,PC}
; A bit of a fudge, but never mind...
; Don't try this in a taskwindow as OS_Byte,165 won't work
; NB OS_Byte,134 reads the *input* cursor, which is the blob during copying
.joincopycursors
                STMFD   R13!,{r0-r2,r14}
                MOV     R0,#165
                SWI     XOS_Byte          ; Read output cursor pos to (R1,R2)
                SWIVC   XOS_WriteI+13     ; Send CR to join copy cursor
                SWIVC   XOS_WriteI+31     ; And then reposition cursor
                MOVVC   R0,R1
                SWIVC   XOS_WriteC
                MOVVC   R0,R2
                SWIVC   XOS_WriteC
                LDMFD   R13!,{r0-r2,PC}
.uphistmatchsub STMFD   R13!,{R0-R5,R14}  ; Go back to history line with
;                BL      addnewhistifmod   ; start matching whole of latest
                BL      caselessteq_init
                LDR     R2,[R9,#buf]      ; line
                TST     R8,#fEdit%
                LDREQ   R4,[R9,#match]
                TSTEQ   R4,#1<<31         ; EQ iff positive
                BEQ     uhmkeepgoing
                ADD     R4,R6,R7
.uphistmatchlp  LDRB    R14,[R4],#1
                TEQ     R14,#13
                BNE     uphistmatchlp
                SUB     R4,R4,R7
                SUB     R4,R4,#1
                STR     R4,[R9,#match]
.uhmkeepgoing   LDR     R5,[r9,#cur]      ; R5->current history line
                CMN     R5,#-(-1)
                LDREQ   R5,[R9,#end]      ; If at bottom
                TEQ     R2,R5             ; Catch buf=end if it's empty
.uhmbiglp       SUBNE   R5,R5,#1
                TEQ     R2,R5
                BEQ     uhmbeep           ; If we've hit the top
.uphistmatchlp2 LDRB    R14,[R5,#-1]!     ; Skip to beginning of prev
                TEQ     R14,#13           ; line in history
                BNE     uphistmatchlp2
                ADD     R5,R5,#1
                SUBS    R3,R4,#1
                BMI     uhmautomatch      ; Page up/down on empty line
.uphistmatchlp3 LDRB    R1,[R5,R3]
                LDRB    R0,[R7,R3]
                BL      caselessteq       ; Corrupts R1
                BNE     uhmbiglp
                SUBS    R3,R3,#1
                BPL     uphistmatchlp3    
                ;match!
.dnmautomatch
.uhmautomatch   MOV     R0,R5
                BL      fetchhist
                LDMFD   R13!,{R0-R5,PC}
.uhmbeep
.dnmbeep
.dhmbeep        LDMFD   R13!,{R0-R5,R14}
                B       beep
;should stack same regs as uphistmatch
.dnhistmatchsub STMFD   R13!,{R0-R5,R14}  ; Go forwards to history line with
;                BL      addnewhistifmod   ; start matching whole of latest
                BL      caselessteq_init
                LDR     R2,[R9,#buf]      ; line
                TST     R8,#fEdit%
                LDREQ   R4,[R9,#match]
                TSTEQ   R4,#1<<31         ; EQ iff positive
                BEQ     dnmkeepgoing
                ADD     R4,R6,R7
.dnhistmatchlp  LDRB    R14,[R4],#1
                TEQ     R14,#13
                BNE     dnhistmatchlp
                SUB     R4,R4,R7
                SUB     R4,R4,#1
                STR     R4,[R9,#match]
.dnmkeepgoing   LDR     R5,[r9,#cur]      ; R5->current history line
                CMN     R5,#-(-1)
                BEQ     dnmbeep           ; At the bottom
.dnmbiglp
.dnhistmatchlp2 LDRB    R14,[R5],#1       ; Skip to beginning of next
                CMP     R14,#13           ; line in history
                BGT     dnhistmatchlp2
                BLT     dhm_hitbottom
                SUBS    R3,R4,#1
                BMI     dnmautomatch      ; Page up/down on empty line
.dnhistmatchlp3 LDRB    R1,[R5,R3]
                LDRB    R0,[R7,R3]
                BL      caselessteq       ; Corrupts R1
                BNE     dnmbiglp
                SUBS    R3,R3,#1
                BPL     dnhistmatchlp3
                B       dnmautomatch
;
.dhm_hitbottom  LDR     R14,[R9,#match]   ; No more matches, but if match=0
                TEQ     R14,#0            ; first pageup was from a blank
                BNE     dhmbeep           ; line, so recall one
                BL      dispblankgap
                LDMFD   R13!,{R0-R5,PC}
; line has been cleared by ^L or similar, so redraw it and reposition cursor
.redrawline     STMFD   R13!,{R0,R1,R14}
                MOV     R1,R7
.redrawlp       LDRB    R0,[R1],#1        ; Redraw the line
                CMP     R0,#13
                BEQ     redrawlp_exit
                BL      writec
                B       redrawlp
.redrawlp_exit  SUB     R1,R1,R7
                SUBS    R1,R1,R6          ; (# lefts needed to move cursor
.returncurslp   SUBNES  R1,R1,#1          ; back to insertion position) +1
                SWINE   XOS_WriteI+8
                BNE     returncurslp
                LDMFD   R13!,{R0,R1,PC}
.outctrlchar    TST     R8,#fEchoBuf
                BNE     nextchar
                SWI     XOS_WriteC        ; If an error corrupts R0,
                TEQ     R0,#ASC"L"-64     ; then redraw won't happen
                TEQNE   R0,#30            ; which is fine
                BLEQ    prompt_and_line
                B       nextchar
.prompt_and_line
                STMFD   R13!,{R14}
                BL      display_prompt
                BL      redrawline        ; Redraw line if nuked
                LDMFD   R13!,{PC}
; Force insert mode for this character
.printins       STMFD   R13!,{R8,R14}
                BIC     R8,R8,#fOver%
                BL      printable
                LDMFD   R13!,{R8,PC}
; Put a printable character (&20-&7E, &80-&FF) in the buffer and on screen
; used by vanilla, yank, and filename completion code
; /E R0=char /X R6,R11 updated
.printable      CMP     R0,R8,LSR#24      ; Check char within range
                MOVLT   PC,R14
                STMFD   R13!,{R0,R1,R14}
                AND     R1,R8,#255
                CMP     R0,R1
                LDMGTFD R13!,{R0,R1,PC}
                TST     r8,#fOver%        ; Overstrike mode ?
                BEQ     trickyinsert
                LDRB    R1,[R7,R6]        ; BEEP if cursor at end of line
                TEQ     R1,#13            ; and buffer is full
                TEQEQ   R6,R10
                BEQ     beepnexitifeq
                STRB    R0,[R7,R6]        ; Store char in buffer and
                BL      writec            ; display it on screen
                ADD     R6,R6,#1
                CMP     R1,#13            ; Replace CR if cursor was at the
                STREQB  R1,[R7,R6]        ; end of the line
                BL      modified
                BL      checktildes
                LDMFD   R13!,{R0,R1,PC}
.beepnexitifeq  LDMFD   R13!,{R0,R1,R14}
                B       beep
                ;
.trickyinsert   MOV     R1,R6
.ti_findeol     LDRB    R14,[R7,R1]
                TEQ     R14,#13
                ADDNE   R1,R1,#1
                BNE     ti_findeol
                CMP     R1,R10            ; Line full ?
                BEQ     beepnexitifeq     ; Yes, so BEEP and return
.ti_movelp      LDRB    R14,[R7,R1]       ; Move any chars to the right of
                ADD     R1,R1,#1          ; the cursor up one byte in memory
                STRB    R14,[R7,R1]
                SUB     R1,R1,#2
                CMP     R1,R6
                BGE     ti_movelp
                STRB    R0,[R7,R6]        ; Store char
                CMP     R6,R11            ; If inserting to left of mark
                ADDLT   R11,R11,#1        ; then move it right too
                ADD     R6,R6,#1
                BL      writec            ; Display char
                MOV     R0,#0             ; No space needed
                BL      redrawtail
                LDMFD   R13!,{R0,R1,PC}
;/E R9 -> current instance
;!HACK! needs adjusting for client buffer case...
.erasethisbuf   STMFD   R13!,{R0-R3,R14}  ; Delete contents of buffer used
                LDR     R1,[R9,#buf]      ; by current instance and adjust
                LDR     R14,[R12,#head]   ; ptrs of other instances using
                ADD     R2,R1,#1          ; the same buffer
                MOV     R0,#0
                STRB    R0,[R1]           ; Mark buffer empty
                MVN     R3,#NOT(-1)
.erasethisbuflp LDR     R0,[R14,#buf]     ; Adjust ptrs of other instances
                TEQ     R0,R1             ; using same buffer
                BNE     erasethisbufsk
                STR     R2,[R14,#end]
                LDR     R0,[R14,#cur]
                CMP     R0,#0             ; Change if not 0 (inactive) or
                STRGT   R3,[R14,#cur]     ; -1 (no change of value)
.erasethisbufsk LDR     R14,[R14,#next]
                TEQ     R14,#0
                BNE     erasethisbuflp
                LDMFD   R13!,{R0-R3,PC}
.striptildes    STMFD   R13!,{R14}
                LDR     R14,[R12,#flags]
                TST     R14,#f_NoTildes
                LDMNEFD R13!,{PC}         ; Check if tilde expansion disabled
.striptildeslp  LDRB    R14,[R7]          ; Remove leading tildes
                TEQ     R14,#ASC"~"       ; NB R14=13 if buffer empty
                LDMNEFD R13!,{PC}
                BL      gotostart
                BL      suckuptail
                B       striptildeslp
.fnkeyexpand    LDR     R2,[R1,#4]
                SUBS    R2,R2,#1
                STRNE   R2,[R1,#4]
                LDR     R0,[R1]
                LDRB    R0,[R0,-R2]
                BNE     vanilla
                MOV     R2,R0
                MOV     R0,R1             ; Free buffer if this is the
                BL      free              ; last char of the expansion
                STR     R0,[R9,#fkeybuf]
                MOV     R0,R2
                B       vanilla
; /X NE iff fShiftPressed, CS iff fCtrlPressed
.checkmodkeys   STMFD   R13!,{R0-R2,R14}
                MOV     R0,#202
                MOV     R1,#0
                MOV     R2,#&ff
                SWI     XOS_Byte          ; Read keyboard state
                MOVS    R0,R1,LSR#7       ; Set C to reflect Ctrl key
                TST     R1,#(1<<3)        ; Set Z to reflect Shift key
                LDMFD   R13!,{R0-R2,PC}
; Clear out all buffers - *EraseHistory
.erasehistory   LDR     R12,[R12,#0]
; Shift-Ctrl-Delete
.eraseallbufs   STMFD   R13!,{R0-R3,R14}
                MOV     R1,#0
                MVN     R2,#NOT(-1)
                LDR     R0,[R12,#head]
                B       erasehistin
;
.erasehistlp    LDR     R14,[R0,#buf]
                STRB    R1,[R14],#1       ; Mark buffer empty and
                STR     R14,[R0,#end]     ; update buffer end pointer
                LDR     R3,[R0,#cur]
                TEQ     R3,#0
                STRNE   R2,[R0,#cur]      ; Reset cur to -1 if not 0
                LDR     R0,[R0,#next]
.erasehistin    TEQ     R0,#0
                BNE     erasehistlp
                LDMFD   R13!,{R0-R3,PC}
; /E R0 <> 0 => nuke char on display after end of line
.redrawtail     STMFD   R13!,{R0-R2,R14}
                MOV     R2,R0
                BL      modified
                MOV     R1,R6
.redrawtaillp   LDRB    R0,[R7,R1]        ; Redisplay the characters
                CMP     R0,#13
                BEQ     redrawtaillpx
                BL      writec
                ADD     R1,R1,#1
                B       redrawtaillp
.redrawtaillpx  TEQ     R2,#0             ; Nuke next character?
                SWINE   XOS_WriteI+32     ; 32 beats 9 in !Edit taskwindows
                SWINE   XOS_WriteI+127
                SUBS    R1,R1,R6          ; Number of lefts needed to move
.redrawtaillp2  SWINE   XOS_WriteI+8      ; cursor back to insertion position
                SUBNES  R1,R1,#1
                BNE     redrawtaillp2
                BL      checktildes
                LDMFD   R13!,{R0-R2,PC}
.dispblankgap   STMFD   R13!,{R14}
                MVN     R14,#NOT(-1)      ; Set current history to bottom
                STR     R14,[R9,#cur]
                BL      clearline         ; Clear line
                LDMFD   R13!,{PC}
.modified       STMFD   R13!,{R0,R14}
                ORR     r8,r8,#fEdit%     ; Set modified flag
                LDR     r14,[R9,#end]
                SUB     r14,r14,#1
                STR     r14,[R9,#cur]     ; Set current history to end
                MVN     r14,#NOT(-1)
                STR     r14,[R9,#match]   ; Reset pageup/down counter
                TST     r8,#fKeep4D
                BLEQ    freecontext       ; Reset file completing counter
                LDMFD   R13!,{R0,PC}
; Check for leading tilde and expand if unique match
.checktildes    STMFD   R13!,{R0-R4,R14}
                BL      caselessteq_init
                LDR     R14,[R12,#flags]
                TST     R14,#f_NoTildes   ; Check if tilde expansion disabled
                LDREQB  R14,[R7]          ; Check for leading tilde
                TEQEQ   R14,#ASC"~"       ; (Deals with empty line too)
                LDMNEFD R13!,{R0-R4,PC}
                LDRB    R14,[R7,#1]
                TEQ     R14,#13
                LDMEQFD R13!,{R0-R4,PC}   ; Line is just "~"
                LDR     R2,[R9,#buf]
                MOV     R4,#0
                B       checktildesin
                ;
.trynextpl      ADD     R2,R2,R3
.trynextpllp    LDRB    R14,[R2],#1
                CMP     R14,#13
                BGT     trynextpllp       ; Scan for 0 or 13 - 0 means
                BLT     endofhistory      ; no more history
                SUB     R2,R2,#1
.checktildesin  MOV     R3,#1
.matchedpls     LDRB    R0,[R2,R3]
                CMP     R0,#13
                BLE     trynextpl         ; Line is too short to match
                LDRB    R1,[R7,R3]
                BL      caselessteq       ; Corrupts R1
                BNE     trynextpl
                ADD     R3,R3,#1
                LDRB    R14,[R7,R3]
                CMP     R14,#13
                BNE     matchedpls
                TEQ     R4,#0
; + 1 because R2 is on CR of previous line
                ADDEQ   R4,R2,#1          ; R2 is a match - if we find
                BEQ     trynextpl         ; another, it isn't unique
                LDMFD   R13!,{R0-R4,PC}   ; Match isn't unique
                ;
.endofhistory   MOVS    R0,R4             ; If we got a unique match
                BLNE    fetchhist         ; then recall it
                LDMFD   R13!,{R0-R4,PC}
.checkevents    STMFD   R13!,{R0-R4,R14}
                LDR     R1,[R12,#flags]
                TST     R1,#f_NoEvents    ; Check if events disabled
                LDRB    R2,[R7]           ; Check for leading "!"
                TEQEQ   R2,#ASC"!"        ; (Deals with empty line too)
                BEQ     gotbang
                TST     R1,#f_NoHatRepl   ; Check if hat replace disabled
                TEQEQ   R2,#ASC"^"        ; (Deals with empty line too)
                LDMNEFD R13!,{R0-R4,PC}
; got a hat...
                ADD     R1,R7,#1
.checkhatlp     LDRB    R14,[R1],#1
                TEQ     R14,#13
                TEQNE   R14,#ASC"^"
                BNE     checkhatlp
                TEQ     R14,#13
                LDMEQFD R13!,{R0-R4,PC}   ; No second ^
                SUB     R2,R1,#1
.checkhatlp2    LDRB    R14,[R2,#1]!      ; Look for third ^
                TEQ     R14,#13
                TEQNE   R14,#ASC"^"
                BNE     checkhatlp2
                TEQ     R14,#13
                MOVEQ   R3,R2
                ADDNE   R3,R2,#1
;     ^foo^bar^<-R3
; R7-> R1->   <-R2
                LDR     R14,[R9,#buf]
                LDRB    R14,[R14]
                TEQ     R14,#0
                LDMEQFD R13!,{R0-R4,R14}  ; No lines in buffer
                BEQ     beep
                LDR     R4,[R9,#end]
                SUB     R0,R4,#1
.hatlp          LDRB    R14,[R0,#-1]!
                CMP     R14,#32
                BGE     hatlp
                ADD     R0,R0,#1
;     echo foo world
; R0->           R4->
;
; check for string (R7+1), len (R1-R7-2)
; in string R0, len (R4-R0-1)
; if there, replace with string (r1), len (r2-r1) and append R3
                STMFD   R13!,{r5,r6,r8-r9,r11-r12}
                MOV     R11,R0
                ADD     R5,R7,#1 ; R5 = start of string to look for
                SUB     R8,R4,R0
                SUB     R8,R8,#1 ; R8 = len of string to search in
                SUB     R6,R1,R7
                SUBS    R6,R6,#2 ; R6 = len of string to look for
                BEQ     hatmatch ; If it's empty, the match at start
                SUBS    R8,R8,R6 ; now R8 = # of positions to try
                BLT     hatnomatch
.hatlp2         SUB     r12,r6,#1
.hatlp3         LDRB    r9,[r5,r12]
                LDRB    r14,[r11,r12]
                TEQ     r9,r14
                BNE     hatnext
                SUBS    r12,r12,#1
                BGE     hatlp3
.hatmatch
; found a match at r11
;
;     ^foo^bar^<-R3
; R7-> R1->   <-R2
;  R5->
;     echo foo world
; R0->           R4->
;     R11->
;
; memmove(R7+(r4-r0-1)-r6+(r2-r1),r3,strlen(r3)+1); /* do tail */
; !HACK! do this bit properly
;BL showregs
STMFD R13!,{r0}
                SUB     R0,R4,R0
                SUB     R0,R0,#1
                SUB     R0,R0,R6
                ADD     R0,R0,R2
                SUB     R0,R0,R1
                ADD     R0,R0,R7
                SUB     R12,R0,#1
.hatrepllp0     LDRB    R14,[R12,#1]!
                CMP     R14,#32
                BGE     hatrepllp0
                SUB     R12,R12,R7
                CMP     R12,R10
                LDMGTFD R13!,{r0}
                BGT     hatnomatch ; wouldn't fit in buffer
                CMP     R3,R0
                BLO     hattailrevcopy
                BEQ     hattaildone
.hatrepllp      LDRB    R14,[R3],#1
                STRB    R14,[R0],#1
                CMP     R14,#32
                BGE     hatrepllp
                B       hattaildone
;
.hattailrevcopy
.hatreplrevlp   LDRB    R14,[R3,R12]
                STRB    R14,[R0,R12]
                SUBS    R12,R12,#1
                BGE     hatreplrevlp
;
.hattaildone
                LDMFD   R13!,{r0}
; memcopy(R7+(r11-r0),r5,r6); /* do replace */
                ADD     R3,R7,R11
                SUB     R3,R3,R0
                STMFD   R13!,{r0}
                MOV     R0,R1
                SUBS    R4,R2,R1
.hatrepllp3     LDRNEB  R14,[R0],#1
                STRNEB  R14,[R3],#1
                SUBNES  R4,R4,#1
                BNE     hatrepllp3
                LDMFD   R13!,{r0}
; memcopy(R7,r0,r11-r0); /* do head */
                MOV     R3,R7
                SUBS    R4,R11,R0
.hatrepllp2     LDRNEB  R14,[R0],#1
                STRNEB  R14,[R3],#1
                SUBNES  R4,R4,#1
                BNE     hatrepllp2
; memcopy(R7+(r11-r0)+r6,r11+r5,r8); /* do rest */
                ADD     R0,R6,R11
                ADD     R3,R3,R2
                SUB     R3,R3,R1
                MOVS    R4,R8
.hatrepllp4     LDRNEB  R14,[R0],#1
                STRNEB  R14,[R3],#1
                SUBNES  R4,R4,#1
                BNE     hatrepllp4
;
                LDMFD   R13!,{r5,r6,r8-r9,r11-r12}
                BL      showline
                LDMFD   R13!,{R0-R4,PC}
;
.hatnext        ADD     R11,R11,#1
                SUBS    R8,R8,#1
                BGE     hatlp2
.hatnomatch     LDMFD   R13!,{r5,r6,r8-r9,r11-r12}
                LDMFD   R13!,{R0-R4,R14}
; !HACK complain a bit more
                B       beep
;
.gotbang        MOV     R1,R7
                LDRB    R3,[R1,#1]!
                TEQ     R3,#ASC"!"        ; !! means !-1
                MVNEQ   R2,#NOT(-1)
                ADDEQ   R1,R1,#1
                BEQ     chkev_neg
                TEQ     R3,#ASC"-"
                MOVNE   R14,R3
                LDREQB  R14,[R1,#1]!
                SUB     R2,R14,#ASC"0"
                CMP     R2,#10
                LDMHSFD R13!,{R0-R4,PC}   ; Not a digit...
.checkeventlp   LDRB    R14,[R1,#1]!
                SUB     R14,R14,#ASC"0"
                CMP     R14,#10
                ADDLO   R2,R2,R2,ASL#2
                ADDLO   R2,R14,R2,ASL#1   ; R2 = R2*10 + R14
                BLO     checkeventlp
                TEQ     R3,#ASC"-"
                RSBEQ   R2,R2,#0
                ; R2 = event number (1 is first line), -ve means from bottom
                ; R1 -> rest of line (after !! !-4 !7 etc)
                BEQ     chkev_neg
                LDR     R3,[R9,#buf]
                MOV     R0,R2
.chkev_lp
.chkev_lp2      LDRNEB  R14,[R3],#1
                CMPNE   R14,#13
                BGT     chkev_lp2         ; Skip a line
                BLT     chkev_notfound
                SUBS    R0,R0,#1          ; EQ means zero means end of buffer
                BNE     chkev_lp          ; Otherwise decrement count
                B       chkev_Done
;
.chkev_neg      LDR     R3,[R9,#end]
                LDR     R4,[R9,#buf]
                MOV     R0,R2
                SUB     R3,R3,#1
.chkevneg_lp    CMP     R3,R4             ; Check not start of buf
                BEQ     chkev_notfound
.chkevneg_lp2   LDRNEB  R14,[R3,#-1]!
                CMPNE   R14,#13
                BGT     chkevneg_lp2      ; Skip a line
                ADDS    R0,R0,#1          ; EQ means zero means end of buffer
                BNE     chkevneg_lp       ; Otherwise decrement count
                ADD     R3,R3,#1
;
.chkev_Done     ; R3 -> buffered history entry to recall
                ; R10 is max length
                SUB     R0,R1,#1
.chkev_lp3      LDRB    R14,[R0,#1]!
                TEQ     R14,#13
                BNE     chkev_lp3
                SUB     R0,R0,R1          ; R0 = length of tail of line
                SUB     R2,R3,#1
.chkev_lp4      LDRB    R14,[R2,#1]!
                CMP     R14,#32
                BGE     chkev_lp4
                SUB     R2,R2,R3          ; R2 = length of recalled line
                ADD     R14,R0,R2         ; R14 = total len of combined line
                CMP     R14,R10
                BGE     chkev_notfound    ; Expanded line too long ):
                                          ; (use GE to allow for terminator)
; reverse/forward copy tail of line by r2-(r1-r7) bytes
; ie from r1 to r7+r2 for r0+1 bytes
                ADD     R0,R0,#2
                ADD     R4,R7,R2
                CMP     R1,R4
                BGT     chkev_forcopy
.chkev_lp5      SUBS    R0,R0,#1
                LDRB    R14,[R1,R0]
                STRB    R14,[R4,R0]
                BNE     chkev_lp5
                B       chkev_skp
;
.chkev_forcopy
.chkev_lp5f     SUBS    R0,R0,#1
                LDRB    R14,[R1],#1
                STRB    R14,[R4],#1
                BNE     chkev_lp5f
;
.chkev_skp
.chkev_lp6      SUBS    R2,R2,#1          ; Copy recalled line from history
                LDRB    R14,[R3,R2]       ; into buffer
                STRB    R14,[R7,R2]
                BNE     chkev_lp6
                BL      showline
                LDMFD   R13!,{R0-R4,PC}
.chkev_notfound LDMFD   R13!,{R0-R4,R14}  ; No such event
                B       beep
; Displays current line...
.showline       STMFD   R13!,{r0,r14}
                SWI     XOS_NewLine
                MOV     R0,R7
                BL      writecr
                SWI     XOS_NewLine
                LDMFD   R13!,{r0,PC}
.writecr        STMFD   R13!,{R0,R1,R14}
                MOV     R1,R0
.wcr_lp         LDRB    R0,[R1],#1
                CMP     R0,#32
                LDMLTFD R13!,{R0,R1,PC}
                BL      writec
                B       wcr_lp
]
IF 0 THEN
[OPTA%
;!HACK! this is a bit nasty - also doesn't cope unless 1-or-all history
; push R0 in case XOS_WriteI returns an error
.dump           STMFD   R13!,{R0,R1,R9,R14}
                LDR     R12,[R12,#0]
                LDR     R9,[R12,#head]
                TEQ     R9,#0
                LDMEQFD R13!,{R0,R1,R9,PC}
                LDR     R1,[R12,#lastth]
.dumpinstlp     LDR     R14,[R9,#taskh]
                TEQ     R1,R14
                SWIEQ   XOS_WriteI+ASC"*" ; Mark current buffer
                SWINE   XOS_WriteI+ASC" "
                LDR     R0,[R9,#buf]
                BL      outhex
                SWI     XOS_NewLine
                LDR     R9,[R9,#next]
                TEQ     R9,#0
                BNE     dumpinstlp
                LDMFD   R13!,{R0,R1,R9,PC}
]
ENDIF
[OPTA%
;!HACK! this is a bit nasty - also doesn't cope unless 1-or-all history
; push R0 in case XOS_WriteI returns an error
.recall         STMFD   R13!,{R0,R1,R9,R14}
]
IF 0 THEN
[OPTA%
BL dump
]
ENDIF
[OPTA%
                LDR     R12,[R12,#0]
                LDR     R9,[R12,#head]
                TEQ     R9,#0
                LDMEQFD R13!,{R0,R1,R9,PC}
                LDR     R14,[R12,#flags]
                TST     R14,#f_LocalHist  ; Local history?
                BEQ     recall_rcbuffer
                LDR     R1,[R12,#lastth]
.recallinstlp   LDR     R14,[R9,#taskh]
                TEQ     R1,R14
]
IF oldrecall% THEN
[OPTA%
                SWIEQ   XOS_WriteI+ASC"*" ; Mark current buffer
                BL      recallbuffer
                LDR     R9,[R9,#next]
                TEQ     R9,#0
]
ELSE
[OPTA%
                BEQ     recall_rcbuffer
                LDRNE   R9,[R9,#next]
                TEQNE   R9,#0
]
ENDIF
[OPTA%
                BNE     recallinstlp
                LDMFD   R13!,{R0,R1,R9,PC}
.recall_rcbuffer
                BL      recallbuffer      ; If not, display buffer contents
                LDMFD   R13!,{R0,R1,R9,PC}; and exit
;/E R9->instance
.recallbuffer   STMFD   R13!,{R0-R4,R14}
                LDR     R2,[R9,#buf]
                LDRB    R14,[R2],#1
                TEQ     R14,#0
                BEQ     recallempty
                MOV     R3,#0             ; History line counter
                MOV     R1,#4             ; Pad width
                ADR     R0,szrecallheader
                BL      pprint
.recallloop     ADD     R3,R3,#1
                MOV     R0,R3
                BL      outpadval
                SWI     XOS_WriteI+ASC":"; Output "  nn<colon>"
.recallloop2    LDRB    R0,[R2],#1
                CMP     R0,#13
                SWIGT   XOS_WriteC
                BGT     recallloop2
                SWI     XOS_NewLine
                BEQ     recallloop        ; 0 marks end of history
                LDMFD   R13!,{R0-R4,PC}
                ;
.recallempty    ADR     R0,szbufferempty
                BL      pprint
                LDMFD   R13!,{R0-R4,PC}
.szrecallheader FNpp(   "Current contents of history buffer:"+cr$+bl$)
.szbufferempty  FNpp(   "The history buffer is empty."+cr$+bl$)
                ALIGN
; Delete entry from current history buffer. For other instances using same
; buffer, adjust end and maybe cur
; /E R0 -> start of line to remove from current history buffer
.delhistent     STMFD   R13!,{R0-R4,R14}
                MOV     R1,R0
                LDRB    R14,[R1],#1
                CMP     R14,#13
                LDMLEFD R13!,{R0-R4,PC}
                MOV     R3,R0             ; Preserve for later
.delhistentlp   LDRB    R14,[R1],#1
                CMP     R14,#13
                BGT     delhistentlp
                STRLTB  R14,[R0,#-1]
.delhistentmvlp LDRGEB  R14,[R1],#1       ; !HACK! what if we delete last
                STRGEB  R14,[R0],#1       ; line?  Where does cur point?
                CMPGE   R14,#13
                BGE     delhistentmvlp
                LDR     R14,[R12,#head]
                SUB     R1,R1,R0          ; Length of line removed
                LDR     R4,[R9,#buf]
                STR     R0,[R9,#end]      ; For client buffers
                TEQ     R14,#0
                LDMEQFD R13!,{R0-R4,PC}   ; Only happens for client buffers
.delhistentlp2  LDR     R2,[R14,#buf]
                TEQ     R2,R4
                BNE     notsamebuffer
                STR     R0,[R14,#end]
                LDR     R2,[R14,#cur]
                CMN     R2,#-(-1)         ; If at bottom, don't adjust
                BEQ     notsamebuffer
                CMP     R2,R3             ; If deleted line was before this
                SUBHI   R2,R2,R1          ; instance's cur, move cur back so
                STRHI   R2,[R14,#cur]     ; it still points to same line
                                          ; (NB cur=0 is never changed)
                                          ; Also, if cur was the deleted line
                                          ; then it will now point to the
                                          ; next line (!HACK! if we delete
                                          ; last line and it's cur elsewhere
                                          ; ...?)
.notsamebuffer  LDR     R14,[R14,#next]
                TEQ     R14,#0
                BNE     delhistentlp2
                LDMFD   R13!,{R0-R4,PC}
; Add new history entry which is copied from linebuffer.
; If it duplicates an entry, then the old history entry is deleted
; otherwise the oldest history entries may be deleted to make room.
; Only exception - New entry is not added if no editing has been done
; on the line (i.e. it's up or down arrow and ¬)
; There are three cases here -
; (a) Line already in history => delete old copy and new will fit
; (b) Line isn't in history, but free space > line length
; (c) Line isn't in history, and free space <= line length
;     so we need to delete old lines until there's room
.addnewhistifmod
                TST     r8,#fEdit%        ; Don't add line if it's
                MOVEQ   PC,R14            ; unmodified
.addnewhist     STMFD   R13!,{R0-R5,R14}
                LDRB    R14,[R7]          ; See if line has leading space
                TEQ     R14,#32           ; and if so, check flags to see
                LDREQ   R14,[R12,#flags]  ; if we should store the line
                EOREQ   R14,R14,#f_NoLeadSpc
                TSTEQ   R14,#f_NoLeadSpc
                LDMEQFD R13!,{R0-R5,PC}
                ADD     R3,R7,R6          ; Find end of line, starting from
.anh_findeollp  LDRB    R14,[R3],#1       ; current position to save a bit
                CMP     R14,#32           ; of effort
                BGE     anh_findeollp     ; R3 = # bytes needed to store line
                SUB     R3,R3,R7          ;  = (length of line)+1
                LDR     R14,[R12,#minlen] ; Minimum length of line to store
                CMP     R3,R14
                LDRHI   R14,[R12,#maxlen] ; Maximum length of line to store
                SUBHI   R0,R3,#2          ; R0 = (length of line)-1
                CMPHI   R14,R0
                LDMLSFD R13!,{R0-R5,PC}   ; Don't add if below min/above max
                LDR     R14,[R9,#limit]
                LDR     R1,[R9,#buf]
                LDRB    R5,[R1],#1
                SUB     R14,R14,R1        ; R14 = (size of buffer) -1
                CMP     R3,R14            ; (allowing for inital CR in buf)
                LDMGTFD R13!,{R0-R5,R14}  ; If line won't fit, delete
                BGT     erasethisbuf      ; contents of buffer and exit
                TEQ     R5,#0             ; Is buffer empty?
                BEQ     anhwillfit        ; If so, case (b)
                LDR     R14,[R12,#flags]
                TST     R14,#f_KeepDupl   ; Check the "keep duplicates" flag
                BNE     noduplicate       ; If set, don't bother looking
.trynexthist    MOV     R2,R7
.anhcomparelp   LDRB    R14,[R2],#1
                LDRB    R0,[R1],#1
                CMP     R14,#32
                BLT     anhlineend
                CMP     R14,R0
                BEQ     anhcomparelp
.nomatch
.anhloop        CMP     R0,#13
                LDRGTB  R0,[R1],#1
                BGT     anhloop
                BEQ     trynexthist
.noduplicate
; found zero => reached end of buffer
; so we're in case (b) or (c) and we need R3 bytes free (= len of line +1)
                LDR     R2,[R9,#limit]    ; Set R2 to max value for end
                SUB     R2,R2,R3          ; which allows line to fit in
                LDR     R0,[R9,#buf]
                ADD     R0,R0,#1          ; Set up R0 for delhistent
.anhnukeloop    LDR     R14,[R9,#end]
                CMP     R14,R2
                BLO     anhwillfit
                BL      delhistent        ; If not enough space, remove
                B       anhnukeloop       ; first history entry and repeat
.anhwillfit     LDR     R1,[R9,#end]
                MOV     R14,#13
                STRB    R14,[R1,#-1]
                MOV     R2,R7
.anh_copylp     LDRB    R0,[R2],#1
                CMP     R0,#32
                STRGEB  R0,[R1],#1
                BGE     anh_copylp
                MOV     R14,#0
                STRB    R14,[R1],#1
                STR     R1,[R9,#end]      ; Needed for client buffers
                LDR     R0,[R9,#buf]      ; Update buffer end pointers
                LDR     R14,[R12,#head]
                TEQ     R14,#0
                LDMEQFD R13!,{R0-R5,PC}   ; Only happens for client buffers
.anh_adjbuflp   LDR     R2,[R14,#buf]
                TEQ     R0,R2
                STREQ   R1,[R14,#end]
                LDR     R14,[R14,#next]
                TEQ     R14,#0
                BNE     anh_adjbuflp
                LDMFD   R13!,{R0-R5,PC}
;
.anhlineend     CMP     R0,#13
                BGT     nomatch           ; Line in history is longer
; Found match, so in case (a)
; therefore, copy rest of buffer back by length of this line and add line
; to end of buffer (& there must be enough space)
                LDMLTFD R13!,{R0-R5,PC}   ; Line same as previous entry so
                SUB     R1,R1,#1          ; Run back to start of line
.anh_backlp     LDRB    R14,[R1,#-1]!
                CMP     R14,#32
                BGE     anh_backlp
                ADD     R0,R1,#1
                BL      delhistent
                B       anhwillfit
; Print a right-justified decimal value
; /E R0 = signed value to be printed, R1 = Field width (0 = no padding)
.outpadval      STMFD   R13!,{R0-R3,R14}
                MOV     R3,R1
                SUB     R13,R13,#12
                MOV     R1,R13
                MOV     R2,#12
                SWI     "XOS_ConvertInteger4" ; /X R0 = R1 on entry
                BVS     outpadvalerr      ; Just in case...
                SUB     R2,R1,R0          ; Length of result
                SUBS    R3,R3,R2
.outpadvallp    SWIGT   XOS_WriteI+ASC" "
                SUBGTS  R3,R3,#1
                BGT     outpadvallp
                SUB     R0,R1,R2          ; R0 = R1 - (R1-R0_orig) = R0_orig
                SWI     XOS_Write0        ; (in case SWI error corrupts R0)
.outpadvalerr   ADD     R13,R13,#12
                LDMFD   R13!,{R0-R3,PC}
; /E R0, bit0 -> 0 underline, 1 block, bit1 -> 0 flashing, 1 steady
.setcursorshape TST     R8,#fTaskwndw%
                MOVNE   PC,R14            ; Don't bother in taskwindow
                STMFD   R13!,{R0-R3,R14}
                MOV     R3,R0
                SWI     XOS_WriteI+23
                SWI     XOS_WriteI+0
                SWI     XOS_WriteI+10
                TST     R3,#%01           ; Test block/u-line
                MOVNE   R1,#7             ; Send extra zero
                BNE     vduzeros
                MVN     R0,#NOT(-1)       ; Current mode
                MOV     R1,#0             ; Read ModeFlags
                SWI     "XOS_ReadModeVariable"
                TST     R2,#%10           ; Teletext mode ?
                SWINE   XOS_WriteI+19     ; Yes, probably mode 7
                SWIEQ   XOS_WriteI+7      ; Otherwise 'normal' mode
                MOV     R1,#6
.vduzeros       ADR     R0,eight_zeros
                SWI     XOS_WriteN        ; Write out R1 zeros
                SWI     XOS_WriteI+23
                SWI     XOS_WriteI+1
                TST     R3,#%10           ; Test flashing/steady
                SWIEQ   XOS_WriteI+3
                SWINE   XOS_WriteI+2
                MOV     R1,#7
                ADR     R0,eight_zeros
                SWI     XOS_WriteN        ; Write out R1 zeros
                CMP     R0,R0
                LDMFD   R13!,{R0-R3,PC}

.eight_zeros    & 0:& 0

; /E R5 = private word pointer, R12 = contents of private word
; /X R12 -> newly allocated workspace if R12=0 on entry
.claimspace     TEQ     R12,#0            ; Have we already got workspace ?
                MOVNE   PC,R14            ; If yes, return
                STMFD   R13!,{R0-R4,R10,R14}
                MOV     R0,#sizeofheader  ; Lineeditor global data block
                BL      malloc
                MOVS    R12,R0
                BEQ     badworkspace      ; malloc returns 0 if claim failed
                MOV     R0,#256           ; Scratch block
                BL      malloc
                TEQ     R0,#0
                MOVEQ   R0,R12
                BEQ     claims_free      ; malloc returns 0 if claim failed
                STR     R0,[R12,#tmp256]
                MOV     R0,#129
                MOV     R1,#0
                MOV     R2,#&FF
                SWI     XOS_Byte
                STR     R1,[R12,#osver]   ; &A3 = RISC OS 3.00
                MOV     R0,#0
                STR     R0,[R12,#head]
                STR     R0,[R12,#lastth]
                STR     R0,[R12,#morebufs]
]
IF countclientbuf% THEN
[OPTA%
                STR     R0,[R12,#clbufcnt]
]
ENDIF
[OPTA%
                MOV     R1,#0
                MOV     R2,#0
                MOV     R3,#0
                MOV     R4,#&00000100     ; ins flash/under; over flash/block
                BL      le_setopts
                STR     R12,[R5]          ; Save workspc in priv. word
                LDMFD   R13!,{R0-R4,R10,PC}
.claims_free    BL      free
.badworkspace   LDMFD   R13!,{R0-R4,R10,R14}
.noroomerror    ADR     R0,noroom
                STMFD   R13!,{R14}
                SWI     "XOS_GenerateError"
                LDMFD   R13!,{PC}
;
; NB not necessarily in RMA nowadays
.noroom         & &101              ; No room in RMA error
                = "Couldn't allocate memory"+bl$
                ALIGN
; Emit a beep - a subroutine so we can easily get beeps in taskwindows
; other than !Zap ones (which cope) later.
; Also, this preserves R0 and flags even if the SWI returns an error.

.beep           STMFD   R13!,{R0-R4,R14}
                MOV     R0,#213
                MOV     R1,#0
                MOV     R2,#255
                SWI     XOS_Byte
                MOV     R3,R2
                MOV     R4,R1
                MOV     R0,#211
                MOV     R1,#0
                MOV     R2,#255
                SWI     XOS_Byte
                MOV     R0,R1
                MOV     R1,R2,LSR #3 ; map &80-&f8 -> &10-&1f
                ADD     R1,R1,#&ff00
                ADD     R1,R1,#&00e1 ; map &10-&1f -> &fff1-0
                BIC     R1,R1,#&ff0000
                MOV     R2,R4
                SWI     "XSound_Control"
                LDMFD   R13!,{R0-R4,PC}

.edstatus       STMFD   R13!,{R1,R9,R14}
                LDR     R12,[R12,#0]
                LDR     R9,[R12,#head]
                TEQ     R9,#0
                LDMEQFD R13!,{R1,R9,PC}
                LDR     R14,[R12,#flags]
                TST     R14,#f_LocalHist  ; Local history?
                BEQ     call_edstbuf
                LDR     R1,[R12,#lastth]
.edstatusinstlp LDR     R14,[R9,#taskh]
                TEQ     R1,R14
                SWIEQ   XOS_WriteI+ASC"*" ; Mark current buffer
                BL      edstatusbuffer
                LDRVC   R9,[R9,#next]
                MOVVS   R9,#0
                TEQ     R9,#0
                BNE     edstatusinstlp
                LDMFD   R13!,{R1,R9,PC}
.call_edstbuf   BL      edstatusbuffer
                LDMFD   R13!,{R1,R9,PC}
; !HACK! give %age of buffer used, etc (eg maybe average length of line)
.edstatusbuffer STMFD   R13!,{R0-R3,R14}
                LDR     R3,[R9,#buf]
                ADR     R0,edstatushead
                BL      pprint
                LDR     R14,[R9,#limit]
                LDR     R1,[R9,#end]
                SUB     R1,R14,R1         ; Bytes free in hist buffer
                SUB     R2,R14,R3         ; Size of hist buffer
                BL      docolumns
                SWI     XOS_WriteS
                = "Lines"+bl$
                ALIGN
                MOV     R0,#0
                MOV     R2,R3             ; For next pass of loop
.edstatclinelp
.edstatclinelp2 LDRB    R14,[R3],#1       ; Count the number of lines
                CMP     R14,#13
                BGT     edstatclinelp2
                ADDEQ   R0,R0,#1
                BEQ     edstatclinelp
                MOV     R1,#15
                BL      outpadval
                SWI     XOS_NewLine
                LDMFD   R13!,{R0-R3,PC}
.edstatushead  := tab$+tab$+"Used"+tab$+"Free"+hspc$+hspc$+hspc$
                = "Total"+cr$+"Size (bytes)"+bl$
                ALIGN
; pretty print
; /E R0 -> string to print
.pprint         STMFD   R13!,{R0-R1,R14}
                ADR     R1,ppdict
;                ADR     R2,szSpecial
                SWI     "XOS_PrettyPrint"
                LDMFD   R13!,{R0-R1,PC}
.ppdict         :]
N%=0:REPEAT N%+=1:dummy=FNdict(D$(N%)):UNTIL N%=M%
[OPT A%
                = 0
                ALIGN
.loadhistory    STMFD   R13!,{R7,R9,R14}
                MOV     R7,R0             ; Preserve filename
                LDR     R12,[R12,#0]
                LDR     R9,[R12,#head]
                MOVS    R0,R9
                MOVEQ   R1,#0
                BLEQ    newinst           ; If no buffers, create one...
                MOVS    R9,R0
                BEQ     lh_nobufs
                ;
                LDR     R14,[R12,#flags]
                TST     R14,#f_LocalHist  ; Local history?
                BEQ     lh_global
                ;
                LDR     R1,[R12,#lastth]
.lh_findinstlp  LDR     R14,[R9,#taskh]
                TEQ     R1,R14
                LDRNE   R9,[R9,#next]
                TEQNE   R9,#0
                BNE     lh_findinstlp
                TEQ     R9,#0
                BEQ     lh_nobufs
                ;
.lh_global      MOV     R1,R7             ; Make R1->filename
                MOV     R0,#&4C           ; Generate errors, don't open dirs
                SWI     "XOS_Find"        ; Returns R0=handle
                LDMVSFD R13!,{R7,R9,PC}   ; return V flag
                MOV     R1,R0             ; Put file handle into R1
                ;
                LDR     R2,[R9,#buf]
                LDR     R7,[R12,#tmp256]
                MOV     R6,#0
.lh_linelp      MOV     R3,R7
                MOV     R5,#255
.lh_charlp      SWI     "XOS_BGet"
                BVS     lh_badswi
                BCS     lh_eof
                STRB    R0,[R3],#1
                CMP     R0,#32
                BLT     lh_addnewhist
                SUBS    R5,R5,#1
                BGE     lh_charlp
.lh_skipcharlp  SWI     "XOS_BGet"        ; Ignore to end of this line
                BVS     lh_badswi
                BCS     lh_done
                CMP     R0,#32
                BGE     lh_skipcharlp
                B       lh_linelp
.lh_addnewhist  BL      addnewhist
                B       lh_linelp
;
.lh_eof         MOV     R0,#0
                STRB    R0,[R3],#1
                BL      addnewhist
                ;
.lh_done        MOV     R0,#0
                SWI     "XOS_Find"        ; Close file
                LDMFD   R13!,{R7,R9,PC}   ; If no error R0 preserved, so R0=0
;
.lh_nobufs      LDMFD   R13!,{R7,R9,R14}
                B       noroomerror
;
.lh_badswi      MOV     R2,R0
                MOV     R0,#0
                SWI     "XOS_Find"        ; Try to close file
                MOV     R0,R2
                SWI     "XOS_GenerateError"
                LDMFD   R13!,{R7,R9,PC}
; if global history, no problem
; if local history, save history for last used buffer (tobedone!HACK!)
; if no last used buffer, save empty file
; /E R0->filename
; /X R0->error, if any ; R7-R11 preserved
.savehistory    MOV     R6,R14
                MOV     R1,R0
                MOV     R0,#&8C           ; Generate errors, don't open dirs
                SWI     "XOS_Find"        ; Returns R0=handle
                MOVVS   PC,R6
                ;
                MOV     R3,R0             ; Keep filehandle safe
                MOV     R0,#18
                MOV     R2,#&F00
                ORR     R2,R2,#&FF        ; &FFF => Text
                SWI     "XOS_File"        ; Set type to text
                MOV     R1,R3             ; Put file handle into R1
; Ignore errors in setting filetype in case it's something like "vdu;"
;                BVS     sh_badswi
                ;
                LDR     R12,[R12,#0]
                LDR     R5,[R12,#head]
                TEQ     R5,#0
                BEQ     sh_nobufs
                ;
                LDR     R14,[R12,#flags]
                TST     R14,#f_LocalHist  ; Local history?
                BEQ     sh_global
                ;
                LDR     R2,[R12,#lastth]
.sh_findinstlp  LDR     R14,[R5,#taskh]
                TEQ     R2,R14
                LDRNE   R5,[R5,#next]
                TEQNE   R5,#0
                BNE     sh_findinstlp
                TEQ     R5,#0
                BEQ     sh_nobufs
                ;
.sh_global      LDR     R2,[R5,#buf]
                LDR     R3,[R5,#end]
                ADD     R2,R2,#1
                CMP     R2,R3
                BHS     sh_nobufs
                ;
.sh_lp          LDRB    R0,[R2],#1
                CMP     R0,#32
                MOVLT   R0,#10            ; End lines with '\n'
                SWI     "XOS_BPut"
                BVS     sh_badswi
                CMP     R2,R3
                BLO     sh_lp
                ;
.sh_nobufs      MOV     R0,#0
                SWI     "XOS_Find"        ; Close file
                MOV     PC,R6             ; If no error R0 preserved, so R0=0
                ;
.sh_badswi      MOV     R2,R0
                SWI     "XOS_Find"        ; Try to close file
                MOV     R0,R2
                SWI     "XOS_GenerateError"
                MOV     PC,R6
.canon          MOV     R1,R6
.canonlp        LDRB    R14,[R7,R1]
                TEQ     R14,#ASC" "
                TEQNE   R14,#ASC""""
                BEQ     canonout
                SUBS    R1,R1,#1
                BPL     canonlp
.canonout       ADD     R1,R1,#1
                ADD     R1,R1,R7
                MOV     R0,#37
                MOV     R2,#0
                MOV     R3,#0
                MOV     R4,#0
                MOV     R5,#0
                SWI     "XOS_FSControl"
                BVS     oops
                RSB     R5,R5,#1
                ADD     R0,R5,#18
                BL      malloc
                MOVS    R2,R0
                BEQ     oops
                MOV     R0,#37
                ADD     R2,R2,#18
                SWI     "XOS_FSControl"
                BVS     oops
                MOV     R0,#17
                MOV     R1,R2
                SWI     "XOS_File"       ; Check it's a directory (or image)
                MOV     R2,R1
                BVS     oops_free
                CMP     R0,#2
                BLO     oops_free
                SUB     R0,R2,#18
                ADR     R1,filer_opendir
                LDMIA   R1,{R1,R3-R5,R14}
                STMIA   R0,{R1,R3-R5}
                STRB    R14,[R0,#16]
                MOV     R14,R14,LSR #8
                STRB    R14,[R0,#17]
                SWI     "XOS_CLI"
                SUB     R0,R2,#18
                BL      free
                B       nextchar
;
.oops_free      SUB     R0,R2,#16
                BL      free
.oops           BL      beep
                B       nextchar
.filer_opendir := "%Filer_OpenDir -s "
FNassert ("P%-filer_opendir=18")
ALIGN
;.filer_closedir = "%Filer_CloseDir "
; /E
; R1 -> "path"
; R2 -> buffer to return matches
; R3 = max # to read [¬ next/prev]
; R4 = context count (or 0 initially)
; R5 = size of R2 buffer
; R6 -> wildcard "filename"
; /X
; R3 = # actually read
; R4 = updated context count or -ve for no more matches
; NB last read may return R3>0 and R4=-1
; flags preserved...
;
; [ VS => bad filename, etc
; may corrupt other flags (OS_GBPB gives R3=0 <=> CC) ]
;
.listfilenames  STMFD   R13!,{R0,R14}
FNtrace("listfilenames")
                LDR     R0,[R9,#compcontext]
                LDR     R0,[R0,#type]
                TEQ     R0,#typeSysvar
                LDMEQFD R13!,{R0,R14}
                BEQ     listsysvars
                TEQ     R0,#typeFS
                LDMEQFD R13!,{R0,R14}
                BEQ     listFS
                TEQ     R0,#typeCmd
                LDMEQFD R13!,{R0,R14}
                BEQ     listcmd
                ;
                MOV     R0,#9
                SWI     XOS_GBPB
                TEQ     R0,#9
                MVNNE   R4,#NOT(-1)
                MOVNE   R3,#0
FNtrace("leaving listfilenames")
                LDMFD   R13!,{R0,PC}

.listfilenames2 STMFD   R13!,{R0,R14}
FNtrace("listfilenames2")
                LDR     R0,[R9,#compcontext]
                LDR     R0,[R0,#type]
                TEQ     R0,#typeSysvar
                LDMEQFD R13!,{R0,R14}
                BEQ     listsysvars2
                TEQ     R0,#typeFS
                LDMEQFD R13!,{R0,R14}
                BEQ     listFS2
                TEQ     R0,#typeCmd
                LDMEQFD R13!,{R0,R14}
                BEQ     listcmd2
                ;
                MOV     R0,#10            ; R0=12 is a RO3 enhancement
                SWI     XOS_GBPB
                TEQ     R0,#10
                MVNNE   R4,#NOT(-1)
                MOVNE   R3,#0
                LDMFD   R13!,{R0,PC}

.nextfilename   STMFD   R13!,{R0,R14}
                LDR     R0,[R9,#compcontext]
                LDR     R0,[R0,#type]
                TEQ     R0,#typeSysvar
                LDMEQFD R13!,{R0,R14}
                BEQ     nextsysvar
                TEQ     R0,#typeFS
                LDMEQFD R13!,{R0,R14}
                BEQ     nextFS
                TEQ     R0,#typeCmd
                LDMEQFD R13!,{R0,R14}
                BEQ     nextcmd
                ;
                MOV     R0,#9
.nextfilenamelp TEQ     R4,#0
                LDMMIFD R13!,{R0,PC}
                MOV     R3,#1             ; Read one at a time
                SWI     XOS_GBPB
                TEQ     R0,#9
                MVNNE   R4,#NOT(-1)
                MOVNE   R3,#0
                LDMNEFD R13!,{R0,PC}      ; Possibly bad dir name
                BCC     nextfilenamelp    ; Were no leafnames read?
                LDMFD   R13!,{R0,PC}

.prevfilename   STMFD   R13!,{R0,R7,R14}
                LDR     R0,[R9,#compcontext]
                LDR     R0,[R0,#type]
                TEQ     R0,#typeSysvar
                LDMEQFD R13!,{R0,R7,R14}
                BEQ     prevsysvar
                TEQ     R0,#typeFS
                LDMEQFD R13!,{R0,R7,R14}
                BEQ     prevFS
                TEQ     R0,#typeCmd
                LDMEQFD R13!,{R0,R7,R14}
                BEQ     prevcmd
                ;
                MOV     R0,#9
                SUB     R7,R4,#1
.prevfilenamelp SUB     R7,R7,#1
                MOVS    R4,R7
                LDMMIFD R13!,{R0,R7,PC}
                MOV     R3,#1
                SWI     XOS_GBPB
                TEQ     R0,#9
                MVNNE   R4,#NOT(-1)
                MOVNE   R3,#0
                TEQ     R4,#0
                LDMMIFD R13!,{R0,R7,PC}   ; Possibly bad dir name
                BCC     prevfilenamelp    ; Were no leafnames read?
                LDMFD   R13!,{R0,R7,PC}

.nextsysvar
.listsysvars    STMFD   R13!,{R0-R2,R14}
FNtrace("nextsysvar/listsysvars")
; ignore R1 -> "path" ?!?
; ignore R3 and only return one match
                MOV     R1,R2
                MOV     R2,R5
                MOV     R0,R6
                MOV     R3,R4
                MOV     R4,#0
                SWI     "XOS_ReadVarVal"
                BVS     lsv_nope
                MOV     R4,R3
.listsysvarslp  LDRB    R14,[R3],#1
                STRB    R14,[R1],#1
                TEQ     R14,#0
                BNE     listsysvarslp
                MOV     R3,#1
                LDMFD   R13!,{R0-R2,PC}
;
.lsv_nope       MVN     R4,#NOT(-1)
                MOV     R3,#0
                LDMFD   R13!,{R0-R2,PC}
.listsysvars2   STMFD   R13!,{R0-R2,R14}
; ignore R1 -> "path" ?!?
; ignore R3 and only return one match
                ADD     R1,R2,#20 ;4
                SUB     R2,R5,#20
                MOV     R0,R6
                MOV     R3,R4
                MOV     R4,#0             ; Don't force to string...
                SWI     "XOS_ReadVarVal"
                BVS     lsv_nope
                STR     R4,[R1,#-4]       ; Store type of variable
                MOV     R2,R1             ; For after loop
                MOV     R4,R3
.listsysvars2lp LDRB    R14,[R3],#1
                STRB    R14,[R1],#1
                TEQ     R14,#0
                BNE     listsysvars2lp
                LDRB    R14,[R3]          ; Load type from OS data structure
                STR     R14,[R2,#-8]      ; to spot code variables
                MOV     R3,#1
                LDMFD   R13!,{R0-R2,PC}

.prevsysvar     STMFD   R13!,{R0-R2,R7,R8,R14}
; ignore R1 -> "path" ?!?
; ignore R3 and only return one match
                MOV     R7,R4 ; "r3_cur"
                MOV     R1,R2
                MOV     R0,R6
                MOV     R3,#0
.prevsysvarlp   MOV     R2,R5
                MOV     R4,#0
                MOV     R8,R3
                SWI     "XOS_ReadVarVal"
                BVS     psv_nope ; If var under finger is deleted or ...?
                TEQ     R3,R7
                BNE     prevsysvarlp
                MOVS    R4,R8
                BEQ     psv_nope
.psvcopylp      LDRB    R14,[R8],#1
                STRB    R14,[R1],#1
                TEQ     R14,#0
                BNE     psvcopylp
                MOV     R3,#1
                LDMFD   R13!,{R0-R2,R7,R8,PC}
;
.psv_nope       MVN     R4,#NOT(-1)
                MOV     R3,#0
                LDMFD   R13!,{R0-R2,R7,R8,PC}
.nextFS
.listFS         STMFD   R13!,{R0-R2,R14}
; ignore R1 -> "path" ?!?
; ignore R3 and only return one match
                MOV     R3,R5
                MOV     R0,#33
.lfslp          ADD     R1,R4,#1
                CMP     R1,#&100
                BHS     lfs_nope
                SWI     "XOS_FSControl"
                BVS     lfs_nope
                MOV     R4,R1
                LDRB    R14,[R2]
                TEQ     R14,#0
                BEQ     lfslp
                BL      wildmatch
                BNE     lfslp
                MOV     R3,#1
                LDMFD   R13!,{R0-R2,PC}
;
.lfs_nope       MVN     R4,#NOT(-1)
                MOV     R3,#0
                LDMFD   R13!,{R0-R2,PC}

.listFS2        STMFD   R13!,{R0-R2,R5,R14}
; ignore R1 -> "path" ?!?
; ignore R3 and only return one match
                ADD     R2,R2,#20 ;4
                SUB     R3,R5,#20 ;4
                MOV     R0,#33
.lfs2lp         ADD     R1,R4,#1
                CMP     R1,#&100
                BHS     lfs2_nope
                SWI     "XOS_FSControl"
                BVS     lfs2_nope
                MOV     R4,R1
                LDRB    R14,[R2]
                TEQ     R14,#0
                BEQ     lfs2lp
                BL      wildmatch
                BNE     lfs2lp
                MOV     R5,R2
                MOV     R0,#13
                SWI     "XOS_FSControl"   ; Returns R2 -> FS Info block
                LDR     R14,[R2,#&20]     ; Get FS Information Word
                STR     R14,[R5,#-4]      ; And note down as "type"
                MOV     R3,#1
                LDMFD   R13!,{R0-R2,R5,PC}
;
.lfs2_nope      MVN     R4,#NOT(-1)
                MOV     R3,#0
                LDMFD   R13!,{R0-R2,R5,PC}

.prevFS         STMFD   R13!,{R0-R2,R14}
; ignore R1 -> "path" ?!?
; ignore R3 and only return one match
                MOV     R3,R5
                MOV     R0,#33
.pfslp          SUBS    R1,R4,#1
                BLE     lfs_nope
                SWI     "XOS_FSControl"
                BVS     lfs_nope
                MOV     R4,R1
                LDRB    R14,[R2]
                TEQ     R14,#0
                BEQ     pfslp
                BL      wildmatch
                BNE     pfslp
                MOV     R3,#1
                LDMFD   R13!,{R0-R2,PC}

; R4 context value must be positive. Since here it's a word aligned pointer,
; we shift it right 2 bits before letting the outside world see it, then
; shift left when it gets passed back in
.nextcmd
.listcmd        STMFD   R13!,{R0-R2,R14}
; ignore R1 -> "path" ?!? !HACK! really?
; ignore R3 and only return one match
                MOVS    R4,R4,LSL#2
                LDREQ   R4,[R9,#root]
                LDRNE   R4,[R4,#tree_r%]
                TEQ     R4,#0
                BEQ     lcmd_nope
.lcmd_common    MOV     R0,R2
                LDR     R1,[R4,#tree_val%]
                ; !HACK! need to think about buffer size in R5
                BL      strcpy ; corrupts r0-r3
                MOV     R3,#1
                MOV     R4,R4,LSR#2
                LDMFD   R13!,{R0-R2,PC}
;
.lcmd_nope      MVN     R4,#NOT(-1)
                MOV     R3,#0
                LDMFD   R13!,{R0-R2,PC}
.listcmd2       STMFD   R13!,{R0-R2,R14}
; ignore R1 -> "path" ?!?
; ignore R3 and only return one match
                ADD     R2,R2,#20 ;4
                SUB     R3,R5,#20 ;4
                MOVS    R4,R4,LSL#2
                LDREQ   R4,[R9,#root]
                LDRNE   R4,[R4,#tree_r%]
                TEQ     R4,#0
                BEQ     lcmd_nope
                LDR     R1,[R4,#tree_type%]
                STR     R1,[R2,#-4] ; Note down as "type"
                B       lcmd_common
.prevcmd        STMFD   R13!,{R0-R2,R14}
; ignore R1 -> "path" ?!?
; ignore R3 and only return one match
                MOVS    R4,R4,LSL#2
                LDRNE   R4,[R4,#tree_l%]
                TEQNE   R4,#0
                BNE     lcmd_common
                B       lcmd_nope
; /E
; R2 -> String to match against
; R6 -> Wildmat-like pattern
;       ('*' matches 0 or more chars, '#' matches any single char)
; Match is case insensitive
;
; /X
; Z=1 (EQ) if wildcard matches string
; may trash other flags
.wildmatch      STMFD   R13!,{r2,r0,r6,r14}
.wildmatchlp    LDRB    r0,[r6],#1        ; Character from pattern
;BL showregs
                TEQ     r0,#ASC"*"
                BEQ     wildmatchstar
                ;
                LDRB    r14,[r2],#1
                ;
                TST     r0,#&E0 ; EQ iff <32
                TSTEQ   r14,#&E0 ; EQ iff <32
                LDMEQFD R13!,{r2,r0,r6,PC} ; Return EQ
                ;
                CMP     r14,#ASC" "       ; Stop '#' matching string term.
                TEQGE   r0,#ASC"#"
                TEQNE   r0,r14
                BEQ     wildmatchlp
                ;
                EOR     r14,r0,r14
                TEQ     r14,#32
                LDMNEFD R13!,{r2,r0,r6,PC} ; Return NE
                BIC     r14,r0,#32
                CMP     r14,#ASC"A"
                RSBGES  r14,r14,#ASC"Z"
                BGE     wildmatchlp       ; Ignoring case, letters match
                LDMFD   R13!,{r2,r0,r6,PC} ; Return NE
                ;
.wildmatchstar                            ; Handle '*' wildcard
.wildmatstarlp  BL      wildmatch
                LDMEQFD R13!,{r2,r0,r6,PC} ; Return EQ
                ;
                LDRB    r14,[r2],#1
                CMP     r14,#ASC" "
                BGE     wildmatstarlp
                ;
                LDMFD   R13!,{r2,r0,r6,PC} ; Return NE

; Same as above, but only require wildmat pattern to match a prefix
; (i.e. the start of the string)
.wildmatchpfx   STMFD   R13!,{r2,r0,r6,r14}
.wildmatchpfxlp LDRB    r0,[r6],#1        ; Character from pattern
                TEQ     r0,#ASC"*"
                BEQ     wildmatchpfxst
                ;
                LDRB    r14,[r2],#1
                ;
                TST     r0,#&E0 ; EQ iff <32
                LDMEQFD R13!,{r2,r0,r6,PC} ; Return EQ
                ;
                CMP     r14,#ASC" "       ; Stop '#' matching string term.
                TEQGE   r0,#ASC"#"
                TEQNE   r0,r14
                BEQ     wildmatchpfxlp
                ;
                EOR     r14,r0,r14
                TEQ     r14,#32
                LDMNEFD R13!,{r2,r0,r6,PC} ; Return NE
                BIC     r14,r0,#32
                CMP     r14,#ASC"A"
                RSBGES  r14,r14,#ASC"Z"
                BGE     wildmatchpfxlp    ; Ignoring case, letters match
                LDMFD   R13!,{r2,r0,r6,PC} ; Return NE
                ;
.wildmatchpfxst                           ; Handle '*' wildcard
.wildmatpfxstlp  BL      wildmatchpfx
                LDMEQFD R13!,{r2,r0,r6,PC} ; Return EQ
                ;
                LDRB    r14,[r2],#1
                CMP     r14,#ASC" "
                BGE     wildmatpfxstlp
                ;
                LDMFD   R13!,{r2,r0,r6,PC} ; Return NE
.complete4dos   STMFD   R13!,{R2-R7,R14}
                MOV     R6,R0             ; Wildcarded filename
                LDR     R2,[R9,#gbpbbuf]  ; Buffer to store filename
                MOV     R5,#bufsize%      ; Buffer size for results
                LDR     R0,[R9,#compcontext]
                LDR     R4,[R0,#context]
                TEQ     R4,#0
                MOVMI   R4,#0
                BL      afilename
                TEQ     R4,#0
                MOVMI   R1,#0
                STRPL   R4,[R0,#context]
                MOVPL   R0,R2
                MOVPL   R1,#1
                LDMFD   R13!,{R2-R7,PC}
                ;
.c4d_nomatch    MOV     R1,#0             ; Values
                LDMFD   R13!,{R2-R7,PC}
.afilename      TST     R8,#fCompRev      ; Scrolling back thru' completions?
                BEQ     nextfilename
                B       prevfilename
; /E R0 -> wildcarded filename (null-terminated) (ie ends -II 42 0)
;    R1 -> directory name (null-terminated)
; /X R0 -> buffer (maxlen% bytes) for return of (possibly partial) match
;    R1 =  # files matching spec (so 1=exact, 0=no match)
; in routine,   R7 = # files matching spec so far
;               R4,R6 only used by OS_GBPB
.completebuffer STMFD   R13!,{R1-R7,R14}  ; NB R1 is hoiked from stack
FNtrace("completebuffer")
                BL      caselessteq_init
                MOV     R6,R0             ; Wildcarded filename
                MOV     R7,#0             ; No files yet
                MOV     R4,#0             ; Reading position
.nomoreleafnms  CMP     R4,#0             ; Any more filenames pending
                BMI     nomatchatall      ; for next OS_GBPB call ?
;                MOV     R0,#9
                LDR     R1,[R13]          ; Recover from stack
                LDR     R2,[R9,#gbpbbuf]  ; Buffer to store filenames
                MOV     R3,#255           ; Max entries to read (ie max poss)
                MOV     R5,#bufsize%      ; Buffer size for results
                BL      listfilenames
                TEQ     R3,#0
                BEQ     nomoreleafnms     ; Were no leafnames read?
                TEQ     R7,#0             ; Is this the first scan ?
                BNE     alreadygotone
                LDR     R5,[R9,#mtchbuf]  ; Yes, so copy first name into
.initialmatchlp LDRB    R0,[R2],#1        ; match buffer
                STRB    R0,[R5],#1
                TEQ     R0,#0
                BNE     initialmatchlp    ; Should drop through if R0=0
; R0 should be zero at this point, so we fall through the findzerolp loop
.alreadyshort   ADD     R7,R7,#1          ; Success so far, so adjust
                SUBS    R3,R3,#1          ; counters and skip to last scan
                BEQ     nomoreleafnms     ; check if all names compared
;!HACK! This is a tad kludgy
.findzerolp     TEQ     R0,#0             ; Find null-terminator of current
                LDRNEB  R0,[R2],#1        ; filename ready for next compare
                BNE     findzerolp
.alreadygotone  LDR     R5,[R9,#mtchbuf]
.leafmatchlp    LDRB    R0,[R2],#1        ; Compare next name with current
                LDRB    R1,[R5],#1        ; match
                TEQ     R1,#0             ; Give up if new name is longer
                BEQ     alreadyshort
                BL      caselessteq       ; Corrupts r1
                BEQ     leafmatchlp       ; Keep looping if next char same
                MOV     R1,#0             ; (Possibly) truncate current match
                STRB    R1,[R5,#-1]!
                LDR     R14,[R9,#mtchbuf]
                TEQ     R5,R14            ; If all chars different, there's
                BNE     alreadyshort      ; no partial match
                MOV     R7,#0
.nomatchatall   LDR     R0,[R9,#mtchbuf]  ; No, so return appropriate
                MOV     R1,R7             ; values
                ADD     R13,R13,#4          ; Lose stacked R1
                LDMFD   R13!,{R2-R7,PC}

; /E R0 -> wildcarded filename (null-terminated) (ie ends -II 42 0)
;    R1 -> directory name (null-terminated)
; in routine,   R7 = # files matching spec so far
;               R4,R6 only used by OS_GBPB
.showcompletions
                STMFD   R13!,{R0-R7,R14}  ; NB R1 is hoiked from stack
                BL      prelist           ; Call for setting colours, etc
                MOV     R6,R0             ; Wildcarded filename
                MOV     R7,#0             ; No files yet
                MOV     R4,#0             ; Reading position
.Snomoreleafnms CMP     R4,#0             ; Any more filenames pending
                BMI     Snomatchatall     ; for next OS_GBPB call ?
;
                MOV     R0,#10            ; R0=12 is a RO3 enhancement
                LDR     R1,[R13,#4]        ; Recover from stack
                LDR     R2,[R9,#gbpbbuf]  ; Buffer to store filenames
                MOV     R3,#255           ; Max entries to read (ie max poss)
                MOV     R5,#bufsize%      ; Buffer size for results
                BL      listfilenames2
                TEQ     R3,#0
                BEQ     Snomoreleafnms    ; Were no leafnames read?
.Sprintlp       SWI     XOS_NewLine
                ADD     R2,R2,#20+3       ; Word align and skip
                BIC     R2,R2,#%11        ; to leafname
                MOV     R1,R2             ; Note pointer to get at type info
.Sprintlp2      LDRB    R0,[R2],#1        ; match buffer
                TEQ     R0,#0
                SWINE   XOS_WriteC
                BNE     Sprintlp2
                ;
                ; !HACK! only set colours if there is a type...
                BL      listtype          ; Call for setting colours, etc
                LDR     R0,[R9,#compcontext]
                LDR     R0,[R0,#type]
                TEQ     R0,#typeFile
                BLEQ    sc_flagsFile
                TEQ     R0,#typeSysvar
                BLEQ    sc_flagsSysvar
                TEQ     R0,#typeFS
                BLEQ    sc_flagsFS
                TEQ     R0,#typeCmd
                BLEQ    sc_flagsCmd
                SWI     "OS_ReadEscapeState"
                BCS     Sprint_escape
                ; !HACK! only set colours if there is a type...
                BL      prelist           ; Call for setting colours, etc
                ADD     R7,R7,#1          ; Add to match count
                SUBS    R3,R3,#1          ; Are there anymore matches in
                BNE     Sprintlp          ; the buffer?
                B       Snomoreleafnms
.Sprint_escape  MOV     R0,#126
                SWI     "XOS_Byte"
                LDMFD   R13!,{R0-R7,PC} ; !HACK!
;
.Snomatchatall  BL      postlist          ; Call for setting colours, etc
                TEQ     R7,#0
                BNE     Snomatch32
                BL      beep
                LDMFD   R13!,{R0-R7,PC}
.Snomatch32     SWI     XOS_NewLine
                LDMFD   R13!,{R0-R7,R14}  ; Need "real" R6,R7 for redrawline
                B       prompt_and_line
;/E R1 -> start of leaf (flags before)
.sc_flagsFile   STMFD   R13!,{R0,R5,R14}
                LDR     R5,[R1,#-4]       ; ObjType 2=>dir/app
                TEQ     R5,#2
                MOVEQ   R5,#&1000<<8
                LDRNE   R5,[R1,#-20]      ; Load Address
                ADDNES  R5,R5,#-&FFF00000 ; Check if top 3 nibbles are &FFF
                MVNLO   R5,#NOT(-1)       ; If not, it's untyped
                MOV     R5,R5,ASR#8       ; Shift down into position
;                LDR     R5,[R1,#-4]      ; FileType, 1000=>dir, 2000=>apps
                RSBS    R5,R5,#&1000      ; See what we have
                SWILE   XOS_WriteI+ASC"." ; If dir/app print trailing '.'
                TEQ     R5,#&1000-&FFE    ; Command
                TEQNE   R5,#&1000-&FFC    ; Utility
                TEQNE   R5,#&1000-&FFB    ; BASIC
                TEQNE   R5,#&1000-&FF8    ; Absolute
                TEQNE   R5,#&1000-&FEB    ; Obey
                SWIEQ   XOS_WriteI+ASC"*" ; If executable print trailing '*'
                LDMFD   R13!,{R0,R5,PC}
;/E R1 -> start of leaf (flags before)
.sc_flagsSysvar STMFD   R13!,{R0,R2,R3,R14}
                LDMDB   R1,{R2,R3}       ; Load type info
                TEQ     R3,#1
                TEQNE   R3,#2
                TEQNE   R2,#16
                SWIEQ   XOS_WriteI+ASC" "
                TEQ     R2,#16
                SWIEQ   XOS_WriteI+ASC"C" ; Code variable is 16
                TEQ     R3,#1
                SWIEQ   XOS_WriteI+ASC"n" ; Number is 1
                TEQ     R3,#2
                SWIEQ   XOS_WriteI+ASC"M" ; Macro is 2
                LDMFD   R13!,{R0,R2,R3,PC}
;/E R1 -> start of leaf (flags before)
.sc_flagsFS     STMFD   R13!,{R0,R14}
                LDR     R14,[R1,#-4]      ; FS Info word
                TST     R14,#1<<16        ; Read-only?
                SWINE   XOS_WriteI+ASC" "
                SWINE   XOS_WriteI+ASC"r" ; If read-only, add " r"
                LDMFD   R13!,{R0,PC}
;/E R1 -> start of leaf (flags before)
.sc_flagsCmd    STMFD   R13!,{R0,R14}
                SWI     XOS_WriteI+32
                LDR     R0,[R1,#-4]      ; CMD_xxx value
                ADR     r14,cmdtypetab-4
                LDR     r0,[r14,r0,LSL#2]
                ADD     r0,r0,r14
                SWI     XOS_Write0
                LDMFD   R13!,{R0,PC}
.cmdtypetab     & cmd_alias-(cmdtypetab-4)
                & cmd_command-(cmdtypetab-4)
                & cmd_fileobj-(cmdtypetab-4)
.cmd_alias:= "Alias"+bl$:ALIGN
.cmd_command:= "Command"+bl$:ALIGN
.cmd_fileobj:= "File/Object"+bl$:ALIGN

; Mark Wooding contributed the basis for this, which saved me writing it ;)
; Writes the CLI$Prompt string or "*" if it can't find it or something
; /E -
; /X -
.display_prompt STMFD   R13!,{R0-R4,R14}  ; Save some registers
                ADR     R0,promptVar      ; Point to the variable name
                LDR     R1,[R12,#tmp256]  ; Use scratch block
                MOV     R2,#256           ; Assume the size
                MOV     R3,#0             ; Start search at beginning
                MOV     R4,#3             ; Expand to a string, please
                SWI     "XOS_ReadVarVal"  ; Read the value nicely
                ADRVS   R1,starPrompt     ; If failed, use standard `*'
                MOVVS   R2,#1             ; Which is one byte long
                MOV     R0,R1             ; Point to the output buffer
                MOV     R1,R2             ; And get the string length
                SWI     "XOS_WriteN"      ; Write so many characters
                BL      preedit           ; And set colour again
                LDMFD   R13!,{R0-R4,PC}   ; And return to caller
.promptVar     := "CLI$Prompt"+bl$
.starPrompt    := "*"               ; Default prompt
                ALIGN
; /E R7 -> line buffer, R6 = Offset of cursor on line (0=start)
;    (R10 = Max length) - not used currently, R8 = flags, etc
; /X R6 updated appropriately
; Note The cursor is moved to the end of the leafname and any deletes done.
;      Characters of the match are inserted into the keyboard buffer. The
;      code is 'lazy' about this and will do the minimum number of deletes
;      and inserts possible. A beep is emitted if the filename cannot be
;      fully completed due to a non/non-exact match.
.completefnm    TST     R8,#fPasswd
                BICNE   R8,R8,#fTcsh OR fShowComp OR fCompRev
                MOVNE   PC,R14
                STMFD   R13!,{R0-R5,R14}
FNtrace("completefnm")
                SWI     "XHourglass_On"
                ;
                MOV     R0,#bufsize%+64   ; 64 bytes extra to allow for
                BL      malloc            ; CDFS bug (returns too much data)
                STR     R0,[R9,#gbpbbuf]
                TEQ     R0,#0
                MOVNE   R0,#maxlen%
                BLNE    malloc
                TEQ     R0,#0
                BEQ     cantexpand        ; Beep if we can't allocate buffers
                STR     R0,[R9,#mtchbuf]
                ;
                LDR     R0,[R9,#compcontext] ; Do we already have context
                TEQ     R0,#0             ; from previous 4DOS expansion?
                BNE     gotcontext
                ;
                MOV     R0,#sizeofcontext
                BL      malloc
                STR     R0,[R9,#compcontext]
                MOVS    R5,R0
                MOVNE   R0,#0
                STRNE   R0,[R5,#dirname]
                STRNE   R0,[R5,#wildfnm]
                MOVNE   R0,#maxpathlen%
                BLNE    malloc
                TEQ     R0,#0             ; (if R5=0, won't matter)
                STRNE   R0,[R5,#dirname]
                MOVNE   R0,#maxlen%
                BLNE    malloc
                TEQ     R0,#0             ; (similarly)
                BEQ     cantexpand        ; Beep if we can't allocate buffers
                STR     R0,[R5,#wildfnm]
                ;
                MVN     R0,#NOT(-1)
                STR     R0,[R5,#context]
                MOV     R0,#typeFile
                STR     R0,[R5,#type]     ; Assume file completion initially
                ;
                BIC     R8,R8,#fAbbrev%   ; Assume not *Acc.Fred initially
                ADD     R4,R6,R7          ; Work backwards to find start
.stillbackinglp CMP     R4,R7             ; of full pathname
                BEQ     hitstartofline
                LDRB    R14,[R4,#-1]!
                TEQ     R14,#ASC" "
                TEQNE   R14,#ASC""""
                BNE     stillbackinglp
                ADD     R4,R4,#1          ; Adjust to point to start of path
; !HACK! What about a line which has leading spaces?
; currently it's never treated as a command
; It would be useful if "<stuff> *<partialcommand>" were interpreted as if
; the * before the partial command were a wildcard and not skipped
                B       gotstart
;
.hitstartofline LDRB    R14,[R4],#1
                TEQ     R14,#ASC"*"
                BNE     nostars
                LDR     R0,[R9,#compcontext]
                MOV     R14,#typeCmd
                STR     R14,[R0,#type]
.skipstarslp    LDRB    R14,[R4],#1
                TEQ     R14,#ASC"*"
                BEQ     skipstarslp
.nostars        TEQ     R14,#ASC"@"
                TEQNE   R14,#ASC"$"
                TEQNE   R14,#ASC"&"
                TEQNE   R14,#ASC"^"
                TEQNE   R14,#ASC"%"
                TEQNE   R14,#ASC"\"
; !HACK! abandon completion if "|" found?  Skip "|"?
                ORRNE   R8,R8,#fAbbrev%   ; Might be *Acc.Fred case
                SUB     R4,R4,#1
                B       gotstart
                ;
.nomatchmade    LDR     R4,[R9,#compcontext]
                LDR     R4,[R4,#type]
                TEQ     R4,#typeFile
                BNE     cantexpand
                TST     R8,#fAbbrev%      ; Worth considering as *Acc.Fred?
                BEQ     cantexpand
; Look for '.' from start of line - don't need to explicitly skip leading
; stars - it's done as we look for the '.'
                BIC     R8,R8,#fAbbrev%   ; This is the line's last chance
                MOV     R4,R7             ; Try to find the dot that marks
.seekdotlp      LDRB    R14,[R4],#1       ; end of the abbreviated *-command
                TEQ     R14,#13
                BEQ     cantexpand        ; If no dot found, leave alone
                TEQ     R14,#ASC"."
                BNE     seekdotlp
.gotstart       MOV     R2,R4             ; Copy pointer to start of pathname
FNtrace("gotstart")
                ADD     R5,R6,R7          ; Now go forwards to find
.stillgoinglp   LDRB    R14,[R5],#1       ; the full pathname end
                BIC     R14,R14,#2        ; Look for double quotes
                CMP     R14,#32           ; or space or control
                BGT     stillgoinglp
                SUB     R5,R5,#1
                MOV     R1,R5
                MOV     R3,#ASC"<"
.backdirlp      LDRB    R0,[R5,#-1]!      ; Work back from end to...
; check for -"<" (but not with ">" after)
                TEQ     R0,R3
                BEQ     completesysvar
                CMP     R5,R2             ; ...find the separator between
                BLS     blankdir          ; the pathname and leafname
                TEQ     R0,#ASC">"
                MOVEQ   R3,#256           ; 256 won't match any byte value
                TEQ     R0,#ASC"-"        ; This catches the "-adfs-foo"
                LDREQB  R14,[R2]          ; temporary FS case.
                TEQEQ   R14,#ASC"-"       ; NB '-' is OK in filenames, so
                TEQNE   R0,#ASC":"        ; check very carefully.
                ADDEQ   R5,R5,#1          ; Path should include a trailing
                TEQNE   R0,#ASC"."        ; '-' or colon but not trailing '.'
                BNE     backdirlp
                ;
                SUB     R14,R5,R4         ; Can't expand if
                CMP     R14,#maxpathlen%  ; (R5-R4)>=maxpathlen%
                BGE     cantexpand
                LDR     R3,[R9,#compcontext]
                LDR     R3,[R3,#dirname]  ; Point to pathname buffer
.copytofullbflp LDRB    R14,[R4],#1       ; Copy pathname into buffer
                STRB    R14,[R3],#1
                CMP     R4,R5
                BLT     copytofullbflp
                CMP     R0,#ASC"."        ; Adjust if . was separator
                ADDEQ   R5,R5,#1          ; (leave out from pathname _and_
                MOVEQ   R4,R5             ; leafname)
                B       notblankskip
;
.completesysvar
                LDR     R4,[R9,#compcontext]
                MOV     R14,#typeSysvar
                STR     R14,[R4,#type]
                ADD     R5,R5,#1
                MOV     R4,R5
                B       merge
;
.blankdir       MOVLT   R5,R2             ; Catch "foo." and ""
                LDRB    R14,[R2]
                TEQ     R14,#ASC"-"       ; Check for FS completion
                ADDEQ   R5,R5,#1
                LDR     R3,[R9,#compcontext]
                MOVEQ   R14,#typeFS
                STREQ   R14,[R3,#type]
                LDR     R3,[R3,#dirname]  ; Point to pathname buffer
                MOV     R4,R5
.notblankskip   MOV     R0,#0             ; Truncating pathname
                STRB    R0,[R3]
.merge
                TST     R8,#fTcsh         ; tcsh style completion?
                LDREQ   R14,[R9,#compcontext]
                LDREQ   R14,[R14,#context]; If not, then 4DOS - see if
                TSTEQ   R14,#1<<31        ; we're already doing it...
                BEQ     c4d_already
                LDR     R3,[R9,#compcontext]
                LDR     R3,[R3,#wildfnm]
                ADD     R2,R3,#maxlen%-1
.copywildfnmlp  CMP     R4,R1
                BGE     allcopied
                LDRB    R0,[R4],#1
                STRB    R0,[R3],#1
                CMP     R3,R2
                BNE     copywildfnmlp     ; Branch if leafname not too long
.cantexpand     BLEQ    beep              ; Beep because no unique match
                B       compfreebufxit
                ;
.allcopied      CMP     R0,#ASC"*"        ; Add a * to the end of leafname
                MOVNE   R0,#ASC"*"        ; if it doesn't already have one
                STRNEB  R0,[R3],#1
                MOV     R0,#0             ; Terminate the leafname
                STRB    R0,[R3]
;                SUB     R0,R2,#maxlen%-1  ; So r0 -> leafname
;
                LDR     r0,[r9,#compcontext]
                LDR     r3,[r0,#type]
                TEQ     r3,#typeCmd
                BLEQ    command_completion
;
.c4d_already    LDR     R3,[R9,#compcontext]
                STR     R5,[R3,#match_s]
                STR     R1,[R3,#match_e]
.gotcontext     LDR     R3,[R9,#compcontext]
                LDR     R0,[R3,#wildfnm]  ; R0 -> wildcarded leafname
                LDR     R1,[R3,#dirname]  ; R1 -> pathname
;BL showregs
                TST     R8,#fTcsh
                BEQ     not_tcsh
                BL      completebuffer    ; Returns r1 = #matches
FNtrace("returned from completebuffer")
                CMP     R1,#1
                BEQ     erkerkerk
                BL      beep              ; Match wasn't unique, so beep
                TST     R8,#fShowComp
                BEQ     erkerkerk
                STMFD   R13!,{r0,r1}
                LDR     R1,[R9,#compcontext]
                LDR     R0,[R1,#wildfnm]  ; R0 -> wildcarded leafname
                LDR     R1,[R1,#dirname]  ; R1 -> pathname
                BL      showcompletions
                LDMFD   R13!,{r0,r1}
                B       erkerkerk
;
.not_tcsh       TST     R8,#fShowComp
                BNE     go_showcompletions
                BL      complete4dos      ; Returns fMatchFound
                CMP     R1,#1
                BMI     nomatchmade       ; R1=0? => No match at all
                BLNE    beep              ; Match wasn't unique, so beep
.erkerkerk      CMP     R1,#1
                BMI     nomatchmade       ; R1=0? => No match at all
                MOVNE   R1,#0
                BLEQ    checkfordir       ; Returns R1=char to append or 0
                TST     R8,#fTcsh
                ORREQ   r8,r8,#fKeep4D    ; Preserve things for 4DOS matching
                LDR     R3,[R9,#compcontext]
;BL showregs
                LDR     R5,[R3,#match_s]
                LDR     R3,[R3,#match_e]
                BL      dothestringthing
FNtrace("donethestringthing")
                MOVS    R0,R1             ; Insert a trailing something if
                BLNE    printins          ; appropriate
FNtrace("done printins")
                ADD     R3,R7,R6
                LDR     R0,[R9,#compcontext]
                TEQ     R0,#0             ; printins might have nuked it
;BL showregs
                STRNE   R3,[R0,#match_e]
                BIC     r8,r8,#fKeep4D
.compfreebufxit FNtrace("compfreebufxit")
                LDR     R0,[R9,#gbpbbuf]  ; Free any allocated buffers
                BL      free
                STR     R0,[R9,#gbpbbuf]
                LDR     R0,[R9,#mtchbuf]
                BL      free
                STR     R0,[R9,#mtchbuf]
                LDR     R5,[R9,#compcontext]
                TEQ     R5,#0
                LDRNE   R0,[R5,#context]
                TEQNE   R0,#0
                BLMI    freecontext       ; Don't free context if 4DOS
                ;
                SWI     "XHourglass_Off"
FNtrace("leaving completefnm")
                LDMFD   R13!,{R0-R5,PC}
.go_showcompletions
                BL      showcompletions
                B       compfreebufxit
.freecontext    STMFD   R13!,{R0,R1,R14}
                LDR     R1,[R9,#compcontext]
                TEQ     R1,#0
                LDMEQFD R13!,{R0,R1,PC}
                ;
                LDR     R0,[R1,#dirname]
                TEQ     R0,#0
                BLNE    free
                LDR     R0,[R1,#wildfnm]
                TEQ     R0,#0
                BLNE    free
                MOV     R0,R1
                BL      free
                STR     R0,[R9,#compcontext]
                BL      free_cmdtree
                LDMFD   R13!,{R0,R1,PC}
; /E R0->leafname
; /X R1 = extra char to append (or 0 for none)
.checkfordir    STMFD   R13!,{R0,R2-R5,R14}
;                TST     R8,#fTcsh         ; Don't use with 4DOS completion
;                LDMEQFD R13!,{R0,R2-R5,PC}^ ; test duplicated for now
                LDR     R1,[R9,#compcontext]
                LDR     R14,[R1,#type]
                MOV     R1,#0
                TEQ     R14,#typeSysvar
                MOVEQ   R1,#ASC">"
                TEQ     R14,#typeFS
                MOVEQ   R1,#ASC"-"
                TEQ     R14,#typeFile
                LDMNEFD R13!,{R0,R2-R5,PC}
;                TST     R8,#fTcsh         ; Don't use with 4DOS completion
;                LDRNE   R4,[R12,#flags]
;                TSTNE   R4,#f_TrailDots   ; Trailing dots enabled?
                LDR     R4,[R12,#flags]
                TST     R4,#f_TrailDots   ; Trailing dots enabled?
                LDMEQFD R13!,{R0,R2-R5,PC}
                LDR     R4,[R9,#compcontext]
                LDR     R4,[R4,#dirname]  ; R4 -> pathname
                MOV     R1,R0             ; R1 -> leafname
                SUB     R0,R4,#1
; Stick a dot on the end if it's not empty and doesn't end with colon
.checkfordirlp  LDRB    R14,[R0,#1]!
                CMP     R14,#32
                BGE     checkfordirlp
                TEQ     R0,R4
                LDRNEB  R2,[R0,#-1]
                TEQNE   R2,#ASC":"
                MOVNE   R2,#ASC"."
                STRNEB  R2,[R0],#1
                STRNEB  R14,[R0],#1
                MOV     R0,#13            ; Find using path -> R4
                SWI     "XOS_File"
                TEQ     R0,#2             ; Directory found ?
                MOVEQ   R1,#ASC"."        ; If so append a "."
                MOVNE   R1,#0
                LDMFD   R13!,{R0,R2-R5,PC}
;/E
; R0 -> string to insert <nul terminated or something>
; R3 -> end of source string
; R5 -> to start of source string
; (R6=cursor position)
; (R7->linebuffer)
;   xxxxxxSSSSSSSyyyyyy
;R7>   R5>    R3>
;        R7+R6>
.dothestringthing
                STMFD   R13!,{R0,R2-R3,R5,R14}
                MOV     R2,R0
                SUB     R6,R3,R6          ; # chars cursor is from pathend
                SUB     R6,R6,R7
.compmvrightlp  SUBS    R6,R6,#1
                SWIPL   XOS_WriteI+9
                BPL     compmvrightlp
                SUB     R6,R3,R7          ; Need normal R6 for suckuptail
.lazyloop       LDRB    R0,[R2],#1        ; !HACK! for extra laziness, overtype too
                CMP     R5,R3             ; Redraw as little as possible
                BGE     addfullname       ; No need to delete any chars
                LDRB    R14,[R5],#1
                TEQ     R0,R14
                BEQ     lazyloop
                SUB     R5,R5,#1
                SUB     R3,R3,R5          ; Partial name width
                MOV     R5,R0
.compdelleftlp  SUBS    R3,R3,#1
                BMI     go_addfullname
                SWI     XOS_WriteI+127
                SUB     R6,R6,#1
                BL      suckuptail
                B       compdelleftlp
.go_addfullname MOV     R0,R5
.addfullname
.addfullnamelp  TEQ     R0,#0
                LDMEQFD R13!,{R0,R2-R3,R5,PC}
                BL      printins          ; Pretend character was typed
                LDRB    R0,[R2],#1        ; Insert full name
                B       addfullnamelp
;;;;;;;;;;;;;;;;;;;; command completion code ;;;;;;;;;;;;;;;;;;;;
;/E r0 -> completion context structure, r9 -> instance block
.command_completion
                STMFD   r13!,{r0-r8,r14} ; !REGS!
                BL      free_cmdtree
; !HACK! incorporate next few lines elsewhere
;                LDRB    r14,[r0]
;                TEQ     r14,#ASC"|"       ; Check for comment
;                LDMEQFD r13!,{r0-r8,pc}^ ; !REGS!
;dirname -> directory bit (might be prefix; or prefix;dir or dir.ectory)
;wildfnm -> wildcarded leafname
                MOV     r8,r0
                LDR     r1,[r8,#dirname]
                LDRB    r14,[r1]
                TEQ     r14,#0
                LDREQ   r1,[r8,#wildfnm] ; no pfx so just use leafname
                BEQ     ccnopfx
                LDR     r0,[R12,#tmp256] ; # !HACK! 256 enough?
                BL      strcpy ; corupts r0-r3
                LDR     r0,[R12,#tmp256]
.ccskiplp       LDRB    r14,[r0],#1
                TEQ     r14,#0
                BNE     ccskiplp
                SUB     r0,r0,#1
                LDRB    r14,[r0,#-1]
                TEQ     r14,#ASC":"
                MOVNE   r14,#ASC"."
                STRNEB  r14,[r0],#1
                LDR     r1,[r8,#wildfnm]
                BL      strcpy ; corupts r0-r3
                LDR     r1,[R12,#tmp256]
.ccnopfx
                                          ; Check fs<colon> prefix by
                MOV     r0,#11            ; trying to set temporary FS
                SWI     "XOS_FSControl"
                MOV     r0,r1
; <fs><colon><command>
;            ^r0
;
; <module><colon><command>
; ^r0
;
; <command>
; ^r0
                CMN     r2,#-(-1)         ; -1 means we didn't set an FS,
                BNE     cmdcomp_isfs      ; so SWI had no effect
; !HACK! maybe check first char is A-Z a-z 0-9 or _ or ! or a few others
.cmdcomplp2     LDRB    r14,[r1],#1
                CMP     r14,#ASC":"
                CMPNE   r14,#ASC"."
                CMPNE   r14,#32
                BGT     cmdcomplp2
                CMP     r14,#ASC":"
                BNE     cmdcomp_notmod
                SUB     r1,r1,#1
                CMP     r1,r0
                BLE     cmdcomp_notmod
; Prefix given, so look in that module, if it exists
                MOV     r7,r1
                MOV     r1,r0
                LDRB    r8,[r7]
                MOV     r14,#0
                STRB    r14,[r7]
                MOV     r0,#18
                SWI     "XOS_Module"
                STRB    r8,[r7]
                ADD     r0,r7,#1
                MOVVC   r1,r3
                MOVVC   r2,#0
                BLVC    checkmod
.cmdcomp_dofilecomp
; !HACK! "!!! Normal file completion !!!"
                B       cmdcomp_done
;
.cmdcomp_notmod
.cmdcomp_isfs
; Check for command in all modules
                BL      nomodprefix
; don't treat repeat.!r as a command, even though it could be
; it's probably filename completion that's intended
                MOV     r1,r0
.cmdcomplp3     LDRB    r14,[r1],#1
                CMP     r14,#ASC"."
                CMPNE   r14,#32
                BGT     cmdcomplp3
                CMP     r14,#ASC"."
                BEQ     cmdcomp_dofilecomp
                BL      checkrunpath      ; Now check along Run$Path
.cmdcomp_done   MOV     r0,#19            ; Restore current FS
                SWI     "XOS_FSControl"
                BL      flatten_cmd
;                BL      print_cmd
                LDMFD   r13!,{r0-r8,pc} ; !REGS!
.aliasbuf:= "Alias$"
ALIGN
;/E r0 -> command
.checkalias     STMFD   r13!,{r0-r5,r14}
FNtrace("checkalias")
                MOV     R3, #256
                MOV     R0, #6
                SWI     "XOS_Module"
                LDMVSFD R13!, {R0-R5, PC}
                LDR     R0, aliasbuf           ;put "Alias$" in buffer
                STR     R0, [R2, #0]
                LDR     R0, aliasbuf+4
                STR     R0, [R2, #4]
                ADD     R1, R2, #LEN("Alias$")
                MOV     R5, R2
                LDMIA   R13, {R2}
; " ""#$%&*,/ colon <>\^|" not allowed
.chkaliaslp     LDRB    r3,[r2],#1
                CMP     r3,#ASC"!"
                BEQ     chkaliaslpok
                CMP     r3,#38
                BLT     chkaliaslpout
                CMP     r3,#127
                BGE     chkaliaslpout
                TEQ     r3,#ASC","
;                TEQNE   r3,#-"*" ; "*" is a wildcard...
                TEQNE   r3,#ASC"/"
                TEQNE   r3,#ASC":"
                TEQNE   r3,#ASC"<"
                TEQNE   r3,#ASC">"
                TEQNE   r3,#ASC"\"
                TEQNE   r3,#ASC"^"
                TEQNE   r3,#ASC"|"
                BEQ     chkaliaslpout
.chkaliaslpok   STRB    r3,[r1],#1
                B       chkaliaslp
.chkaliaslpout
.chkaliaslp2    MOV     r14,#ASC"*" ; not needed if * on end !HACK!
                STRB    r14,[r1],#1 ; not needed if * on end !HACK!
                MOV     r14,#0
                STRB    r14,[r1],#1
                MOV     r3,#0
.chkaliaslp3    MOV     R0, R5
                MOV     r1,#0
                MOV     r2,#1<<31
                MOV     r4,#0
                SWI     "XOS_ReadVarVal"
;,A$,0,1<<31,R3,0,,,N,R3,TYPE
                CMP     R2,#0
                BEQ     chkaliasnope
;                BPL     chkaliaslp3 ; !HACK! won't happen?
                ADD     r0,r3,#6
                MOV     r1,#CMD_alias
                BL      store_cmd
                B       chkaliaslp3
.chkaliasnope   ADD     R1, R5, #LEN("Alias$")
                MOV     r2,#0
.chkaliaslp5    LDRB    r14,[r1,#1]! ; truncate at previous dot, if any
                TEQ     r14,#ASC"."
                MOVEQ   r2,r1
                TEQ     r14,#0
                BNE     chkaliaslp5
                MOVS    r1,r2
                BNE     chkaliaslp2
                MOV     R2, R5
                MOV     R0, #7
                SWI     "XOS_Module"       ; free temp allocation
                LDMFD   r13!,{r0-r5,PC}

.checkmodchain  STMFD   r13!,{r0-r8,r14}  ; Check modules in order
                MOV     r7,#0
                MOV     r8,r0
.checkmodchainlp
                MOV     r1,r7
                MOV     r0,#12
                MOV     r2,#0
                SWI     "XOS_Module"      ; 12
                LDMVSFD r13!,{r0-r8,pc}
                ADD     r7,r7,#1
                MOV     r0,r8
                MOV     r1,r3
                MOV     r2,#0
                BL      checkmod
                B       checkmodchainlp
; check secondary and primary FS modules (eg ADFS, Filecore)
.checkfsmods    STMFD   r13!,{r0-r3,r14}
                MOV     r3,r0
                MOV     r0,#30
                SWI     "XOS_FSControl"
                MOVVC   r0,r3
                MOVVC   r2,#1
                BLVC    checkmod          ; 2nd FS RM
                MOV     r0,#20
                SWI     "XOS_FSControl"
                MOVVC   r0,r3
                MOVVC   r2,#1
                BLVC    checkmod          ; 1st FS RM
                LDMFD   r13!,{r0-r3,pc}
; /E R0 -> command, R1 -> module, r2 = fFS
.checkmod       STMFD   r13!, {r0-r2,r4-r6,r10,r14}
                MOVS    r10,r1
                LDRNE   r4,[r10,#24]
                TEQNE   r4,#0
                LDMEQFD r13!, {r0-r2,r4-r6,r10,pc}
                MOV     r5,r2
                ADD     R4,R10,R4          ; r4 -> module command table
                MOV     r6,r0             ; Pattern to match against
                SUB     R4,R4,#16
.chkmodlp       LDRB    R14,[R4,#16]!
                TEQ     R14,#0
                LDMEQFD r13!, {r0-r2,r4-r6,r10,pc}
                MOV     r2,r4             ; Command name
.chkmodlp2      LDRB    r14,[r4],#1        ; Find command info block
                TEQ     r14,#0
                BNE     chkmodlp2
                ADD     r4,r4,#3
                BIC     r4,r4,#3           ; Round up to 4 byte boundary
                LDR     r14,[r4]
                TEQ     r14,#0
                BEQ     chkmodlp           ; No code => not command
                LDR     r14,[r4,#4]
                TEQ     r5,r14,LSR#31
                TSTEQ   r14,#1<<30        ; Is it a *Configure option?
                BNE     chkmodlp
; /E R2 -> String to match against, R6 -> Wildmat-like pattern
; /X Z=1 (EQ) iff wildcard matches string, may trash other flags
                BL      wildmatch ; now have trailing "*" so pfx not needed
;                BL      wildmatchpfx
                BNE     chkmodlp          ; Command doesn't match pattern
; !HACK! need to turn "." or whatever in command line into zero or whatever
; r8 -> first non matching char in command line
; r7 -> first non matching char in command in module
;                LDRB    r14,[r8]
;                CMP     r14,#32
;                BLE     chkmod_yep
;                TEQ     r14,#ASC"."
;                BNE     chkmod_notmatch
;                LDRB    r14,[r7]
;                TEQ     r14,#0
;                BEQ     chkmod_notmatch
; match and has code ie is command
; LDR r0,[r10,#16]
; ADD r0,r0,r10
; r0 -> module name
;!HACK!    fFS X$+=" (as FS)"
                MOV     r0,r2
                MOV     r1,#CMD_command
                BL      store_cmd
                B       chkmodlp
.runpath:= "Run$Path"+CHR$0
ALIGN
.checkrunpath   STMFD   r13!,{r0-r8,r10-r11,r14}
FNtrace("checkrunpath")
                MOV     r6,r0
;
;SYS "XOS_ReadVarVal","Run$Path",0,1<<31,0,0,,,N,R3,TYPE
                ADR     r0,runpath
                MOV     r1,#0
                MOV     r2,#1<<31
                MOV     r3,#0
                MOV     r4,#0
                SWI     "XOS_ReadVarVal"
                CMP     r2,#0
                LDMPLFD r13!,{r0-r8,r10-r11,pc}
                RSBS    r2,r2,#0          ; MI <=> r2 is (and was) 1<<31
                MOVMI   r2,#256           ; so use 256 byte buffer
                ; need r2 bytes pointed to by r1
                MOV     r0,r2
                BL      malloc
                MOVS    r1,r0
                LDMEQFD r13!,{r0-r8,r10-r11,r14}
                BEQ     beep ; malloc failed, so beep and bail out !HACK!
                STMFD   r13!,{r1}
                ;
                ADR     r0,runpath
                MOV     r3,#0
                MOV     r4,#3
                SWI     "XOS_ReadVarVal"
                MOV     r14,#0
                STRB    r14,[r1,r2]
                ; R% r1 , P% r8 , Q% r10
                MOV     r8,r1
.chkrunpathlp                             ; Skip leading spaces
.chkrunpathlp2  LDRB    r14,[r8],#1
                TEQ     r14,#ASC" "
                BEQ     chkrunpathlp2
                SUB     r8,r8,#1
                SUB     r10,r8,#1
; skip r10 to "," or end of string
.chkrunpathlp3  LDRB    r14,[r10,#1]!
                CMP     r14,#ASC","
                CMPNE   r14,#ASC" "
                BGT     chkrunpathlp3
;
; G$ r11
                LDR     R11,[R9,#mtchbuf]  ; Slight abuse, but mtchbuf is filename sized
                MOV     r7,r11 ; F$="" if we chkrunpathskip
                CMP     r10,r8
                BLE     chkrunpathskip
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
                LDRB    r14,[r10,#-1]
                TEQ     r14,#ASC"."
                SUBEQ   r10,r10,#1
                TEQNE   r14,#ASC":"
                BEQ     chkrunpathskip
; end r7
                MOV     r7,r10
.chkrunpathlp4  TEQ     r8,r10
                BEQ     chkrunpath_x
                LDRB    r14,[r10,#-1]!
                TEQ     r14,#ASC"."
                TEQNE   r14,#ASC":"
                BNE     chkrunpathlp4
                ADD     r10,r10,#1
.chkrunpath_x
; memcpy( r11, r10, r7 - r10 )
                SUB     r0,r7,r10
; !HACK! check r0 not too long
                ADD     r7,r0,r11 ; now "F$" r7
.chkrunpathlp4a SUBS    r0,r0,#1
                LDRGEB  r14,[r10,r0]
                STRGEB  r14,[r11,r0]
                BGT     chkrunpathlp4a
                LDRB    r14,[r10,#-1]
                TEQ     r14,#ASC"."
                SUBEQ   r10,r10,#1
.chkrunpathskip LDRB    r14,[r10]
                TEQ     r14,#0
                MOVNE   r0,#13
                STRNEB  r0,[r10],#1
                TEQ     r14,#ASC","
                BEQ     chkrunpath_y
.chkrunpathlp5  LDRB    r14,[r10],#1
                CMP     r14,#ASC","
                CMPNE   r14,#31
                BGT     chkrunpathlp5
.chkrunpath_y
; "F$" = r7, A% r6 (last use, except that we need to preserve for big loop)
                MOV     r0,r6
                MOV     r2,r7
FNtrace("chkrunpathlp6")
;BL showregs
.chkrunpathlp6  LDRB    r14,[r0],#1
                CMP     r14,#32
                STRGEB  r14,[r2],#1
                BGE     chkrunpathlp6
                MOV     r14,#ASC"*" ; not needed if * on end !HACK!
                STRB    r14,[r2],#1 ; not needed if * on end !HACK!
                MOV     r14,#0
                STRB    r14,[r2]
                MOV     r4,#0
.chkrunpathlp7
;   SYS "OS_GBPB",10,P%,D%,1,R4,2048,F$,,,,R3,R4 ; flgs
                MOV     r0,#10
                MOV     r1,r8
                LDR     R2,[R9,#gbpbbuf]
                MOV     r5,#bufsize%
                MOV     r3,#255 ; much faster to read as many as we can per OS_GBPB
                STMFD   r13!,{r6}
                MOV     r6,r11
                SWI     "XOS_GBPB"
                LDMFD   r13!,{r6}
                BVS     chkrunpathgbpberr
                CMP     R3,#0
                BLE     chkrunnoobj
.chkrunchkobj
; OK if object is
; * a file or an application directory/imagefile
; * RISC OS >3.5 and directory
; * appl
; !HACK! what about images (D%!16=3)?  Simes reckons same as files
; !HACK! in the directory/app case, ought to check for !Run
                LDRB    r14,[r2,#20]
                TEQ     r14,#ASC"!"
                BEQ     chkpathok
                LDR     r14,[r2,#16]
                TST     r14,#1
                BNE     chkpathok
                TEQ     r14,#2 ;!HACK! if ((type&1)==0) surely it must be 2 ???
                BNE     chkrunpathgbpbnotexec
                LDR     R14,[R12,#osver]
                CMP     r14,#&A5 ; osver RO 3.5 (I think)
                BLT     chkrunpathgbpbnotexec
.chkpathok
                ADD     r0,r2,#20
                SUB     r14,r7,r11
                ADD     r0,r0,r14
                MOV     r1,#CMD_fileobj
                BL      store_cmd
.chkrunpathgbpbnotexec
                ADD     r2,r2,#20
.chkrunpathnextobjlp
                LDRB    r14,[r2],#1
                TEQ     r14,#0
                BNE     chkrunpathnextobjlp
                ADD     r2,r2,#3
                BIC     r2,r2,#3 ; Round up to next word boundary
                SUBS    r3,r3,#1
                BNE     chkrunchkobj
.chkrunnoobj    CMN     r4,#-(-1)
                BNE     chkrunpathlp7
.chkrunpathgbpberr
                MOV     r8,r10
                LDRB    r14,[r10,#-1]
                TEQ     r14,#0
                BNE     chkrunpathlp
                ;
                LDMFD   r13!,{r0}
                BL      free ; Release Run$Path buffer
                ;
                LDMFD   r13!,{r0-r8,r10-r11,pc}
.nomodprefix    STMFD   r13!,{r1-r2,r14}
  ; Check for aliases if not suppressed by '%'
                LDRB    r14,[r0]
                TEQ     r14,#ASC"%"
                ADDEQ   r0,r0,#1
                BLNE    checkalias
                LDR     r1,[r12,#pKernel] ; Check kernel first
                MOV     r2,#0
                TEQ     r1,#0
                BLNE    checkmod
                BL      checkmodchain
                BL      checkfsmods
                LDMFD   r13!,{r1-r2,pc}
]:tree_val%=8:tree_type%=12:tree_l%=0:tree_r%=4:[OPT A%
; /E r0 -> cmd name, r1 = type code
.store_cmd      STMFD   r13!,{r0-r3,r4-r6,r12,r14}
                MOV     r4,r0
                MOV     r5,r1
                ADD     r12,r9,#root
.store_cmdlp    LDR     r6,[r12]
                TEQ     r6,#0
                BEQ     store_cmd_new
                LDR     r1,[r6,#tree_val%]
                MOV     r0,r4
                BL      stricmp
                LDMEQFD r13!,{r0-r3,r4-r6,r12,pc} ; already got it
                ADDGT   r12,r6,#tree_r%
                ADDLT   r12,r6,#tree_l%
                B       store_cmdlp
;
.store_cmd_new  MOV     r0,#16+240 ; !HACK!
                BL      malloc
                TEQ     r0,#0
                LDMEQFD r13!,{r0-r3,r4-r6,r12,pc} ; aargh
                MOV     r1,#0
                MOV     r2,#0
                ADD     r3,r0,#16
                STMIA   r0,{r1,r2,r3,r5}
.scn_lp         LDRB    r14,[r4],#1
                STRB    r14,[r3],#1
                TEQ     r14,#0
                BNE     scn_lp
FNassert("tree_l%=0 AND tree_r%=4 AND tree_val%=8 AND tree_type%=12")
                STR     r0,[r12]
                LDMFD   r13!,{r0-r3,r4-r6,r12,pc}
; corrupts r1-r3, returns flags
.stricmp
 STMFD   r13!,{r4,r14}
 MOV     r2,r0
 MVN     r0,#NOT -1
 SWI     "XTerritory_UpperCaseTable"
 BVS     simple_stricmp
.stricmplp
 LDRB    r3,[r2],#1
 LDRB    r14,[r1],#1
 LDRB    r3,[r0,r3]
 LDRB    r14,[r0,r14]
 ORRS    r4,r3,r14 ; Test for end of both strings
 LDMEQFD r13!,{r4,pc} ; If both end together, return 0 (strings equal)
 SUBS    r4,r3,r14
 BEQ     stricmplp
 LDMFD   r13!,{r4,pc}
.simple_stricmp
.stricmplp
 LDRB    r3,[r2],#1
 LDRB    r14,[r1],#1
 ORRS    r0,r3,r14 ; Test for end of both strings
 BIC     r3,r3,#32 ; crude caselessness !HACK!
 BIC     r14,r14,#32
 LDMEQFD r13!,{r4,pc} ; If both end together, return 0 (strings equal)
 SUBS    r0,r3,r14
 BEQ     stricmplp
 LDMFD   r13!,{r4,pc}
; corrupts r0-r3, r0 return value not important
.strcpy
.strcpylp
 LDRB    r2,[r1],#1
 STRB    r2,[r0],#1
 TEQ     r2,#0
 BNE     strcpylp
 MOV     pc,r14
; On entry:
;  root -> O
;         / \
; tree_l V   V tree_r
;            B
;           / \
;   tree_l V   V tree_r
;
; On exit:
; root -> O <-> O ->
;           r l    r
.flatten_cmd    STMFD   r13!,{r0,r1,r14}
                LDR     r0,[R9,#root]
                MOV     r1,#0
                TEQ     r0,#0
                BLNE    fl_cmd_subtree ; corrupts r0,r1
                LDMFD   r13!,{r0,r1,pc}
; NB this routine corrupts r0,r1
; This is done as it may recurse a lot, and stack space is precious
; /E r0 -> node, r1 -> last node
.fl_cmd_subtree STMFD   r13!,{r12,r14}
                MOV     r12,r0
.fl_cmd_sublp   LDR     r0,[r12,#tree_l%]
                TEQ     r0,#0
                BLNE    fl_cmd_subtree
                TEQ     r1,#0
                STRNE   r1,[r12,#tree_l%] ; left most node already has l=0
                STRNE   r12,[r1,#tree_r%]
                STREQ   r12,[r9,#root]    ; root is now left-most node
                MOV     r1,r12
                LDR     r12,[r12,#tree_r%]
                TEQ     r12,#0
                BNE     fl_cmd_sublp
                LDMFD   r13!,{r12,pc}
.free_cmdtree   STMFD   r13!,{r0,r1,r14}
                LDR     r1,[R9,#root]
.free_cmdlp     MOVS    r0,r1
                LDRNE   r1,[r1,#tree_r%]
                STREQ   r0,[R9,#root]
                LDMEQFD r13!,{r0,r1,pc}
                BL      free
                B       free_cmdlp
;.print_cmd      STMFD   r13!,{r0,r12,r14}
;                LDR     r12,[r9,#root]
;                TEQ     r12,#0
;.pr_cmd_lp      LDRNE   r0,[r12,#tree_val%]
;                SWINE   XOS_Write0
;                SWINE   XOS_NewLine
;                LDRNE   r12,[r12,#tree_r%]
;                TEQNE   r12,#0
;                BNE     pr_cmd_lp
;                LDMFD   r13!,{r0,r12,pc}^
; Find Kernel Pseudo-Module
; Hacky, but works for RISC OS-s 2.0, 3.1, 3.5 and hopefully the rest
.kmodid:= "MODULE#"+CHR$0:ALIGN
.findkmod       STMFD   r13!,{r0-r3,r14}
                MOV     r0,#19
                MOV     r1,#0
                MVN     r2,#0
                SWI     "XOS_Module" ; On exit, r3 -> module name
                MOV     r0,r3,LSR #20 ; round down to megabyte boundary
                MOV     r0,r0,LSL #20
                LDR     r1,kmodid
                LDR     r2,kmodid+4
                ORR     r3,r3,#1 ; so we don't get EQ
.findkmodlp     LDR     r14,[r0],#4
.kfalsealarm    CMP     r14,r1
                CMPNE   r0,r3
                BLO     findkmodlp
                BNE     knotfound ; relies on NE
                LDR     r14,[r0],#4
                TEQ     r14,r2
                BNE     kfalsealarm
.knotfound      MOVNE   r0,#0
                STR     r0,[r12,#pKernel]
                LDMFD   r13!,{r0-r3,pc}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.postlist
.preedit        STMFD   r13!,{r0-r4,R14}
                ADR     R0,prevar
.prepostjoin    LDR     R1,[R12,#tmp256]
                MOV     R2,#256
                MOV     R3,#0
                MOV     R4,#3
                SWI     "XOS_ReadVarVal"
                LDMVSFD r13!,{r0-r4,pc}
                MOV     R0,R1
                MOVS    R1,R2
                SWINE   XOS_WriteN
                LDMFD   r13!,{r0-r4,pc}
.postedit       STMFD   r13!,{r0-r4,R14}
                ADR     R0,postvar
                B       prepostjoin
.prelist        STMFD   r13!,{r0-r4,R14}
                ADR     R0,prelistvar
                B       prepostjoin
.listtype       STMFD   r13!,{r0-r4,R14}
                ADR     R0,listtypevar
                B       prepostjoin
.prevar        := "LineEditor$Edit":= 0
.postvar       := "LineEditor$Output":= 0
.prelistvar    := "LineEditor$List":= 0
.listtypevar   := "LineEditor$Type":= 0
                ALIGN
; /E R0 -> buffer (b30=>echo char in R4,b31=>echo only chars entering buffer)
; !HACK! bit 31 ignored currently
;    R1 = Max length (NB may be >255),
;    R2,R3 = Min, Max -II values to be inserted in buffer
; /X R1 = Length of buffer read, excluding CR
.myreadlinev    STMFD   R13!,{R0,R2,R3,R4,R6-R11,R14} ; no PC any more
                TEQ     PC,PC
                BICNE   R7,R0,#%11<<30    ; Copy parameters to
                MOVEQ   R7,R0             ; where we want them
                MOV     R10,R1
                AND     R8,R3,#255
                ORR     R8,R8,R2,LSL#24   ; Shift loses high bits
                MOVNE   R0,R0,LSR#30
                MOVEQ   R0,R4,LSR#30
                AND     R4,R4,#255
                ORR     R8,R8,R0,LSL#(LN fPasswd / LN 2)
;                TST     R0,#1<<31         ; Echo only chars entering buffer?
;                ORRNE   R8,R8,#f<summat>  ; If so, set flag
                BL      readtaskhandle
                TEQ     R0,#0             ; Now R0=taskh/0 if not in taskwndw
                ORRNE   R8,R8,#fTaskwndw% ; Set taskwindow flag
                LDR     R9,[R12,#head]
.searchinstlp   TEQ     R9,#0
                BEQ     neednewinst
                LDR     R14,[R9,#taskh]
                TEQ     R14,R0
                LDRNE   R9,[R9,#next]
                BNE     searchinstlp
                B       foundinst
;
.neednewinst    MOV     R1,#0
                BL      newinst
                MOVS    R9,R0
                BEQ     cantcreateinst
                LDR     R0,[R9,#taskh]
                MOV     R1,#swichunk AND &FFFFF000
                ORR     R1,R1,#swichunk AND &00000FFF
                SWI     "XOS_ServiceCall"
                MOVVS   R1,#1
                TEQ     R1,#0
                MOVNE   R0,#0 ; default flags for taskwindow server
                ; !HACK! now store flags
                ; !HACK! flags for command line?
                ; !HACK! can we guess server?
.foundinst      BL      dogenericlineedit
                LDMFD   R13!,{R0,R2,R3,R4,R6-R11,R14,PC} ; don't pass on call

                .cantcreateinst MOVS    R0,R9             ; did the malloc-s fail
                BLNE    free              ; free _will_ ignore a NULL pointer
                BL      beep
                                          ; Pass onto next ReadLineV claimant
                LDMFD   R13!,{R0,R2,R3,R6-R11,PC}

.readtaskhandle STMFD   R13!,{R14}
                MOV     R0,#3             ; Read fDesktopActive (RO3+)
                SWI     XWimp_ReadSysInfo
                TEQ     R0,#0
                MOVNE   R0,#5             ; Read active task handle if in
                SWINE   XWimp_ReadSysInfo ; taskwindow (RO3+) (corrupts R1)
                LDMVCFD R13!,{pc}         ; (RO3+) we now have it, so return
                MOV     R0,#20
                MOV     R1,#0
                MOV     R2,#0
                STMFD   R13!,{r1,r2}      ; Build 5-word msg block on stack
                STMFD   R13!,{r0,r1,r2}   ; holding { 20, 0, 0, 0, 0 }
                MOV     R0,#19            ; Either RISC OS 2 or Arthur or
                MOV     R1,R13            ; the Wimp module is unplugged
                MVN     R2,#NOT(-1)       ; so try RO2 method to find taskh
                SWI     XWimp_SendMessage ; NB RO2 returns VS for ShellCLI
                MOVVS   R0,#0             ; 0 => Not in a taskwindow
                LDRVC   R0,[R13,#4]       ; Read task handle returned
                ADD     R13,R13,#20       ; Restore stack pointer
                LDMFD   R13!,{pc}
; \E as OS_ReadLine, but flag bits moved to R6 b0 b1; R5 = buffer ID
; \X as OS_ReadLine, except R2,R3 preserved
.ReadLine       STMFD   R13!,{R2-R11,R14}
                AND     R5,R5,#3
                MOV     R7,R0             ; Copy parameters to
                MOV     R10,R1            ; where we want them
                AND     R8,R3,#255
                ORR     R8,R8,R2,LSL#24   ; Shift loses high bits
                ORR     R8,R8,R5,LSL#(LN fPasswd / LN 2)
                MOV     R9,R6
                BL      validate_id
                BLVC    dogenericlineedit
                LDMFD   R13!,{R2-R11,PC}
; \E as for .dolineedit (except for fCopy bit in R8)
; \X as for OS_ReadLine, except R6-R11 may be corrupt
.dogenericlineedit
                STMFD   R13!,{R14}
                MOV     R11,#4            ; Store values of *FX 221-228
.ollylp         RSB     R0,R11,#225       ; Program FN keys to return
                MOV     R1,#2             ; extended codes ie zero
                MOV     R2,#0             ; byte followed by code
                SWI     XOS_Byte          ; NB Error corrupts R0
                AND     R1,R1,#&FF
                ORR     R3,R1,R3,LSL#8
                SUBS    R11,R11,#1
                STMEQFD R13!,{R3}         ; Save on the stack
                CMN     R11,#-(-4)
                BNE     ollylp
                MOV     R0,#219
                MOV     R1,#&8A
                MOV     R2,#0
                SWI     XOS_Byte          ; Set up TAB key WIMP style
                STMFD   R13!,{R1,R3}      ; Save on the stack
                MOV     R0,#4             ; Make cursor keys act as
                MOV     R1,#2             ; function keys
                SWI     XOS_Byte          ; Returns r1=old state, r2=?
                TEQ     R1,#0
                ORREQ   r8,r8,#fCopy%     ; COPYing is ok iff *FX4,0
                BL      preedit
                BL      dolineedit        ; Actually input a line!
                BL      postedit
                MOV     R0,#0
                STR     R0,[R9,#r7]       ; No line
                MOV     R0,#4
                SWI     XOS_Byte          ; Restore cursor keys
                LDMFD   R13!,{R1,R3}      ; Retrieve from stack
                MOV     R0,#219
                MOV     R2,#0
                SWI     XOS_Byte          ; Restore TAB key
                MOV     R11,#4
.ollylp2        ADD     R0,R11,#224       ; Restore FN key interprettns
                AND     R1,R3,#&FF
                MOV     R2,#0
                SWI     XOS_Byte          ; NB Error corrupts R0
                MOV     R3,R3,LSR #8
                SUBS    R11,R11,#1
                LDMEQFD R13!,{R3}
                CMN     R11,#-(-4)
                BNE     ollylp2
                MOV     R1,R6             ; Now R1=length of line
                MOV     R14,#0
                STR     R14,[R9,#cur]     ; Mark instance inactive
                TST     r8,#fEsc%         ; See if escape was pressed
                BEQ     notesc
                SUBS    R0,R0,#0          ; C=1, V=0
                LDMFD   R13!,{PC}
.notesc         ADDS    R0,R0,#0          ; C=0, V=0
                LDMFD   R13!,{PC}
; /E R0 = task handle or = 0 for not a taskwindow or = -1 for client buffer
;    R1 = buffer size (or 0 for default)
; /X R0 -> new instance or = 0 if couldn't create
.newinst        STMFD   R13!,{r1-r3,r6,r9,r14}
                MOVS    R3,R1
                LDREQ   R3,[R12,#bufsize]
                MOV     R1,R0
                MOV     R0,#sizeofinst    ; Create new instance for taskh R0
                BL      malloc            ; (either new taskwindow or first
                MOVS    R9,R0             ; use of command line)
                LDMEQFD R13!,{r1-r3,r6,r9,PC} ; If malloc failed...
                CMN     R1,#-(-1)         ; Check for client buffer case
                BEQ     neednewbuffer     ; and don't share buffer if it is
                LDR     R14,[R12,#flags]
                TST     R14,#f_LocalHist  ; Check flag for multibuffer
                BNE     neednewbuffer     ; Local buffers, so create one
                LDR     R0,[R12,#head]
                TEQ     R0,#0             ; If we already have an instance,
                BNE     newinst_skip      ; copy its buffer
                TEQ     R1,#0             ; Just create an instance for
                BEQ     neednewbuffer     ; non-TaskWindows
                MOV     R0,#0
                MOV     R6,R1
                MOV     R1,R3             ; Buffer size
                BL      newinst
                MOV     R1,R6             ; Restore Task Handle to R1
                TEQ     R0,#0
                MOVEQ   R0,R9
                LDMEQFD R13!,{r1-r3,r6,r9,r14} ; If couldn't create cli inst
                BEQ     free
.newinst_skip   LDMIB   R0,{R2,R6,R14}    ; If global then copy buf, end,
                STMIA   R9,{R0,R2,R6,R14} ; and limit from first buffer
                B       nonewbuffer       ; and put old head into next
;
.neednewbuffer  MOV     R0,R3,ASL#10      ; Convert to Kbytes
                MOV     R2,R0
                BL      malloc
                TEQ     R0,#0
                MOVEQ   R0,R9
                LDMEQFD R13!,{r1-r3,r6,r9,r14} ; If malloc failed...
                BEQ     free
                ADD     R2,R0,R2
                STR     R2,[R9,#limit]
                STR     R0,[R9,#buf]
                MOV     R14,#0
                STRB    R14,[R0],#1
                STR     R0,[R9,#end]
.nonewbuffer    STR     R1,[R9,#taskh]    ; Task handle
                MOV     R0,#0
                STR     R0,[R9,#fkeybuf]  ; No fkey active
                STR     R0,[R9,#yankbuf]  ; No yank-able text
                STR     R0,[R9,#cur]      ; Inactive
                STR     R0,[R9,#r7]       ; No line
                STR     R0,[R9,#root]     ; No command completion tree
                CMN     R1,#-(-1)
                LDRNE   R0,[R12,#head]    ; Link into appropriate list
                LDREQ   R0,[R12,#morebufs]
                STR     R0,[R9,#next]
                STRNE   R9,[R12,#head]
                STREQ   R9,[R12,#morebufs]
                MOV     R0,R9             ; Return R0 pointing to current
                LDMFD   R13!,{r1-r3,r6,r9,PC} ; instance
.claimreadlinev STMFD   R13!,{R0-R2,R14}
                MOV     R0,#ReadLineV     ; Claim ReadLineV
                ADR     R1,myreadlinev
                MOV     R2,R12
                SWI     "XOS_Claim"
                LDMFD   R13!,{R0-R2,PC}
.relreadlinev   STMFD   R13!,{R0-R2,R14}
                MOV     R0,#ReadLineV     ; Release ReadLineV
                ADR     R1,myreadlinev
                MOV     R2,R12
                SWI     "XOS_Release"
                CMP     R0,R0
                LDMFD   R13!,{R0-R2,PC}
]
IF NOT RISCOS311% THEN
[OPT A%
; Try to get a dynamic area
.alloc_init     STMFD   R13!,{r0-r8,r14}
                MOV     R0,#0    ; reason code- create
                MVN     R1,#NOT(-1)   ; number not specified
                MOV     R2,#0    ; initial size
                MVN     R3,#NOT(-1)   ; base not specified
                MOV     R4,#%10000010 ; not dragged, single mapped;
                                      ; cacheable, bufferable
                                      ; inaccessible in usr mode
                MOV     R5,#unison_area_max_size
                ADR     R6,area_handler
                MOV     R7,R12
                ADR     R8,area_title
                SWI     "XOS_DynamicArea"
                MOVVS   R3,#0 ; no dynamic areas it seems
                ADR     R0,area_info
                MOV     R4,#0     ; area_blocks
                STMIA   R0,{R1-R4}
                LDMFD   R13!,{r0-r8,PC}
; Delete a dynamic area if we've got one
.alloc_final    STMFD   R13!,{r0,r1,r2-r8,r14}
                LDR     R1,area_base
                TEQ     R1,#0
                MOVNE   R0,#0
                STRNE   R0,area_base
                LDRNE   R1,area_number
                MOVNE   R0,#1    ; reason code- delete
                SWINE   "XOS_DynamicArea"
                CMP     R0,R0
                LDMFD   R13!,{r0,r1,r2-r8,PC}
.area_info
.area_number    &    0 ; !HACK! these 4 need to be writable
.area_size      &    0
.area_base      &    0
.area_blocks    &    0
; *************************************** unison dynamic area handling code
.area_handler
  MOV   PC,R14
.area_title:= "LineEditor Buffers":= 0:ALIGN
]
area_size_overhead = 64
area_block_overhead = 32
[OPT A%
  ; entry- R3 = required size
  ; exit-  R2 = pointer to claimed block
  ;        R3 preserved
.unison_alloc   STMFD   R13!,{R1,R3-R8,R14}
                LDR     R1,area_blocks
                CMP     R1,#0
                BLEQ    unison_alloc_init_heap
                BVS     unison_alloc_error
    ; attempt to allocate a block
.unison_alloc_alloc
                MOV     R0,#2     ; get heap block
                LDR     R1,area_base
    ; r3 set
                SWI     "XOS_Heap"
                BVS     unison_alloc_error
                CMP     R2,#0
                BVS     unison_alloc_failed
                LDR     R1,area_blocks
                ADD     R1,R1,#1
                STR     R1,area_blocks
                BL      unison_shrink_area
                LDMFD   R13!,{R1,R3-R8,PC}
.unison_alloc_failed
    ; attempt to add some more memory to the heap
                LDR     R0,area_number
                ADD     R1,R3,#area_block_overhead
                SWI     "XOS_ChangeDynamicArea"
    ; find out how large the dynamic area actually is
                LDRVC   R0,area_number
                SWIVC   "XOS_ReadDynamicArea"
                BVS     unison_alloc_error
                STMFD   R13!,{R3}
                LDR     R0,area_size
                STR     R1,area_size
                SUB     R3,R1,R0
                MOV     R0,#5    ; extend heap
                LDR     R1,area_base
                SWI     "XOS_Heap"
                LDMFD   R13!,{R3}
                BVC     unison_alloc_alloc
.unison_alloc_error
                LDR     R1,[R0]
                CMP     R1,#&184 ; ie no_room_in_heap_err
                BEQ     unison_alloc_failed
                SWI     "XOS_GenerateError"
                LDMFD   R13!,{R1,R3-R8,PC}
.unison_alloc_init_heap
                STMFD   R13!,{R1-R4,R14}
                LDR     R0,area_number
                ADD     R1,R3,#area_size_overhead       ; required size
                SWI     "XOS_ChangeDynamicArea"
                LDMVSFD R13!,{R1-R4,PC}
                STR     R1,area_size
                MOV     R3,R1
                MOV     R0,#0        ; initialise heap
                LDR     R1,area_base
                SWI     "XOS_Heap"
                LDMFD   R13!,{R1-R4,PC}
.unison_shrink_area
                STMFD   R13!,{R2-R3,R14}
                LDR     R8,area_size
                LDR     R1,area_blocks
                CMP     R1,#0    ; no block - size to zero
                BEQ     unison_shrink_area_vanish
                MOV     R0,#5    ; shrink heap
                LDR     R1,area_base
                RSB     R3,R8,#0
                SWI     "XOS_Heap"
;  LDMVSFD R13!,{R2-R3,PC}^
                ADDS    R14,R3,R8 ; (-r3==r8)?
                MOVEQ   R3,R8
; R3 = number of bytes the heap was shrunk by
                RSB     R1,R3,#0
                LDR     R0,area_number
                SWI     "XOS_ChangeDynamicArea"
                SUBVC   R8,R8,R1    ; r1 = bytes moved
                STRVC   R8,area_size
; change size of heap to reflect this new size
                SUBVC   R3,R3,R1     ; difference in bytes between the heap and the change in size of the dynamic area
                MOV     R0,#5
                LDR     R1,area_base
                SWI     "XOS_Heap"
                LDMFD   R13!,{R2-R3,PC}
.unison_shrink_area_vanish
                LDR     R0,area_number
                RSB     R1,R8,#0
                SWI     "XOS_ChangeDynamicArea"
                SUBVC   R8,R8,R1
                STRVC   R8,area_size
                LDMFD   R13!,{R2-R3,PC}
]
ENDIF
[OPT A%
; /E R0=#bytes to allocate; /X R0->block or =0 if no room
; NB It seems that under RISC OS 2, OS_Module,6 can return R2=0, VC under
; some circumstances (RKL hit this problem) - this routine copes
.malloc         STMFD   R13!,{R1,R2,R3,R14}
                MOV     R3,R0
]
IF NOT RISCOS311% THEN
[OPT A%
                LDR     R1,area_base
                CMP     R1,#0
                BNE     dynmalloc
]
ENDIF
[OPT A%
                MOV     R0,#6
                SWI     "XOS_Module"
.mallocback     MOVVC   R0,R2
                MOVVS   R0,#0
                LDMFD   R13!,{R1,R2,R3,PC}
;
]
IF NOT RISCOS311% THEN
[OPT A%
.dynmalloc      BL      unison_alloc
                B       mallocback
]
ENDIF
[OPT A%
; /E R0->block to free or =0 (ignored), /X R0=0 [useful for zeroing ptrs]
; *** NB returns 0 (C free doesn't) ***
.free           STMFD   R13!,{R1,R2,R14}
                MOVS    R2,R0
                BEQ     free_null
]
IF NOT RISCOS311% THEN
[OPT A%
                LDR     R1,area_base
                CMP     R1,#0
                BNE     dynfree
]
ENDIF
[OPT A%
                MOV     R0,#7
                SWI     "XOS_Module"
.free_null      MOV     R0,#0
                LDMFD   R13!,{R1,R2,PC}
]
IF NOT RISCOS311% THEN
[OPT A%
;
; R1 = area_base
; R2 = pointer to block to free
.dynfree        STMFD   R13!,{R3-R8}
                MOV     R0,#3     ; free block
                SWI     "XOS_Heap"
                LDRVC   R1,area_blocks
                SUBVC   R1,R1,#1
                STRVC   R1,area_blocks
                BLVC    unison_shrink_area
                LDMFD   R13!,{R3-R8}
                B       free_null
]
ENDIF
[OPT A%
; /E r0,r1 = chars to teq; /X Z set appropriately, other flags, r1 undef'd
.caselessteq    STMFD   R13!,{r14}
                LDR     r14,[r12,#upcasetable]
                TEQ     r14,#0
                BEQ     caselessteq_old
                LDRB    r0,[r14,r0]
                LDRB    r1,[r14,r1]
                TEQ     r0,r1
                LDMFD   R13!,{pc}
.caselessteq_old
                EORS    r1,r0,r1
                LDMEQFD R13!,{pc}          ; Simple - exact match
                TEQ     r1,#32
                LDMNEFD R13!,{pc}          ; Simplish - can't match
                BIC     r0,r0,#32
                CMP     r0,#ASC"Z"
                RSBLTS  r1,r0,#ASC"A"
                TSTLT   r0,#0              ; If LT, then force EQ
                LDMFD   R13!,{pc}
.caselessteq_init
 STMFD   R13!,{R0,R1,R14}
 MVN     r0,#0 ; -1
 SWI     "XTerritory_UpperCaseTable"
 MOVVS   r0,#0
 STR     r0,[r12,#upcasetable]
 LDMFD   R13!,{R0,R1,PC}
]
IF debug% THEN
[OPT A%
.dump           STMFD   R13!,{R12,R14}
                MOV     R12,R13
                BL      recall
                LDMFD   R13!,{R12,PC}
.showregs       STMFD   R13!,{R0,R14}      ; Change offset on r13 below if
                STMFD   R13!,{R1}          ; stacking changed
                STMFD   R13!,{R2}
                MOV     R2,R14
                SWI     XOS_NewLine
                SWI     XOS_WriteI+ASC"R"
                SWI     XOS_WriteI+ASC"0"
                SWI     XOS_WriteI+ASC" "
                SWI     XOS_WriteI+ASC" "
                BL      outhex
                SWI     XOS_WriteI+ASC" "
                SWI     XOS_WriteI+ASC"R"
                SWI     XOS_WriteI+ASC"1"
                SWI     XOS_WriteI+ASC" "
                SWI     XOS_WriteI+ASC" "
                MOV     R0,R1
                BL      outhex
                SWI     XOS_WriteI+ASC" "
                MOV     R1,R2
                LDMFD   R13!,{R2}
]
FOR l%=2 TO9
[OPT A%
                SWI     XOS_WriteI+ASC"R"
                SWI     XOS_WriteI+ASC"0"+l%
                SWI     XOS_WriteI+ASC" "
                SWI     XOS_WriteI+ASC" "
                MOV     R0,l%
                BL      outhex
]
IF (l%AND3)=3 THEN
[OPT A%
                SWI     XOS_NewLine
]
ELSE
[OPT A%
                SWI     XOS_WriteI+ASC" "
]
ENDIF
NEXT
FOR l%=10 TO13
[OPT A%
                SWI     XOS_WriteI+ASC"R"
                SWI     XOS_WriteI+ASC"1"
                SWI     XOS_WriteI+ASC"0"+l%-10
                SWI     XOS_WriteI+ASC" "
                ADD     R0,l%,#(-12*(l%=13)) ; Offset for stack pointer
                BL      outhex
]
IF (l%AND3)=3 THEN
[OPT A%
                SWI     XOS_NewLine
]
ELSE
[OPT A%
                SWI     XOS_WriteI+ASC" "
]
ENDIF
NEXT
[OPT A%
                SWI     XOS_WriteI+ASC"P"
                SWI     XOS_WriteI+ASC"C"
                SWI     XOS_WriteI+ASC" "
                SWI     XOS_WriteI+ASC" "
                MOV     R0,R1 ; R14 on entry
                BL      outhex
                SWI     XOS_NewLine
                LDMFD   R13!,{R1}
                LDMFD   R13!,{R0,PC}
.outhex         STMFD   R13!,{R0-R2,R14}
                SUB     R13,R13,#12
                MOV     R1,R13
                MOV     R2,#9
                SWI     "XOS_ConvertHex8"
                SWIVC   XOS_Write0
                ADD     R13,R13,#12
                LDMFD   R13!,{R0-R2,PC}
]
ENDIF
[OPT A%
.pprinthelp     MOV     R6,R14
                BL      pprint
                MOV     R0,#0
                MOV     PC,R6

.jmptab         FNkeytab
]
NEXT

FOR N%=1 TO M%:PRINT U%(N%),N%(N%),(U%(N%)+N%(N%)-1)*(LEN K$(N%)-2)-4,K$(N%):NEXT
SYS "OS_GetEnv" TO P$
I%=INSTR(P$,"-quit ")
IF I% THEN
 P$=MID$(P$,I%+6):WHILE LEFT$(P$,1)=" ":P$=MID$(P$,2):ENDWHILE
 I%=INSTR(P$," "):IF I% P$=LEFT$(P$,I%-1):IF LEFT$(P$,1)="""" P$=MID$(P$,2)
 J%=0:REPEAT I%=J%:J%=INSTR(P$,".",I%+1):UNTIL J%=0
 IF I% P$=LEFT$(P$,I%)
ELSE P$=""
ENDIF
PRINT"'"P$;fnm$"'"
SYS "OS_File",&0A,P$+fnm$,&FFA,,org,O%
END


DEF PROCinitdict
LOCAL I%,N%
DIM K$(256),D$(256),U%(256),N%(256)
N%=0:REPEAT N%+=1:READ C$:I%=INSTR(C$,"~")
WHILE I%:C$=LEFT$(C$,I%-1)+cr$+MID$(C$,I%+1):I%=INSTR(C$,"~"):ENDWHILE
D$(N%)=C$:UNTIL C$="":M%=N%-1
FOR N%=M% TO 1 STEP -1
 K$="":S%=1
 REPEAT
  I%=INSTR(D$(N%),"^")
  IF I% THEN
   J%=INSTR(D$(N%),"^",I%+1):IF J%=0 PRINT"Mismatched ^ in dictionary":STOP
   L$=LEFT$(D$(N%),I%-1):R$=MID$(D$(N%),J%+1)
   IF J%>I%+1 THEN
    T$=MID$(D$(N%),I%+1,J%-I%-1):K%=N%+1
    WHILE T$<>K$(K%):K%+=1:IF K%>M% PRINT"Bad nested dictionary tokens":STOP
    ENDWHILE
    K$+=MID$(D$(N%),S%,I%-S%)+T$:S%=J%+1-LEN T$
    D$(N%)=L$+esc$+CHR$ K%+R$:N%(K%)+=1
   ELSE K$+=esc$+CHR$0:S%=J%+1:D$(N%)=L$+esc$+CHR$0+R$
   ENDIF
  ENDIF
 UNTIL I%=0
 REPEAT I%=INSTR(K$,"  "):IF I% K$=LEFT$(K$,I%)+MID$(K$,I%+2)
 UNTIL I%=0
 K$(N%)=K$+MID$(D$(N%),S%)
NEXT
ENDPROC

DEF FNdict(A$):[OPT(A%ANDNOT1):= LEN A$+2:= A$:= 0:]:=0

DEF FNtab(B%,Z%):LOCAL V%:IF B%<P%-jmptab PRINT"cockup in key table":STOP
V%=(Z%-base)DIV4:IF V%>255 PRINT"value for table too big":STOP
IF V%<0 PRINT"value for table too small":STOP
[OPT(A%ANDNOT1):= STRING$(B%-(P%-jmptab),CHR$((vanilla-base)DIV4)):= V%:]
=0

DEF FNtb2(B%,C%,Z%):LOCAL V%:IF B%<P%-jmptab PRINT"cockup in key table":STOP
V%=(Z%-base)DIV4:IF V%>255 PRINT"value for table too big":STOP
IF V%<0 PRINT"value for table too small":STOP
IF C%<B% PRINT"range is empty":STOP
[OPT(A%ANDNOT1):= STRING$(B%-(P%-jmptab),CHR$((vanilla-base)DIV4))
= STRING$(C%-B%+1,CHR$ V%):]:=0

DEF FNpp(S$)
LOCAL N%,I%,K$,f%,J%,l%
REPEAT
 N%=0
 REPEAT
  N%+=1:K$=K$(N%):l%=LEN K$
  I%=INSTR(S$,K$)
  IF I%=0 AND RIGHT$(K$)=" " THEN
   I%=INSTR(S$,LEFT$(K$)+esc$)
   IF I% THEN
    f%=ASC(K$(ASC(MID$(S$,I%+LEN K$,1))))
    IF f%=32 OR f%=9 l%-=1 ELSE I%=0
   ENDIF
  ENDIF
  IF I%=0 AND LEFT$(K$,1)=" " THEN
   K$=MID$(K$,2)
   J%=0
   REPEAT
    J%=INSTR(S$,K$,J%+1)
    f%=(MID$(S$,J%-2,1)=esc$)
    IF f% IF RIGHT$(K$(ASC MID$(S$,J%-1,1)))=" " I%=J%
   UNTIL I% OR J%=0
   IF I%=0 AND RIGHT$(K$)=" " THEN
    K$=LEFT$(K$)
    J%=0
    REPEAT
     J%=INSTR(S$,K$+esc$,J%+1)
     f%=(MID$(S$,J%-2,1)=esc$)
     IF f% IF RIGHT$(K$(ASC MID$(S$,J%-1,1)))=" " I%=J%
     IF I% THEN
      f%=ASC(K$(ASC(MID$(S$,I%+LEN K$+1,1))))
      IF f%=32 OR f%=9 ELSE I%=0
     ENDIF
    UNTIL I% OR J%=0
   ENDIF
   l%=LEN K$
  ENDIF
 UNTIL I% OR N%=M%
 IF I% S$=LEFT$(S$,I%-1)+esc$+CHR$ N%+MID$(S$,I%+l%):IF (A%AND2) U%(N%)+=1
UNTIL I%=0
[OPT(A%ANDNOT1):= S$:]
=0

DEF PROCerr
ON ERROR OFF
ERROR ERR,REPORT$+" at line "+STR$ ERL
ENDPROC

REM Use ~ for CR
DATA "^Syntax: ^*^^"
DATA " (for^ current ^^ line^ only)"
DATA "s with start matching."
DATA " mark^ and ^^ cursor^"
DATA " history buffer"
DATA "wards through "
DATA " Line Editor "
DATA "overtype mode"
DATA "*Configure Ed"
DATA "Move^ cursor^ "
DATA " completion"
DATA " character "
DATA " displays "
DATA "underscore"
DATA "^ to ^end^ of ^"
DATA " contents "
DATA "	Flashing "
DATA " previous"
DATA " current "
DATA "filename"
DATA "Return, "
DATA "Syntax: "
DATA "	Steady "
DATA "default"
DATA "RISC OS"
DATA " cursor"
DATA " set: "
DATA "Delete"
DATA "Clear "
DATA " sets "
DATA "nsert"
DATA " line"
DATA " and "
DATA " the "
DATA "Step "
DATA "~bit "
DATA "ight"
DATA "Down"
DATA " to "
DATA " of "
DATA "lags"
DATA "eft"
DATA ""

DEF FNkeytab
[OPT A%
; Unused Ctrl-<key> combinations GLORSVZ\]_ (^I could be reclaimed)
    FNtab(&000,setmark)      ; cSpace
    FNtab(&001,gotostart)    ; cA
    FNtab(&002,left)         ; cB
    FNtab(&003,showcomp)     ; cC
    FNtab(&004,deleteright)  ; cD
    FNtab(&005,gotoend)      ; cE
    FNtab(&006,right)        ; cF
    FNtab(&008,deleteleft)   ; cH
    FNtab(&009,dotcshcomp)   ; cI       ; Try tcsh fnm complet'n
    FNtab(&00A,return)       ; cJ
    FNtab(&00B,killeol)      ; cK
    FNtab(&00D,enter)        ; cM
    FNtab(&00E,downhistreq)  ; cN       ; Recall next line
    FNtab(&00F,copy);fileropen)    ; cO
    FNtab(&010,uphistreq)    ; cP       ; Recall previous line
    FNtab(&011,quote)        ; cQ
    FNtab(&014,transpose)    ; cT
    FNtab(&015,delline)      ; cU
    FNtab(&017,wipe)         ; cW
    FNtab(&018,swapmarkcursor);cX
    FNtab(&019,yank)         ; cY
    FNtab(&01B,escape)       ; ESCAPE
    FNtab(&01C,deleteleft)   ; <-|
    FNtab(&01D,enter)        ; ¬
    FNtab(&01E,gotostart)    ; HOME
    FNtab(&01F,wipehistory)  ; cDELETE
    FNtb2(&020,&07E,vanilla) ; SPACE-~
    FNtab(&07F,deleteleft)   ; Ǒ
;OL FNtab(&07F,deleteright)  ; Ǒ
    FNtb2(&080,&0FF,vanilla) ; top bit set characters
    FNtab(&104,delword)      ; scD
    FNtab(&10A,enter)        ; scJ
    FNtab(&10C,vanilla)      ; scL
    FNtab(&10E,vanilla)      ; scN
    FNtab(&10F,vanilla)      ; scO
    FNtab(&114,vanilla)      ; scT
    FNtab(&11A,vanilla)      ; scZ
    FNtab(&11D,vanilla)      ; sRETURN
    FNtab(&11F,wipeallhistory);scDELETE
    FNtab(&120,vanilla)      ; sSPACE
    FNtab(&12B,escape)       ; c[
    FNtab(&13D,vanilla)      ; cRETURN
    FNtab(&152,setmark)      ; sc2
    FNtab(&15D,vanilla)      ; scRETURN
    FNtb2(&161,&165,vanilla) ; k/-k+
    FNtab(&166,enter)        ; kEnter
    FNtab(&167,vanilla)      ; k.
    FNtab(&17F,deleteright)  ; sDELETE
    FNtb2(&180,&189,fnkey)   ; F0-F9
    FNtab(&18A,dotcshcompshow);TAB      ; Try tcsh fnm complet'n
    FNtab(&18B,copy)         ; COPY
    FNtab(&18C,left)         ; LEFT
    FNtab(&18D,right)        ; RIGHT
    FNtab(&18E,downhistreq)  ; DOWN     ; Recall next line
    FNtab(&18F,uphistreq)    ; UP       ; Recall previous line
    FNtab(&19A,completenext) ; sTAB     ; Try 4DOS fnm complet'n
    FNtab(&19B,copy)         ; sCOPY    [like !Zap]
    FNtab(&19C,prevword)     ; sLEFT
    FNtab(&19D,nextword)     ; sRIGHT
    FNtab(&19E,dnhistmatch)  ; sDOWN
    FNtab(&19F,uphistmatch)  ; sUP
    FNtab(&1AB,gotoend)      ; cCOPY
    FNtab(&1AC,gotostart)    ; cLEFT
    FNtab(&1AD,gotoend)      ; cRIGHT
    FNtab(&1AE,cdown)        ; cDOWN
    FNtab(&1AF,oldesthist)   ; cUP
    FNtab(&1BA,completeprev) ; scTAB    ; Try 4DOS fnm complet'n
    FNtb2(&1CA,&1CC,fnkey)   ; F10-F12
    FNtab(&1CD,toggleinsert) ; INSERT
    FNtab(&1DD,removeline)   ; sINSERT
    FNtab(&1FF,vanilla)      ; forces generation of end of table
]
=0

DEF FNtrace(m$)
IF trace% THEN
[OPT A%
STMFD    R13!,{r0}
SWI      XOS_WriteS
= m$+lfcr$+bl$
ALIGN
LDMFD    R13!,{r0}
]
ENDIF
=0

DEF FNassert(a$)
IF EVAL a$ ELSE PRINT "Assertion '"a$"' failed":STOP
=0

DEF FNADRL(R%,T%)
LOCAL H%:IF T% AND 3 THEN H%=255:ELSE H%=1023
PRINT ~P% T%;
H%=(T% AND NOT H%)+(P%+8 AND H%):T%-=H%
PRINT ~H% T% H%+T%
IF T%>=0 THEN [OPT A%:ADR R%,H%:ADD R%,R%,#T%:]=0
[OPT A%:ADR R%,H%:SUB R%,R%,#-T%
]
=0

DATA 42
DATA ignore, beepignore, left, right, delword, cright, cleft, sright, sleft
DATA toggleinsert, delline, removeline, complete, completenext, completeprev
DATA setmark, copy, swapmark, cut, deletenext, delete, wipehistory, deltoend
DATA paste, swapchars, quote, vanilla, cup, cdown, up, down, sup, sdown
DATA escape, fnkey, wipeallhistory, enter, return, uncopy
DATA showcomp, completeshow, fileropen
