File: doc_wiki.pl

package info (click to toggle)
swi-prolog 5.10.1-1%2Bsqueeze1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 76,436 kB
  • ctags: 45,143
  • sloc: ansic: 290,417; perl: 215,108; sh: 5,411; java: 5,136; makefile: 5,021; cpp: 2,168; yacc: 843; xml: 77; sed: 12
file content (1332 lines) | stat: -rw-r--r-- 34,532 bytes parent folder | download
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
/*  $Id$

    Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        J.Wielemaker@uva.nl
    WWW:           http://www.swi-prolog.org
    Copyright (C): 2006-2009, University of Amsterdam

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    As a special exception, if you link this library with other files,
    compiled with a Free Software compiler, to produce an executable, this
    library does not by itself cause the resulting executable to be covered
    by the GNU General Public License. This exception does not however
    invalidate any other reasons why the executable file might be covered by
    the GNU General Public License.
*/

:- module(pldoc_wiki,
	  [ wiki_codes_to_dom/3,	% +Codes, +Args, -DOM
	    wiki_lines_to_dom/3,	% +Lines, +Map, -DOM
	    section_comment_header/3,	% +Lines, -Header, -RestLines
	    summary_from_lines/2,	% +Lines, -Codes
	    indented_lines/3,		% +Text, +PrefixChars, -Lines
	    strip_leading_par/2,	% +DOM0, -DOM
	    normalise_white_space/3,	% -Text, //
	    autolink_file/2		% +FileName, -Type
	  ]).
:- use_module(library(lists)).
:- use_module(library(debug)).
:- use_module(library(memfile)).
:- use_module(library(pairs)).
:- use_module(library(option)).


		 /*******************************
		 *	    WIKI PARSING	*
		 *******************************/

%%	wiki_lines_to_dom(+Lines:lines, +Args:list(atom), -Term) is det
%
%	Translate a Wiki text into  an   HTML  term suitable for html//1
%	from the html_write library.

wiki_lines_to_dom(Lines, Args, HTML) :-
	tokenize_lines(Lines, Tokens0),
	normalise_indentation(Tokens0, Tokens),
	wiki_structure(Tokens, -1, Pars),
	wiki_faces(Pars, Args, HTML).


%%	wiki_codes_to_dom(+String, +Args, -DOM) is det.
%
%	Translate a plain text into a DOM term.
%
%	@param String	Plain text.  Either a string or a list of codes.

wiki_codes_to_dom(Codes, Args, DOM) :-
	indented_lines(Codes, [], Lines),
	wiki_lines_to_dom(Lines, Args, DOM).


%%	wiki_structure(+Lines:lines, +BaseIndent,
%%		       -Blocks:list(block)) is det
%
%	Get the structure in terms  of block-level elements: paragraphs,
%	lists and tables. This processing uses   a mixture of layout and
%	punctuation.

wiki_structure([], _, []) :- !.
wiki_structure([_-[]|T], BI, Pars) :- !,	% empty lines
	wiki_structure(T, BI, Pars).
wiki_structure(Lines, _, [\tags(Tags)]) :-
	tags(Lines, Tags), !.
wiki_structure(Lines, BI, [P1|PL]) :-
	take_block(Lines, BI, P1, RestLines),
	wiki_structure(RestLines, BI, PL).

%%	take_block(+Lines, +BaseIndent, ?Block, -RestLines) is semidet.
%
%	Take a block-structure from the input.  Defined block elements
%	are lists, table, hrule, section header and paragraph.

take_block([_-[]|Lines], BaseIndent, Block, Rest) :- !,
	take_block(Lines, BaseIndent, Block, Rest).
take_block([N-_|_], BaseIndent, _, _) :-
	N < BaseIndent, !,
	fail.				% less indented
take_block(Lines, BaseIndent, List, Rest) :-
	list_item(Lines, Type, Indent, LI, LIT, Rest0), !,
	Indent > BaseIndent,
	rest_list(Rest0, Type, Indent, LIT, [], Rest),
	List0 =.. [Type, LI],
	(   ul_to_dl(List0, List)
	->  true
	;   List0 = dl(Items)
	->  List = dl(class=wiki, Items)
	;   List = List0
	).
take_block([N-['|'|RL1]|LT], _, Table, Rest) :-
	phrase(row(R0), RL1),
	rest_table(LT, N, RL, Rest), !,
	Table = table(class=wiki, [tr(R0)|RL]).
take_block([0-[-,-|More]|LT], _, Block, LT) :-	% seperation line
	maplist(=(-), More), !,
	Block = hr([]).
take_block([_-[@|_]], _, _, _) :- !,		% starts @tags section
	fail.
take_block([_-L1|LT], _, Section, LT) :-
	section_line(L1, Section), !.
take_block([_-Verb|Lines], _, Verb, Lines) :-
	verbatim_term(Verb), !.
take_block([I-L1|LT], BaseIndent, Elem, Rest) :- !,
	append(L1, PT, Par),
	rest_par(LT, PT, I, BaseIndent, MaxI, Rest),
	(   MaxI >= BaseIndent+16
	->  Elem = center(Par)
	;   MaxI >= BaseIndent+4
	->  Elem = blockquote(Par)
	;   Elem = p(Par)
	).
take_block([Verb|Lines], _, Verb, Lines).


%%	list_item(+Lines, ?Type, ?Indent, -LI0, -LIT, -RestLines) is det.
%
%	Create a list-item. Naturally this should produce a single item,
%	but DL lists produce two items, so   we create the list of items
%	as a difference list.
%
%	@tbd	Pass base-indent

list_item([Indent-Line|LT], Type, Indent, Items, ItemT, Rest) :- !,
	list_item_prefix(Type, Line, L1),
	(   Type == dl
	->  split_dt(L1, DT0, DD1),
	    append(DD1, LIT, DD),
	    strip_ws_tokens(DT0, DT),
	    Items = [dt(DT),dd(DD)|ItemT]
	;   append(L1, LIT, LI0),
	    Items = [li(LI0)|ItemT]
	),
	rest_list_item(LT, Type, Indent, LIT, Rest).

%%	rest_list_item(+Lines, +Type, +Indent, -RestItem, -RestLines) is det
%
%	Extract the remainder (after the first line) of a list item.

rest_list_item(Lines, _Type, Indent, RestItem, RestLines) :-
	take_blocks_at_indent(Lines, Indent, Blocks, RestLines),
	(   Blocks = [p(Par)|MoreBlocks]
	->  append(['\n'|Par], MoreBlocks, RestItem)
	;   RestItem = Blocks
	).

%%	take_blocks_at_indent(+Lines, +Indent, -Pars, -RestLines) is det.
%
%	Process paragraphs and verbatim blocks (==..==) in bullet-lists.

take_blocks_at_indent(Lines, N, [Block|RestBlocks], RestLines) :-
	take_block(Lines, N, Block, Rest0), !,
	take_blocks_at_indent(Rest0, N, RestBlocks, RestLines).
take_blocks_at_indent(Lines, _, [], Lines).


%%	rest_list(+Lines, +Type, +Indent,
%%		  -Items, -ItemTail, -RestLines) is det.

rest_list(Lines, Type, N, Items, IT, Rest) :-
	skip_empty_lines(Lines, Lines1),
	list_item(Lines1, Type, N, Items, IT0, Rest0), !,
	rest_list(Rest0, Type, N, IT0, IT, Rest).
rest_list(Rest, _, _, IT, IT, Rest).

%%	list_item_prefix(?Type, +Line, -Rest) is det.

list_item_prefix(ul, [*, ' '|T], T) :- !.
list_item_prefix(ul, [-, ' '|T], T) :- !.
list_item_prefix(dl, [$, ' '|T], T) :-
	split_dt(T, _, _), !.
list_item_prefix(ol, [w(N), '.', ' '|T], T) :-
	atom_codes(N, [D]),
	between(0'0, 0'9, D).

split_dt(In, DT, Rest) :-
	append(DT, [':'|Rest0], In),
	(   Rest0 == []
	->  Rest = []
	;   Rest0 = [' '|Rest]
	), !.


%%	ul_to_dl(+UL, -DL) is semidet.
%
%	Translate an UL list into a DL list   if  all entries are of the
%	form "* <term> nl, <description>" or all   items  are of the for
%	[[PredicateIndicator]].

ul_to_dl(ul(Items), Description) :-
	term_items(Items, DLItems, []),
	(   terms_to_predicate_includes(DLItems, Preds)
	->  Description = dl(class(predicates), Preds)
	;   Description = dl(class(termlist), DLItems)
	).

term_items([], T, T).
term_items([LI|LIs], DLItems, Tail) :-
	term_item(LI, DLItems, Tail1),
	term_items(LIs, Tail1, Tail).

%%	term_item(+LI, -DLItem, ?Tail) is semidet.
%
%	If LI is of the form <Term> followed  by a newline, return it as
%	dt-dd  tuple.  The  <dt>  item    contains  a  term  \term(Term,
%	Bindings).

term_item(li(Tokens),
	  [ dt(class=term, \term(Term, Bindings)),
	    dd(Descr)
	  | Tail
	  ], Tail) :-
	(   (   append(TermTokens, ['\n'|Descr], Tokens)
	    ->	true
	    ;	TermTokens = Tokens,
		Descr = []
	    )
	->  new_memory_file(MemFile),
	    open_memory_file(MemFile, write, Out),
	    forall(member(T, TermTokens),
		   write_token(Out, T)),
	    write(Out, ' .\n'),
	    close(Out),
	    open_memory_file(MemFile, read, In),
	    catch(call_cleanup((read_dt_term(In, Term, Bindings),
				read_dt_term(In, end_of_file, [])),
			       (close(In),
				free_memory_file(MemFile))),
		  _, fail)
	).

write_token(Out, w(X)) :- !,
	write(Out, X).
write_token(Out, X) :-
	write(Out, X).

read_dt_term(In, Term, Bindings) :-
	read_term(In, Term,
		  [ variable_names(Bindings),
		    module(pldoc_modes)
		  ]).

terms_to_predicate_includes([], []).
terms_to_predicate_includes([dt(class=term, \term([[PI]], [])), dd([])|T0],
			    [\include(PI, predicate, [])|T]) :-
	is_pi(PI),
	terms_to_predicate_includes(T0, T).

is_pi(Name/Arity) :-
	atom(Name),
	integer(Arity),
	between(0, 20, Arity).
is_pi(Name//Arity) :-
	atom(Name),
	integer(Arity),
	between(0, 20, Arity).


%%	row(-Cells)// is det.

row([C0|CL]) -->
	cell(C0), !,
	row(CL).
row([]) -->
	[].

cell(td(C)) -->
	tokens(C0),
	['|'], !,
	{ strip_ws_tokens(C0, C)
	}.

rest_table([N-['|'|RL1]|LT], N, [tr(R0)|RL], Rest) :- !,
	phrase(row(R0), RL1),
	rest_table(LT, N, RL, Rest).
rest_table(Rest, _, [], Rest).

%%	rest_par(+Lines, -Par,
%%		 +BaseIndent, +MaxI0, -MaxI, -RestLines) is det.
%
%	Take the rest of a paragraph. Paragraphs   are  ended by a blank
%	line or the start of a list-item.   The latter is a bit dubious.
%	Why not a  general  block-level   object?  The  current defition
%	allows for writing lists without a blank line between the items.

rest_par([], [], _, MaxI, MaxI, []) :- !.
rest_par([_-[]|Rest], [], _, MaxI, MaxI, Rest) :- !.
rest_par(Lines, [], _, MaxI, MaxI, Lines) :-
	Lines = [_-Verb|_],
	verbatim_term(Verb), !.
rest_par([I-L|Rest], [], _, MaxI, MaxI, [I-L|Rest]) :-
	list_item_prefix(_, L, _), !.
rest_par([I-L1|LT], ['\n'|Par], BI, MaxI0, MaxI, Rest) :-
	append(L1, PT, Par),
	MaxI1 is max(I, MaxI0),
	rest_par(LT, PT, BI, MaxI1, MaxI, Rest).


%%	section_line(+Tokens, -Section) is det.
%
%	Extract a section using the Twiki   conventions. The section may
%	be preceeded by [Word], in which case we generate an anchor name
%	Word for the section.

section_line([-,-,-|Rest], Section) :-
	plusses(Rest, Section).

plusses([+, ' '|Rest], h1(Attrs, Content)) :-
	hdr_attributes(Rest, Attrs, Content).
plusses([+, +, ' '|Rest], h2(Attrs, Content)) :-
	hdr_attributes(Rest, Attrs, Content).
plusses([+, +, +, ' '|Rest], h3(Attrs, Content)) :-
	hdr_attributes(Rest, Attrs, Content).
plusses([+, +, +, +, ' '|Rest], h4(Attrs, Content)) :-
	hdr_attributes(Rest, Attrs, Content).

hdr_attributes(List, Attrs, Content) :-
	strip_leading_ws(List, List2),
	(   List2 = ['[',w(Name),']'|List3]
	->  strip_ws_tokens(List3, Content),
	    Attrs = [class(wiki), name(Name)]
	;   Attrs = class(wiki),
	    strip_ws_tokens(List, Content)
	).


%%	strip_ws_tokens(+Tokens, -Stripped)
%
%	Strip leading and trailing whitespace from a token list.  Note
%	the the whitespace is already normalised.

strip_ws_tokens([' '|T0], T) :- !,
	strip_ws_tokens(T0, T).
strip_ws_tokens(L0, L) :-
	append(L, [' '], L0), !.
strip_ws_tokens(L, L).


%%	strip_leading_ws(+Tokens, -Stripped) is det.
%
%	Strip leading whitespace from a token list.

strip_leading_ws([' '|T], T) :- !.
strip_leading_ws(T, T).


		 /*******************************
		 *	       TAGS		*
		 *******************************/

%%	tags(+Lines:lines, -Tags) is semidet.
%
%	If the first line is a @tag, read the remainder of the lines to
%	a list of \tag(Name, Value) terms.

tags(Lines, Tags) :-
	collect_tags(Lines, Tags0),
	keysort(Tags0, Tags1),
	pairs_values(Tags1, Tags2),
	combine_tags(Tags2, Tags).

%%	collect_tags(+IndentedLines, -Tags) is semidet
%
%	Create a list Order-tag(Tag,Tokens) for   each @tag encountered.
%	Order is the desired position as defined by tag_order/2.
%
%	@tbd Tag content is  often  poorly   aligned.  We  now  find the
%	alignment of subsequent lines  and  assume   the  first  line is
%	alligned with the remaining lines.

collect_tags([], []).
collect_tags([Indent-[@,String|L0]|Lines], [Order-tag(Tag,Value)|Tags]) :-
	tag_name(String, Tag, Order), !,
	strip_leading_ws(L0, L),
	rest_tag(Lines, Indent, VT, RestLines),
	normalise_indentation(VT, VT1),
	wiki_structure([0-L|VT1], -1, Value0),
	strip_leading_par(Value0, Value),
	collect_tags(RestLines, Tags).


%%	tag_name(+String, -Tag:atom, -Order:int) is semidet.
%
%	If String denotes a know tag-name,

tag_name(w(Name), Tag, Order) :-
	(   renamed_tag(Name, Tag),
	    tag_order(Tag, Order)
	->  print_message(warning, pldoc(deprecated_tag(Name, Tag)))
	;   tag_order(Name, Order)
	->  Tag = Name
	;   print_message(warning, pldoc(unknown_tag(Name))),
	    fail
	).


rest_tag([], _, [], []) :- !.
rest_tag(Lines, Indent, [], Lines) :-
	Lines = [Indent-[@,w(_Name)|_]|_], !.
rest_tag([L|Lines0], Indent, [L|VT], Lines) :-
	rest_tag(Lines0, Indent, VT, Lines).


%%	renamed_tag(+DeprecatedTag:atom, -Tag:atom) is semidet.
%
%	Declaration for deprecated tags.

renamed_tag(exception, throws).


%%	tag_order(+Tag:atom, -Order:int) is semidet.
%
%	Both declares the know tags and  their expected order. Currently
%	the tags are forced into  this   order  without  warning. Future
%	versions may issue a warning if the order is inconsistent.

tag_order(param,       1).
tag_order(error,       2).		% same as throw
tag_order(throws,      3).
tag_order(author,      4).
tag_order(version,     5).
tag_order(see,	       6).
tag_order(deprecated,  7).
tag_order(compat,      8).		% PlDoc extension
tag_order(copyright,   9).
tag_order(license,    10).
tag_order(bug,	      11).
tag_order(tbd,	      12).


%%	combine_tags(+Tags:list(tag(Key, Value)), -Tags:list) is det.
%
%	Creates the final tag-list.  Tags is a list of
%
%		* \params(list(param(Name, Descr)))
%		* \tag(Name, list(Descr))
%
%	Descr is a list of tokens.

combine_tags([], []).
combine_tags([tag(param, V1)|T0], [\params([P1|PL])|Tags]) :- !,
	param_tag(V1, P1),
	param_tags(T0, PL, T1),
	combine_tags(T1, Tags).
combine_tags([tag(Tag,V0)|T0], [\tag(Tag, [V0|Vs])|T]) :-
	same_tag(Tag, T0, T1, Vs),
	combine_tags(T1, T).

param_tag([PT|Descr0], param(PN, Descr)) :-
	word_of(PT, PN),
	strip_leading_ws(Descr0, Descr).

word_of(w(W), W) :- !.			% TBD: check non-word param
word_of(W, W).

param_tags([tag(param, V1)|T0], [P1|PL], T) :- !,
	param_tag(V1, P1),
	param_tags(T0, PL, T).
param_tags(T, [], T).

same_tag(Tag, [tag(Tag, V)|T0], T, [V|Vs]) :- !,
	same_tag(Tag, T0, T, Vs).
same_tag(_, L, L, []).


		 /*******************************
		 *	       FACES		*
		 *******************************/

%%	wiki_faces(+Structure, +ArgNames, -HTML) is det.
%
%	Given the wiki structure, analyse the content of the paragraphs,
%	list items and table cells and apply font faces and links.

wiki_faces(DOM0, ArgNames, DOM) :-
	structure_term(DOM0, Functor, Content0), !,
	wiki_faces_list(Content0, ArgNames, Content),
	structure_term(DOM, Functor, Content).
wiki_faces(Verb, _, Verb) :-
	verbatim_term(Verb), !.
wiki_faces(Content0, ArgNames, Content) :-
	assertion(is_list(Content0)),
	phrase(wiki_faces(Content, ArgNames), Content0), !.

wiki_faces_list([], _, []).
wiki_faces_list([H0|T0], Args, [H|T]) :-
	wiki_faces(H0, Args, H),
	wiki_faces_list(T0, Args, T).

%%	structure_term(+Term, -Functor, -Content) is semidet.
%%	structure_term(-Term, +Functor, +Content) is det.
%
%	(Un)pack a term describing structure, so  we can process Content
%	and re-pack the structure.

structure_term(\tags(Tags), tags, [Tags]) :- !.
structure_term(\params(Params), params, [Params]) :- !.
structure_term(param(Name,Descr), param(Name), [Descr]) :- !.
structure_term(\tag(Name,Value), tag(Name), [Value]) :- !.
structure_term(\include(What,Type,Opts), include(What,Type,Opts), []) :- !.
structure_term(dl(Att, Args), dl(Att), [Args]) :- !.
structure_term(dt(Att, Args), dt(Att), [Args]) :- !.
structure_term(table(Att, Args), table(Att), [Args]) :- !.
structure_term(h1(Att, Args), h1(Att), [Args]) :- !.
structure_term(h2(Att, Args), h2(Att), [Args]) :- !.
structure_term(h3(Att, Args), h3(Att), [Args]) :- !.
structure_term(h4(Att, Args), h4(Att), [Args]) :- !.
structure_term(hr(Att), hr(Att), []) :- !.
structure_term(p(Args), p, [Args]) :- !.
structure_term(Term, Functor, Args) :-
	functor(Term, Functor, 1),
	structure_tag(Functor), !,
	Term =.. [Functor|Args].

structure_tag(ul).
structure_tag(ol).
structure_tag(dl).
structure_tag(li).
structure_tag(dt).
structure_tag(dd).
structure_tag(table).
structure_tag(tr).
structure_tag(td).
structure_tag(blockquote).
structure_tag(center).

%%	verbatim_term(?Term) is det
%
%	True if Term must be passes verbatim.

verbatim_term(pre(_,_)).
verbatim_term(\term(_,_)).

%%	wiki_faces(-WithFaces, +ArgNames)// is nondet.
%
%	Apply font-changes and automatic  links   to  running  text. The
%	faces are applied after discovering   the structure (paragraphs,
%	lists, tables, keywords).

wiki_faces([], _) -->
	[].
wiki_faces([H|T], ArgNames) -->
	wiki_face(H, ArgNames),
	wiki_faces(T, ArgNames).

wiki_face(var(Arg), ArgNames) -->
	[w(Arg)],
	{ memberchk(Arg, ArgNames)
	}, !.
wiki_face(b(Bold), _) -->
	[*, w(Bold), *], !.
wiki_face(b(Bold), ArgNames) -->
	[*,'|'], wiki_faces(Bold, ArgNames), ['|',*], !.
wiki_face(i(Italic), _) -->
	['_', w(Italic), '_'], !.
wiki_face(i(Italic), ArgNames) -->
	['_','|'], wiki_faces(Italic, ArgNames), ['|','_'], !.
wiki_face(code(Code), _) -->
	[=, w(Code), =], !.
wiki_face(code(Code), _) -->
	[=,'|'], wiki_faces(Code, []), ['|',=], !.
wiki_face(\predref(Name/Arity), _) -->
	[ w(Name), '/' ], arity(Arity),
	{ functor_name(Name)
	}, !.
wiki_face(\predref(Module:(Name/Arity)), _) -->
	[ w(Module), ':', w(Name), '/' ], arity(Arity),
	{ functor_name(Name)
	}, !.
wiki_face(\predref(Name/Arity), _) -->
	prolog_symbol_char(S0),
	symbol_string(SRest), [ '/' ], arity(Arity), !,
	{ atom_chars(Name, [S0|SRest])
	}.
wiki_face(\predref(Name//Arity), _) -->
	[ w(Name), '/', '/' ], arity(Arity),
	{ functor_name(Name)
	}, !.
wiki_face(\predref(Module:(Name//Arity)), _) -->
	[ w(Module), ':', w(Name), '/', '/' ], arity(Arity),
	{ functor_name(Name)
	}, !.
wiki_face(\include(Name, Type, Options), _) -->
	['[','['], file_name(Base, Ext), [']',']'],
	{ autolink_extension(Ext, Type), !,
	  file_name_extension(Base, Ext, Name),
	  resolve_file(Name, Options, [])
	}, !.
wiki_face(Link, _ArgNames) -->		% [[Label][Link]]
	['[','['],
	tokens(LabelParts),
	[']','['],
	wiki_link(Link, [label(Label), relative(true), end(']')]),
	[']',']'], !,
	{ make_label(LabelParts, Label) }.
wiki_face(Link, _ArgNames) -->
	wiki_link(Link, []), !.
wiki_face(Word, _) -->
	[ w(Word) ], !.
wiki_face(SpaceOrPunct, _) -->
	[ SpaceOrPunct ],
	{ atomic(SpaceOrPunct) }, !.
wiki_face(FT, ArgNames) -->
	[Structure],
	{ wiki_faces(Structure, ArgNames, FT)
	}.


%%	make_label(+Parts, -Label) is det.
%
%	Translate the [[Parts][...] into a label

make_label(Parts, Label) :-
	phrase(image_label(Label), Parts), !.
make_label(Parts, Label) :-
	untag(Parts, Atoms),
	atomic_list_concat(Atoms, Label).

untag([], []).
untag([w(W)|T0], [W|T]) :- !,
	untag(T0, T).
untag([H|T0], [H|T]) :-
	untag(T0, T).


image_label(\include(Name, image, Options)) -->
	file_name(Base, Ext),
	{ autolink_extension(Ext, image),
	  file_name_extension(Base, Ext, Name),
	  resolve_file(Name, Options, RestOptions)
	},
	file_options(RestOptions).


%%	file_options(-Options) is det.
%
%	Extracts additional processing options for  files. The format is
%	;name="value",name2=value2,... Spaces are not allowed.

file_options(Options) -->
	[;], nv_pairs(Options), !.
file_options([]) -->
	[].

nv_pairs([H|T]) -->
	nv_pair(H),
	(   [',']
	->  nv_pairs(T)
	;   {T=[]}
	).

nv_pair(Option) -->
	[ w(Name), =,'"'], tokens(Tokens), ['"'], !,
	{ untag(Tokens, Atoms),
	  atomic_list_concat(Atoms, Value0),
	  catch(atom_number(Value0, Value), _, Value=Value0),
	  Option =.. [Name,Value]
	}.


%%	wiki_link(-Link, +Options)// is semidet.
%
%	True if we can find a link to a file or URL. Links are described
%	as one of:
%
%	    $ filename :
%	    A filename defined using autolink_file/2 or
%	    autolink_extension/2
%	    $ <url-protocol>://<rest-url> :
%	    A fully qualified URL
%	    $ '<' URL '>' :
%	    Be more relaxed on the URL specification.

wiki_link(\file(Name, FileOptions), Options) -->
	file_name(Base, Ext),
	{ file_name_extension(Base, Ext, Name),
	  (   autolink_file(Name, _)
	  ;   autolink_extension(Ext, _)
	  ), !,
	  resolve_file(Name, FileOptions, Options)
	}.
wiki_link(\file(Name, FileOptions), Options) -->
	[w(Name)],
	{ autolink_file(Name, _), !,
	  resolve_file(Name, FileOptions, Options)
	}, !.
wiki_link(a(href(Ref), Label), Options) -->
	[ w(Prot),:,/,/], { url_protocol(Prot) },
	{ option(end(End), Options, space)
	},
	tokens_no_whitespace(Rest), peek_end_url(End), !,
	{ atomic_list_concat([Prot, :,/,/ | Rest], Ref),
	  option(label(Label), Options, Ref)
	}.
wiki_link(a(href(Ref), Label), Options) -->
	[<, w(Alias), :],
	{ user:url_path(Alias, _)
	},
	tokens_no_whitespace(Rest), [>],
	{ atomic_list_concat(Rest, Local),
	  (   Local == ''
	  ->  Term =.. [Alias,'.']
	  ;   Term =.. [Alias,Local]
	  ),
	  expand_url_path(Term, Ref),
	  option(label(Label), Options, Ref)
	}.
wiki_link(a(href(Ref), Label), Options) -->
	[<],
	(   { option(relative(true), Options),
	      Parts = Rest
	    }
	->  tokens_no_whitespace(Rest)
	;   { Parts = [Prot, : | Rest]
	    },
	    [w(Prot), :], tokens_no_whitespace(Rest)
	),
	[>], !,
	{ atomic_list_concat(Parts, Ref),
	  option(label(Label), Options, Ref)
	}.


%%	filename(-Name:atom, -Ext:atom)// is semidet.
%
%	Matches a filename.  A filename is defined as a	sequence
%	<segment>{/<segment}.<ext>.

file_name(FileBase, Extension) -->
	segment(S1),
	segments(List),
	['.'], file_extension(Extension), !,
	{ atomic_list_concat([S1|List], '/', FileBase) }.

segment(..) -->
	['.','.'], !.
segment(Word) -->
	[w(Word)].

segments([H|T]) -->
	['/'], !,
	segment(H),
	segments(T).
segments([]) -->
	[].

file_extension(Ext) -->
	[w(Ext)],
	{ autolink_extension(Ext, _)
	}.


%%	resolve_file(+Name, -Options, ?RestOptions) is det.
%
%	Find the actual file based on the pldoc_file global variable. If
%	present  and  the   file   is    resolvable,   add   an   option
%	absolute_path(Path) that reflects the current   location  of the
%	file.

resolve_file(Name, Options, Rest) :-
	nb_current(pldoc_file, RelativeTo),
	RelativeTo \== [],
	absolute_file_name(Name, Path,
			   [ relative_to(RelativeTo),
			     access(read),
			     file_errors(fail)
			   ]), !,
	Options = [ absolute_path(Path) | Rest ].
resolve_file(_, Options, Options).


%%	arity(-Arity:int)// is semidet.
%
%	True if the next token can be  interpreted as an arity. That is,
%	refers to a non-negative integers of at most 20. Although Prolog
%	allows for higher arities, we assume 20   is  a fair maximum for
%	user-created predicates that are documented.

arity(Arity) -->
	[ w(Word) ],
	{ catch(atom_number(Word, Arity), _, fail),
	  Arity >= 0, Arity < 20
	}.

%%	symbol_string(-String)// is nondet
%
%	Accept a sequence of Prolog symbol characters, starting with the
%	shortest (empty) match.

symbol_string([]) -->
	[].
symbol_string([H|T]) -->
	[H],
	{ prolog_symbol_char(H) },
	symbol_string(T).

prolog_symbol_char(C) -->
	[C],
	{ prolog_symbol_char(C) }.

%%	prolog_symbol_char(?Char)
%
%	True if char is classified by Prolog as a symbol char.

prolog_symbol_char(#).
prolog_symbol_char($).
prolog_symbol_char(&).
prolog_symbol_char(*).
prolog_symbol_char(+).
prolog_symbol_char(-).
prolog_symbol_char(.).
prolog_symbol_char(/).
prolog_symbol_char(:).
prolog_symbol_char(<).
prolog_symbol_char(=).
prolog_symbol_char(>).
prolog_symbol_char(?).
prolog_symbol_char(@).
prolog_symbol_char(\).
prolog_symbol_char(^).
prolog_symbol_char(`).
prolog_symbol_char(~).


functor_name(String) :-
	sub_atom(String, 0, 1, _, Char),
	char_type(Char, lower).

url_protocol(http).
url_protocol(ftp).
url_protocol(mailto).

peek_end_url(space) -->
	peek(End),
	{ space_atom(End) }, !.
peek_end_url(space) -->
	eos, !.
peek_end_url(Token) -->
	peek(Token), !.

space_atom(' ').
space_atom('\r').
space_atom('\n').

%%	autolink_extension(?Ext, ?Type) is nondet.
%
%	True if Ext is a filename extensions that create automatic links
%	in the documentation.

autolink_extension(Ext, prolog) :-
	user:prolog_file_type(Ext,prolog).
autolink_extension(txt, wiki).
autolink_extension(gif, image).
autolink_extension(png, image).
autolink_extension(jpg, image).
autolink_extension(jpeg, image).

%%	autolink_file(?File, -Type) is nondet.
%
%	Files to which we automatically create links, regardless of the
%	extension.

autolink_file('README', wiki).
autolink_file('TODO', wiki).
autolink_file('ChangeLog', wiki).

		 /*******************************
		 *	     SECTIONS		*
		 *******************************/

%%	section_comment_header(+Lines, -Header, -RestLines) is semidet.
%
%	Processes   /**   <section>   comments.   Header   is   a   term
%	\section(Type, Title), where  Title  is   an  atom  holding  the
%	section title and Type is an atom holding the text between <>.
%
%	@param Lines	List of Indent-Codes.
%	@param Header	DOM term of the format \section(Type, Title),
%			where Type is an atom from <type> and Title is
%			a string holding the type.

section_comment_header([_-Line|Lines], Header, Lines) :-
	phrase(section_line(Header), Line).

section_line(\section(Type, Title)) -->
	ws, "<", word(Codes), ">", normalise_white_space(TitleCodes),
	{ atom_codes(Type, Codes),
	  atom_codes(Title, TitleCodes)
	}.


%%	normalise_white_space(-Text)// is det.
%
%	Text is input after deleting leading   and  trailing white space
%	and mapping all internal white space to a single space.

normalise_white_space(Text) -->
	ws,
	normalise_white_space2(Text).

normalise_white_space2(Text) -->
	non_ws(Text, Tail),
	ws,
	(   eos
	->  { Tail = "" }
	;   { Tail = [32|T2] },
	    normalise_white_space2(T2)
	).


		 /*******************************
		 *	     TOKENIZER		*
		 *******************************/

%%	tokenize_lines(+Lines:lines, -TokenLines) is det
%
%	Convert Indent-Codes into Indent-Tokens

tokenize_lines([], []) :- !.
tokenize_lines(Lines, [Pre|T]) :-
	verbatim(Lines, Pre, RestLines), !,
	tokenize_lines(RestLines, T).
tokenize_lines([I-H0|T0], [I-H|T]) :-
	phrase(line_tokens(H), H0),
	tokenize_lines(T0, T).


%%	line_tokens(-Tokens:list)// is det.
%
%	Create a list of tokens, where  is  token   is  either  a ' ' to
%	denote spaces, a  term  w(Word)  denoting   a  word  or  an atom
%	denoting a punctuation character.

line_tokens([H|T]) -->
	line_token(H), !,
	line_tokens(T).
line_tokens([]) -->
	[].

line_token(T) -->
	[C],
	(   { code_type(C, space) }
	->  ws,
	    { T = ' ' }
	;   { code_type(C, alnum) },
	    word(Rest),
	    { atom_codes(W, [C|Rest]),
	      T = w(W)
	    }
	;   { char_code(T, C) }
	).

word([C0|T]) -->
	[C0],  { code_type(C0, alnum) }, !,
	word(T).
word([0'_, C1|T]) -->
	[0'_, C1],  { code_type(C1, alnum) }, !,
	word(T).
word([]) -->
	[].


%%	verbatim(+Lines, -Pre, -RestLines) is det.
%
%	Extract a verbatim environment.  The  returned   Pre  is  of the
%	format pre(Class, String). The indentation of  the leading == is
%	substracted from the indentation of the verbatim lines.
%
%	Verbatim environment is delimited as
%
%	==
%		...,
%		verbatim(Lines, Pre, Rest)
%		...,
%	==

verbatim([Indent-"=="|Lines], Indent-pre(class(code),Pre), RestLines) :-
	verbatim_body(Lines, Indent, [10|PreCodes], [],
		      [Indent-"=="|RestLines]), !,
	atom_codes(Pre, PreCodes).

verbatim_body(Lines, _, PreT, PreT, Lines).
verbatim_body([I-L|Lines], Indent, [10|Pre], PreT, RestLines) :-
	PreI is I - Indent,
	phrase(pre_indent(PreI), Pre, PreT0),
	verbatim_line(L, PreT0, PreT1),
	verbatim_body(Lines, Indent, PreT1, PreT, RestLines).

%%	pre_indent(+Indent)// is det.
%
%	Insert Indent leading spaces.  Note we cannot use tabs as these
%	are not expanded by the HTML <pre> element.

pre_indent(N) -->
	{ N > 0, !,
	  N2 is N - 1
	}, " ",
	pre_indent(N2).
pre_indent(_) -->
	"".

verbatim_line(Line, Pre, PreT) :-
	append(Line, PreT, Pre).


		 /*******************************
		 *	      SUMMARY		*
		 *******************************/

%%	summary_from_lines(+Lines:lines, -Summary:list(codes)) is det.
%
%	Produce a summary for Lines. Similar  to JavaDoc, the summary is
%	defined as the first sentence of the documentation. In addition,
%	a sentence is also ended by an  empty   line  or  the end of the
%	comment.

summary_from_lines(Lines, Sentence) :-
	skip_empty_lines(Lines, Lines1),
	summary2(Lines1, Sentence0),
	end_sentence(Sentence0, Sentence).

summary2(_, Sentence) :-
	Sentence == [], !.		% we finished our sentence
summary2([], []) :- !.
summary2([_-[]|_], []) :- !.		% empty line
summary2([_-[0'@|_]|_], []) :- !.	% keyword line
summary2([_-L0|Lines], Sentence) :-
	phrase(sentence(Sentence, Tail), L0, _),
	summary2(Lines, Tail).

sentence([C,End], []) -->
	[C,End],
	{ \+ code_type(C, period),
	  code_type(End, period)		% ., !, ?
	},
	white, !.
sentence([0' |T0], T) -->
	space, !,
	ws,
	sentence(T0, T).
sentence([H|T0], T) -->
	[H],
	sentence(T0, T).
sentence([0' |T], T) -->		% '
	eos.

white -->
	space.
white -->
	eos.

%%	skip_empty_lines(+LinesIn, -LinesOut) is det.
%
%	Remove empty lines from the start of the input.  Note that
%	this is used both to process character and token data.

skip_empty_lines([], []).
skip_empty_lines([_-[]|Lines0], Lines) :- !,
	skip_empty_lines(Lines0, Lines).
skip_empty_lines(Lines, Lines).

end_sentence("", "").
end_sentence(" ", ".") :- !.
end_sentence([H|T0], [H|T]) :-
	end_sentence(T0, T).


		 /*******************************
		 *	  CREATE LINES		*
		 *******************************/

%%	indented_lines(+Text:list(codes), +Prefixes:list(codes),
%%		       -Lines:list) is det.
%
%	Extract a list of lines  without   leading  blanks or characters
%	from Prefix from Text. Each line   is a term Indent-Codes, where
%	Indent specifies the line_position of the real text of the line.

indented_lines(Comment, Prefixes, Lines) :-
	must_be(codes, Comment),
	phrase(split_lines(Prefixes, Lines), Comment).

split_lines(_, []) -->
	end_of_comment, !.
split_lines(Prefixes, [Indent-L1|Ls]) -->
	take_prefix(Prefixes, 0, Indent0),
	white_prefix(Indent0, Indent),
	take_line(L1),
	split_lines(Prefixes, Ls).


%%	end_of_comment// is det.
%
%	Succeeds if we hit the end of the comment.
%
%	@bug	%*/ will be seen as the end of the comment.

end_of_comment -->
	eos, !.
end_of_comment -->
	ws, stars, "*/", !.

stars --> [].
stars --> "*", !, stars.


%%	take_prefix(+Prefixes:list(codes), +Indent0:int, -Indent:int)// is det.
%
%	Get the leading characters  from  the   input  and  compute  the
%	line-position at the end of the leading characters.

take_prefix(Prefixes, I0, I) -->
	{ member(Prefix, Prefixes) },
	prefix(Prefix), !,
	{ string_update_linepos(Prefix, I0, I) }.
take_prefix(_, I, I) -->
	[].

prefix([]) --> [].
prefix([H|T]) --> [H], prefix(T).

white_prefix(I0, I) -->
	[C],
	{  code_type(C, white), !,
	   update_linepos(C, I0, I1)
	},
	white_prefix(I1, I).
white_prefix(I, I) -->
	[].

%%	string_update_linepos(+Codes, +Pos0, -Pos) is det.
%
%	Update line-position after adding Codes at Pos0.

string_update_linepos([], I, I).
string_update_linepos([H|T], I0, I) :-
	update_linepos(H, I0, I1),
	string_update_linepos(T, I1, I).

%%	update_linepos(+Code, +Pos0, -Pos) is det.
%
%	Update line-position after adding Code.
%
%	@tbd	Currently assumes tab-width of 8.

update_linepos(0'\t, I0, I) :- !,
	I is (I0\/7)+1.
update_linepos(0'\b, I0, I) :- !,
	I is max(0, I0-1).
update_linepos(0'\r, _, 0) :- !.
update_linepos(0'\n, _, 0) :- !.
update_linepos(_, I0, I) :-
	I is I0 + 1.

%%	take_line(-Line:codes)// is det.
%
%	Take  a  line  from  the  input.   Line  does  not  include  the
%	terminating \r or \n character(s), nor trailing whitespace.

take_line([]) -->
	"\r\n", !.			% DOS file
take_line([]) -->
	"\n", !.			% Unix file
take_line(Line) -->
	[H], { code_type(H, white) }, !,
	take_white(White, WT),
	(   nl
	->  { Line = [] }
	;   { Line = [H|White] },
	    take_line(WT)
	).
take_line([H|T]) -->
	[H], !,
	take_line(T).
take_line([]) -->			% end of string
	[].

take_white([H|T0], T) -->
	[H],  { code_type(H, white) }, !,
	take_white(T0, T).
take_white(T, T) -->
	[].

%%	normalise_indentation(+LinesIn, -LinesOut) is det.
%
%	Re-normalise the indentation, such that the  lef-most line is at
%	zero.  Note that we skip empty lines in the computation.

normalise_indentation(Lines0, Lines) :-
	skip_empty_lines(Lines0, Lines1),
	Lines1 = [I0-_|Lines2], !,
	smallest_indentation(Lines2, I0, Subtract),
	(   Subtract == 0
	->  Lines = Lines0
	;   maplist(substract_indent(Subtract), Lines0, Lines)
	).
normalise_indentation(Lines, Lines).

smallest_indentation([], I, I).
smallest_indentation([_-[]|T], I0, I) :- !,
	smallest_indentation(T, I0, I).
smallest_indentation([X-_|T], I0, I) :-
	I1 is min(I0, X),
	smallest_indentation(T, I1, I).

substract_indent(Subtract, I0-L, I-L) :-
	I is max(0,I0-Subtract).


		 /*******************************
		 *	       MISC		*
		 *******************************/

%%	strip_leading_par(+Dom0, -Dom) is det.
%
%	Remove the leading paragraph for  environments where a paragraph
%	is not required.

strip_leading_par([p(C)|T], L) :- !,
	append(C, T, L).
strip_leading_par(L, L).


		 /*******************************
		 *	     DCG BASICS		*
		 *******************************/

%%	eos// is det
%
%	Peek at end of input

eos([], []).

%%	ws// is det
%
%	Eagerly skip layout characters

ws -->
	[C], {code_type(C, space)}, !,
	ws.
ws -->
	[].

%	space// is det
%
%	True if then next code is layout.

space -->
	[C],
	{code_type(C, space)}.

%%	non_ws(-Text, ?Tail) is det.
%
%	True if the  difference  list  Text-Tail   is  the  sequence  of
%	non-white-space characters.

non_ws([H|T0], T) -->
	[H],
	{ \+ code_type(H, space) }, !,
	non_ws(T0, T).
non_ws(T, T) -->
	[].


%%	nl//
%
%	Get end-of-line

nl -->
	"\r\n", !.
nl -->
	"\n".

%%	peek(H)//
%
%	True if next token is H without eating it.

peek(H, L, L) :-
	L = [H|_].

%%	tokens(-Tokens:list)// is nondet.
%
%	Defensively take tokens from the input.  Backtracking takes more
%	tokens.  Do not include structure terms.

tokens([]) --> [].
tokens([H|T]) --> token(H), tokens(T).

%%	tokens_no_whitespace(-Tokens:list(atom))// is nondet.
%
%	Defensively take tokens from the  input. Backtracking takes more
%	tokens.  Tokens  cannot  include  whitespace.  Word  tokens  are
%	returned as their represented words.

tokens_no_whitespace([]) -->
	[].
tokens_no_whitespace([Word|T]) -->
	[ w(Word) ], !,
	tokens_no_whitespace(T).
tokens_no_whitespace([H|T]) -->
	[H],
	{ \+ space_atom(H) },
	tokens_no_whitespace(T).

token(Token) -->
	[Token],
	{ token(Token) }.

token(w(_)) :- !.
token(Token) :- atom(Token).