aboutsummaryrefslogtreecommitdiffstats
path: root/src/asciideck_tables_pass.erl
blob: 1adcd1e289c980f727e38e5fcd1e8a183abb74c1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
%% Copyright (c) 2017-2018, Loïc Hoguin <[email protected]>
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

%% This pass parses and builds a table from the contents
%% of a table block.
%%
%% Asciidoc User Guide 23
%%
%% @todo Rows and cells are currently not annotated.
-module(asciideck_tables_pass).

-export([run/1]).

-define(IS_WS(C), (C =:= $\s) or (C =:= $\t) or (C =:= $\n).

run([]) ->
	[];
run([Table={table, _, _, _}|Tail]) ->
	[table(Table)|run(Tail)];
run([Block|Tail]) ->
	[Block|run(Tail)].

table({table, Attrs, Contents, Ann}) ->
	{Cells, NumCols} = parse_table(Contents, Attrs),
	Children = rows(Cells, NumCols),
	{table, Attrs, Children, Ann}.

-ifdef(TEST).
table_test() ->
	{table, _, [
		{row, _, [
			{cell, _, [{paragraph, _, <<"1">>, _}], _},
			{cell, _, [{paragraph, _, <<"2">>, _}], _},
			{cell, _, [{paragraph, _, <<"A">>, _}], _}
		], _},
		{row, _, [
			{cell, _, [{paragraph, _, <<"3">>, _}], _},
			{cell, _, [{paragraph, _, <<"4">>, _}], _},
			{cell, _, [{paragraph, _, <<"B">>, _}], _}
		], _},
		{row, _, [
			{cell, _, [{paragraph, _, <<"5">>, _}], _},
			{cell, _, [{paragraph, _, <<"6">>, _}], _},
			{cell, _, [{paragraph, _, <<"C">>, _}], _}
		], _}
	], _} = table({table, #{}, <<
		"|1 |2 |A\n"
		"|3 |4 |B\n"
		"|5 |6 |C">>, #{line => 1}}),
	ok.
-endif.

%% If the cols attribute is not specified, the number of
%% columns is the number of cells on the first line.
parse_table(Contents, #{<<"cols">> := Cols}) ->
	{parse_cells(Contents, []), num_cols(Cols)};
%% We get the first line, parse the cells in it then
%% count the number of columns in the table. Finally
%% we parse all the remaining cells.
parse_table(Contents, _) ->
	case binary:split(Contents, <<$\n>>) of
		%% We only have the one line. Who writes tables like this?
		[Line] ->
			Cells = parse_cells(Line, []),
			{Cells, length(Cells)};
		%% We have a useful table with more than one line. Good user!
		[Line, Rest] ->
			Cells0 = parse_cells(Line, []),
			Cells = parse_cells(Rest, lists:reverse(Cells0)),
			{Cells, length(Cells0)}
	end.

%% @todo Don't discard Specs.
num_cols(Cols) ->
	try binary_to_integer(Cols) of
		Int -> Int
	catch _:_ ->
		Specs0 = binary:split(Cols, <<$,>>, [global]),
		Specs = [parse_specs(Spec) || Spec <- Specs0],
		lists:sum([M || #{multiplier := M} <- Specs])
	end.

-ifdef(TEST).
num_cols_test_() ->
	Tests = [
		{<<"4">>, 4},
		{<<">s,^m,e">>, 3},
		{<<"3,^2,^2,10">>, 4},
		{<<"^1,4*2">>, 5},
		{<<"e,m,^,>s">>, 4},
		{<<"2<d,2*,4d,>">>, 5},
		{<<"4*<">>, 4},
		{<<"3*.^">>, 3},
		{<<"2*,.>">>, 3},
		{<<".<,.^,.>">>, 3},
		{<<".<,.^,^.>">>, 3}
	],
	[{V, fun() -> R = num_cols(V) end} || {V, R} <- Tests].
-endif.

%% Asciidoc User Guide 23.4
%%
%% [<multiplier>*][<horizontal>][.<vertical>][<width>][<style>]
parse_specs(Bin0) ->
	{ok, Bin1, Spec1} = parse_specs_multiplier(Bin0, #{}),
	%% Width and alignment positions may be switched.
	{ok, Bin4, Spec4} = case Bin1 of
		<<C, _/bits>> when C >= $0, C =< $9 ->
			{ok, Bin2, Spec2} = parse_specs_width(Bin1, Spec1),
			{ok, Bin3, Spec3} = parse_specs_horizontal(Bin2, Spec2),
			parse_specs_vertical(Bin3, Spec3);
		_ ->
			{ok, Bin2, Spec2} = parse_specs_horizontal(Bin1, Spec1),
			{ok, Bin3, Spec3} = parse_specs_vertical(Bin2, Spec2),
			parse_specs_width(Bin3, Spec3)
	end,
	parse_specs_style(Bin4, Spec4).

parse_specs_multiplier(Bin, Spec) ->
	case binary:split(Bin, <<"*">>) of
		[_] ->
			{ok, Bin, Spec#{multiplier => 1}};
		[Multiplier, Rest] ->
			{ok, Rest, Spec#{multiplier => binary_to_integer(Multiplier)}}
	end.

parse_specs_horizontal(Bin, Spec) ->
	case Bin of
		<<"<", Rest/bits>> -> {ok, Rest, Spec#{horizontal => left}};
		<<"^", Rest/bits>> -> {ok, Rest, Spec#{horizontal => center}};
		<<">", Rest/bits>> -> {ok, Rest, Spec#{horizontal => right}};
		_ -> {ok, Bin, Spec#{horizontal => left}}
	end.

parse_specs_vertical(Bin, Spec) ->
	case Bin of
		<<".<", Rest/bits>> -> {ok, Rest, Spec#{vertical => top}};
		<<".^", Rest/bits>> -> {ok, Rest, Spec#{vertical => middle}};
		<<".>", Rest/bits>> -> {ok, Rest, Spec#{vertical => bottom}};
		_ -> {ok, Bin, Spec#{vertical => top}}
	end.

parse_specs_width(Bin, Spec) ->
	case binary:split(Bin, <<"%">>) of
		[_] ->
			case binary_take_while_integer(Bin, <<>>) of
				{<<>>, _} ->
					{ok, Bin, Spec#{width => 1, width_unit => proportional}};
				{Width, Rest} ->
					{ok, Rest, Spec#{width => binary_to_integer(Width), width_unit => proportional}}
			end;
		[Percent, Rest] ->
			{ok, Rest, Spec#{width => binary_to_integer(Percent), width_unit => percent}}
	end.

binary_take_while_integer(<<C, R/bits>>, Acc) when C >= $0, C =< $9 ->
	binary_take_while_integer(R, <<Acc/binary, C>>);
binary_take_while_integer(Rest, Acc) ->
	{Acc, Rest}.

parse_specs_style(<<>>, Spec) ->
	Spec#{style => default};
parse_specs_style(Bin, Spec) ->
	Style = parse_specs_match_style(Bin, [
		<<"default">>, <<"emphasis">>, <<"monospaced">>, <<"strong">>,
		<<"header">>, <<"literal">>, <<"verse">>
	]),
	Spec#{style => Style}.

parse_specs_match_style(Prefix, [Style|Tail]) ->
	case binary:longest_common_prefix([Prefix, Style]) of
		0 -> parse_specs_match_style(Prefix, Tail);
		_ -> binary_to_atom(Style, latin1)
	end.

-ifdef(TEST).
parse_specs_test_() ->
	Res = fun(Override) ->
		maps:merge(#{
			multiplier => 1,
			horizontal => left,
			vertical => top,
			width => 1,
			width_unit => proportional,
			style => default
		}, Override)
	end,
	Tests = [
		{<<"3">>, Res(#{width => 3})},
		{<<"10">>, Res(#{width => 10})},
		{<<">s">>, Res(#{horizontal => right, style => strong})},
		{<<"^m">>, Res(#{horizontal => center, style => monospaced})},
		{<<"e">>, Res(#{style => emphasis})},
		{<<"^2">>, Res(#{horizontal => center, width => 2})},
		{<<"4*2">>, Res(#{multiplier => 4, width => 2})},
		{<<"^">>, Res(#{horizontal => center})},
		{<<">">>, Res(#{horizontal => right})},
		{<<"2<h">>, Res(#{width => 2, horizontal => left, style => header})},
		{<<"2*">>, Res(#{multiplier => 2})},
		{<<"4*<">>, Res(#{multiplier => 4, horizontal => left})},
		{<<"3*.^">>, Res(#{multiplier => 3, vertical => middle})},
		{<<".>">>, Res(#{vertical => bottom})}
	],
	[{V, fun() -> R = parse_specs(V) end} || {V, R} <- Tests].
-endif.

parse_cells(Contents, Acc) ->
	Cells = split_cells(Contents),%binary:split(Contents, [<<$|>>], [global]),
	do_parse_cells(Cells, Acc).
	%% Split on |
	%% Look at the end of each element see if there's a cell specifier
	%% Add it as an attribute to the cell for now and consolidate
	%% when processing rows.

split_cells(Contents) ->
	split_cells(Contents, <<>>, []).

split_cells(<<>>, Cell, Acc) ->
	lists:reverse([Cell|Acc]);
split_cells(<<$\\, $|, R/bits>>, Cell, Acc) ->
	split_cells(R, <<Cell/binary, $|>>, Acc);
split_cells(<<$|, R/bits>>, Cell, Acc) ->
	split_cells(R, <<>>, [Cell|Acc]);
split_cells(<<C, R/bits>>, Cell, Acc) ->
	split_cells(R, <<Cell/binary, C>>, Acc).

%% Malformed table (no pipe before cell). Process it like it is a single cell.
do_parse_cells([Contents], Acc) ->
	%% @todo Annotations.
	lists:reverse([{cell, #{specifiers => <<>>}, Contents, #{}}|Acc]);
%% Last cell. There are no further cell specifiers.
do_parse_cells([Specs, Contents0], Acc) ->
	Contents = asciideck_block_parser:parse(Contents0),
	%% @todo Annotations.
	Cell = {cell, #{specifiers => Specs}, Contents, #{}},
	lists:reverse([Cell|Acc]);
%% If there are cell specifiers we need to extract them from the cell
%% contents. Cell specifiers are everything from the last whitespace
%% until the end of the binary.
do_parse_cells([Specs, Contents0|Tail], Acc) ->
	NextSpecs = <<>>, %% @todo find_r(Contents0, <<>>),
	Len = byte_size(Contents0) - byte_size(NextSpecs),
	<<Contents1:Len/binary, _/bits>> = Contents0,
	Contents = asciideck_block_parser:parse(Contents1),
	%% @todo Annotations.
	Cell = {cell, #{specifiers => Specs}, Contents, #{}},
	do_parse_cells([NextSpecs|Tail], [Cell|Acc]).

%% @todo This is not correct. Not all remaining data is specifiers.
%% In addition, for columns at the end of the line this doesn't apply.
%% Find the remaining data after the last whitespace character.
%find_r(<<>>, Acc) ->
%	Acc;
%find_r(<<C, Rest/bits>>, _) when ?IS_WS(C) ->
%	find_r(Rest, Rest);
%find_r(<<_, Rest/bits>>, Acc) ->
%	find_r(Rest, Acc).

-ifdef(TEST).
parse_table_test() ->
	{[
		{cell, _, [{paragraph, _, <<"1">>, _}], _},
		{cell, _, [{paragraph, _, <<"2">>, _}], _},
		{cell, _, [{paragraph, _, <<"A">>, _}], _},
		{cell, _, [{paragraph, _, <<"3">>, _}], _},
		{cell, _, [{paragraph, _, <<"4">>, _}], _},
		{cell, _, [{paragraph, _, <<"B">>, _}], _},
		{cell, _, [{paragraph, _, <<"5">>, _}], _},
		{cell, _, [{paragraph, _, <<"6">>, _}], _},
		{cell, _, [{paragraph, _, <<"C">>, _}], _}
	], 3} = parse_table(<<
		"|1 |2 |A\n"
		"|3 |4 |B\n"
		"|5 |6 |C">>, #{}),
	ok.

parse_table_escape_pipe_test() ->
	{[
		{cell, _, [{paragraph, _, <<"1">>, _}], _},
		{cell, _, [{paragraph, _, <<"2">>, _}], _},
		{cell, _, [{paragraph, _, <<"3 |4">>, _}], _},
		{cell, _, [{paragraph, _, <<"5">>, _}], _}
	], 2} = parse_table(<<
		"|1 |2\n"
		"|3 \\|4 |5">>, #{}),
	ok.
-endif.

%% @todo We currently don't handle colspans and rowspans.
rows(Cells, NumCols) ->
	rows(Cells, [], NumCols, [], NumCols).

%% End of row.
rows(Tail, Acc, NumCols, RowAcc, CurCol) when CurCol =< 0 ->
	%% @todo Annotations.
	Row = {row, #{}, lists:reverse(RowAcc), #{}},
	rows(Tail, [Row|Acc], NumCols, [], NumCols);
%% Add a cell to the row.
rows([Cell|Tail], Acc, NumCols, RowAcc, CurCol) ->
	rows(Tail, Acc, NumCols, [Cell|RowAcc], CurCol - 1);
%% End of a properly formed table.
rows([], Acc, _, [], _) ->
	lists:reverse(Acc);
%% Malformed table. Even if we expect more columns,
%% if there are no more cells there's nothing we can do.
rows([], Acc, _, RowAcc, _) ->
	%% @todo Annotations.
	Row = {row, #{}, lists:reverse(RowAcc), #{}},
	lists:reverse([Row|Acc]).