Skip to content

代码块差异效果支持开始和结束行的使用方式 #4613

Closed as not planned
Closed as not planned
@ajiho

Description

@ajiho

Is your feature request related to a problem? Please describe.

如果代码块中的代码特别长特别多的时候有时候想高亮一大片就特别麻烦,需要每行都写[!code ++] 或者[!code --]标记

现在的方式:

  ```js
  foo  // [!code ++]
  foo  // [!code ++]
  foo  // [!code ++]
  foo  // [!code ++]
  foo  // [!code ++]
  foo  // [!code ++]
  foo  // [!code ++]
  foo  // [!code ++]
  foo  // [!code ++]
  bar  // [!code ++]
  bar  // [!code ++]
  bar  // [!code ++]
  bar  // [!code ++]
  bar  // [!code ++]
  ```

希望的方式

  ```js
  foo  // [!code ++:start]
  foo  
  foo 
  foo 
  foo 
  foo 
  foo  
  foo  
  foo 
  bar  
  bar 
  bar 
  bar 
  bar  // [!code ++:end]
  ```

Image

为什么会有这个想法是因为这是从实际的文档维护中遇到的麻烦的地方,并不是我无端的想法,希望可以把这个特性内置到vitepress中

Describe the solution you'd like

这里有一个解决方案
也是我之前提出的问题#4602,根据答案进行的演化

import { defineConfig } from 'vitepress'

export default defineConfig({
  markdown: {
    codeTransformers: [
      {
        span(span, i, j, line) {
          if (
            !['js', 'javascript', 'ts', 'typescript'].includes(
              this.options.lang,
            )
          ) {
            return
          }

          const text = span.children[0]
          if (!text || text.type !== 'text') return

          const startMarker = '[!code ++:start]'
          const endMarker = '[!code ++:end]'
          const markers = [startMarker, endMarker]

          if (markers.some((marker) => text.value.includes(marker))) {
            this.addClassToHast(this.pre, 'has-diff')
            this.addClassToHast(line, ['diff', 'add'])
          }
          if (text.value.includes(startMarker)) {
            text.value = text.value.slice(0, -20)
            this.insideHighlightBlock = true // 标记高亮开始
          } else if (text.value.includes(endMarker)) {
            text.value = text.value.slice(0, -20)
            this.insideHighlightBlock = false // 标记高亮结束
          }
        },

        line(line, i) {
          if (this.insideHighlightBlock) {
            // 从开始标记开始高亮
            this.addClassToHast(line, ['diff', 'add'])
          }
        },
      }
    ]
  }
})

上面的代码考虑的还是不够周全,但是想法和简单实现已经给出,如果觉得可行,请内置到viterepss中

Describe alternatives you've considered

No response

Additional context

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    upstreamRelated to the dependencies

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions