This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Grim Reaper's profile picture

Predictive Text (Files)

Started by Grim Reaper, 19 July 2012 - 07:38 AM
Grim Reaper #1
Posted 19 July 2012 - 09:38 AM
After much goofing around I decided I might try to do something somewhat productive for a change… And this is the spoil of my labor. ;)/>/>

Simply put, this is a function rather than a full API, however it serves its purpose nonetheless.
This function will predict (very simply) the file name you are typing based on what you have already typed.

I apologize for any 'inefficient' code, but it is late and I don't care all that much :P/>/>

I hope you all enjoy and put it to good use, thanks.

Spoiler


local tFiles = fs.list("/")
local sInput = ""
local nFilesDisplayed = 0
local select = 0 -- 0 is the textField

local function clear() term.clear(); term.setCursorPos( 1, 1 ) end

local function getInputAndPredictText()
while true do
clear()

-- Predict the text --
for i=4, nFilesDisplayed+3 do -- Clear the space where the text is drawn
term.setCursorPos(3, i)
term.write(string.rep(" ", 46))
end
for i=1, #tFiles do
if string.sub(tFiles[i], 1, string.len(sInput)) == sInput then
nFilesDisplayed = nFilesDisplayed+1

term.setCursorPos(3, nFilesDisplayed+4)
if select == nFilesDisplayed then
term.write(">"..tFiles[i])
if not fs.isDir( tFiles[i] ) then sSelectedFile = tFiles[i] end
else     term.write(" "..tFiles[i]) end
end
end
term.setCursorPos(3, 4); term.write(string.rep(" ", string.len("No matches found.")))
if nFilesDisplayed == 0 then term.setCursorPos(3, 4); term.write("No matches found.") end

term.setCursorPos(1, 1); term.write("> ")
term.setCursorPos(3, 1)
term.write(sInput)
event, char = os.pullEvent()

if select == 0 then
term.setCursorBlink(true)
if event == "char" then sInput = sInput .. char 
elseif event == "key" and char == 14 then
term.setCursorPos(3, 1); term.write(string.rep(" ", string.len(sInput)))
sInput = string.sub(sInput, 1, string.len(sInput)-1)
elseif event == "key" and char == 208 then term.setCursorBlink(false); select = select+1

elseif event == "key" and char == 28 and sInput == "exit" then term.setCursorBlink(false); break
end
else
term.setCursorBlink(false)
if event == "key" and char == 208 and select < nFilesDisplayed then select = select+1
elseif event == "key" and char == 200 and select-1 == 0 then term.setCursorBlink(true); select = 0
elseif event == "key" and char == 200 then select = select-1
elseif event == "key" and char == 28 and sSelectedFile ~= "isDir" then os.run({ ["shell"] = shell }, sSelectedFile)
end
end

nFilesDisplayed = 0
end
end

clear()
term.setCursorBlink(true)
getInputAndPredictText()

Feel free to post any critiques, however I ask that they be constructive rather than a call out. :)/>/>
Grim Reaper #2
Posted 24 July 2012 - 01:22 AM
~ Fixed a couple GUI and reset issues.