Ahmad Ismail
Ahmad Ismail

Reputation: 13952

Replace leading spaces with asterisk(s)

I have two vscode snippets that replace leading four space with *.

  "Replace leading 4 spaces of non-empty lines with *": {
    "body": [
      "${TM_SELECTED_TEXT/^([ ]{4})(.+)$/* $2/gm}"
    ],
    "description": "Replace leading 4 spaces of non-empty lines with *"
  },
  "Replace leading 8 spaces of non-empty lines with **": {
    "body": [
      "${TM_SELECTED_TEXT/^([ ]{8})(.+)$/** $2/gm}"
    ],
    "description": "Replace leading 8 spaces of non-empty lines with **"
  },

I want to create a single snippet that will merge both and do the following:

Sample Input:

Motivation's First Law (Law of Persistence):
    A person will remain in their current state of motivation
    In simpler terms, individuals tend to maintain their current

Motivation's Second Law (Law of Momentum):
    The rate of change of motivation of a person is 
    In simpler terms, this law suggests that the greater 

Sample Output:

* Motivation's First Law (Law of Persistence):
** A person will remain in their current state of motivation
** In simpler terms, individuals tend to maintain their current

* Motivation's Second Law (Law of Momentum):
** The rate of change of motivation of a person is
** In simpler terms, this law suggests that the greater

How can I do that?

Upvotes: 0

Views: 33

Answers (1)

Mark
Mark

Reputation: 182771

Try this keybinding for a snippet (or just use the snippet part) - in your keybindings.json:

{
  "key": "alt+w",
  "command": "editor.action.insertSnippet",
  "args": {
    "snippet": "${TM_SELECTED_TEXT/^([ ]{8})|^([ ]{4})/${1:+** }${2:+* }/gm}"
  },
  "when": "editorHasSelection"
}

The order of the regular expression part is important. It gets any leading 8 spaces into capture group 1. Or any leading 4 spaces into capture group 2.

Then the transform part ${1:+** } means if there is a group 1 insert ** .

Likewise, ${2:+* } means if there is a capture group 2 insert * .

You will never have both a capture group 1 and 2 in the same match.

Upvotes: 1

Related Questions