Vscode Snippet

우리가 흔히 사용하는 IDE (Integrated Development Environment)는 본질적으로는 메모장과 크게 다르지 않다. 하지만 Vscode를 개발한 Microsoft에서는 메모장에 비해 개발자의 니즈를 더 잘 알고 있었고, 그래서 개발자에게 편한 세팅들을 추가해왔다. 그 중 하나가, 오늘 다룰 Snippet이다.

요즘에는, github copilot등 많은 AI 도구의 발전으로 모르는 사람이 많으며, 필자 또한 이름만 듣고 세팅을 해본적은 없었다. 그러나, 블로그를 작성하다보니, front matter 등에 귀찮은 부분이 많아 한번 찾아보면서 그 기록들을 남기고자 한다.

Snippet 이란?

Snippet(스니펫)은 Visual Studio Code에서 자주 사용하는 코드 조각을 단축키처럼 빠르게 불러와 자동으로 완성해주는 기능이다. 즉, 반복 작성하는 코드 패턴을 몇 글자만 입력하고 탭(Tab)을 누르면 전체 코드가 자동으로 생성되는 기능이다.

Snippet의 위치 및 파일 생성

File > Preferences > Configure User Snippet

위의 블록처럼 접근을 하게되면, 아래와 같은 선택지를 주는데, 필자는 블로그에서만 사용할 것이기 때문에 markdown에만 적용되는 3번 선택지로 진행하였다.

  1. New Global Snippet File
  2. New Snippets for ‘~~~’
  3. 다양한 파일 format들 (markdown, cpp 기타 등등)

Snippet의 설정

처음 파일을 만들게 되면 다음과 같은 형식을 줄 것이다.

{
	// Place your snippets for markdown 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"
	// }
}

그렇다.. 이게 다이다. 그냥 json 형식으로 넣으면 끝이다! 조금더, 자세히 설명을 하자면,

  • prefix : 호출할 때 사용할 것
  • body : 호출되는 것
  • description (optional) : 해당 snippet에 대한 설명

예를 들어서, \\textbf{}tb에 매핑하려면 다음과 같이 하면 된다.

{
    "textboldformat":{
        "prefix" : "tb"
        "body" : "\\textbf{}"
    }
}

나의 snippet 설정

일단, 필자의 경우 귀찮은 head matter들을 작성해주는 것을 원했기에 다음과 같이 작성하였다.

{
  "Frontmatter": {
    "prefix": "postfm",
    "description": "post front matter",
    "body": [
      "---",
      "title: \"\"",
      "layout: single",
      "excerpt: \"\"",
      "categories: [\"AI\", \"Paper-review\"]",
      "tags:",
      "  - ",
      "  - ",
      "  - ",
      "date: ${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE}",
      "last_modified_at: ${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE}",
      "published: true",
      "use_math: false",
      "math: false",
      "mermaid: false",
      "classes: wide",
      "toc: true",
      "toc_sticky: true",
      "author_profile: false",
      "---",
      "",
      "$0"
    ]
  }
}

Snippet 설정 이후의 것들

우리는 위에서 snippet을 만드는 법에 관하여 논의하였다. 그렇다면 바로 사용하면 사용이 될까?
정답은 “아니다!” 이다.

우리는 settings.json에 다음과 같은 구절을 추가해줘야, 정상적으로 동작하게 된다.

"[markdown]": {
    "editor.quickSuggestions": {
        "other": "on",
        "comments": "off",
        "strings": "off"
    }
}

settings.json의 경우 ‘Ctrl+Shift+P’를 누른 후 ‘settings.json’을 입력하면 Preferences: Open User Settings (Json)이 나온다. 들어가서 수정하면 된다!

References

https://code.visualstudio.com/docs/editing/userdefinedsnippets https://kimjy99.github.io/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D/snippet/