mauro3 / OrgTables.jl

Read Emacs org-mode tables
Other
9 stars 0 forks source link

Writer based on Tables.jl #3

Open non-Jedi opened 3 years ago

non-Jedi commented 3 years ago

I've developed the following writer based on Tables.jl. Obviously needs some work to integrate into this package, so I'm attaching it to an issue (for now) instead of making a PR. In my own smoke-testing, it seems to work relatively well. Not optimized by any means.

It doesn't yet support directly writing AbstractVector/AbstractMatrix, but it should be pretty easy to add dispatch to support such cases.

Looks like we should also insert zero-width spaces a escape characters for any special characters. But I haven't done so yet. Or maybe enclose any special characters in ~verbatim~? Not sure what the best way of handling newlines though.

using Tables

struct OrgTable{T}
    data::T
end

function Base.show(io::IO, ::MIME"text/org", x::OrgTable)
    header = [' ' * string(n) * ' ' for n in Tables.columnnames(x.data)]
    rows = Vector{String}[]
    lengths = length.(header)

    for tablerow in Tables.rows(x.data)
        row = [' ' * string(v) * ' ' for v in tablerow]
        lengths .= max.(length.(row), lengths)
        push!(rows, row)
    end

    # Write header
    for (s, l) in zip(header, lengths)
        print(io, '|', rpad(s, l))
    end
    println(io, '|')

    # Write |---+---| divider
    print(io, '|')
    let (a, rest) = Iterators.peel(lengths)
        print(io, '-'^a)
        for n in rest
            print(io, '+', '-'^n)
        end
    end
    println(io, '|')

    # Write rows
    for row in rows
        for (s, l) in zip(row, lengths)
            print(io, '|', rpad(s, l))
        end
        println(io, '|')
    end
end

Posting this here based on a comment you made to me over 2 years ago. Took me a while to circle back around to this.

mauro3 commented 3 years ago

As you've probably guessed by the long time it took to reply: I'm not using this package at the moment. If you think this outdated package can serve as a starting point for good org-table support, then please use it. However, I'll only join once I need this again. If you want to do a PR, that would be fine too.

non-Jedi commented 3 years ago

@ronisbr Do you think this functionality might be appropriate for PrettyTables? It seems ridiculously small to register as its own package, and I don't have interest at the moment in maintaining an org parser...

ronisbr commented 3 years ago

Hi @non-Jedi !

Yes, it will be quite easy to implement a backend to output a Tables.jl as an org table. In fact, I really liked the idea. I will open an issue to do this.