Open content files via link in vscode from server-mode preview

When a project gets bigger, it can become annoying to look up content files in a large folder structure. I’m always using Hugo in server-mode to get an instant local preview and wanted to open the content files from there.

So I created two small partials two place before and after an HTML element without a link in my templates. They check if Hugo is running in server-mode and expect a parameter sourcePath with the full path of the project content directory.

If both prerequisites are fullfilled, they wrap the HTML element in a link. This link contains the full local path preceded by vscode://file and opens the content file in a local vscode instance.

vscode_start.html

{{- if .Site.IsServer -}}
{{- with (.Param "sourcePath") -}}
   {{ $src := . }}
   {{- with $.File -}}
       {{- $path := print "vscode://file" $src .Path  -}}
       <a {{ printf "href=%q" $path | safeHTMLAttr }} rel="nofollow">
   {{- end -}}
{{- end -}}
{{ else }}
   {{ warnf "Unable to find and open local content files. Missing 'sourcePath' parameter in the configuration." }}
{{ end }}{{- /**/ -}}

vscode_end.html

{{ if .Site.IsServer }}
    {{- with (.Param "sourcePath") }}
        {{- with $.File }}
          </a>
        {{- end }}
    {{- end }}
{{ end }}{{- /**/ -}}

I’ve published those two also as a small Hugo module.

Maybe this will come in handy for you,
Georg

This is really useful, but I suspect you can get rid of the sourcePath. What if you do:

{{{ with .File }}
 {{- $path := print "vscode://file" .Filename  -}}
{{ end }}

Or something …?

I wrote this a while ago. If I remember correctly, vscode needs an absolut path and Hugo only knows about the path relative to the project root. But I’ll give it a try.

I’m pretty sure .Filename is an absolute path.

Thanks. This is really handy. In server mode I typically render a couple of status bars below the header and before the content.

image

The edit link on the left is new, as of this morning. Nice.

You’re right, sourcePathis gone and no one will miss it.

It would be cool if we could enable the same for the templates used for a given page … (we now actual have the bits and pieces for that, it would slow down the build some, but it could be added behind a flag …).

@bep

https://github.com/gohugoio/hugoDocs/issues/1623#issuecomment-1324051507

Can we document .Filename? This indirectly exposes $HOME in some cases.

Yes, we should document it; I don’t see us ever removing it. We have a security policy that says that “template files” is trusted. Also, I suspect we have other places where we show mount folder info (it’s fairly hard to reason about where a particular file is in a multi-theme swetup). We cannot let security paranoia spoil obviously useful features.