Search code examples
datetimevisual-studio-codevscode-snippets

vscode insert date time each new line?


I would like to (ab)use vscode as a tool for some specific live-logging. For this purpose I would like to have it insert the current date, time at the beginning of each line. I did look here: How to insert current date time in vscode? but it only goes half-way there. I have only recently moved from Atom to VScode and am a bit daunted by trying to do this from first principles - any pointers would be most welcome!

As a bonus: if this function could be created so that it only takes place in files which have been saved with a specific file extension, that would be even more awesome! Otherwise I need to turn on/off this feature every time I use VScode for something else...


Solution

  • Using a macro extension like multi-command put this into your settings:

    "multiCommand.commands": [
    
      {
        "command": "multiCommand.insertTimeonNewline",
    
        "sequence": [
          "editor.action.insertLineAfter",        
          {
            "command": "editor.action.insertSnippet",
            "args": {
              "snippet": "$CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND  "
            }
          },
        ]  
      }
    ]
    

    And this into keybindings.json:

    {
      "key": "enter",
      "command": "extension.multiCommand.execute",
      "args": { "command": "multiCommand.insertTimeonNewline" },
      "when": "editorTextFocus && resourceExtname =~ /\\.php/"
    },
    

    Change that extension at the end of the when clause to whatever extension you need to use.

    Now Eenter will enter a new line and put the time at the beginning of it. You should modify the time variables if you want year, month, etc.

    insert time on newline demo