Commit cf115817 authored by Miguel Angel Reina Ortega's avatar Miguel Angel Reina Ortega
Browse files

Fix to allow grid tables to be indented:

- once converted, the html code block will be indented as the original table was
parent 7866cb69
Loading
Loading
Loading
Loading
Loading
+34 −3
Changes for generateSpecWebSite/gridTableTools.py: 34 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -28,6 +28,35 @@ def setLoggers(info:Callable=print, debug:Callable=print, error:Callable=print)
	printError = error


def _common_indent(text:str) -> str:
	"""Leading spaces or tabs shared by every non-blank line."""
	lines = [line for line in text.split('\n') if line.strip()]
	if not lines:
		return ''
	prefix = re.match(r'[ \t]*', lines[0]).group(0)
	for line in lines[1:]:
		lead = re.match(r'[ \t]*', line).group(0)
		while prefix and not lead.startswith(prefix):
			prefix = prefix[:-1]
	return prefix


def _strip_common_indent(lines:list[str]) -> list[str]:
	"""Drop the indent shared by every non-blank line so parsing starts at + or |."""
	indents = [len(re.match(r'[ \t]*', line).group(0)) for line in lines if line.strip()]
	if not indents or min(indents) == 0:
		return lines
	indent = min(indents)
	return [re.sub(rf'^[ \t]{{0,{indent}}}', '', line) for line in lines]


def _indent_block(text:str, indent:str) -> str:
	"""Prefix every line so the HTML stays inside a surrounding list item."""
	if not indent:
		return text
	return re.sub(r'^', indent, text, flags = re.MULTILINE)


class GridCell:
	"""	Represents a grid table cell. """
	
@@ -149,8 +178,9 @@ def parseGridTableWithSpans(gridTable:str) -> tuple[GridTableRowList, GridTableR
	headerDelimiterPositions:list[int] = []
	delimiterPositions:list[int] = []
	
	# Split the input into lines
	lines:list[str] = [line for line in gridTable.rstrip().split('\n')]
	# Split the input into lines. A table inside a list is indented; drop that
	# shared indent so the separator patterns still match at the first + or |.
	lines:list[str] = _strip_common_indent(gridTable.rstrip().split('\n'))


	# Detect separator lines by pattern (it does not take into account partial separators
@@ -692,6 +722,7 @@ def generateHtmlTableWithSpans(gridTable:str) -> str:
	#regexLists = r'(?:(?:(?:[-*+]|\d+\.)\s+[^' + re.escape(_nextListElementMark) + r']+' + re.escape(_nextListElementMark) + r')+)\s*<br\s*/?>\s*<br\s*/?>'
	#regexLists = r'(?:^\s*(?:(?:[-*+]|\d+\.)\s+[^' + re.escape(_nextListElementMark) + r']+' + re.escape(_nextListElementMark) + r')+)'
	
	indent = _common_indent(gridTable)
	try:
		gridHeader, gridBody = parseGridTableWithSpans(gridTable)
	except Exception as e:
@@ -775,5 +806,5 @@ def generateHtmlTableWithSpans(gridTable:str) -> str:

	html += '</tbody>\n'
	html += '</table>'
	return html
	return _indent_block(html, indent)
+7 −5
Changes for generateSpecWebSite/markdownTools.py: 7 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -502,14 +502,16 @@ def analyseMarkdown(filename:Optional[str]=None, inLines:Optional[list[str]]=Non
			gridTable += line
			continue
		if inGridTable:
			if matchGridTableHeaderSeparator.match(line) or matchGridTableBodySeparator.match(line):
			# Separator patterns do not allow a leading indent. Match them on the
			# stripped line, and keep the original line so the HTML can be indented again.
			stripped = line.lstrip(' \t')
			if (matchGridTableHeaderSeparator.match(stripped)
					or matchGridTableBodySeparator.match(stripped)
					or matchGridTableSeparator.match(stripped)
					or matchTable.match(line)):
				#outClauses[-1].append(Line(line, LineType.TABLESEPARATOR))
				gridTable += line
				continue
			elif matchTable.match(line):
				#outClauses[-1].append(Line(line, LineType.TABLEROW))
				gridTable += line
				continue
			else:
				inGridTable = False
				processGridTable()
+37 −6
Changes for gitlabFilter/grid_table_filter.rb: 37 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -26,9 +26,9 @@ module Banzai
          # Anything, starting with | blocks which are ignored by this filter
          # +---+---+---+---+

          ^\+(:?-+:?\+)+$\n         # First separator line
          (?:^[|+][^\n]*$\n)*
          ^\+(-+\+)+$           # Last separator line
          ^[ \t]*\+(:?-+:?\+)+$\n         # First separator line
          (?:^[ \t]*[|+][^\n]*$\n)*
          ^[ \t]*\+(-+\+)+$           # Last separator line

        )
      }mx
@@ -117,6 +117,35 @@ module Banzai
        GRID_TABLE_SEPARATOR.match?(line)
      end

      # Remove the indent shared by every non-blank line, so a table nested in a list
      # is parsed from the first + or |.
      def strip_common_indent(lines)
        indents = lines.reject { |line| line.strip.empty? }.map { |line| line[/\A[ \t]*/].size }
        return lines if indents.empty? || indents.min.zero?

        indent = indents.min
        lines.map { |line| line.sub(/\A[ \t]{0,#{indent}}/, '') }
      end

      # Leading spaces or tabs shared by every non-blank line of the table.
      def common_indent_string(text)
        lines = text.split("\n").reject { |line| line.strip.empty? }
        return '' if lines.empty?

        prefix = lines.first[/\A[ \t]*/]
        lines.drop(1).each do |line|
          lead = line[/\A[ \t]*/]
          prefix = prefix.chop until prefix.empty? || lead.start_with?(prefix)
        end
        prefix
      end

      def indent_block(text, indent)
        return text if indent.empty?

        text.gsub(/^/, indent)
      end

      # Helper method to handle content in cells
      # rubocop:disable Metrics/PerceivedComplexity -- PoC
      def handling_content(cell, content)
@@ -274,8 +303,10 @@ module Banzai
      # rubocop:disable Metrics/CyclomaticComplexity -- PoC
      # rubocop:disable Metrics/PerceivedComplexity -- PoC
      def parse_pandoc_table_with_spans(pandoc_table)
        # Split the input into lines and remove trailing spaces
        # Split the input into lines and remove trailing spaces.
        # A table inside a list is indented; drop that shared indent so column positions stay aligned.
        lines = pandoc_table.rstrip.split("\n").map(&:rstrip)
        lines = strip_common_indent(lines)

        # Retrieve separator indices
        separator_indices = lines.each_index.select { |i| separator?(lines[i]) }
@@ -702,8 +733,8 @@ module Banzai
          # Extract the grid table content from the match
          grid_table = match[:code]
          if grid_table
            # Convert grid table to HTML table
            generate_html_table_with_spans(grid_table)
            # Convert grid table to HTML table and keep the list indent.
            indent_block(generate_html_table_with_spans(grid_table), common_indent_string(grid_table))
          else
            # Return original text if no grid table found
            match.to_s