VSCode 自定义代码片段
VSCode 可以很方便的自定义代码片段,一起来把自己常用的代码编成模板吧
操作过程:
- 依次点击 文件–首选项–用户代码片段
- 如果你想在所有工作区使用,选择新建全局代码片段
如果你想限定作用域,选择新建文件夹的代码片段
然后给片段文件起个名字,保存
会有以下内容自动生成,这是使用说明,你可以选择全部删掉
{
// Place your Cpp workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope
// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is
// used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
// Placeholders with the same ids are connected.
// Example:
// "Print to console": {
// "scope": "javascript,typescript",
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
}
3.样例代码说明:
这是之前提到的重定向片段
{
"Print to console": {
"scope": "cpp", //作用的语言,可多选,如"c,cpp,javascript,typescript",
"prefix": "fre", //触发器,可自定义
"body": [
"#ifdef LOCAL",
" freopen(\"E:/Cpp/1.in\", \"r\", stdin);",
" freopen(\"E:/Cpp/1.out\", \"w\", stdout);",
"#endif",
" $0" //回车后光标位置
],
"description": "Freopen" //名称
}
}
注:
- json输出"时要用\转义
- 双引号里面的空格都可以打印出来,最好算好空格数,出来排版效果好
- 触发器最好避开关键字与内置函数名字,长度最好三个字符以上
接下来就是发挥创造力的时候了
- cpp框架
{
"Print to console": {
"scope": "cpp",
"prefix": "cpp",
"body": [
"#include <algorithm>",
"#include <iostream>",
"using namespace std;",
"const int maxn = 1005;",
"$1",
"int main() {",
"#ifdef LOCAL",
" freopen(\"E:/Cpp/1.in\", \"r\", stdin);",
" freopen(\"E:/Cpp/1.out\", \"w\", stdout);",
"#endif",
"",
"",
"",
"",
"",
"",
" return 0;",
"}",
""
],
"description": "A cpp file template."
}
}
- 有限状态自动机框架
{
"Print to console": {
"scope": "cpp",
"prefix": "state",
"body": [
"#include <iostream>",
"#define Error -1",
"#define Start 0",
"#define Accept 1",
"#define Q1 2",
"#define Q2 3",
"#define Q3 4",
"#define Q4 5",
"",
"int main() {",
"#ifdef LOCAL",
" freopen(\"E:/Cpp/1.in\", \"r\", stdin);",
" freopen(\"E:/Cpp/1.out\", \"w\", stdout);",
"#endif",
" int state = Start;",
" char ch;",
" $1",
" while (state != Accept && state != Error) {",
" switch (state) {",
" case Start:",
" break;",
" case Q1:",
" break;",
" case Q2:",
" break;",
" case Q3:",
" break;",
" case Q4:",
" break;",
" ",
" }",
" }",
" if (state == Accept)",
" printf();",
" else",
" printf();",
"",
" return 0;",
"}"
],
"description": "A template of state"
}
}
- 这是个很好用的格式化输出模板(OJ经常要的每个输出那个空格隔开,但是最后一个后面不能有空格)三改的最简版本哦
{
"Print to console": {
"scope": "cpp",
"prefix": "print",
"body": [
"for(int ${2:i} = 0; ${2:i} < ${1:n}; ${2:i}++)",
" printf(i ? \" %d\" : \"%d\", $3[i]);",
"putchar('\\n');"
],
"description": "Print"
}
}
- for循环
{
"Print to console": {
"scope": "cpp",
"prefix": "fo",
"body": [
"for(int ${2:i} = 0; ${2:i} < ${1:n}; ${2:i}++)",
"$3"
],
"description": "Loop"
}
}