内联宏处理器扩展示例
- 目的
-
创建一个名为
man的内联宏,用于链接到另一个 man 页。
ManpageInlineMacro
class ManInlineMacro < Asciidoctor::Extensions::InlineMacroProcessor
use_dsl
named :man
name_positional_attributes 'volnum'
def process parent, target, attrs
doc = parent.document
text = manname = target
suffix = (volnum = attrs['volnum']) ? %((#{volnum})) : ''
if doc.basebackend? 'html'
target = %(#{manname}#{doc.outfilesuffix})
doc.register :links, target
node = create_anchor parent, text, type: :link, target: target
elsif doc.backend == 'manpage'
node = create_inline parent, :quoted, manname, type: :strong
else
node = create_inline parent, :quoted, manname
end
create_inline parent, :quoted, %(#{node.convert}#{suffix})
end
end
用法
Asciidoctor::Extensions.register do
inline_macro ManInlineMacro
end
Asciidoctor.convert_file 'sample-with-man-link.adoc', safe: :safe
技巧与窍门
应用替换
在处理内联宏时,大多数替换项已经应用(因为宏是最后一个替换项之一)。为了让处理器将替换项应用于扩展返回的 Inline 节点的文本,您必须在节点实例本身上指定这些扩展。
您可以使用 subs 属性指定要应用于节点文本的替换项。此属性接受一个符号、一个符号数组或一个逗号分隔的字符串。
假设我们希望将普通替换项应用于文本。以下是实现此目的的方法:
create_inline_pass parent, '*https://example.org[Learn more]*',
attributes: { 'subs' => :normal }
此内联直通节点将生成一个链接,该链接的链接文本具有粗体强调(即粗体)。
您也可以将替换项指定为字符串,该字符串的解析方式与块上的 subs 属性的值相同。
create_inline_pass parent, '*https://example.org[Learn more]*',
attributes: { 'subs' => 'quotes,macros' }
您可以指定任何您想要应用的替换项,以及它们的顺序。
除了创建内联直通节点之外,您还可以创建一个带有额外替换项的格式化文本跨度。
create_inline parent, :quoted, 'https://asciidoctor.org.cn is _awesome_!',
attributes: { 'subs' => :quotes }
:quoted 主类型代表一个格式化文本跨度。在这种情况下,我们不需要应用 macros 替换项,因为链接尚未转换。