vuepress / core

Vue-Powered Static Site Generator
https://vuepress.vuejs.org
MIT License
2.29k stars 926 forks source link

feat(markdown): add title support for code blocks (close #1277) #1456

Closed nruffing closed 9 months ago

nruffing commented 9 months ago

Before submitting the PR, please make sure you do the following

What is the purpose of this pull request?

Description

Add support for being able to set a title for code blocks (e.g. a filename).

In case the data-ext attribute was being used for something else in a theme I added a new data-title attribute for the title and its value falls back to be the same as data-ext if an explicit title is not specified.

I opted to use enclose the title in < and > instead of square brackets so it would also easily work with the import code plugin which is already using square brackets.

Example

```ts <config/foo.ts> {1,2}:no-line-numbers
const foo = 'foo'

function bar () {
  return 1024
}


Tests have also been updated.

If we like this approach I can create a PR in `theme-default` to change the css to pull from the `data-title` attribute and update the docs.

closes #1277 

### Screenshots

<!-- If your PR includes UI changes, please provide before/after screenshots. If there are any other images that add context to the PR, add them here as well -->

**Before**

**After**
meteorlxy commented 9 months ago

Any reference of the [] and <> of other markdown extensions? I think it would be better to use a commonly used mark so that users could migrate from other framework to vuepress with ease (and vice versa 😅 )

nruffing commented 9 months ago

Here are some examples I found with some quick research. Based on this I could be on board with a key/value syntax like title="config/foo.ts".

fenceparser

```ts twoslash {1-3, 5} title="Hello, World"

## [MyST](https://mystmd.org/guide/code#showing-a-filename)

````md
```{code} yaml
:filename: myst.yml
project:
  title: Showing Filenames in code-blocks

## [Docusaurus](https://docusaurus.io/docs/markdown-features/code-blocks)

````md
```jsx title="/src/components/HelloCodeTitle.js"
function HelloCodeTitle(props) {
  return <h1>Hello, {props.name}</h1>;
}

## [rehype-code-titles](https://unifiedjs.com/explore/package/rehype-code-titles/#input)

````md
```typescript:lib/mdx.ts
meteorlxy commented 9 months ago

Agree with the key-value implementation. It's also a more extendable syntax

nruffing commented 9 months ago

Sounds good. I will make those changes.