[英]Converting header or text file information to code using Linux/Vim
I found myself writing a really simple conversion from OpenCL error codes to a human readable string. 我发现自己编写了一个非常简单的从OpenCL错误代码到人类可读字符串的转换。 The 50 or so different codes are defined in a header file like this:
50个左右的不同代码在头文件中定义,如下所示:
...
#define CL_INVALID_CONTEXT -34
#define CL_INVALID_QUEUE_PROPERTIES -35
#define CL_INVALID_COMMAND_QUEUE -36
#define CL_INVALID_HOST_PTR -37
...
I put all of these in a huge switch/case using expert copy/pasting: 我使用专家拷贝/粘贴将所有这些放在一个巨大的开关/案例中:
...
case CL_INVALID_CONTEXT:
return "CL_INVALID_CONTEXT";
case CL_INVALID_QUEUE_PROPERTIES:
return "CL_INVALID_QUEUE_PROPERTIES";
case CL_INVALID_COMMAND_QUEUE:
return "CL_INVALID_COMMAND_QUEUE";
case CL_INVALID_HOST_PTR:
return "CL_INVALID_HOST_PTR";
...
Since I've recently started to use Vim, I am thinking there might be a way to do this in a more efficient way using Linux command tools and Vim. 由于我最近开始使用Vim,我想可能有一种方法可以使用Linux命令工具和Vim以更有效的方式执行此操作。 There was a similar post here where someone claimed to have done it with Emacs.
这里有一个类似的帖子,有人声称已经用Emacs完成了它。 Any ideas on how to avoid wasting 15 minutes with a similar task next time?
关于如何避免下次浪费15分钟执行类似任务的任何想法?
(I know that oclErrorSting() might exist but let's disregard that for generality's sake!) (我知道oclErrorSting()可能存在,但为了一般性的缘故,让我们忽略它!)
You can do this in Vim with a search and replace: 您可以在Vim中执行此操作并进行搜索并替换:
%s/#define \(\w\+\).*/case \1:^M return "\1";/g
The trick to getting the ^M
in the output is to type CTRL-V
and then Enter
where you want put a newline in the output. 在输出中获取
^M
的技巧是键入CTRL-V
然后Enter
要在输出中放置换行符的位置。
This will do the replacement on the entire file. 这将替换整个文件。
This works by doing a seach which matches the entire line and replacing it with your desired text. 这可以通过执行搜索来匹配整行并将其替换为您想要的文本。 Each name is captured into a group in the search, that's what the
\\(\\w\\+\\)
is doing, then the matched text is used twice in the replacement. 在搜索中将每个名称捕获到一个组中,即
\\(\\w\\+\\)
正在执行的操作,然后匹配的文本在替换中使用两次。
The other generic solution for repetitive tasks is to use macros
, or complex repeats are they are called in help. 重复性任务的另一个通用解决方案是使用
macros
,或者在帮助中调用复杂的重复。
Basically you start recording your inputs in a register, create a single case, and then go to the next line of your define. 基本上,您开始在寄存器中记录输入,创建单个案例,然后转到定义的下一行。
See :help q
for more details. 有关详细信息,请参阅
:help q
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.