VSCode Snippets用法
郝伟 2022/08/07
点击左下角的齿轮图案,然后找到Command Palette选项(或者使用快捷键Ctrl + Shift + P),在VSCode窗口上方出现的搜索框输入Insert Snippets即可查看到
代码段默认保存在本机,在Windows系统下,用户的代码段文件默认为 C:\Users\hao\AppData\Roaming\Code\User\snippets\python.json,默认内容如下:
{ "Print to console": { "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console" } }
需要注意:无论是本地库还是远程库,都使用本地的代码段文件。
Place your snippets for python here. Each snippet is defined under a snippet name and has a prefix, body and description.
prefix is what is used to trigger the snippet;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.description is the information provided to help readers understand the meaning of this item.每个片段包括三个定义:prefix, body and description。
prefix 用于触发代码段的单词或Key,如 pydes 激活描述代码(见下方示例)body 代码段的主体$1, $2 用于制表位,$0 用于最终光标位置,${1:label}, ${2:another} 用于占位符。 具有相同 id 的占位符被连接。description 代码段的描述,用于为帮助读者理解该代码段的含义而提供的介绍信息。{ "Print to console": { "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console" } }
{ "Print to console": { "prefix": "log", "body": [ "console.log('$1');", "$2" ], "description": "Log output to console" }, "File description": { "prefix": "fdes", "body": [ "# encoding=utf-8\n'''\n作者:郝伟老师\n日期:$1\n描述:\n历史:\n'''", "$2" ], "description": "Log output to console" }, "Python Show":{ "prefix": "pyshow", "body":[ "def retrieve_name_ex(var):\n stacks = inspect.stack()\n try:\n code = stacks[2].code_context[0] # 获得调用行的代码\n callFunc = stacks[1].function # 获得调用的函数名\n # 获得函数中起始索引位置,以取得变量名称的字符串\n startIndex = code.index("(", code.index(callFunc) + len(callFunc)) + 1\n endIndex = code.index(")", startIndex)\n name=code[startIndex:endIndex].strip() # 获得变量名称\n return name\n except:\n return ""\ndef show(var):\n print(retrieve_name_ex(var), '=', var)" ], "description": "powerful print" } }
"[markdown]": { "editor.defaultFormatter": "darkriszty.markdown-table-prettify", "editor.unicodeHighlight.ambiguousCharacters": false,//默认值 "editor.wordWrap": "on",//默认值 "editor.quickSuggestions": { "comments": "on", "strings": "on", "other": "on" }//默认为flase },
C:\Users\hao\AppData\Roaming\Code\User\settings.json,在保存时就会自动重启VSCode。[1] 官网说明文档, https://code.visualstudio.com/docs/editor/userdefinedsnippets
[2] CSDN文章:VSCode中snippets(代码模板)的使用, https://blog.csdn.net/angry_rooster/article/details/118560317