The language service that powers VS Code's Markdown support, extracted so that it can be reused by other editors and tools

Overview

VS Code Markdown Language Service

Note this project is actively being developed and not yet ready for production use!

The language service that powers VS Code's Markdown support, extracted so that it can be reused by other editors and tools.

Features

This library targets CommonMark. Support for other Markdown dialects and extensions is not within the scope of this project.

Currently supported language features:

  • Document links (clickable spans in the editor)

    Supported links include:

    • Links to headers within the current file: [text](#header)
    • Absolute and relative links to files: [text](path/to/file.md)
    • Reference links: [text][link-name]
  • Document symbols

    Finds all headers within a markdown file

  • Workspace symbols

    Find all headers across all markdown files in the workspace.

  • Folding ranges

    Folding ranges are computed for:

    • Header sections
    • Region sections
    • Lists
    • Block elements
  • Smart select (expand selection)

  • Completions

    Supports completions for:

    • Links to headers
    • Path links
    • Reference links
  • Find all references

    Supports finding references to:

    • Headers
    • Path links
    • Fragments in links
    • Reference links
  • Definitions

    Supports finding definitions headers and reference links.

  • Renames

    Supports renaming of headers and links.

Usage

To get started using this library, first install it into your workspace:

npm install vscode-markdown-languageservice

To use the language service, first you need to create an instance of it using createLanguageService. We use dependency injection to allow the language service to be used in as many contexts as possible.

import * as md from 'vscode-markdown-languageservice';

// Implement these
const parser: md.IMdParser = ...;
const workspace: md.IWorkspace = ...;
const logger: md.ILogger = ...;

const languageService = md.createLanguageService({ workspace, parser, logger });

After creating the service, you can ask it for the language features it supports:

// We're using the vscode-language types in this demo
// If you want to use them, make sure to run:
//
//     npm install vscode-languageserver vscode-languageserver-textdocument
//
// However you can also bring your own types if you want to instead.

import { CancellationTokenSource } from 'vscode-languageserver';
import { TextDocument } from 'vscode-languageserver-textdocument';

const cts = new CancellationTokenSource();

// Create a virtual document that holds our file content
const myDocument = TextDocument.create(
	URI.file('/path/to/file.md').toString(), // file path
	'markdown', // file language
	1, // version
	[ // File contents
		'# Hello',
		'from **Markdown**',
		'',
		'## World!',
	].join('\n')
);

const symbols = await languageService.getDocumentSymbols(myDocument, cts.token);

See example.cjs for complete, minimal example of using the language service. You can run in using node example.cjs.

Additional Links

Contributing

If you're interested in contributing

  1. Clone this repo
  2. Install dependencies using npm install
  3. Start compilation using npm run watch

You can run the unit tests using npm test or by opening the project in VS Code and pressing F5 to debug.

Comments
  • Expose IMdLinkComputer for custom link computers

    Expose IMdLinkComputer for custom link computers

    See https://github.com/microsoft/vscode-markdown-languageservice/issues/7#issuecomment-1286220696 for discussion on motivation.

    See here for a proof-of-concept implementation of IMdLinkComputer using mdast to gather the links. It's incomplete as it doesn't bother to set any of the sub-ranges correctly, since the intended use-case is simply to gather the diagnostics about links and the line number alone is sufficient for the intended output. That implementation also won't be able to detect broken reference links (where the definition is missing) since mdast just considers those as text in a paragraph so the information isn't available in the AST. It is of course also inefficient since it fully parses the Markdown twice since there are two different implementations, but that wasn't an issue for the intended use-case (pulls all diagnostics for ~225 files in a few seconds).

    opened by dsanders11 3
  • markdown link in format [`abc`] not shown as link

    markdown link in format [`abc`] not shown as link

    Does this issue occur when all extensions are disabled?: Yes

    [`abc`]  // <-- this is not shown as link
    
    [`abc`]: https://some-link
    

    The preview is working as expected.

    I sometimes do that to links so that spell checker will ignore them.

    Version: 1.72.0 (user setup) Commit: 64bbfbf67ada9953918d72e1df2f4d8e537d340e Date: 2022-10-04T23:20:39.912Z Electron: 19.0.17 Chromium: 102.0.5005.167 Node.js: 16.14.2 V8: 10.2.154.15-electron.0 OS: Windows_NT x64 10.0.22621 Sandboxed: No

    opened by unional 3
  • MD files don't always get marked dirty & don't always identify problems

    MD files don't always get marked dirty & don't always identify problems

    After initially filing this on VSCode, I'm refiling it here as I've only been able to reproduce on MD files, and consistently on the same files across machines. (in my case I'm using this primarily with my Obsidian vault... but I can duplicate all behavior with Obsidian closed, so it's not related to the syncing, or anything else in that app)

    When I say "certain files" at the start of the next paragraph, I haven't noticed any pattern that would let me be more specific

    For certain files, when the file is open, problems will not get yellow squiggles under them although they show int he problems list & the tab turns yellow. When this occurs, editing the document will not mark the file dirty, resulting in Save doing nothing. With a file in this state, closing & restarting VSCode will mark the file as dirty, but saving it will not mark the file as clean (unless the save is triggered by closing the dirty file). At that point restarting VSCode again will still show the file dirty even though it's saved. Saving here will result in a file conflict error from VSCode, although both versions are identical. If instead of saving the file, the file is Reverted, the file will then be marked clean again.

    A side effect of this is that closing one of these dirty but unsaved files will result in the sidebar showing a count of dirty files that is greater than the number of dirty files open in tabs.

    Some things I've tried, and their results...

    • disabling all extensions: no effect... the problems went away since Markdownlint was off, but the same files still produced the same behavior
    • deleting my %APPSETTINGS%/Code folder, except for the user settings json, keybindings json, and snippets... no effect
    • opening a file that consistently reproduces this issue, and removing the problem area... get the file to save, restart VSCode, open the file, then restore the file contents to its original... that file now behaves correctly, consistently

    I did pour through the logging in the VSCode Output window and the only error I saw was an unexpected null thrown from the changecase extension... ~~but it was showing in the MD language service logs even when I had that extension disabled (and yes, I had restarted)~~

    if there's anything else I can copy-paste in here that might help isolate this, please let me know

    opened by af4jm 3
  • Fix https://github.com/microsoft/vscode/issues/156859

    Fix https://github.com/microsoft/vscode/issues/156859

    This patch fixes https://github.com/microsoft/vscode/issues/156859.

    I'd like to add test cases for this pull request if you tell me how to do this. I find src/test/documentLinks.test.ts only tests the range of the output.

    opened by cyn-cheng 3
  • links fenced with backticks are not detected

    links fenced with backticks are not detected

    A link such as monospaced are not detected by vscode markdown services and removed during "organize link definitions" source action

    [`monospaced`][link1]
    
    [link1]: #someref
    

    2022-10-14_11-23-14 (1)

    opened by hellt 1
  • Markdown link without extension such as  file.test doesn't open correct file

    Markdown link without extension such as file.test doesn't open correct file

    If you are able to validate those links, then should clicking the link go to the right place? Clicking readme.test should go to readme.test.md but just tries to open readme.test image

    Originally posted by @roblourens in https://github.com/microsoft/vscode/issues/153094#issuecomment-1225007454

    bug markdown 
    opened by mjbvz 1
  • Support link with column numbers in the markdown editor

    Support link with column numbers in the markdown editor

    Hi 👋

    The ticket https://github.com/microsoft/vscode/issues/40140 added support for following markdown links that specify local paths including line numbers.

    Existing behaviour:

    Given two files and their content:

    a.md:

    [b](./b.md#L3)
    

    b.md:

    1
    2
    3ABC
    4
    5
    

    Clicking on link ./b.md#L3 in the markdown editor opens b.md with the cursor at the beginning of line 3.

    Requested behaviour:

    With this ticket I would liken to request support for adding also column numbers, so:

    a.md:

    [b](./b.md#L3C3)
    

    b.md:

    1
    2
    3ABC
    4
    5
    

    Clicking on link ./b.md#L3C3 in the markdown editor should open b.md with the cursor position in line 3, letter B.

    Thanks! 🙏

    opened by acecilia 1
  • Add markdown linter support and Improve markdown default theme

    Add markdown linter support and Improve markdown default theme

    Hello, Maybe you can consider to support markdown lint and default theme such as github markdown theme etc. It will be very useful.

    markdown linter markdown github theme markdown all in one

    I think you can include them in one plugin, because too many plugin are complex. It's just my advice!

    opened by li1234yun 1
  • Invalid link diagnostics support

    Invalid link diagnostics support

    Tracks moving support for computing diagnostics from VS Code to this service

    We should also explore switching to a pull model for diagnostics since the LSP now supports this

    opened by mjbvz 1
  • Make sure api-extractor output dir exists

    Make sure api-extractor output dir exists

    API extract does not auto create the directories it needs. This causes our release pipeline to fail

    Also fixes api extractor running using the wrong tsconfig, which was generating a lot of warnings

    opened by mjbvz 0
  • Show all Symbols: Can't match when first letter is capitalized

    Show all Symbols: Can't match when first letter is capitalized

    Does this issue occur when all extensions are disabled?: Yes

    • VS Code Version: 1.73.0
    • OS Version: Windows 11 22H2

    Steps to Reproduce:

    屏幕截图 2022-11-04 054225 屏幕截图 2022-11-04 054255

    opened by liyuhang1997 0
  • Figure out what to do about case insensitive file systems (if anything)

    Figure out what to do about case insensitive file systems (if anything)

    From https://github.com/microsoft/vscode/issues/167857

    Problem

    Paths on windows are case insensitive. However this library makes a lot of assumptions about paths being case sensitive. Examples:

    • Path validation
    • Find all references
    • Rename

    This means that if the casing of paths doesn't exactly match, we can end up missing references and reporting false positive diagnostics. We should figure out what to do about this (if anything)

    opened by mjbvz 1
  • Markdown footnote validation

    Markdown footnote validation

    Does this issue occur when all extensions are disabled?: Yes/No Yes

    • VS Code Version: 1.73.1
    • OS Version: Windows_NT x64 10.0.19044

    Steps to Reproduce:

    1. Create new markdown file
    2. Type a text:
    text[^1]
    [^1]: footnote
    
    1. See problems: (×) No link definition found: '^1' (link.no-such-reference) [Ln 1, Col 6] 2022-11-22 14_23_58-test md - 555 - Visual Studio Code
    bug 
    opened by mail2nnv 2
  • Markdown lint for links is not correct.

    Markdown lint for links is not correct.

    Does this issue occur when all extensions are disabled?: Yes/No

    This is the markdown link I wrote

    ### [fs.openSync(path[,flags[,mode]])](https://nodejs.org/api/fs.html#fsopensyncpath-flags-mode)
    

    VS Code linter complains that link.no-such-reference image

    • VS Code Version: 1.73.1
    • OS Version: Windows_NT x64 10.0.19044

    Steps to Reproduce:

    1. Create a markdown file
    2. Copy this code into the file
      ### [fs.openSync(path[,flags[,mode]])](https://nodejs.org/api/fs.html#fsopensyncpath-flags-mode)
      
    bug 
    opened by krave1986 1
  • `markdown.validate.referenceLinks.enabled` Improperly marking Jekyll YAML Headers as

    `markdown.validate.referenceLinks.enabled` Improperly marking Jekyll YAML Headers as "No like definition found"

    Type: Bug

    1. Have a jekyll YAML header in a markdown file like this
    ---
    title:      Post Title Here
    author:     Person Doe
    categories: [catagory1, catagory2]
    tags:       [tag1, tag2]
    ---
    
    1. The catagory and tags info within the [] will be marked as "No like definition found"

    VS Code version: Code 1.73.0 (8fa188b2b301d36553cbc9ce1b0a146ccb93351f, 2022-11-01T15:38:50.881Z) OS version: Darwin x64 21.6.0 Modes: Sandboxed: No

    System Info

    |Item|Value| |---|---| |CPUs|Intel(R) Core(TM) i9-8950HK CPU @ 2.90GHz (12 x 2900)| |GPU Status|2d_canvas: enabled
    canvas_oop_rasterization: disabled_off
    direct_rendering_display_compositor: disabled_off_ok
    gpu_compositing: enabled
    metal: disabled_off
    multiple_raster_threads: enabled_on
    opengl: enabled_on
    rasterization: enabled
    raw_draw: disabled_off_ok
    skia_renderer: enabled_on
    video_decode: enabled
    video_encode: enabled
    vulkan: disabled_off
    webgl: enabled
    webgl2: enabled
    webgpu: disabled_off| |Load (avg)|3, 2, 2| |Memory (System)|32.00GB (10.15GB free)| |Process Argv|.| |Screen Reader|no| |VM|0%|

    Extensions (52)

    Extension|Author (truncated)|Version ---|---|--- better-comments|aar|3.0.2 Bookmarks|ale|13.3.1 preview-mp4|ana|0.0.1 converttoasciiart|Bit|1.0.3 doxdocgen|csc|1.4.0 vscode-markdownlint|Dav|0.48.1 gitlens|eam|13.0.3 prettier-vscode|esb|9.9.0 linter-gfortran|for|3.2.0 pythonsnippets|frh|1.0.2 ginfuru-vscode-jekyll-syntax|gin|0.1.1 todo-tree|Gru|0.0.219 fortran-ls|han|0.6.2 jenkinsfile-support|ivo|1.1.0 vscode-edit-csv|jan|0.7.2 better-cpp-syntax|jef|1.16.3 vsc-python-indent|Kev|1.18.0 vscode-cudacpp|kri|0.1.1 vscode-hdf5-viewer|loc|0.0.3 bash-ide-vscode|mad|1.14.0 vscode-autohotkey-plus-plus|mar|3.0.0 git-graph|mhu|1.30.0 anaconda-extension-pack|ms-|1.0.1 isort|ms-|2022.4.0 python|ms-|2022.18.0 vscode-pylance|ms-|2022.11.10 jupyter|ms-|2022.9.1202862440 jupyter-keymap|ms-|1.0.0 jupyter-renderers|ms-|1.0.12 vscode-jupyter-cell-tags|ms-|0.1.6 vscode-jupyter-slideshow|ms-|0.1.5 remote-containers|ms-|0.262.3 remote-ssh|ms-|0.90.1 remote-ssh-edit|ms-|0.84.0 remote-wsl|ms-|0.72.0 vscode-remote-extensionpack|ms-|0.21.0 cpptools|ms-|1.12.4 vsliveshare|ms-|1.0.5750 autodocstring|njp|0.6.1 clang-tidy|not|0.5.1 nsight-vscode-edition|nvi|2022.2.31663688 material-icon-theme|PKi|4.21.0 trailing-spaces|sha|0.4.1 rewrap|stk|1.16.3 code-spell-checker|str|2.10.1 cmantic|tde|0.9.0 pdf|tom|1.2.0 latex-support|tor|3.10.0 errorlens|use|3.6.0 snippet-creator|vin|1.1.0 better-align|wwm|1.1.6 markdown-all-in-one|yzh|3.4.3

    (5 theme extensions excluded)

    bug 
    opened by bcaddy 1
  • Feature Request: Show current reference link definition on hover

    Feature Request: Show current reference link definition on hover

    While working in a long Markdown document that extensively uses reference links, it can sometimes be frustrating to have to navigate to the link definitions and back to your original context while authoring/editing.

    Hovering on a reference link allows you to go down to the definition:

    Screenshot showing the go to definition UI when hovering on a reference

    And you can use the go-to/find-all references to go back, but the UX isn't as smooth as it could be. It always requires some context switching to leave your current context, check the link, then go back.

    If possible, it would be preferable to show the current definition in the hover UI and keep the option to jump to the definition if needed.

    help wanted 
    opened by michaeltlombardi 0
Releases(0.2.0)
  • 0.2.0(Oct 31, 2022)

    0.2.0 October 31, 2022

    • Added diagnostics for unused link definitions.
    • Added diagnostics for duplicated link definitions.
    • Added quick fixes for removing duplicate / unused link definitions.
    • Added document highlight provider.
    • Polish Update links on file rename.
    • Fix detection of reference link shorthand for names with spaces.
    • Fix reference links references should be case in-sensitive.
    • Fix reference links should resolve to first matching link definition.
    Source code(tar.gz)
    Source code(zip)
  • 0.1.0(Sep 28, 2022)

    • Added getCodeActions to get code actions.
      • Added a code action to extract all occurrences of a link in a file to a link definition at the bottom.
    • Added organizeLinkDefinitions which sorts link definitions to the bottom of the file and also optionally removes unused definitions.
    • getDocumentSymbols now takes an optional includeLinkDefinitions option to also include link definitions in the document symbols.
    • Added a resolveLinkTarget method which can be used to figure out where a link points based on its text and containing document.
    • Make document links use more generic commands instead of internal VS Code commands.
    • Fix document links within notebooks.
    • Fix detection of image reference links.
    • Use custom command name for triggering rename.
    • Add IPullDiagnosticsManager.disposeDocumentResources to clean up watchers when a file is closed in the editor.
    • Fix false positive diagnostic with files that link to themselves.
    • Use parsed markdown to generate header slugs instead of using the original text.
    • Make getRenameFilesInWorkspaceEdit return full sets of participating edits.
    • Bundle d.ts files using api-extractor.
    Source code(tar.gz)
    Source code(zip)
Owner
Microsoft
Open source projects and samples from Microsoft
Microsoft
Functions and objects that make it easier to add fields to Portable Text editors for accessibility meta information, like language changes or abbreviations.

Porta11y Porta11y is a collection of accessibility-focused annotations, decorators and validators for Sanity’s Portable Text editor. Portable Text is

Hidde de Vries 21 Aug 25, 2022
A website for tracking community support for BIP21 QR codes that support on-chain and lightning bitcoin payments.

BIP21 Microsite This is a WIP microsite to promote the usage of a BIP21 payment URI QR code that can include lightning invoices or offers. Wallet supp

Stephen DeLorme 16 Nov 27, 2022
This is a project that is used to execute python codes in the web page. You can install and use it in django projects, You can do any operations that can be performed in python shell with this package.

Django execute code This is a project that is used to execute python codes in the web page. You can install and use it in django projects, You can do

Shinu 5 Nov 12, 2022
This is a Next.js app that powers my Twitch overlays. Good luck and godspeed!

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Adam Elmore 17 Sep 27, 2022
😂 is a self-hostable blog engine built on the tech that powers christine.website

?? ?? is a blog engine powered by Deno. ?? has no canonical pronunciation, and users are not encouraged to come up with one. ?? is and always will be

Xe Iaso 25 Sep 4, 2022
The CSS design system that powers GitHub

Primer CSS The CSS implementation of GitHub's Primer Design System Documentation Our documentation site lives at primer.style/css. You'll be able to f

Primer 11.6k Jan 7, 2023
Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all with IndexedDB. Perfectly suitable for your next (PWA) app.

BrowstorJS ?? ?? ?? Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all

Nullix 8 Aug 5, 2022
A markdown-it plugin that process images through the eleventy-img plugin. Can be used in any projects that uses markdown-it.

markdown-it-eleventy-img A markdown-it plugin that process images through the eleventy-img plugin. Can be used in any projects that use markdown-it. F

null 25 Dec 20, 2022
Elven Tools Dapp - Elrond blockckchain frontend dapp demo. Primarily for NFT minting, but it can be used for other purposes.

Elven Tools Dapp Docs: elven.tools/docs/landing-page.html Demo: dapp-demo.elven.tools Sneak peek: youtu.be/ATSxD3mD4dc The Dapp is built using Nextjs

Elven Tools 24 Jan 1, 2023
Query for CSS brower support data, combined from caniuse and MDN, including version support started and global support percentages.

css-browser-support Query for CSS browser support data, combined from caniuse and MDN, including version support started and global support percentage

Stephanie Eckles 65 Nov 2, 2022
CodePlay is a Web App that helps the user to input HTML,CSS and JS code in the Code editors and display the resultant web page in real-time

CodePlay A codepen clone Setup Clone repository Create and go to the directory where you want to place the repository cd my-directory Clone the proj

Aniket Kumar 5 Sep 24, 2022
Trusted timestamps that you can physically include in photos, videos and live streams using QR codes and audible data signals.

QR Date This is the reference implementation for the first version of QR Date, a signed timestamp inside a QR code that you can use to verify the date

QR Date 36 Oct 5, 2022
A JavaScript Library for building custom text editors with ease 📝

A JavaScript Library for building custom text editors with ease Show your support! Scriptor.js This is a bare bone text editor library, meant to creat

Marketing Pipeline 20 Oct 12, 2022
This plugin allows you to stick toolbar for summernote editors.

Summernote Sticky Toolbar This is a simple plugin for Summernote that makes the toolbar sticky. preview.mp4 Installation Classic Include the plugin sc

İlyas Özkurt 6 Oct 5, 2022
BHIMUPIJS is a npm module which can validate, verify and generate QR Codes for UPI IDs.

bhimupijs BHIMUPIJS is a npm module which can validate, verify and generate QR Codes for UPI IDs. Installation Install this npm package globally. npm

Emmadi Sumith Kumar 18 Nov 21, 2022
We are creating a Library that would ensure developers do not reinvent the wheel anymore as far as Authentication is concerned. Developers can easily register and download authentication codes that suits their need at any point.

#AuthWiki Resource Product Documentation Figma Database Schema First Presentation Live Link API Documentation Individual Contributions User Activity U

Zuri Training 17 Dec 2, 2022
An obsidian plugin for uploading local images embedded in markdown to remote store and export markdown for publishing to static site.

Obsidian Publish This plugin cloud upload all local images embedded in markdown to specified remote image store (support imgur only, currently) and ex

Addo.Zhang 7 Dec 13, 2022
A plugin for the Obsidian markdown note application, adding functionality to render markdown documents with multiple columns of text.

Multi-Column Markdown Take your boring markdown document and add some columns to it! With Multi Column Markdown rather than limiting your document lay

Cameron Robinson 91 Jan 2, 2023