How to pad out line to certain length using regex replace and snippets

前端 未结 2 1880
孤街浪徒
孤街浪徒 2020-12-22 13:07

// My Section -----------------------------------------------------------------

The above is the desired result.


Imagine this scenario

相关标签:
2条回答
  • 2020-12-22 13:28

    You can use callback function of replace and based on length you can replace values

    let str = `// ----------------------------------------------------------------------------
    // firebase
    
    // ----------------------------------------------------------------------------
    // utils`
    
    let final = str.replace(/^.*$/gm, (match)=>{
      return match.length === 0 ? match : match.length > 20 ? match.substr(0,20) : match + `-`.repeat(20-match.length)
    })
    
    console.log(final)

    0 讨论(0)
  • 2020-12-22 13:37

    I doubt you can do what you want in one step, without running some code. But you can do it with a macro so you can have multiple steps fired at once. In this example I am using the macro extension multi-command, but there are other macro extensions out there.

    In your settings.json:

    "multiCommand.commands": [
    
     {
       "command": "multiCommand.commentSection",
       // "interval": 750,  // you don't need this, just for illustration
    
       "sequence": [  
         "cursorEnd",            
         {
           "command": "type",  // add 75 -'s'
           "args": {
             "text": " ---------------------------------------------------------------------------"
           }
         },
    
         "editor.action.addCommentLine",
    
         // select this wrapped line so the next snippet can use TM_SELECTED_TEXT
         "cursorHomeSelect",
         "cursorHomeSelect",
    
         {
           "command": "editor.action.insertSnippet",  // trim to first 80 characters
           "args": {
             "snippet": "${TM_SELECTED_TEXT/(.{80}).*/$1/g}",
           }
         }
       ]
     }
    ],
    

    And then whatever keybinding you choose in keybindings.json

    {
      "key": "ctrl+alt+-",
      "command": "extension.multiCommand.execute",
      "args": { "command": "multiCommand.commentSection" }
    },
    

    The basic idea is to add too many hyphens - say 75 - and then select the entire wrapped line and keep only the first 80 characters, thus trimming the trailing hyphens to fill out to 80 total characters on the line.

    It works on blank lines too as the end of the demo demonstrates.

    0 讨论(0)
提交回复
热议问题