+function raw_mode!(mode::Bool)
+ if ccall(:jl_tty_set_mode, Int32, (Ptr{Void}, Int32), STDIN.handle, mode) != 0
+ throw("FATAL: Terminal unable to enter raw mode.")
+ end
+end
+
+function getKey()
+ raw_mode!(true)
+ byte = readbytes(STDIN, 1)[1]
+ raw_mode!(false)
+
+ if byte == 0x0d
+ return 0x0a
+ elseif byte == 127
+ return 0x08
+ else
+ return byte
+ end
+end
+
+KEY_CFA = defPrimWord("KEY", () -> begin
+ pushPS(Int(getKey()))
+ return NEXT
+end)
+
+function getLineFromSTDIN()
+
+ function getFrag(s)
+ chars = collect(s)
+ slashIdx = findlast(chars, '\\')
+
+ if slashIdx > 0
+ return join(chars[slashIdx:length(chars)])
+ else
+ return nothing
+ end
+ end
+
+ function backspaceStr(s, bsCount)
+ oldLen = length(s)
+ newLen = max(0, oldLen - bsCount)
+ return join(collect(s)[1:newLen])
+ end
+
+ line = ""
+ while true
+ key = Char(getKey())
+
+ if key == '\n'
+ print(" ")
+ return AbstractString(line)
+
+ elseif key == '\x04'
+ if isempty(line)
+ return string("\x04")
+ end
+
+ elseif key == '\b'
+ if !isempty(line)
+ print("\b\033[K")
+ line = backspaceStr(line, 1)
+ end
+
+ elseif key == '\e'
+ # Strip ANSI escape sequence
+ nextKey = Char(getKey())
+ if nextKey == '['
+ while true
+ nextKey = Char(getKey())
+ if nextKey >= '@' || nextKey <= '~'
+ break
+ end
+ end
+ end
+
+ elseif key == '\t'
+ # Currently do nothing
+
+ frag = getFrag(line)
+ if frag != nothing
+ if haskey(REPLCompletions.latex_symbols, frag)
+ print(repeat("\b", length(frag)))
+ print("\033[K")
+ comp = REPLCompletions.latex_symbols[frag]
+ line = string(backspaceStr(line, length(frag)), comp)
+ print(comp)
+ end
+ end
+
+ else
+ print(key)
+ line = string(line, key)
+ end
+ end
+end
+