从命令行读取输入时允许进行行编辑 [英] Allow line editing when reading input from the command line

查看:105
本文介绍了从命令行读取输入时允许进行行编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道如何从用户键盘获取输入. 我可以使用readLine()方法或

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!

推荐答案

您正在寻找的是" libedit 在macOS上.

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

要通过Swift命令行工具使用它,您需要

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

    桥接头文件中的
  • #include <readline/readline.h>
  • 将"libedit.tbd"添加到 目标的构建阶段".
  • #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.

这是Swift程序的最小示例:

Here is a minimal example Swift program:

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

重要:您必须在终端中运行它,它在Xcode调试器控制台中无法正常工作.

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

在输入 Return 之前,可以编辑每个输入行, 与您在终端机中可以执行的操作类似.还有

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.

有关更多信息,请在终端中致电man 3 readline.

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))
}

用法示例:

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

这篇关于从命令行读取输入时允许进行行编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆