Allow line editing when reading input from the command line

为君一笑 提交于 2019-12-06 14:47:25

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