+++
title = 'Update Lastmod Using vim'
date = 2022-05-01T10:28:05+01:00
lastmod = 2022-05-29T07:37:05+01:00
draft = false
tags = ['editor', 'text', 'vim']
categories = ['tech']
+++

I think it is very important to add date information about articles’ creation time and modification time.
There are various ways to do this. I usually prefer when this be done automatically by
{{< target-blank url="https://www.vim.org" linktext="my favorite editor" >}} and so I wrote a short function:

```
function! LastMod()
        if expand('%:p:h') =~ 'path/to/my/hugo-website/www.nixre.net/content'
                let l:cursorpos = winsaveview()
                let l:timestamp = strftime('%Y-%m-%dT%H:%M:%S+02:00')
                silent! exe ':%s/^\(lastmod:\).*$/\1 ' . expand(l:timestamp) . '/'
                call winrestview(l:cursorpos)
        endif
endfunction
```

The markdown sources are inside the content folder of my hugo website and the `expand('%:p:h')` of the file that 
is currently loaded into the buffer will show the absolute path to the directory that contains the file.
Vim will check if the string afterwards `path/to/my/[..]/content` is part of path to the currently loaded file.
If so then first it saves the properties of the current window, like cursorposition and so. Then it creates a
local variable `l:timestamp` with the current timestamp, searches the line that begins with `lastmod:` and
updates this line with the current timestamp in `l:timestamp`. As last step it resets the window that was saved
into the `l:cursorpos` variable in the first step.

Now to make vim execute this function I added an autocommand group which calls the above function:

```
augroup www.nixre.net
        au!
        au BufWrite /full/path/to/my/hug-website/www.nixre.net/content/**.md call LastMod()
augroup end
```

This tells vim to call the function if I save a file that has the .md extension in the given path. This way vim
always updates the timestamp string in the frontmatter field `lastmod:` when I save the buffer’s content to the file.
