首页 > 解决方案 > Snippet for title in restructured text in vs code

问题描述

In restructured text, titles are written with equal number of nonalphanumeric 7-bit ASCII character as the title text. The underline and overline if both used, should be equal and at least as long as title text. From the official docs:

Titles are underlined (or over- and underlined) with a printing nonalphanumeric 7-bit ASCII character. Recommended choices are "= - ` : ' " ~ ^ _ * + # < >". The underline/overline must be at least as long as the title text.

Example of a title

=========================================================
Main titles are written using equals signs over and under
=========================================================

I want to create a VS Code snippet for this. What I could do was only this,

"Title RST": {
    "prefix": "title",
    "body": [
      "="
      "$1"
      "=\n"
      "$0"
    ],
    "description": "Title for restructured text"
  }

Is there a way to know the length of the text that will be typed, and correspondingly insert same number of overline and underline =.

In yasnippet in emacs, they do it as:

${1:$(make-string (string-width yas-text) ?\=)}
${1:Title}
${1:$(make-string (string-width yas-text) ?\=)}

$0

Any help how to implement such snippet in VS code? I looked under snippets in restructured text extension for VS Code here but could not find that suits my needs.

标签: visual-studio-codeemacsrestructuredtextvscode-snippetsyasnippet

解决方案


  "Title RST": {
    "prefix": "title",
    "body": [
      "${1/./=/g}",
      "$1",
      "${1/./=/g}",
      "$0"
    ],
    "description": "Title for restructured text"
  },

The transforms ${1/./=/g} just replace every character in your text $1 with a = in the line above and below your text.

You need commas at the end of your snippet entries and there is no need for the newline as another line in the snippet body is already a newline.

When you type your text hit Tab and the transform will be completed.

snippet transform


You asked if was possible to get the over/underlines to show as =s immediately upon typing your title text. But that isn't possible with vscode snippets, a transform is required and that won't happen until the Tab.

It can be done with HyperSnips version (a little more trouble to set up than plain vscode snippets, but not much):

snippet title "Title" A
``rv =  '='.repeat(t[0].length)``
$1
``rv = '='.repeat(t[0].length)``
endsnippet

HypeSnips demo


推荐阅读