]> git.lyx.org Git - lyx.git/blob - src/paragraph_funcs.C
Small refactoring of DocBook stuff
[lyx.git] / src / paragraph_funcs.C
1 /**
2  * \file paragraph_funcs.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "paragraph_funcs.h"
14
15 #include "buffer.h"
16 #include "bufferparams.h"
17
18 #include "debug.h"
19 #include "encoding.h"
20 #include "errorlist.h"
21 #include "factory.h"
22 #include "gettext.h"
23 #include "iterators.h"
24 #include "language.h"
25 #include "lyxlex.h"
26 #include "lyxrc.h"
27 #include "paragraph_pimpl.h"
28 #include "texrow.h"
29 #include "vspace.h"
30
31 #include "insets/insetbibitem.h"
32 #include "insets/insethfill.h"
33 #include "insets/insetlatexaccent.h"
34 #include "insets/insetline.h"
35 #include "insets/insetnewline.h"
36 #include "insets/insetpagebreak.h"
37 #include "insets/insetoptarg.h"
38 #include "insets/insetspace.h"
39 #include "insets/insetspecialchar.h"
40 #include "insets/insettabular.h"
41
42 #include "support/lstrings.h"
43 #include "support/std_sstream.h"
44
45 using lyx::pos_type;
46
47 using lyx::support::bformat;
48 using lyx::support::subst;
49
50 using std::endl;
51 using std::string;
52 using std::istringstream;
53 using std::ostream;
54
55
56 extern string bibitemWidest(Buffer const &);
57
58
59 namespace {
60
61 bool moveItem(Paragraph & from, Paragraph & to,
62         BufferParams const & params, pos_type i, pos_type j)
63 {
64         char const tmpchar = from.getChar(i);
65         LyXFont tmpfont = from.getFontSettings(params, i);
66
67         if (tmpchar == Paragraph::META_INSET) {
68                 InsetOld * tmpinset = 0;
69                 if (from.getInset(i)) {
70                         // the inset is not in a paragraph anymore
71                         tmpinset = from.insetlist.release(i);
72                 }
73
74                 if (!to.insetAllowed(tmpinset->lyxCode()))
75                         return false;
76                 to.insertInset(j, tmpinset, tmpfont);
77         } else {
78                 if (!to.checkInsertChar(tmpfont))
79                         return false;
80                 to.insertChar(j, tmpchar, tmpfont);
81         }
82         return true;
83 }
84
85 }
86
87
88 void breakParagraph(BufferParams const & bparams,
89                     ParagraphList & paragraphs,
90                     ParagraphList::iterator par,
91                     pos_type pos,
92                     int flag)
93 {
94         // create a new paragraph, and insert into the list
95         ParagraphList::iterator tmp = paragraphs.insert(boost::next(par),
96                                                         Paragraph());
97
98         // without doing that we get a crash when typing <Return> at the
99         // end of a paragraph
100         tmp->layout(bparams.getLyXTextClass().defaultLayout());
101         // remember to set the inset_owner
102         tmp->setInsetOwner(par->inInset());
103
104         if (bparams.tracking_changes)
105                 tmp->trackChanges();
106
107         // this is an idea for a more userfriendly layout handling, I will
108         // see what the users say
109
110         // layout stays the same with latex-environments
111         if (flag) {
112                 tmp->layout(par->layout());
113                 tmp->setLabelWidthString(par->params().labelWidthString());
114         }
115
116         bool const isempty = (par->allowEmpty() && par->empty());
117
118         if (!isempty && (par->size() > pos || par->empty() || flag == 2)) {
119                 tmp->layout(par->layout());
120                 tmp->params().align(par->params().align());
121                 tmp->setLabelWidthString(par->params().labelWidthString());
122
123                 tmp->params().spaceBottom(par->params().spaceBottom());
124                 par->params().spaceBottom(VSpace(VSpace::NONE));
125
126                 tmp->params().depth(par->params().depth());
127                 tmp->params().noindent(par->params().noindent());
128
129                 // copy everything behind the break-position
130                 // to the new paragraph
131
132 #ifdef WITH_WARNINGS
133 #warning this seems wrong
134 #endif
135                 /* FIXME: if !keepempty, empty() == true, then we reach
136                  * here with size() == 0. So pos_end becomes - 1. Why
137                  * doesn't this cause problems ???
138                  */
139                 pos_type pos_end = par->size() - 1;
140                 pos_type i = pos;
141                 pos_type j = pos;
142
143                 for (; i <= pos_end; ++i) {
144                         Change::Type change = par->lookupChange(i);
145                         if (moveItem(*par, *tmp, bparams, i, j - pos)) {
146                                 tmp->setChange(j - pos, change);
147                                 ++j;
148                         }
149                 }
150
151                 for (i = pos_end; i >= pos; --i)
152                         par->eraseIntern(i);
153         }
154
155         if (pos)
156                 return;
157
158         tmp->params().spaceTop(par->params().spaceTop());
159         par->params().clear();
160
161         par->layout(bparams.getLyXTextClass().defaultLayout());
162
163         // layout stays the same with latex-environments
164         if (flag) {
165                 par->layout(tmp->layout());
166                 par->setLabelWidthString(tmp->params().labelWidthString());
167                 par->params().depth(tmp->params().depth());
168         }
169
170         // subtle, but needed to get empty pars working right
171         if (bparams.tracking_changes) {
172                 if (!par->size()) {
173                         par->cleanChanges();
174                 } else if (!tmp->size()) {
175                         tmp->cleanChanges();
176                 }
177         }
178 }
179
180
181 void breakParagraphConservative(BufferParams const & bparams,
182                                 ParagraphList & paragraphs,
183                                 ParagraphList::iterator par,
184                                 pos_type pos)
185 {
186         // create a new paragraph
187         ParagraphList::iterator tmp = paragraphs.insert(boost::next(par),
188                                                         Paragraph());
189         tmp->makeSameLayout(*par);
190
191         // When can pos > size()?
192         // I guess pos == size() is possible.
193         if (par->size() > pos) {
194                 // copy everything behind the break-position to the new
195                 // paragraph
196                 pos_type pos_end = par->size() - 1;
197
198                 for (pos_type i = pos, j = pos; i <= pos_end; ++i)
199                         if (moveItem(*par, *tmp, bparams, i, j - pos))
200                                 ++j;
201
202                 for (pos_type k = pos_end; k >= pos; --k)
203                         par->erase(k);
204         }
205 }
206
207
208 void mergeParagraph(BufferParams const & bparams,
209                     ParagraphList & paragraphs,
210                     ParagraphList::iterator par)
211 {
212         ParagraphList::iterator the_next = boost::next(par);
213
214         // first the DTP-stuff
215         par->params().spaceBottom(the_next->params().spaceBottom());
216
217         pos_type pos_end = the_next->size() - 1;
218         pos_type pos_insert = par->size();
219
220         // ok, now copy the paragraph
221         for (pos_type i = 0, j = 0; i <= pos_end; ++i)
222                 if (moveItem(*the_next, *par, bparams, i, pos_insert + j))
223                         ++j;
224
225         paragraphs.erase(the_next);
226 }
227
228
229 ParagraphList::iterator depthHook(ParagraphList::iterator pit,
230                                   ParagraphList const & plist,
231                                   Paragraph::depth_type depth)
232 {
233         ParagraphList::iterator newpit = pit;
234         ParagraphList::iterator beg = const_cast<ParagraphList&>(plist).begin();
235
236         if (newpit != beg)
237                 --newpit;
238
239         while (newpit != beg && newpit->getDepth() > depth) {
240                 --newpit;
241         }
242
243         if (newpit->getDepth() > depth)
244                 return pit;
245
246         return newpit;
247 }
248
249
250 ParagraphList::iterator outerHook(ParagraphList::iterator pit,
251                                   ParagraphList const & plist)
252 {
253         if (!pit->getDepth())
254                 return const_cast<ParagraphList&>(plist).end();
255         return depthHook(pit, plist,
256                          Paragraph::depth_type(pit->getDepth() - 1));
257 }
258
259
260 bool isFirstInSequence(ParagraphList::iterator pit,
261                        ParagraphList const & plist)
262 {
263         ParagraphList::iterator dhook = depthHook(pit, plist, pit->getDepth());
264         return (dhook == pit
265                 || dhook->layout() != pit->layout()
266                 || dhook->getDepth() != pit->getDepth());
267 }
268
269
270 int getEndLabel(ParagraphList::iterator p, ParagraphList const & plist)
271 {
272         ParagraphList::iterator pit = p;
273         Paragraph::depth_type par_depth = p->getDepth();
274         while (pit != const_cast<ParagraphList&>(plist).end()) {
275                 LyXLayout_ptr const & layout = pit->layout();
276                 int const endlabeltype = layout->endlabeltype;
277
278                 if (endlabeltype != END_LABEL_NO_LABEL) {
279                         if (boost::next(p) == const_cast<ParagraphList&>(plist).end())
280                                 return endlabeltype;
281
282                         Paragraph::depth_type const next_depth = boost::next(p)->getDepth();
283                         if (par_depth > next_depth ||
284                             (par_depth == next_depth &&
285                              layout != boost::next(p)->layout()))
286                                 return endlabeltype;
287                         break;
288                 }
289                 if (par_depth == 0)
290                         break;
291                 pit = outerHook(pit, plist);
292                 if (pit != const_cast<ParagraphList&>(plist).end())
293                         par_depth = pit->getDepth();
294         }
295         return END_LABEL_NO_LABEL;
296 }
297
298
299 namespace {
300
301 ParagraphList::iterator
302 TeXEnvironment(Buffer const & buf,
303                ParagraphList const & paragraphs,
304                ParagraphList::iterator pit,
305                ostream & os, TexRow & texrow,
306                LatexRunParams const & runparams);
307
308 ParagraphList::iterator
309 TeXOnePar(Buffer const & buf,
310           ParagraphList const & paragraphs,
311           ParagraphList::iterator pit,
312           ostream & os, TexRow & texrow,
313           LatexRunParams const & runparams,
314           string const & everypar = string());
315
316
317 ParagraphList::iterator
318 TeXDeeper(Buffer const & buf,
319           ParagraphList const & paragraphs,
320           ParagraphList::iterator pit,
321           ostream & os, TexRow & texrow,
322           LatexRunParams const & runparams)
323 {
324         lyxerr[Debug::LATEX] << "TeXDeeper...     " << &*pit << endl;
325         ParagraphList::iterator par = pit;
326
327         while (par != const_cast<ParagraphList&>(paragraphs).end() &&
328                      par->params().depth() == pit->params().depth()) {
329                 if (par->layout()->isEnvironment()) {
330                         par = TeXEnvironment(buf, paragraphs, par,
331                                              os, texrow, runparams);
332                 } else {
333                         par = TeXOnePar(buf, paragraphs, par,
334                                              os, texrow, runparams);
335                 }
336         }
337         lyxerr[Debug::LATEX] << "TeXDeeper...done " << &*par << endl;
338
339         return par;
340 }
341
342
343 ParagraphList::iterator
344 TeXEnvironment(Buffer const & buf,
345                ParagraphList const & paragraphs,
346                ParagraphList::iterator pit,
347                ostream & os, TexRow & texrow,
348                LatexRunParams const & runparams)
349 {
350         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << &*pit << endl;
351
352         BufferParams const & bparams = buf.params();
353
354         LyXLayout_ptr const & style = pit->layout();
355
356         Language const * language = pit->getParLanguage(bparams);
357         Language const * doc_language = bparams.language;
358         Language const * previous_language =
359                 (pit != const_cast<ParagraphList&>(paragraphs).begin())
360                 ? boost::prior(pit)->getParLanguage(bparams)
361                 : doc_language;
362         if (language->babel() != previous_language->babel()) {
363
364                 if (!lyxrc.language_command_end.empty() &&
365                     previous_language->babel() != doc_language->babel()) {
366                         os << subst(lyxrc.language_command_end, "$$lang",
367                                     previous_language->babel())
368                            << endl;
369                         texrow.newline();
370                 }
371
372                 if (lyxrc.language_command_end.empty() ||
373                     language->babel() != doc_language->babel()) {
374                         os << subst(lyxrc.language_command_begin, "$$lang",
375                                     language->babel())
376                            << endl;
377                         texrow.newline();
378                 }
379         }
380
381         bool leftindent_open = false;
382         if (!pit->params().leftIndent().zero()) {
383                 os << "\\begin{LyXParagraphLeftIndent}{" <<
384                         pit->params().leftIndent().asLatexString() << "}\n";
385                 texrow.newline();
386                 leftindent_open = true;
387         }
388
389         if (style->isEnvironment()) {
390                 if (style->latextype == LATEX_LIST_ENVIRONMENT) {
391                         os << "\\begin{" << style->latexname() << "}{"
392                            << pit->params().labelWidthString() << "}\n";
393                 } else if (style->labeltype == LABEL_BIBLIO) {
394                         // ale970405
395                         os << "\\begin{" << style->latexname() << "}{"
396                            <<  bibitemWidest(buf)
397                            << "}\n";
398                 } else if (style->latextype == LATEX_ITEM_ENVIRONMENT) {
399                         os << "\\begin{" << style->latexname() << '}'
400                            << style->latexparam() << '\n';
401                 } else
402                         os << "\\begin{" << style->latexname() << '}'
403                            << style->latexparam() << '\n';
404                 texrow.newline();
405         }
406         ParagraphList::iterator par = pit;
407         do {
408                 par = TeXOnePar(buf, paragraphs, par, os, texrow, runparams);
409
410                 if (par != const_cast<ParagraphList&>(paragraphs).end() && par->params().depth() > pit->params().depth()) {
411                             if (par->layout()->isParagraph()) {
412
413                             // Thinko!
414                             // How to handle this? (Lgb)
415                             //&& !suffixIs(os, "\n\n")
416                                     //) {
417                                 // There should be at least one '\n' already
418                                 // but we need there to be two for Standard
419                                 // paragraphs that are depth-increment'ed to be
420                                 // output correctly.  However, tables can
421                                 // also be paragraphs so don't adjust them.
422                                 // ARRae
423                                 // Thinkee:
424                                 // Will it ever harm to have one '\n' too
425                                 // many? i.e. that we sometimes will have
426                                 // three in a row. (Lgb)
427                                 os << '\n';
428                                 texrow.newline();
429                         }
430                         par = TeXDeeper(buf, paragraphs, par, os, texrow,
431                                         runparams);
432                 }
433         } while (par != const_cast<ParagraphList&>(paragraphs).end()
434                  && par->layout() == pit->layout()
435                  && par->params().depth() == pit->params().depth()
436                  && par->params().leftIndent() == pit->params().leftIndent());
437
438         if (style->isEnvironment()) {
439                 os << "\\end{" << style->latexname() << "}\n";
440                 texrow.newline();
441         }
442
443         if (leftindent_open) {
444                 os << "\\end{LyXParagraphLeftIndent}\n";
445                 texrow.newline();
446         }
447
448         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << &*par << endl;
449         return par;  // ale970302
450 }
451
452
453 InsetOptArg * optArgInset(Paragraph const & par)
454 {
455         // Find the entry.
456         InsetList::const_iterator it = par.insetlist.begin();
457         InsetList::const_iterator end = par.insetlist.end();
458         for (; it != end; ++it) {
459                 InsetOld * ins = it->inset;
460                 if (ins->lyxCode() == InsetOld::OPTARG_CODE) {
461                         return static_cast<InsetOptArg *>(ins);
462                 }
463         }
464         return 0;
465 }
466
467
468 ParagraphList::iterator
469 TeXOnePar(Buffer const & buf,
470           ParagraphList const & paragraphs,
471           ParagraphList::iterator pit,
472           ostream & os, TexRow & texrow,
473           LatexRunParams const & runparams,
474           string const & everypar)
475 {
476         lyxerr[Debug::LATEX] << "TeXOnePar...     " << &*pit << " '"
477                 << everypar << "'" << endl;
478         BufferParams const & bparams = buf.params();
479
480         InsetOld const * in = pit->inInset();
481         bool further_blank_line = false;
482         LyXLayout_ptr style;
483
484         // well we have to check if we are in an inset with unlimited
485         // length (all in one row) if that is true then we don't allow
486         // any special options in the paragraph and also we don't allow
487         // any environment other then "Standard" to be valid!
488         if (in == 0 || !in->forceDefaultParagraphs(in)) {
489                 style = pit->layout();
490
491                 if (pit->params().startOfAppendix()) {
492                         os << "\\appendix\n";
493                         texrow.newline();
494                 }
495
496                 if (!pit->params().spacing().isDefault()
497                         && (pit == const_cast<ParagraphList&>(paragraphs).begin()
498                             || !boost::prior(pit)->hasSameLayout(*pit)))
499                 {
500                         os << pit->params().spacing().writeEnvirBegin() << '\n';
501                         texrow.newline();
502                 }
503
504                 if (style->isCommand()) {
505                         os << '\n';
506                         texrow.newline();
507                 }
508
509                 if (pit->params().spaceTop().kind() != VSpace::NONE) {
510                         os << pit->params().spaceTop().asLatexCommand(bparams);
511                         further_blank_line = true;
512                 }
513
514                 if (further_blank_line) {
515                         os << '\n';
516                         texrow.newline();
517                 }
518         } else {
519                 style = bparams.getLyXTextClass().defaultLayout();
520         }
521
522         Language const * language = pit->getParLanguage(bparams);
523         Language const * doc_language = bparams.language;
524         Language const * previous_language =
525                 (pit != const_cast<ParagraphList&>(paragraphs).begin())
526                 ? boost::prior(pit)->getParLanguage(bparams)
527                 : doc_language;
528
529         if (language->babel() != previous_language->babel()
530             // check if we already put language command in TeXEnvironment()
531             && !(style->isEnvironment()
532                  && (pit == const_cast<ParagraphList&>(paragraphs).begin() ||
533                      (boost::prior(pit)->layout() != pit->layout() &&
534                       boost::prior(pit)->getDepth() <= pit->getDepth())
535                      || boost::prior(pit)->getDepth() < pit->getDepth())))
536         {
537                 if (!lyxrc.language_command_end.empty() &&
538                     previous_language->babel() != doc_language->babel())
539                 {
540                         os << subst(lyxrc.language_command_end, "$$lang",
541                                     previous_language->babel())
542                            << endl;
543                         texrow.newline();
544                 }
545
546                 if (lyxrc.language_command_end.empty() ||
547                     language->babel() != doc_language->babel())
548                 {
549                         os << subst(lyxrc.language_command_begin, "$$lang",
550                                     language->babel())
551                            << endl;
552                         texrow.newline();
553                 }
554         }
555
556         if (bparams.inputenc == "auto" &&
557             language->encoding() != previous_language->encoding()) {
558                 os << "\\inputencoding{"
559                    << language->encoding()->LatexName()
560                    << "}\n";
561                 texrow.newline();
562         }
563
564         switch (style->latextype) {
565         case LATEX_COMMAND:
566                 os << '\\' << style->latexname();
567
568                 // Separate handling of optional argument inset.
569                 if (style->optionalargs == 1) {
570                         InsetOptArg * it = optArgInset(*pit);
571                         if (it)
572                                 it->latexOptional(buf, os, runparams);
573                 }
574                 else
575                         os << style->latexparam();
576                 break;
577         case LATEX_ITEM_ENVIRONMENT:
578         case LATEX_LIST_ENVIRONMENT:
579                 os << "\\item ";
580                 break;
581         case LATEX_BIB_ENVIRONMENT:
582                 // ignore this, the inset will write itself
583                 break;
584         default:
585                 break;
586         }
587
588         os << everypar;
589         bool need_par = pit->simpleTeXOnePar(buf, bparams,
590                                              outerFont(pit, paragraphs),
591                                              os, texrow, runparams);
592
593         // Make sure that \\par is done with the font of the last
594         // character if this has another size as the default.
595         // This is necessary because LaTeX (and LyX on the screen)
596         // calculates the space between the baselines according
597         // to this font. (Matthias)
598         //
599         // Is this really needed ? (Dekel)
600         // We do not need to use to change the font for the last paragraph
601         // or for a command.
602         LyXFont const outerfont(outerFont(pit, paragraphs));
603
604         LyXFont const font =
605                 (pit->empty()
606                  ? pit->getLayoutFont(bparams, outerfont)
607                  : pit->getFont(bparams, pit->size() - 1, outerfont));
608
609         bool is_command = style->isCommand();
610
611         if (style->resfont.size() != font.size()
612             && boost::next(pit) != const_cast<ParagraphList&>(paragraphs).end()
613             && !is_command) {
614                 if (!need_par)
615                         os << '{';
616                 os << "\\" << font.latexSize() << " \\par}";
617         } else if (need_par) {
618                 os << "\\par}";
619         } else if (is_command)
620                 os << '}';
621
622         switch (style->latextype) {
623         case LATEX_ITEM_ENVIRONMENT:
624         case LATEX_LIST_ENVIRONMENT:
625                 if (boost::next(pit) != const_cast<ParagraphList&>(paragraphs).end()
626                     && (pit->params().depth() < boost::next(pit)->params().depth())) {
627                         os << '\n';
628                         texrow.newline();
629                 }
630                 break;
631         case LATEX_ENVIRONMENT: {
632                 // if its the last paragraph of the current environment
633                 // skip it otherwise fall through
634                 ParagraphList::iterator next = boost::next(pit);
635
636                 if (next != const_cast<ParagraphList&>(paragraphs).end()
637                     && (next->layout() != pit->layout()
638                         || next->params().depth() != pit->params().depth()))
639                         break;
640         }
641
642                 // fall through possible
643         default:
644                 // we don't need it for the last paragraph!!!
645                 if (boost::next(pit) != const_cast<ParagraphList&>(paragraphs).end()) {
646                         os << '\n';
647                         texrow.newline();
648                 }
649         }
650
651         if (in == 0 || !in->forceDefaultParagraphs(in)) {
652                 further_blank_line = false;
653
654                 if (pit->params().spaceBottom().kind() != VSpace::NONE) {
655                         os << pit->params().spaceBottom().asLatexCommand(bparams);
656                         further_blank_line = true;
657                 }
658
659                 if (further_blank_line) {
660                         os << '\n';
661                         texrow.newline();
662                 }
663
664                 if (!pit->params().spacing().isDefault()
665                         && (boost::next(pit) == const_cast<ParagraphList&>(paragraphs).end()
666                             || !boost::next(pit)->hasSameLayout(*pit)))
667                 {
668                         os << pit->params().spacing().writeEnvirEnd() << '\n';
669                         texrow.newline();
670                 }
671         }
672
673         // we don't need it for the last paragraph!!!
674         if (boost::next(pit) != const_cast<ParagraphList&>(paragraphs).end()) {
675                 os << '\n';
676                 texrow.newline();
677         } else {
678                 // Since \selectlanguage write the language to the aux file,
679                 // we need to reset the language at the end of footnote or
680                 // float.
681
682                 if (language->babel() != doc_language->babel()) {
683                         if (lyxrc.language_command_end.empty())
684                                 os << subst(lyxrc.language_command_begin,
685                                             "$$lang",
686                                             doc_language->babel())
687                                    << endl;
688                         else
689                                 os << subst(lyxrc.language_command_end,
690                                             "$$lang",
691                                             language->babel())
692                                    << endl;
693                         texrow.newline();
694                 }
695         }
696
697         lyxerr[Debug::LATEX] << "TeXOnePar...done " << &*boost::next(pit) << endl;
698         return ++pit;
699 }
700
701 } // anon namespace
702
703
704 //
705 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
706 //
707 void latexParagraphs(Buffer const & buf,
708                      ParagraphList const & paragraphs,
709                      ostream & os,
710                      TexRow & texrow,
711                      LatexRunParams const & runparams,
712                      string const & everypar)
713 {
714         bool was_title = false;
715         bool already_title = false;
716         LyXTextClass const & tclass = buf.params().getLyXTextClass();
717         ParagraphList::iterator par = const_cast<ParagraphList&>(paragraphs).begin();
718         ParagraphList::iterator endpar = const_cast<ParagraphList&>(paragraphs).end();
719
720         // if only_body
721         while (par != endpar) {
722                 InsetOld * in = par->inInset();
723                 // well we have to check if we are in an inset with unlimited
724                 // length (all in one row) if that is true then we don't allow
725                 // any special options in the paragraph and also we don't allow
726                 // any environment other then "Standard" to be valid!
727                 if (in == 0 || !in->forceDefaultParagraphs(in)) {
728                         LyXLayout_ptr const & layout = par->layout();
729
730                         if (layout->intitle) {
731                                 if (already_title) {
732                                         lyxerr <<"Error in latexParagraphs: You"
733                                                 " should not mix title layouts"
734                                                 " with normal ones." << endl;
735                                 } else if (!was_title) {
736                                         was_title = true;
737                                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
738                                                 os << "\\begin{"
739                                                     << tclass.titlename()
740                                                     << "}\n";
741                                                 texrow.newline();
742                                         }
743                                 }
744                         } else if (was_title && !already_title) {
745                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
746                                         os << "\\end{" << tclass.titlename()
747                                             << "}\n";
748                                 }
749                                 else {
750                                         os << "\\" << tclass.titlename()
751                                             << "\n";
752                                 }
753                                 texrow.newline();
754                                 already_title = true;
755                                 was_title = false;
756                         }
757
758                         if (layout->is_environment) {
759                                 par = TeXOnePar(buf, paragraphs, par, os, texrow,
760                                                 runparams, everypar);
761                         } else if (layout->isEnvironment() ||
762                                 !par->params().leftIndent().zero())
763                         {
764                                 par = TeXEnvironment(buf, paragraphs, par, os,
765                                                      texrow, runparams);
766                         } else {
767                                 par = TeXOnePar(buf, paragraphs, par, os, texrow,
768                                                 runparams, everypar);
769                         }
770                 } else {
771                         par = TeXOnePar(buf, paragraphs, par, os, texrow,
772                                         runparams, everypar);
773                 }
774         }
775         // It might be that we only have a title in this document
776         if (was_title && !already_title) {
777                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
778                         os << "\\end{" << tclass.titlename()
779                             << "}\n";
780                 }
781                 else {
782                         os << "\\" << tclass.titlename()
783                             << "\n";
784                                 }
785                 texrow.newline();
786         }
787 }
788
789
790 namespace {
791
792 int readParToken(Buffer & buf, Paragraph & par, LyXLex & lex, string const & token)
793 {
794         static LyXFont font;
795         static Change change;
796
797         BufferParams const & bp = buf.params();
798
799         if (token[0] != '\\') {
800                 string::const_iterator cit = token.begin();
801                 for (; cit != token.end(); ++cit) {
802                         par.insertChar(par.size(), (*cit), font, change);
803                 }
804         } else if (token == "\\begin_layout") {
805                 lex.eatLine();
806                 string layoutname = lex.getString();
807
808                 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
809                 change = Change();
810
811                 LyXTextClass const & tclass = bp.getLyXTextClass();
812
813                 if (layoutname.empty()) {
814                         layoutname = tclass.defaultLayoutName();
815                 }
816
817                 bool hasLayout = tclass.hasLayout(layoutname);
818
819                 if (!hasLayout) {
820                         lyxerr << "Layout '" << layoutname << "' does not"
821                                << " exist in textclass '" << tclass.name()
822                                << "'." << endl;
823                         lyxerr << "Trying to use default layout instead."
824                                << endl;
825                         layoutname = tclass.defaultLayoutName();
826                 }
827
828                 par.layout(bp.getLyXTextClass()[layoutname]);
829
830                 // Test whether the layout is obsolete.
831                 LyXLayout_ptr const & layout = par.layout();
832                 if (!layout->obsoleted_by().empty())
833                         par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
834
835                 par.params().read(lex);
836
837         } else if (token == "\\end_layout") {
838                 lyxerr << "Solitary \\end_layout in line " << lex.getLineNo() << "\n"
839                        << "Missing \\begin_layout?.\n";
840         } else if (token == "\\end_inset") {
841                 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
842                        << "Missing \\begin_inset?.\n";
843         } else if (token == "\\begin_inset") {
844                 InsetOld * inset = readInset(lex, buf);
845                 if (inset)
846                         par.insertInset(par.size(), inset, font, change);
847                 else {
848                         lex.eatLine();
849                         string line = lex.getString();
850                         buf.error(ErrorItem(_("Unknown Inset"), line,
851                                             buf.paragraphs().back().id(),
852                                             0, par.size()));
853                         return 1;
854                 }
855         } else if (token == "\\family") {
856                 lex.next();
857                 font.setLyXFamily(lex.getString());
858         } else if (token == "\\series") {
859                 lex.next();
860                 font.setLyXSeries(lex.getString());
861         } else if (token == "\\shape") {
862                 lex.next();
863                 font.setLyXShape(lex.getString());
864         } else if (token == "\\size") {
865                 lex.next();
866                 font.setLyXSize(lex.getString());
867         } else if (token == "\\lang") {
868                 lex.next();
869                 string const tok = lex.getString();
870                 Language const * lang = languages.getLanguage(tok);
871                 if (lang) {
872                         font.setLanguage(lang);
873                 } else {
874                         font.setLanguage(bp.language);
875                         lex.printError("Unknown language `$$Token'");
876                 }
877         } else if (token == "\\numeric") {
878                 lex.next();
879                 font.setNumber(font.setLyXMisc(lex.getString()));
880         } else if (token == "\\emph") {
881                 lex.next();
882                 font.setEmph(font.setLyXMisc(lex.getString()));
883         } else if (token == "\\bar") {
884                 lex.next();
885                 string const tok = lex.getString();
886
887                 if (tok == "under")
888                         font.setUnderbar(LyXFont::ON);
889                 else if (tok == "no")
890                         font.setUnderbar(LyXFont::OFF);
891                 else if (tok == "default")
892                         font.setUnderbar(LyXFont::INHERIT);
893                 else
894                         lex.printError("Unknown bar font flag "
895                                        "`$$Token'");
896         } else if (token == "\\noun") {
897                 lex.next();
898                 font.setNoun(font.setLyXMisc(lex.getString()));
899         } else if (token == "\\color") {
900                 lex.next();
901                 font.setLyXColor(lex.getString());
902         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
903
904                 // Insets don't make sense in a free-spacing context! ---Kayvan
905                 if (par.isFreeSpacing()) {
906                         if (token == "\\InsetSpace")
907                                 par.insertChar(par.size(), ' ', font, change);
908                         else if (lex.isOK()) {
909                                 lex.next();
910                                 string const next_token = lex.getString();
911                                 if (next_token == "\\-")
912                                         par.insertChar(par.size(), '-', font, change);
913                                 else {
914                                         lex.printError("Token `$$Token' "
915                                                        "is in free space "
916                                                        "paragraph layout!");
917                                 }
918                         }
919                 } else {
920                         InsetOld * inset = 0;
921                         if (token == "\\SpecialChar" )
922                                 inset = new InsetSpecialChar;
923                         else
924                                 inset = new InsetSpace;
925                         inset->read(buf, lex);
926                         par.insertInset(par.size(), inset, font, change);
927                 }
928         } else if (token == "\\i") {
929                 InsetOld * inset = new InsetLatexAccent;
930                 inset->read(buf, lex);
931                 par.insertInset(par.size(), inset, font, change);
932         } else if (token == "\\backslash") {
933                 par.insertChar(par.size(), '\\', font, change);
934         } else if (token == "\\newline") {
935                 InsetOld * inset = new InsetNewline;
936                 inset->read(buf, lex);
937                 par.insertInset(par.size(), inset, font, change);
938         } else if (token == "\\LyXTable") {
939                 InsetOld * inset = new InsetTabular(buf);
940                 inset->read(buf, lex);
941                 par.insertInset(par.size(), inset, font, change);
942         } else if (token == "\\bibitem") {
943                 InsetCommandParams p("bibitem", "dummy");
944                 InsetBibitem * inset = new InsetBibitem(p);
945                 inset->read(buf, lex);
946                 par.insertInset(par.size(), inset, font, change);
947         } else if (token == "\\hfill") {
948                 par.insertInset(par.size(), new InsetHFill, font, change);
949         } else if (token == "\\lyxline") {
950                 par.insertInset(par.size(), new InsetLine, font, change);
951         } else if (token == "\\newpage") {
952                 par.insertInset(par.size(), new InsetPagebreak, font, change);
953         } else if (token == "\\change_unchanged") {
954                 // Hack ! Needed for empty paragraphs :/
955                 // FIXME: is it still ??
956                 if (!par.size())
957                         par.cleanChanges();
958                 change = Change(Change::UNCHANGED);
959         } else if (token == "\\change_inserted") {
960                 lex.nextToken();
961                 istringstream is(lex.getString());
962                 int aid;
963                 lyx::time_type ct;
964                 is >> aid >> ct;
965                 change = Change(Change::INSERTED, bp.author_map[aid], ct);
966         } else if (token == "\\change_deleted") {
967                 lex.nextToken();
968                 istringstream is(lex.getString());
969                 int aid;
970                 lyx::time_type ct;
971                 is >> aid >> ct;
972                 change = Change(Change::DELETED, bp.author_map[aid], ct);
973         } else {
974                 lex.eatLine();
975                 string const s = bformat(_("Unknown token: %1$s %2$s\n"),
976                         token, lex.getString());
977
978                 buf.error(ErrorItem(_("Unknown token"), s,
979                                     buf.paragraphs().back().id(),
980                                     0, par.size()));
981                 return 1;
982         }
983         return 0;
984 }
985
986 }
987
988
989 int readParagraph(Buffer & buf, Paragraph & par, LyXLex & lex)
990 {
991         int unknown = 0;
992
993         lex.nextToken();
994         string token = lex.getString();
995
996         while (lex.isOK()) {
997
998                 unknown += readParToken(buf, par, lex, token);
999
1000                 lex.nextToken();
1001                 token = lex.getString();
1002
1003                 if (token.empty())
1004                         continue;
1005
1006                 if (token == "\\end_layout") {
1007                         //Ok, paragraph finished
1008                         break;
1009                 }
1010
1011                 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
1012                                       << token << '\'' << endl;
1013                 if (token == "\\begin_layout" || token == "\\end_document"
1014                     || token == "\\end_inset" || token == "\\begin_deeper"
1015                     || token == "\\end_deeper") {
1016                         lex.pushToken(token);
1017                         lyxerr << "Paragraph ended in line "
1018                                << lex.getLineNo() << "\n"
1019                                << "Missing \\end_layout.\n";
1020                         break;
1021                 }
1022         }
1023
1024         return unknown;
1025 }
1026
1027
1028 LyXFont const outerFont(ParagraphList::iterator pit,
1029                         ParagraphList const & plist)
1030 {
1031         Paragraph::depth_type par_depth = pit->getDepth();
1032         LyXFont tmpfont(LyXFont::ALL_INHERIT);
1033
1034         // Resolve against environment font information
1035         while (pit != const_cast<ParagraphList&>(plist).end() &&
1036                par_depth && !tmpfont.resolved()) {
1037                 pit = outerHook(pit, plist);
1038                 if (pit != const_cast<ParagraphList&>(plist).end()) {
1039                         tmpfont.realize(pit->layout()->font);
1040                         par_depth = pit->getDepth();
1041                 }
1042         }
1043
1044         return tmpfont;
1045 }
1046
1047
1048 ParagraphList::iterator outerPar(Buffer const & buf, InsetOld const * inset)
1049 {
1050         ParIterator pit = const_cast<Buffer &>(buf).par_iterator_begin();
1051         ParIterator end = const_cast<Buffer &>(buf).par_iterator_end();
1052         for ( ; pit != end; ++pit) {
1053
1054                 ParagraphList * plist;
1055                 // the second '=' below is intentional
1056                 for (int i = 0; (plist = inset->getParagraphs(i)); ++i)
1057                         if (plist == &pit.plist())
1058                                 return pit.outerPar();
1059
1060                 InsetList::iterator ii = pit->insetlist.begin();
1061                 InsetList::iterator iend = pit->insetlist.end();
1062                 for ( ; ii != iend; ++ii)
1063                         if (ii->inset == inset)
1064                                 return pit.outerPar();
1065         }
1066         lyxerr << "outerPar: should not happen" << endl;
1067         BOOST_ASSERT(false);
1068         return const_cast<Buffer &>(buf).paragraphs().end(); // shut up compiler
1069 }
1070
1071
1072 Paragraph const & ownerPar(Buffer const & buf, InsetOld const * inset)
1073 {
1074         ParConstIterator pit = buf.par_iterator_begin();
1075         ParConstIterator end = buf.par_iterator_end();
1076         for ( ; pit != end; ++pit) {
1077                 ParagraphList * plist;
1078                 // the second '=' below is intentional
1079                 for (int i = 0; (plist = inset->getParagraphs(i)); ++i)
1080                         if (plist == &pit.plist())
1081                                 return *pit.pit();
1082
1083                 InsetList::const_iterator ii = pit->insetlist.begin();
1084                 InsetList::const_iterator iend = pit->insetlist.end();
1085                 for ( ; ii != iend; ++ii)
1086                         if (ii->inset == inset)
1087                                 return *pit.pit();
1088         }
1089         lyxerr << "ownerPar: should not happen" << endl;
1090         BOOST_ASSERT(false);
1091         return buf.paragraphs().front(); // shut up compiler
1092 }