你不会还在机械重复的输入格式化信息吧?snippet配置来帮你一键生成
大家好,我是亓官劼(qí guān jié ),在【亓官劼】公众号、GitHub、B站、华为开发者论坛等平台分享一些技术博文。放弃不难,但坚持一定很酷!时光荏苒,未来可期,加油~如果喜欢博主的文章可以关注博主的个人公众号【亓官劼】(qí guān jié),如果有需要找博主的话可以在公众号后台留言。建了个小交流群,Q群:545611263。
简介
我们在日常的code过程中时常需要对键入一些说明信息以及一些格式固定,内容较为重复的信息。例如每个源码文件的开头
header
信息,主要包括作者、文件内容、创建/更新日期等信息。最近发现有个小伙伴还在每次重复的键入这些固定的格式化信息,这些重复无意义工作的手动键入,对于一个程序媛来说怎么能忍受呢!
我们可以通过配置user snippet来形成一种代码模板,当我们输入
prefix
的时候,使得他直接生成我们需要的内容,例如:
这是目前在用的
python
文件的
header
模板,当键入
header
的时候可以直接补全这个我每个py文件需要写的一些文件基本信息,这里的日期是自动获取当前的。键入后的显示效果为:
这样我们就不用每个文件都手动键入这些重复信息,不仅仅是
header
的输入,还有每个函数的功能介绍(
这个功能pycharm默认开启了,需要需要自定义的话,需要在配置一下就好
)、
args
、
return
等信息都可以进行配置,甚至我们日常写文档的时候也可以配置。之前看过我文章的小伙伴应该能发现,我刷题的文章结构基本是不会变的,每次变得只有题目和题解、解题思路和题解代码,这里面的
markdown
文档也可以使用
snippet
来直接补全文章的骨架,每次我写刷题文章的时候只需要写出题目和题解、解题思路和题解代码部分就好了,十分的便捷。
snippet配置
既然snippet这么好用,下面来说说如何配置。这里以
Visual Studio Code
为例进行,配置文件的内容是一样的,其他软件配置的区别仅仅是进入到配置文件的方法不同。
在
Visual Studio Code
中按快捷键
Ctrl + Shift + P
调出命令输入框,键入
snippet
,选择
Configure User Snippets
:
然后按回车进行后出现选择需要配置的文件类型,按照需要进行选择,我这里选择的是Python文件
这里可以按需选择, 各类文件的配置都是一样的。进入配置文件后,默认是全部注释掉的内容:
{
// Place your snippets for python here. Each snippet is defined under a snippet name and has a prefix, body and
// description. 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": {
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
}
下面我对他进行配置即可。每个
snippet
有
prefix / body / description
三种属性,分别为前缀(即键入的提示符,例如
header
)、补全的内容、补全的介绍。下面来配置一个新的
header
显示信息,我们希望每次补全可以显示文件描述、文件名、日期、作者、version信息,
prefix
设置为
demo
。具体配置为:
{
// Place your snippets for python here. Each snippet is defined under a snippet name and has a prefix, body and
// description. 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": {
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
"DEMO":{
"prefix": "demo",
"body":[
// "#!/usr/bin/env python",
"# -*- encoding: utf-8 -*-",
"\"\"\"",
// "@文件 :$TM_FILENAME",
"@Description: :",
"@File :$TM_FILENAME",
"@Date :$CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
"@Author :亓官劼([email protected])",
"@version :1.0",
"\"\"\"",
],
"description": "这是一个demo snippet"
},
}
我们将这个文件保存后,新建一个
py
文件,在文件中键入
demo
即可出现补全提示: