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