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