1

I want to restrict more than one space to be typed in VS Code unless it is before the first non-space in a line.

Additionally, if you open a file that was like that already I want those multi-spaces to be removed when saved.

Mark
  • 143,421
  • 24
  • 428
  • 436
user3507230
  • 83
  • 2
  • 9

2 Answers2

2

Here is Trailing Spaces - it looks like a workaround for what you're looking for.

sidverma
  • 1,159
  • 12
  • 24
1

You are really looking for a formatter for these two functionalities: format on type and format on save. However, you can get the first function - "restrict more than one space to be typed in Visual Studio Code unless it is before the first non-space in a line" with the help of an extension HyperSnips.

For setting up that extension, see https://stackoverflow.com/a/62562886/836330

Then say in your all.hsnips file put this:

snippet `(\S)( ){2,}` "found 2 consecutive spaces with no non-whitespace characters preceding" A
``rv = m[1] + " "``
endsnippet

That will work in all language files, you can restrict it to certain languages as mentioned in that answer linked to.

Run the command HyperSnips: Reload Snippets.

Basically you are running a snippet that uses (\S)( ){2,} as the prefix. It will be triggered whenever it detects two or more spaces in a row and will replace them with just one!

The snippet will only be triggered if those two spaces are preceded by a non-whitespace (so some character) and thus your second requirement that multiple spaces be allowed before the first character in a line.

It also works between existing words if you go there to edit - you will not be able to add a space to an existing space!!

Demo:

space restrict demo

The gif doesn't really capture it well but every time I am trying to write a second consecutive space it deletes it leaving only the one.


Your second question was "if you open a file that was like that already I want those multispaces to be removed when saved".

I suggest running a script on save. Using, for example, Trigger on Task Save. In your settings:

"triggerTaskOnSave.tasks": {

  "stripSpaces": [
    "**/*.txt"   // here restricting it to .txt files
  ],
},

This runs the stripSpaces task whener you save a .txt file. That task (in tasks.json) could look like:

{
  "label": "stripSpaces",
  "type": "shell",
  "command": "awk -f stripSpaces.awk ${relativeFile} > temp; mv temp ${relativeFile}"
}

which runs this stripSpaces.awk script:

# strip multiple consecutive spaces from a file
# unless they are the beginning of the line

BEGIN   {
    regex="\\S( ){2,}";
    }
{

if (match($0,regex))    {

    gsub(/( ){2,}/, " ")
    print
}
else print
}

Demo:

awk strip spaces on save demo

Mark
  • 143,421
  • 24
  • 428
  • 436