Allow line editing when reading input from the command line

你离开我真会死。 提交于 2020-01-02 09:10:37

问题


I already know how to get the input from user keyboard. I can use the readLine() method or

 let input = FileHandle.standardInput
 let inputData = input.availableData
 var text = String(data: inputData, encoding: .utf8)

But the two methods get also when the user press an arrow key button. I would like to filter the input in order to remove these data. I want that the user can write something, maybe go back with the left arrow key, change something and insert the data without problem. Thanks!


回答1:


What you are looking for is the “line editing feature” which is provided by libedit on macOS.

In order to use it from a Swift command line tool, you need to

  • #include <readline/readline.h> in the bridging header file,
  • add “libedit.tbd” to the “Link Binary With Libraries” section in the “Build Phases” of your target.

Here is a minimal example Swift program:

while let cString = readline("prompt>") {
    let line = String(cString: cString)
    free(cString)
    print(line)
}

Important: You have to run this in the Terminal, it won't work properly in the Xcode debugger console.

Each input line can be edited before entering Return, similar to what you can do in the Terminal. And with

while let cString = readline("prompt>") {
    add_history(cString) // <-- ADDED
    let line = String(cString: cString)
    free(cString)
    print(line)
}

you can even use the up/down arrow keys to navigate to previously entered lines.

For more information, call man 3 readline in the Terminal.

Here is a possible helper function:

func readlineHelper(prompt: String? = nil, addToHistory: Bool = false) -> String? {
    guard let cString = readline(prompt) else { return nil }
    defer { free(cString) }
    if addToHistory { add_history(cString) }
    return(String(cString: cString))
}

Usage example:

while let line = readlineHelper(addToHistory: true) {
    print(line)
}


来源:https://stackoverflow.com/questions/52794640/allow-line-editing-when-reading-input-from-the-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!