]> git.lyx.org Git - lyx.git/blob - src/output_xhtml.cpp
Check path of Qt tools if qtchooser is detected
[lyx.git] / src / output_xhtml.cpp
1 /**
2  * \file output_xhtml.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Richard Heck
7  *
8  * This code is based upon output_docbook.cpp
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "output_xhtml.h"
16
17 #include "Buffer.h"
18 #include "buffer_funcs.h"
19 #include "BufferParams.h"
20 #include "Counters.h"
21 #include "Font.h"
22 #include "Layout.h"
23 #include "OutputParams.h"
24 #include "Paragraph.h"
25 #include "ParagraphList.h"
26 #include "ParagraphParameters.h"
27 #include "sgml.h"
28 #include "Text.h"
29 #include "TextClass.h"
30
31 #include "support/convert.h"
32 #include "support/debug.h"
33 #include "support/lassert.h"
34 #include "support/lstrings.h"
35 #include "support/textutils.h"
36
37 #include <vector>
38
39 // Uncomment to activate debugging code.
40 // #define XHTML_DEBUG
41
42 using namespace std;
43 using namespace lyx::support;
44
45 namespace lyx {
46
47 namespace html {
48
49 docstring escapeChar(char_type c, XHTMLStream::EscapeSettings e)
50 {
51         docstring str;
52         switch (e) {
53         case XHTMLStream::ESCAPE_NONE:
54                 str += c;
55                 break;
56         case XHTMLStream::ESCAPE_ALL:
57                 if (c == '<') {
58                         str += "&lt;";
59                         break;
60                 } else if (c == '>') {
61                         str += "&gt;";
62                         break;
63                 }
64         // fall through
65         case XHTMLStream::ESCAPE_AND:
66                 if (c == '&')
67                         str += "&amp;";
68                 else
69                         str     +=c ;
70                 break;
71         }
72         return str;
73 }
74
75
76 // escape what needs escaping
77 docstring htmlize(docstring const & str, XHTMLStream::EscapeSettings e)
78 {
79         odocstringstream d;
80         docstring::const_iterator it = str.begin();
81         docstring::const_iterator en = str.end();
82         for (; it != en; ++it)
83                 d << escapeChar(*it, e);
84         return d.str();
85 }
86
87
88 docstring escapeChar(char c, XHTMLStream::EscapeSettings e)
89 {
90         LATTEST(static_cast<unsigned char>(c) < 0x80);
91         return escapeChar(static_cast<char_type>(c), e);
92 }
93
94
95 docstring cleanAttr(docstring const & str)
96 {
97         docstring newname;
98         docstring::const_iterator it = str.begin();
99         docstring::const_iterator en = str.end();
100         for (; it != en; ++it) {
101                 char_type const c = *it;
102                 newname += isAlnumASCII(c) ? c : char_type('_');
103         }
104         return newname;
105 }
106
107
108 docstring StartTag::writeTag() const
109 {
110         docstring output = '<' + from_utf8(tag_);
111         if (!attr_.empty())
112                 output += ' ' + html::htmlize(from_utf8(attr_), XHTMLStream::ESCAPE_NONE);
113         output += ">";
114         return output;
115 }
116
117
118 docstring StartTag::writeEndTag() const
119 {
120         string output = "</" + tag_ + ">";
121         return from_utf8(output);
122 }
123
124
125 bool StartTag::operator==(FontTag const & rhs) const
126 {
127         return rhs == *this;
128 }
129
130
131 docstring EndTag::writeEndTag() const
132 {
133         string output = "</" + tag_ + ">";
134         return from_utf8(output);
135 }
136
137
138 ParTag::ParTag(std::string const & tag, std::string attr,
139        std::string const & parid)
140   : StartTag(tag)
141 {
142         if (!parid.empty())
143                 attr += " id='" + parid + "'";
144         attr_ = attr;
145 }
146
147
148 docstring CompTag::writeTag() const
149 {
150         docstring output = '<' + from_utf8(tag_);
151         if (!attr_.empty())
152                 output += ' ' + html::htmlize(from_utf8(attr_), XHTMLStream::ESCAPE_NONE);
153         output += " />";
154         return output;
155 }
156
157
158
159 namespace {
160
161 string fontToTag(html::FontTypes type)
162 {
163         switch(type) {
164         case FT_EMPH:
165                 return "em";
166         case FT_BOLD:
167                 return "b";
168         case FT_NOUN:
169                 return "dfn";
170         case FT_UBAR:
171         case FT_WAVE:
172         case FT_DBAR:
173                 return "u";
174         case FT_SOUT:
175                 return "del";
176         case FT_ITALIC:
177                 return "i";
178         case FT_UPRIGHT:
179         case FT_SLANTED:
180         case FT_SMALLCAPS:
181         case FT_ROMAN:
182         case FT_SANS:
183         case FT_TYPE:
184         case FT_SIZE_TINY:
185         case FT_SIZE_SCRIPT:
186         case FT_SIZE_FOOTNOTE:
187         case FT_SIZE_SMALL:
188         case FT_SIZE_NORMAL:
189         case FT_SIZE_LARGE:
190         case FT_SIZE_LARGER:
191         case FT_SIZE_LARGEST:
192         case FT_SIZE_HUGE:
193         case FT_SIZE_HUGER:
194         case FT_SIZE_INCREASE:
195         case FT_SIZE_DECREASE:
196                 return "span";
197         }
198         // kill warning
199         return "";
200 }
201
202 string fontToAttribute(html::FontTypes type)
203 {
204         switch(type) {
205         case FT_EMPH:
206         case FT_BOLD:
207                 return "";
208         case FT_NOUN:
209                 return "class='lyxnoun'";
210         case FT_UBAR:
211                 return "";
212         case FT_DBAR:
213                 return "class='dline'";
214         case FT_SOUT:
215                 return "class='strikeout'";
216         case FT_WAVE:
217                 return "class='wline'";
218         case FT_ITALIC:
219                 return "";
220         case FT_UPRIGHT:
221                 return "style='font-style:normal;'";
222         case FT_SLANTED:
223                 return "style='font-style:oblique;'";
224         case FT_SMALLCAPS:
225                 return "style='font-variant:small-caps;'";
226         case FT_ROMAN:
227                 return "style='font-family:serif;'";
228         case FT_SANS:
229                 return "style='font-family:sans-serif;'";
230         case FT_TYPE:
231                 return "style='font-family:monospace;'";
232         case FT_SIZE_TINY:
233         case FT_SIZE_SCRIPT:
234         case FT_SIZE_FOOTNOTE:
235                 return "style='font-size:x-small;'";
236         case FT_SIZE_SMALL:
237                 return "style='font-size:small;'";
238         case FT_SIZE_NORMAL:
239                 return "style='font-size:normal;'";
240         case FT_SIZE_LARGE:
241                 return "style='font-size:large;'";
242         case FT_SIZE_LARGER:
243         case FT_SIZE_LARGEST:
244                 return "style='font-size:x-large;'";
245         case FT_SIZE_HUGE:
246         case FT_SIZE_HUGER:
247                 return "style='font-size:xx-large;'";
248         case FT_SIZE_INCREASE:
249                 return "style='font-size:larger;'";
250         case FT_SIZE_DECREASE:
251                 return "style='font-size:smaller;'";
252         }
253         // kill warning
254         return "";
255 }
256
257 } // end anonymous namespace
258
259
260 FontTag::FontTag(FontTypes type)
261   : StartTag(fontToTag(type), fontToAttribute(type)), font_type_(type)
262 {}
263
264
265 bool FontTag::operator==(StartTag const & tag) const
266 {
267         FontTag const * const ftag = tag.asFontTag();
268         if (!ftag)
269                 return false;
270         return (font_type_ == ftag->font_type_);
271 }
272
273
274 EndFontTag::EndFontTag(FontTypes type)
275           : EndTag(fontToTag(type)), font_type_(type)
276 {}
277
278 } // namespace html
279
280
281
282 ////////////////////////////////////////////////////////////////
283 ///
284 /// XHTMLStream
285 ///
286 ////////////////////////////////////////////////////////////////
287
288 XHTMLStream::XHTMLStream(odocstream & os)
289   : os_(os), escape_(ESCAPE_ALL)
290 {}
291
292
293 #ifdef XHTML_DEBUG
294 void XHTMLStream::dumpTagStack(string const & msg)
295 {
296         *this << html::CR();
297         writeError(msg);
298         *this << html::CR();
299         writeError("Tag Stack");
300         TagDeque::const_reverse_iterator it = tag_stack_.rbegin();
301         TagDeque::const_reverse_iterator en = tag_stack_.rend();
302         for (; it != en; ++it) {
303                 writeError(it->get()->tag_);
304         }
305         writeError("End Tag Stack");
306         *this << html::CR();
307         writeError("Pending Tags");
308         it = pending_tags_.rbegin();
309         en = pending_tags_.rend();
310         for (; it != en; ++it) {
311                 writeError(it->get()->tag_);
312         }
313         writeError("End Pending Tags");
314         *this << html::CR();
315 }
316 #endif
317
318
319 void XHTMLStream::writeError(std::string const & s) const
320 {
321         LYXERR0(s);
322         os_ << from_utf8("<!-- Output Error: " + s + " -->\n");
323 }
324
325
326 namespace {
327         // an illegal tag for internal use
328         static html::StartTag const parsep_tag("&LyX_parsep_tag&");
329 }
330
331
332 bool XHTMLStream::closeFontTags()
333 {
334         if (isTagPending(parsep_tag))
335                 // we haven't had any content
336                 return true;
337
338         // this may be a useless check, since we ought at least to have
339         // the parsep_tag. but it can't hurt too much to be careful.
340         if (tag_stack_.empty())
341                 return true;
342
343         // first, we close any open font tags we can close
344         TagPtr curtag = tag_stack_.back();
345         while (curtag->asFontTag()) {
346                 os_ << curtag->writeEndTag();
347                 tag_stack_.pop_back();
348                 // this shouldn't happen, since then the font tags
349                 // weren't in any other tag.
350                 LBUFERR(!tag_stack_.empty());
351                 curtag = tag_stack_.back();
352         }
353
354         if (*curtag == parsep_tag)
355                 return true;
356
357         // so we've hit a non-font tag.
358         writeError("Tags still open in closeFontTags(). Probably not a problem,\n"
359                    "but you might want to check these tags:");
360         TagDeque::const_reverse_iterator it = tag_stack_.rbegin();
361         TagDeque::const_reverse_iterator const en = tag_stack_.rend();
362         for (; it != en; ++it) {
363                 if (**it == parsep_tag)
364                         break;
365                 writeError((*it)->tag_);
366         }
367         return false;
368 }
369
370
371 void XHTMLStream::startDivision(bool keep_empty)
372 {
373         pending_tags_.push_back(makeTagPtr(html::StartTag(parsep_tag)));
374         if (keep_empty)
375                 clearTagDeque();
376 }
377
378
379 void XHTMLStream::endDivision()
380 {
381         if (isTagPending(parsep_tag)) {
382                 // this case is normal. it just means we didn't have content,
383                 // so the parsep_tag never got moved onto the tag stack.
384                 while (!pending_tags_.empty()) {
385                         // clear all pending tags up to and including the parsep tag.
386                         // note that we work from the back, because we want to get rid
387                         // of everything that hasn't been used.
388                         TagPtr const cur_tag = pending_tags_.back();
389                         pending_tags_.pop_back();
390                         if (*cur_tag == parsep_tag)
391                                 break;
392                 }
393                 return;
394         }
395
396         if (!isTagOpen(parsep_tag)) {
397                 writeError("No division separation tag found in endDivision().");
398                 return;
399         }
400
401         // this case is also normal, if the parsep tag is the last one
402         // on the stack. otherwise, it's an error.
403         while (!tag_stack_.empty()) {
404                 TagPtr const cur_tag = tag_stack_.back();
405                 tag_stack_.pop_back();
406                 if (*cur_tag == parsep_tag)
407                         break;
408                 writeError("Tag `" + cur_tag->tag_ + "' still open at end of paragraph. Closing.");
409                 os_ << cur_tag->writeEndTag();
410         }
411 }
412
413
414 void XHTMLStream::clearTagDeque()
415 {
416         while (!pending_tags_.empty()) {
417                 TagPtr const tag = pending_tags_.front();
418                 if (*tag != parsep_tag)
419                         // tabs?
420                         os_ << tag->writeTag();
421                 tag_stack_.push_back(tag);
422                 pending_tags_.pop_front();
423         }
424 }
425
426
427 XHTMLStream & XHTMLStream::operator<<(docstring const & d)
428 {
429         clearTagDeque();
430         os_ << html::htmlize(d, escape_);
431         escape_ = ESCAPE_ALL;
432         return *this;
433 }
434
435
436 XHTMLStream & XHTMLStream::operator<<(const char * s)
437 {
438         clearTagDeque();
439         docstring const d = from_ascii(s);
440         os_ << html::htmlize(d, escape_);
441         escape_ = ESCAPE_ALL;
442         return *this;
443 }
444
445
446 XHTMLStream & XHTMLStream::operator<<(char_type c)
447 {
448         clearTagDeque();
449         os_ << html::escapeChar(c, escape_);
450         escape_ = ESCAPE_ALL;
451         return *this;
452 }
453
454
455 XHTMLStream & XHTMLStream::operator<<(char c)
456 {
457         clearTagDeque();
458         os_ << html::escapeChar(c, escape_);
459         escape_ = ESCAPE_ALL;
460         return *this;
461 }
462
463
464 XHTMLStream & XHTMLStream::operator<<(int i)
465 {
466         clearTagDeque();
467         os_ << i;
468         escape_ = ESCAPE_ALL;
469         return *this;
470 }
471
472
473 XHTMLStream & XHTMLStream::operator<<(EscapeSettings e)
474 {
475         escape_ = e;
476         return *this;
477 }
478
479
480 XHTMLStream & XHTMLStream::operator<<(html::StartTag const & tag)
481 {
482         if (tag.tag_.empty())
483                 return *this;
484         pending_tags_.push_back(makeTagPtr(tag));
485         if (tag.keepempty_)
486                 clearTagDeque();
487         return *this;
488 }
489
490
491 XHTMLStream & XHTMLStream::operator<<(html::ParTag const & tag)
492 {
493         if (tag.tag_.empty())
494                 return *this;
495         pending_tags_.push_back(makeTagPtr(tag));
496         return *this;
497 }
498
499
500 XHTMLStream & XHTMLStream::operator<<(html::CompTag const & tag)
501 {
502         if (tag.tag_.empty())
503                 return *this;
504         clearTagDeque();
505         os_ << tag.writeTag();
506         *this << html::CR();
507         return *this;
508 }
509
510
511 XHTMLStream & XHTMLStream::operator<<(html::FontTag const & tag)
512 {
513         if (tag.tag_.empty())
514                 return *this;
515         pending_tags_.push_back(makeTagPtr(tag));
516         return *this;
517 }
518
519
520 XHTMLStream & XHTMLStream::operator<<(html::CR const &)
521 {
522         // tabs?
523         os_ << from_ascii("\n");
524         return *this;
525 }
526
527
528 bool XHTMLStream::isTagOpen(html::StartTag const & stag) const
529 {
530         TagDeque::const_iterator sit = tag_stack_.begin();
531         TagDeque::const_iterator const sen = tag_stack_.end();
532         for (; sit != sen; ++sit)
533                 if (**sit == stag)
534                         return true;
535         return false;
536 }
537
538
539 bool XHTMLStream::isTagOpen(html::EndTag const & etag) const
540 {
541         TagDeque::const_iterator sit = tag_stack_.begin();
542         TagDeque::const_iterator const sen = tag_stack_.end();
543         for (; sit != sen; ++sit)
544                 if (etag == **sit)
545                         return true;
546         return false;
547 }
548
549
550 bool XHTMLStream::isTagPending(html::StartTag const & stag) const
551 {
552         TagDeque::const_iterator sit = pending_tags_.begin();
553         TagDeque::const_iterator const sen = pending_tags_.end();
554         for (; sit != sen; ++sit)
555                 if (**sit == stag)
556                         return true;
557         return false;
558 }
559
560
561 // this is complicated, because we want to make sure that
562 // everything is properly nested. the code ought to make
563 // sure of that, but we won't assert (yet) if we run into
564 // a problem. we'll just output error messages and try our
565 // best to make things work.
566 XHTMLStream & XHTMLStream::operator<<(html::EndTag const & etag)
567 {
568         if (etag.tag_.empty())
569                 return *this;
570
571         // if this tag is pending, we can simply discard it.
572         if (!pending_tags_.empty()) {
573
574                 if (etag == *pending_tags_.back()) {
575                         // we have <tag></tag>, so we discard it and remove it
576                         // from the pending_tags_.
577                         pending_tags_.pop_back();
578                         return *this;
579                 }
580
581                 // there is a pending tag that isn't the one we are trying
582                 // to close.
583
584                 // is this tag itself pending?
585                 // non-const iterators because we may call erase().
586                 TagDeque::iterator dit = pending_tags_.begin();
587                 TagDeque::iterator const den = pending_tags_.end();
588                 for (; dit != den; ++dit) {
589                         if (etag == **dit) {
590                                 // it was pending, so we just erase it
591                                 writeError("Tried to close pending tag `" + etag.tag_
592                                         + "' when other tags were pending. Last pending tag is `"
593                                         + to_utf8(pending_tags_.back()->writeTag())
594                                         + "'. Tag discarded.");
595                                 pending_tags_.erase(dit);
596                                 return *this;
597                         }
598                 }
599                 // so etag isn't itself pending. is it even open?
600                 if (!isTagOpen(etag)) {
601                         writeError("Tried to close `" + etag.tag_
602                                  + "' when tag was not open. Tag discarded.");
603                         return *this;
604                 }
605                 // ok, so etag is open.
606                 // our strategy will be as below: we will do what we need to
607                 // do to close this tag.
608                 string estr = "Closing tag `" + etag.tag_
609                         + "' when other tags are pending. Discarded pending tags:\n";
610                 for (dit = pending_tags_.begin(); dit != den; ++dit)
611                         estr += to_utf8(html::htmlize((*dit)->writeTag(), XHTMLStream::ESCAPE_ALL)) + "\n";
612                 writeError(estr);
613                 // clear the pending tags...
614                 pending_tags_.clear();
615                 // ...and then just fall through.
616         }
617
618         // make sure there are tags to be closed
619         if (tag_stack_.empty()) {
620                 writeError("Tried to close `" + etag.tag_
621                          + "' when no tags were open!");
622                 return *this;
623         }
624
625         // is the tag we are closing the last one we opened?
626         if (etag == *tag_stack_.back()) {
627                 // output it...
628                 os_ << etag.writeEndTag();
629                 // ...and forget about it
630                 tag_stack_.pop_back();
631                 return *this;
632         }
633
634         // we are trying to close a tag other than the one last opened.
635         // let's first see if this particular tag is still open somehow.
636         if (!isTagOpen(etag)) {
637                 writeError("Tried to close `" + etag.tag_
638                         + "' when tag was not open. Tag discarded.");
639                 return *this;
640         }
641
642         // so the tag was opened, but other tags have been opened since
643         // and not yet closed.
644         // if it's a font tag, though...
645         if (etag.asFontTag()) {
646                 // it won't be a problem if the other tags open since this one
647                 // are also font tags.
648                 TagDeque::const_reverse_iterator rit = tag_stack_.rbegin();
649                 TagDeque::const_reverse_iterator ren = tag_stack_.rend();
650                 for (; rit != ren; ++rit) {
651                         if (etag == **rit)
652                                 break;
653                         if (!(*rit)->asFontTag()) {
654                                 // we'll just leave it and, presumably, have to close it later.
655                                 writeError("Unable to close font tag `" + etag.tag_
656                                         + "' due to open non-font tag `" + (*rit)->tag_ + "'.");
657                                 return *this;
658                         }
659                 }
660
661                 // so we have e.g.:
662                 //    <em>this is <strong>bold
663                 // and are being asked to closed em. we want:
664                 //    <em>this is <strong>bold</strong></em><strong>
665                 // first, we close the intervening tags...
666                 TagPtr curtag = tag_stack_.back();
667                 // ...remembering them in a stack.
668                 TagDeque fontstack;
669                 while (etag != *curtag) {
670                         os_ << curtag->writeEndTag();
671                         fontstack.push_back(curtag);
672                         tag_stack_.pop_back();
673                         curtag = tag_stack_.back();
674                 }
675                 os_ << etag.writeEndTag();
676                 tag_stack_.pop_back();
677
678                 // ...and restore the other tags.
679                 rit = fontstack.rbegin();
680                 ren = fontstack.rend();
681                 for (; rit != ren; ++rit)
682                         pending_tags_.push_back(*rit);
683                 return *this;
684         }
685
686         // it wasn't a font tag.
687         // so other tags were opened before this one and not properly closed.
688         // so we'll close them, too. that may cause other issues later, but it
689         // at least guarantees proper nesting.
690         writeError("Closing tag `" + etag.tag_
691                 + "' when other tags are open, namely:");
692         TagPtr curtag = tag_stack_.back();
693         while (etag != *curtag) {
694                 writeError(curtag->tag_);
695                 if (*curtag != parsep_tag)
696                         os_ << curtag->writeEndTag();
697                 tag_stack_.pop_back();
698                 curtag = tag_stack_.back();
699         }
700         // curtag is now the one we actually want.
701         os_ << curtag->writeEndTag();
702         tag_stack_.pop_back();
703
704         return *this;
705 }
706
707 // End code for XHTMLStream
708
709 namespace {
710
711 // convenience functions
712
713 inline void openParTag(XHTMLStream & xs, Layout const & lay,
714                        std::string parlabel)
715 {
716         xs << html::ParTag(lay.htmltag(), lay.htmlattr(), parlabel);
717 }
718
719
720 void openParTag(XHTMLStream & xs, Layout const & lay,
721                 ParagraphParameters const & params,
722                 std::string parlabel)
723 {
724         // FIXME Are there other things we should handle here?
725         string const align = alignmentToCSS(params.align());
726         if (align.empty()) {
727                 openParTag(xs, lay, parlabel);
728                 return;
729         }
730         string attrs = lay.htmlattr() + " style='text-align: " + align + ";'";
731         xs << html::ParTag(lay.htmltag(), attrs, parlabel);
732 }
733
734
735 inline void closeTag(XHTMLStream & xs, Layout const & lay)
736 {
737         xs << html::EndTag(lay.htmltag());
738 }
739
740
741 inline void openLabelTag(XHTMLStream & xs, Layout const & lay)
742 {
743         xs << html::StartTag(lay.htmllabeltag(), lay.htmllabelattr());
744 }
745
746
747 inline void closeLabelTag(XHTMLStream & xs, Layout const & lay)
748 {
749         xs << html::EndTag(lay.htmllabeltag());
750 }
751
752
753 inline void openItemTag(XHTMLStream & xs, Layout const & lay)
754 {
755         xs << html::StartTag(lay.htmlitemtag(), lay.htmlitemattr(), true);
756 }
757
758
759 void openItemTag(XHTMLStream & xs, Layout const & lay,
760              ParagraphParameters const & params)
761 {
762         // FIXME Are there other things we should handle here?
763         string const align = alignmentToCSS(params.align());
764         if (align.empty()) {
765                 openItemTag(xs, lay);
766                 return;
767         }
768         string attrs = lay.htmlattr() + " style='text-align: " + align + ";'";
769         xs << html::StartTag(lay.htmlitemtag(), attrs);
770 }
771
772
773 inline void closeItemTag(XHTMLStream & xs, Layout const & lay)
774 {
775         xs << html::EndTag(lay.htmlitemtag());
776 }
777
778 // end of convenience functions
779
780 ParagraphList::const_iterator findLastParagraph(
781         ParagraphList::const_iterator p,
782         ParagraphList::const_iterator const & pend)
783 {
784         for (++p; p != pend && p->layout().latextype == LATEX_PARAGRAPH; ++p)
785                 ;
786
787         return p;
788 }
789
790
791 ParagraphList::const_iterator findEndOfEnvironment(
792                 ParagraphList::const_iterator const & pstart,
793                 ParagraphList::const_iterator const & pend)
794 {
795         ParagraphList::const_iterator p = pstart;
796         Layout const & bstyle = p->layout();
797         size_t const depth = p->params().depth();
798         for (++p; p != pend; ++p) {
799                 Layout const & style = p->layout();
800                 // It shouldn't happen that e.g. a section command occurs inside
801                 // a quotation environment, at a higher depth, but as of 6/2009,
802                 // it can happen. We pretend that it's just at lowest depth.
803                 if (style.latextype == LATEX_COMMAND)
804                         return p;
805
806                 // If depth is down, we're done
807                 if (p->params().depth() < depth)
808                         return p;
809
810                 // If depth is up, we're not done
811                 if (p->params().depth() > depth)
812                         continue;
813
814                 // FIXME I am not sure about the first check.
815                 // Surely we *could* have different layouts that count as
816                 // LATEX_PARAGRAPH, right?
817                 if (style.latextype == LATEX_PARAGRAPH || style != bstyle)
818                         return p;
819         }
820         return pend;
821 }
822
823
824 ParagraphList::const_iterator makeParagraphs(Buffer const & buf,
825                                             XHTMLStream & xs,
826                                             OutputParams const & runparams,
827                                             Text const & text,
828                                             ParagraphList::const_iterator const & pbegin,
829                                             ParagraphList::const_iterator const & pend)
830 {
831         ParagraphList::const_iterator const begin = text.paragraphs().begin();
832         ParagraphList::const_iterator par = pbegin;
833         for (; par != pend; ++par) {
834                 Layout const & lay = par->layout();
835                 if (!lay.counter.empty())
836                         buf.masterBuffer()->params().
837                             documentClass().counters().step(lay.counter, OutputUpdate);
838
839                 // FIXME We should see if there's a label to be output and
840                 // do something with it.
841                 if (par != pbegin)
842                         xs << html::CR();
843
844                 // We want to open the paragraph tag if:
845                 //   (i) the current layout permits multiple paragraphs
846                 //  (ii) we are either not already inside a paragraph (HTMLIsBlock) OR
847                 //       we are, but this is not the first paragraph
848                 // But we do not want to open the paragraph tag if this paragraph contains
849                 // only one item, and that item is "inline", i.e., not HTMLIsBlock (such 
850                 // as a branch). That is the "special case" we handle first.
851                 Inset const * specinset = par->size() == 1 ? par->getInset(0) : 0;
852                 bool const special_case =  
853                         specinset && !specinset->getLayout().htmlisblock();
854
855                 bool const open_par = runparams.html_make_pars
856                         && (!runparams.html_in_par || par != pbegin)
857                         && !special_case;
858
859                 // We want to issue the closing tag if either:
860                 //   (i)  We opened it, and either html_in_par is false,
861                 //        or we're not in the last paragraph, anyway.
862                 //   (ii) We didn't open it and html_in_par is true,
863                 //        but we are in the first par, and there is a next par.
864                 ParagraphList::const_iterator nextpar = par;
865                 ++nextpar;
866                 bool const close_par =
867                         (open_par && (!runparams.html_in_par || nextpar != pend))
868                         || (!open_par && runparams.html_in_par && par == pbegin && nextpar != pend);
869
870                 if (open_par) {
871                         // We do not issue the paragraph id if we are doing 
872                         // this for the TOC (or some similar purpose)
873                         openParTag(xs, lay, par->params(),
874                                    runparams.for_toc ? "" : par->magicLabel());
875                 }
876
877                 docstring const deferred = par->simpleLyXHTMLOnePar(buf, xs, 
878                         runparams, text.outerFont(distance(begin, par)),
879                         open_par, close_par);
880
881                 if (!deferred.empty()) {
882                         xs << XHTMLStream::ESCAPE_NONE << deferred << html::CR();
883                 }
884                 if (close_par) {
885                         closeTag(xs, lay);
886                         xs << html::CR();
887                 }
888         }
889         return pend;
890 }
891
892
893 ParagraphList::const_iterator makeBibliography(Buffer const & buf,
894                                 XHTMLStream & xs,
895                                 OutputParams const & runparams,
896                                 Text const & text,
897                                 ParagraphList::const_iterator const & pbegin,
898                                 ParagraphList::const_iterator const & pend)
899 {
900         // FIXME XHTML
901         // Use TextClass::htmlTOCLayout() to figure out how we should look.
902         xs << html::StartTag("h2", "class='bibliography'")
903            << pbegin->layout().labelstring(false)
904            << html::EndTag("h2")
905            << html::CR()
906            << html::StartTag("div", "class='bibliography'")
907            << html::CR();
908         makeParagraphs(buf, xs, runparams, text, pbegin, pend);
909         xs << html::EndTag("div");
910         return pend;
911 }
912
913
914 bool isNormalEnv(Layout const & lay)
915 {
916         return lay.latextype == LATEX_ENVIRONMENT
917             || lay.latextype == LATEX_BIB_ENVIRONMENT;
918 }
919
920
921 ParagraphList::const_iterator makeEnvironment(Buffer const & buf,
922                                               XHTMLStream & xs,
923                                               OutputParams const & runparams,
924                                               Text const & text,
925                                               ParagraphList::const_iterator const & pbegin,
926                                               ParagraphList::const_iterator const & pend)
927 {
928         ParagraphList::const_iterator const begin = text.paragraphs().begin();
929         ParagraphList::const_iterator par = pbegin;
930         Layout const & bstyle = par->layout();
931         depth_type const origdepth = pbegin->params().depth();
932
933         // open tag for this environment
934         openParTag(xs, bstyle, pbegin->magicLabel());
935         xs << html::CR();
936
937         // we will on occasion need to remember a layout from before.
938         Layout const * lastlay = 0;
939
940         while (par != pend) {
941                 Layout const & style = par->layout();
942                 // the counter only gets stepped if we're in some kind of list,
943                 // or if it's the first time through.
944                 // note that enum, etc, are handled automatically.
945                 // FIXME There may be a bug here about user defined enumeration
946                 // types. If so, then we'll need to take the counter and add "i",
947                 // "ii", etc, as with enum.
948                 Counters & cnts = buf.masterBuffer()->params().documentClass().counters();
949                 docstring const & cntr = style.counter;
950                 if (!style.counter.empty()
951                     && (par == pbegin || !isNormalEnv(style))
952                                 && cnts.hasCounter(cntr)
953                 )
954                         cnts.step(cntr, OutputUpdate);
955                 ParagraphList::const_iterator send;
956
957                 switch (style.latextype) {
958                 case LATEX_ENVIRONMENT:
959                 case LATEX_LIST_ENVIRONMENT:
960                 case LATEX_ITEM_ENVIRONMENT: {
961                         // There are two possiblities in this case.
962                         // One is that we are still in the environment in which we
963                         // started---which we will be if the depth is the same.
964                         if (par->params().depth() == origdepth) {
965                                 LATTEST(bstyle == style);
966                                 if (lastlay != 0) {
967                                         closeItemTag(xs, *lastlay);
968                                         lastlay = 0;
969                                 }
970
971                                 // this will be positive, if we want to skip the
972                                 // initial word (if it's been taken for the label).
973                                 pos_type sep = 0;
974                                 bool const labelfirst = style.htmllabelfirst();
975                                 if (!labelfirst)
976                                         openItemTag(xs, style, par->params());
977
978                                 // label output
979                                 if (style.labeltype != LABEL_NO_LABEL &&
980                                     style.htmllabeltag() != "NONE") {
981                                         if (isNormalEnv(style)) {
982                                                 // in this case, we print the label only for the first
983                                                 // paragraph (as in a theorem).
984                                                 if (par == pbegin) {
985                                                         docstring const lbl =
986                                                                         pbegin->params().labelString();
987                                                         if (!lbl.empty()) {
988                                                                 openLabelTag(xs, style);
989                                                                 xs << lbl;
990                                                                 closeLabelTag(xs, style);
991                                                         }
992                                                         xs << html::CR();
993                                                 }
994                                         } else { // some kind of list
995                                                 if (style.labeltype == LABEL_MANUAL) {
996                                                         openLabelTag(xs, style);
997                                                         sep = par->firstWordLyXHTML(xs, runparams);
998                                                         closeLabelTag(xs, style);
999                                                         xs << html::CR();
1000                                                 }
1001                                                 else {
1002                                                         openLabelTag(xs, style);
1003                                                         xs << par->params().labelString();
1004                                                         closeLabelTag(xs, style);
1005                                                         xs << html::CR();
1006                                                 }
1007                                         }
1008                                 } // end label output
1009
1010                                 if (labelfirst)
1011                                         openItemTag(xs, style, par->params());
1012
1013                                 par->simpleLyXHTMLOnePar(buf, xs, runparams,
1014                                         text.outerFont(distance(begin, par)), true, true, sep);
1015                                 ++par;
1016
1017                                 // We may not want to close the tag yet, in particular:
1018                                 // If we're not at the end...
1019                                 if (par != pend
1020                                         //  and are doing items...
1021                                          && !isNormalEnv(style)
1022                                          // and if the depth has changed...
1023                                          && par->params().depth() != origdepth) {
1024                                          // then we'll save this layout for later, and close it when
1025                                          // we get another item.
1026                                         lastlay = &style;
1027                                 } else
1028                                         closeItemTag(xs, style);
1029                                 xs << html::CR();
1030                         }
1031                         // The other possibility is that the depth has increased, in which
1032                         // case we need to recurse.
1033                         else {
1034                                 send = findEndOfEnvironment(par, pend);
1035                                 par = makeEnvironment(buf, xs, runparams, text, par, send);
1036                         }
1037                         break;
1038                 }
1039                 case LATEX_PARAGRAPH:
1040                         send = findLastParagraph(par, pend);
1041                         par = makeParagraphs(buf, xs, runparams, text, par, send);
1042                         break;
1043                 // Shouldn't happen
1044                 case LATEX_BIB_ENVIRONMENT:
1045                         send = par;
1046                         ++send;
1047                         par = makeParagraphs(buf, xs, runparams, text, par, send);
1048                         break;
1049                 // Shouldn't happen
1050                 case LATEX_COMMAND:
1051                         ++par;
1052                         break;
1053                 }
1054         }
1055
1056         if (lastlay != 0)
1057                 closeItemTag(xs, *lastlay);
1058         closeTag(xs, bstyle);
1059         xs << html::CR();
1060         return pend;
1061 }
1062
1063
1064 void makeCommand(Buffer const & buf,
1065                  XHTMLStream & xs,
1066                  OutputParams const & runparams,
1067                  Text const & text,
1068                  ParagraphList::const_iterator const & pbegin)
1069 {
1070         Layout const & style = pbegin->layout();
1071         if (!style.counter.empty())
1072                 buf.masterBuffer()->params().
1073                     documentClass().counters().step(style.counter, OutputUpdate);
1074
1075         bool const make_parid = !runparams.for_toc && runparams.html_make_pars;
1076         
1077         if (style.labeltype == LABEL_ABOVE)
1078                 xs << html::StartTag("div")
1079                    << pbegin->params().labelString()
1080                    << html::EndTag("div");
1081         else if (style.labeltype == LABEL_CENTERED)
1082                 xs << html::StartTag("div", "style = \"text-align: center;\"")
1083                    << pbegin->params().labelString()
1084                    << html::EndTag("div");
1085
1086         openParTag(xs, style, pbegin->params(),
1087                    make_parid ? pbegin->magicLabel() : "");
1088
1089         // Label around sectioning number:
1090         // FIXME Probably need to account for LABEL_MANUAL
1091         if (style.labeltype != LABEL_NO_LABEL &&
1092             style.labeltype != LABEL_ABOVE &&
1093             style.labeltype != LABEL_CENTERED ) {
1094                 openLabelTag(xs, style);
1095                 xs << pbegin->params().labelString();
1096                 closeLabelTag(xs, style);
1097                 // Otherwise the label might run together with the text
1098                 xs << from_ascii(" ");
1099         }
1100
1101         ParagraphList::const_iterator const begin = text.paragraphs().begin();
1102         pbegin->simpleLyXHTMLOnePar(buf, xs, runparams,
1103                         text.outerFont(distance(begin, pbegin)));
1104         closeTag(xs, style);
1105         xs << html::CR();
1106 }
1107
1108 } // end anonymous namespace
1109
1110
1111 void xhtmlParagraphs(Text const & text,
1112                        Buffer const & buf,
1113                        XHTMLStream & xs,
1114                        OutputParams const & runparams)
1115 {
1116         ParagraphList const & paragraphs = text.paragraphs();
1117         if (runparams.par_begin == runparams.par_end) {
1118                 runparams.par_begin = 0;
1119                 runparams.par_end = paragraphs.size();
1120         }
1121         pit_type bpit = runparams.par_begin;
1122         pit_type const epit = runparams.par_end;
1123         LASSERT(bpit < epit,
1124                 { xs << XHTMLStream::ESCAPE_NONE << "<!-- XHTML output error! -->\n"; return; });
1125
1126         OutputParams ourparams = runparams;
1127         ParagraphList::const_iterator const pend =
1128                 (epit == (int) paragraphs.size()) ?
1129                         paragraphs.end() : paragraphs.constIterator(epit);
1130         while (bpit < epit) {
1131                 ParagraphList::const_iterator par = paragraphs.constIterator(bpit);
1132                 if (par->params().startOfAppendix()) {
1133                         // We want to reset the counter corresponding to toplevel sectioning
1134                         Layout const & lay =
1135                                 buf.masterBuffer()->params().documentClass().getTOCLayout();
1136                         docstring const cnt = lay.counter;
1137                         if (!cnt.empty()) {
1138                                 Counters & cnts =
1139                                         buf.masterBuffer()->params().documentClass().counters();
1140                                 cnts.reset(cnt);
1141                         }
1142                 }
1143                 Layout const & style = par->layout();
1144                 ParagraphList::const_iterator const lastpar = par;
1145                 ParagraphList::const_iterator send;
1146
1147                 switch (style.latextype) {
1148                 case LATEX_COMMAND: {
1149                         // The files with which we are working never have more than
1150                         // one paragraph in a command structure.
1151                         // FIXME
1152                         // if (ourparams.html_in_par)
1153                         //   fix it so we don't get sections inside standard, e.g.
1154                         // note that we may then need to make runparams not const, so we
1155                         // can communicate that back.
1156                         // FIXME Maybe this fix should be in the routines themselves, in case
1157                         // they are called from elsewhere.
1158                         makeCommand(buf, xs, ourparams, text, par);
1159                         ++par;
1160                         break;
1161                 }
1162                 case LATEX_ENVIRONMENT:
1163                 case LATEX_LIST_ENVIRONMENT:
1164                 case LATEX_ITEM_ENVIRONMENT: {
1165                         // FIXME Same fix here.
1166                         send = findEndOfEnvironment(par, pend);
1167                         par = makeEnvironment(buf, xs, ourparams, text, par, send);
1168                         break;
1169                 }
1170                 case LATEX_BIB_ENVIRONMENT: {
1171                         // FIXME Same fix here.
1172                         send = findEndOfEnvironment(par, pend);
1173                         par = makeBibliography(buf, xs, ourparams, text, par, send);
1174                         break;
1175                 }
1176                 case LATEX_PARAGRAPH:
1177                         send = findLastParagraph(par, pend);
1178                         par = makeParagraphs(buf, xs, ourparams, text, par, send);
1179                         break;
1180                 }
1181                 bpit += distance(lastpar, par);
1182         }
1183 }
1184
1185
1186 string alignmentToCSS(LyXAlignment align)
1187 {
1188         switch (align) {
1189         case LYX_ALIGN_BLOCK:
1190                 // we are NOT going to use text-align: justify!!
1191         case LYX_ALIGN_LEFT:
1192                 return "left";
1193         case LYX_ALIGN_RIGHT:
1194                 return "right";
1195         case LYX_ALIGN_CENTER:
1196                 return "center";
1197         default:
1198                 break;
1199         }
1200         return "";
1201 }
1202
1203 } // namespace lyx