vscode-markdown icon indicating copy to clipboard operation
vscode-markdown copied to clipboard

Feature Request: Add missing links

Open danvk opened this issue 1 year ago • 2 comments

Proposal

When I write Markdown documents, I put some phrases in square braces and then go back and fill in the links later:

I'd like to [link to A] and also [link to B].

It would be helpful to have an action to add missing links to the bottom of the document, i.e. to transform the previous Markdown into this:

I'd like to [link to A] and also [link to B].

[link to A]: 
[link to B]: 

Other information

Eventually I'll fill these in myself so that it looks something like this:

I'd like to [link to A] and also [link to B].

[link to A]: http://example.com/a
[link to B]: http://example.com/b

but having an "Add missing links" action would save me a step.

danvk avatar Aug 15 '23 21:08 danvk

For now I work around this with a Python script that I run via a VS Code task:

#!/usr/bin/env python
"""Add missing links to the bottom of a Markdown document."""

import sys
import re

if __name__ == '__main__':
    (md_file,) = sys.argv[1:]
    old_post = open(md_file).read()

    present = set()
    for m in re.finditer(r'^\[([^]]+)\]: ', old_post, re.M):
        present.add(m.group(1).lower())

    links = []
    for m in re.finditer(r'(?<!!)\[([^]]+)\](?![\[\(])', old_post):
        link = m.group(1)
        if link.lower() not in present:
            links.append(link)

    new_links = '\n'.join(f'[{link}]:' for link in links)

    new_post = f'{old_post}\n{new_links}\n'
    with open(md_file, 'w') as out:
        out.write(new_post)

danvk avatar Aug 15 '23 21:08 danvk

Thanks for the suggestion. It would be interesting but I'm not sure whether there are more people like this. Let's wait and collect more feedback from other users.

yzhang-gh avatar Aug 18 '23 13:08 yzhang-gh