// Generic CSV → Typst table renderer. // // `evaluate` accepts one mode for every cell: // // false // "markup" // "code" // // It can also be an array with one mode per cell, in row-major order: // // (false, false, "markup", "code", false, ..) #import "../core/macros.typ" as macros #import "../theme/tables.typ" as set_tables #let csv-table( source, delimiter: ",", header: true, columns: auto, // false, "markup", "code", or one such value per cell. evaluate: false, // The same definitions are available to every evaluated cell. scope: macros.bigscope, // Theme function to apply afterwards theme-function: none, // Theme name to apply instead of a function, mutually exclusive with theme-function theme-name: none, text-size: none, ) = { if theme-function != none and theme-name != none { panic( "Both a theme name and theming function cannot be supplied at the same time", ) } let data = csv(source, delimiter: delimiter) if data.len() == 0 { return [] } let column-count = data.first().len() let table-columns = if columns == auto { column-count } else { columns } let cell-count = data.flatten().len() if type(evaluate) == array and evaluate.len() != cell-count { panic( "evaluate has " + str(evaluate.len()) + " entries, but the CSV has " + str(cell-count) + " cells", ) } let render(value, index) = { let mode = if type(evaluate) == array { evaluate.at(index) } else { evaluate } if mode == false { value } else if mode == "markup" or mode == "code" { if value == "" { [] } else { eval(value, mode: mode, scope: scope) } } else { panic("Evaluate entries must be false, \"markup\", or \"code\"") } } let rows = () let cell-index = 0 for row in data { let rendered-row = () for value in row { rendered-row.push(render(value, cell-index)) cell-index += 1 } rows.push(rendered-row) } let table = if header { table( columns: table-columns, table.header(..rows.first()), ..rows.slice(1).flatten(), ) } else { table( columns: table-columns, ..rows.flatten(), ) } if theme-function != none { theme-function[#table] } else if theme-name != none { set_tables.set-table-style( table, table-theme: theme-name, text-size: text-size, ) } else { [#table] } }