REM ==========================
REM DBC Challenge: Text Editor
REM Author: Phaelax
REM ==========================
 
maxLines = 256
dim lines$(maxLines)
caretX = 0
caretY = 0
lineCount = 1
Set Text Font "Courier",1
Set Text Size 12
textWidth = text width(" ")
textHeight = text height(" ")
caretDelay = 300
screenWidth = 80
 
 
 
sync on
sync rate 0
 
 
DO
	cls
 
	oldkey = key
	key = asc(inkey$())
	rem so pressing a single key won't display a billion copies 
	if oldkey <> key
		if (key > 31 and key < 127) OR (key > 127 and key < 255)
			if len(lines$(caretY)) < screenWidth
				i$ = chr$(key)
				bc$ = left$(lines$(caretY), caretX)
				ac$ = right$(lines$(caretY), len(lines$(caretY))-caretX)
				lines$(caretY) = bc$ + i$ + ac$
				inc caretX
			endif
		else			
			rem backspace
			if key = 8
				rem if caret is at beginning of line, move above to previous
				rem and append remaining text
				if caretX = 0 and caretY > 0
					caretX = len(lines$(caretY-1))
					lines$(caretY-1) = lines$(caretY-1)+lines$(caretY)
					for t = caretY to lineCount-1
						lines$(t) = lines$(t+1)
					next t
					dec caretY
					dec lineCount
				rem delete previous character
				else
					bc$ = left$(lines$(caretY), caretX-1)
					ac$ = right$(lines$(caretY), len(lines$(caretY))-caretX)
					lines$(caretY) = bc$ + ac$
					dec caretX
				endif
			endif
			rem return key
			if key = 13 and lineCount < maxLines
				bc$ = left$(lines$(caretY), caretX)
				ac$ = right$(lines$(caretY), len(lines$(caretY))-caretX)
				lines$(caretY) = bc$
				for t = lineCount to caretY+1 step -1
					lines$(t) = lines$(t-1)
				next t
				lines$(caretY+1) = ac$
				caretX = 0
				inc caretY
				inc lineCount
			endif
		endif		
	endif
	rem delete key
	if scancode() = 211 and delflag=0
		delflag=1
		bc$ = left$(lines$(caretY), caretX)
		ac$ = right$(lines$(caretY), len(lines$(caretY))-(caretX+1))
		lines$(caretY) = bc$+ac$				
	endif
	if scancode() = 0 then delflag=0
	rem move cursor with arrow keys
	if upkey()=1 and caretY > 0 and flag=0
		flag=1
		length = len(lines$(caretY-1))
		if caretX > length then caretX = length
		dec caretY
	endif
	if downkey()=1 and caretY < 28 and flag=0
		flag=1
		if caretY+1 < lineCount
			length = len(lines$(caretY+1))
			if caretX > length then caretX = length
			inc caretY
		endif
	endif
	if rightkey()=1 and flag=0
		flag=1
		if caretX < len(lines$(caretY)) then inc caretX
	endif
	if leftkey()=1 and flag=0
		flag=1
		if caretX > 0 then dec caretX
	endif
	if upkey()+downkey()+rightkey()+leftkey() = 0 then flag = 0
 
 
	rem display the crap
	gosub displayLines
	gosub displayCaret
 
 
	text 0,460,"X: "+str$(caretX)+", Y: "+str$(caretY)
 
	sync
LOOP
 
 
 
rem
rem
rem
displayCaret:
	if timer() > timestamp+caretDelay
		showCaret = abs(showCaret-1)
		timestamp = timer()
	endif
	if showCaret = 1 then text caretX*textWidth, caretY*textHeight, "_"
RETURN
 
rem
rem
rem
displayLines:
	for j = 0 to 20
		text 0,j*textHeight,lines$(j)
	next j
RETURN