skip to Main Content

The idea is to write 16prem (think: pixel-to-rem) and have Visual Studio Code automatically substitute with 1rem. The IDE would therefore need to recognize that there is a number immediately followed be the keyword prem, divide the number by 16 and give back the result, followed by rem.

Input: 16prem → Output: 1rem
Input: 40prem → Output: 2.5rem

I tried achieving this via Visual Studio Code snippet transformations but am both new to the VS Code snippet syntax and RegEx. Does anyone know if this can be done?

2

Answers


  1. Here is another simple approach. This uses an extension I wrote, Find and Transform, to do a find and replace in the current document and do the necessary math.

    Try this keybinding:

    {
      "key": "alt+c",               // whatever keybinding you want
      "command": "findInCurrentFile",
      "args": {
        "description": "convert px to rem",
        "find": "(\d+)prem",
        "isRegex": true,
    
        "replace": [
          "$${",
            "const ratio = 16;",                      // your base conversion ratio
            "let result = Number($1/ratio).toFixed(1);",
            "result = result.replace('.0', '');",    // if ends with .0, remove it
            "return result + 'rem';",
          "}$$",
        ],
    
        // omit 'restrictFind' to replace all in whole document
        // "restrictFind": "line",  // to do for line at cursor
      }
    }
    

    Use "restrictFind": "line", to make the change on every line with a cursor. Omit the "restrictFind" to replace for entire document.


    You don’t really need to use the prem syntax. You could just change tie find regex to (\d+)px to convert those values (and replace them line by line, or all of them, or the next one, etc.).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search