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