You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何为Asciidoctor代码块添加剪贴板复制按钮扩展?

编辑:我已放弃通过Asciidoctor实现该功能的尝试,转而编写了一个JavaScript函数。仍感谢各位的帮助!

我尝试在.adoc文件的代码块中添加按钮,以便将代码复制到剪贴板。由于完全找不到相关文档,我向Bard咨询了方法,但无法生效,因此最后尝试向其他开发者求助,希望有人能解决这个问题。

我曾尝试添加AsciidoctorJ的"copyblocks"扩展,但始终无法成功,且可能需要知道它的托管位置,这一点我完全找不到线索,所以这条路径已走不通。

目前,我创建了一个asciidoctor.conf文件,内容如下:

Asciidoctor::Extensions.register do
  include Asciidoctor::Extensions::CopyButtonBlockExtension
end

还有一个copy-button.rb文件,内容如下:

require 'asciidoctor/extensions'

class CopyButtonBlockExtension < Asciidoctor::Extensions::BlockProcessor
    use_dsl
  
    named :copy-button
    on_context :source
  
    def process(parent, reader, attrs)
        # Extract code language from the "source" attribute
        lang = attrs['source'].value
    
        # Extract code content from the block
        content = reader.lines.join
    
        # Generate HTML markup for the container element and the copy button
        html = %(
            <div class="custom-code">
                <pre><code class="#{lang}">#{content}</code></pre>
                <button onclick="copyToClipboard(this)">Copy</button>
            </div>
        )
    
        # Return the generated HTML content
        html
    end
end

def copy_to_clipboard(element) {
    const codeElement = element.previousElementSibling.querySelector('code');
    const codeText = codeElement.innerText;

    navigator.clipboard.writeText(codeText)
    .then(() => {
        element.innerText = 'Copied!';
        setTimeout(() => {
            element.innerText = 'Copy';
        }, 2000);
    })
    .catch((error) => {
        console.error('Failed to copy to clipboard:', error);
    });
}

该.rb文件位于src/site/resources/asciidoc/extensions/目录下。由于所有Asciidoc相关内容都是通过maven-site-plugin的asciidoctor-maven-plugin依赖从pom.xml获取的,因此这个目录和.conf文件都是我自行创建的。

我非常希望能解决这个问题,毕竟大多数网站的代码块都有剪贴板复制按钮,且Vuetify也使用Asciidoc编写文档,这功能看似简单,但我已一筹莫展。


内容的提问来源于stack exchange,提问作者Atryx10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 11:43:20