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