diff options
Diffstat (limited to 'docbook/asciidoctor-macros/commaize-block/extension.rb')
-rw-r--r-- | docbook/asciidoctor-macros/commaize-block/extension.rb | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/docbook/asciidoctor-macros/commaize-block/extension.rb b/docbook/asciidoctor-macros/commaize-block/extension.rb new file mode 100644 index 0000000000..9b37823b29 --- /dev/null +++ b/docbook/asciidoctor-macros/commaize-block/extension.rb @@ -0,0 +1,46 @@ +# SPDX-License-Identifier: MIT +require 'asciidoctor/extensions' unless RUBY_ENGINE == 'opal' + +include Asciidoctor + +# An extension that converts a list of lines to an inline Oxford comma-separated list. +# +# Usage +# +# [commaize] +# -- +# item1 +# item2 +# item3 +# -- +# +class CommaizeBlock < Extensions::BlockProcessor + use_dsl + + named :commaize + on_contexts :paragraph, :open + # XXX What's the difference between text, raw, simple, verbatim, etc? + parse_content_as :simple + + def process parent, reader, attrs + lines = reader.lines + sort = attrs.fetch('sort', 'true') == 'true' + + lines.reject { |line| line.empty? } + lines = lines.collect(&:strip) + + if sort + lines = lines.sort_by { |line| line.downcase } + end + + if lines.length < 2 + create_paragraph parent, lines, attrs + elsif lines.length == 2 + create_paragraph parent, (lines.join(" and ")), attrs + else + commaized = lines[0..-2].join(", ") + commaized << ", and " + lines[-1] + create_paragraph parent, commaized, attrs + end + end +end |