]> git.lyx.org Git - features.git/blob - src/paragraph_funcs.C
694c3a9a2bd30884323b8d04ee683d0f43af9e41
[features.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                                                         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                                                         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                LatexRunParams const & runparams);
279
280 ParagraphList::iterator
281 TeXOnePar(Buffer const * buf,
282           ParagraphList const & paragraphs,
283           ParagraphList::iterator pit,
284           ostream & os, TexRow & texrow,
285           LatexRunParams const & runparams,
286           string const & everypar = string());
287
288
289 ParagraphList::iterator
290 TeXDeeper(Buffer const * buf,
291           ParagraphList const & paragraphs,
292           ParagraphList::iterator pit,
293           ostream & os, TexRow & texrow,
294           LatexRunParams const & runparams)
295 {
296         lyxerr[Debug::LATEX] << "TeXDeeper...     " << &*pit << endl;
297         ParagraphList::iterator par = pit;
298
299         while (par != paragraphs.end() &&
300                      par->params().depth() == pit->params().depth()) {
301                 if (par->layout()->isEnvironment()) {
302                         par = TeXEnvironment(buf, paragraphs, par,
303                                              os, texrow, runparams);
304                 } else {
305                         par = TeXOnePar(buf, paragraphs, par,
306                                              os, texrow, runparams);
307                 }
308         }
309         lyxerr[Debug::LATEX] << "TeXDeeper...done " << &*par << endl;
310
311         return par;
312 }
313
314
315 ParagraphList::iterator
316 TeXEnvironment(Buffer const * buf,
317                ParagraphList const & paragraphs,
318                ParagraphList::iterator pit,
319                ostream & os, TexRow & texrow,
320                LatexRunParams const & runparams)
321 {
322         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << &*pit << endl;
323
324         BufferParams const & bparams = buf->params;
325
326         LyXLayout_ptr const & style = pit->layout();
327
328         Language const * language = pit->getParLanguage(bparams);
329         Language const * doc_language = bparams.language;
330         Language const * previous_language =
331                 (pit != paragraphs.begin())
332                 ? boost::prior(pit)->getParLanguage(bparams)
333                 : doc_language;
334         if (language->babel() != previous_language->babel()) {
335
336                 if (!lyxrc.language_command_end.empty() &&
337                     previous_language->babel() != doc_language->babel()) {
338                         os << subst(lyxrc.language_command_end, "$$lang",
339                                     previous_language->babel())
340                            << endl;
341                         texrow.newline();
342                 }
343
344                 if (lyxrc.language_command_end.empty() ||
345                     language->babel() != doc_language->babel()) {
346                         os << subst(lyxrc.language_command_begin, "$$lang",
347                                     language->babel())
348                            << endl;
349                         texrow.newline();
350                 }
351         }
352
353         bool leftindent_open = false;
354         if (!pit->params().leftIndent().zero()) {
355                 os << "\\begin{LyXParagraphLeftIndent}{" <<
356                         pit->params().leftIndent().asLatexString() << "}\n";
357                 texrow.newline();
358                 leftindent_open = true;
359         }
360
361         if (style->isEnvironment()) {
362                 if (style->latextype == LATEX_LIST_ENVIRONMENT) {
363                         os << "\\begin{" << style->latexname() << "}{"
364                            << pit->params().labelWidthString() << "}\n";
365                 } else if (style->labeltype == LABEL_BIBLIO) {
366                         // ale970405
367                         os << "\\begin{" << style->latexname() << "}{"
368                            <<  bibitemWidest(buf)
369                            << "}\n";
370                 } else if (style->latextype == LATEX_ITEM_ENVIRONMENT) {
371                         os << "\\begin{" << style->latexname() << '}'
372                            << style->latexparam() << '\n';
373                 } else
374                         os << "\\begin{" << style->latexname() << '}'
375                            << style->latexparam() << '\n';
376                 texrow.newline();
377         }
378         ParagraphList::iterator par = pit;
379         do {
380                 par = TeXOnePar(buf, paragraphs, par, os, texrow, runparams);
381
382                 if (par != paragraphs.end()&& par->params().depth() > pit->params().depth()) {
383                             if (par->layout()->isParagraph()) {
384
385                             // Thinko!
386                             // How to handle this? (Lgb)
387                             //&& !suffixIs(os, "\n\n")
388                                     //) {
389                                 // There should be at least one '\n' already
390                                 // but we need there to be two for Standard
391                                 // paragraphs that are depth-increment'ed to be
392                                 // output correctly.  However, tables can
393                                 // also be paragraphs so don't adjust them.
394                                 // ARRae
395                                 // Thinkee:
396                                 // Will it ever harm to have one '\n' too
397                                 // many? i.e. that we sometimes will have
398                                 // three in a row. (Lgb)
399                                 os << '\n';
400                                 texrow.newline();
401                         }
402                         par = TeXDeeper(buf, paragraphs, par, os, texrow,
403                                         runparams);
404                 }
405         } while (par != paragraphs.end()
406                  && par->layout() == pit->layout()
407                  && par->params().depth() == pit->params().depth()
408                  && par->params().leftIndent() == pit->params().leftIndent());
409
410         if (style->isEnvironment()) {
411                 os << "\\end{" << style->latexname() << "}\n";
412                 texrow.newline();
413         }
414
415         if (leftindent_open) {
416                 os << "\\end{LyXParagraphLeftIndent}\n";
417                 texrow.newline();
418         }
419
420         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << &*par << endl;
421         return par;  // ale970302
422 }
423
424
425 InsetOptArg * optArgInset(Paragraph const & par)
426 {
427         // Find the entry.
428         InsetList::iterator it = par.insetlist.begin();
429         InsetList::iterator end = par.insetlist.end();
430         for (; it != end; ++it) {
431                 Inset * ins = it.getInset();
432                 if (ins->lyxCode() == Inset::OPTARG_CODE) {
433                         return static_cast<InsetOptArg *>(ins);
434                 }
435         }
436         return 0;
437 }
438
439
440 ParagraphList::iterator
441 TeXOnePar(Buffer const * buf,
442           ParagraphList const & paragraphs,
443           ParagraphList::iterator pit,
444           ostream & os, TexRow & texrow,
445           LatexRunParams const & runparams,
446           string const & everypar)
447 {
448         lyxerr[Debug::LATEX] << "TeXOnePar...     " << &*pit << " '" << everypar
449 << "'" << endl;
450         BufferParams const & bparams = buf->params;
451
452         Inset const * in = pit->inInset();
453         bool further_blank_line = false;
454         LyXLayout_ptr style;
455
456         // well we have to check if we are in an inset with unlimited
457         // lenght (all in one row) if that is true then we don't allow
458         // any special options in the paragraph and also we don't allow
459         // any environment other then "Standard" to be valid!
460         if ((in == 0) || !in->forceDefaultParagraphs(in)) {
461                 style = pit->layout();
462
463                 if (pit->params().startOfAppendix()) {
464                         os << "\\appendix\n";
465                         texrow.newline();
466                 }
467
468                 if (!pit->params().spacing().isDefault()
469                         && (pit == paragraphs.begin() || !boost::prior(pit)->hasSameLayout(*pit))) {
470                         os << pit->params().spacing().writeEnvirBegin() << '\n';
471                         texrow.newline();
472                 }
473
474                 if (style->isCommand()) {
475                         os << '\n';
476                         texrow.newline();
477                 }
478
479                 if (pit->params().pagebreakTop()) {
480                         os << "\\newpage";
481                         further_blank_line = true;
482                 }
483                 if (pit->params().spaceTop().kind() != VSpace::NONE) {
484                         os << pit->params().spaceTop().asLatexCommand(bparams);
485                         further_blank_line = true;
486                 }
487
488                 if (pit->params().lineTop()) {
489                         os << "\\lyxline{\\"
490                            << pit->getFont(bparams, 0, outerFont(pit, paragraphs)).latexSize()
491                            << '}'
492                            << "\\vspace{-1\\parskip}";
493                         further_blank_line = true;
494                 }
495
496                 if (further_blank_line) {
497                         os << '\n';
498                         texrow.newline();
499                 }
500         } else {
501                 style = bparams.getLyXTextClass().defaultLayout();
502         }
503
504         Language const * language = pit->getParLanguage(bparams);
505         Language const * doc_language = bparams.language;
506         Language const * previous_language =
507                 (pit != paragraphs.begin())
508                 ? boost::prior(pit)->getParLanguage(bparams)
509                 : doc_language;
510
511         if (language->babel() != previous_language->babel()
512             // check if we already put language command in TeXEnvironment()
513             && !(style->isEnvironment()
514                  && (pit == paragraphs.begin() ||
515                      (boost::prior(pit)->layout() != pit->layout() &&
516                       boost::prior(pit)->getDepth() <= pit->getDepth())
517                      || boost::prior(pit)->getDepth() < pit->getDepth())))
518         {
519                 if (!lyxrc.language_command_end.empty() &&
520                     previous_language->babel() != doc_language->babel())
521                 {
522                         os << subst(lyxrc.language_command_end, "$$lang",
523                                     previous_language->babel())
524                            << endl;
525                         texrow.newline();
526                 }
527
528                 if (lyxrc.language_command_end.empty() ||
529                     language->babel() != doc_language->babel())
530                 {
531                         os << subst(lyxrc.language_command_begin, "$$lang",
532                                     language->babel())
533                            << endl;
534                         texrow.newline();
535                 }
536         }
537
538         if (bparams.inputenc == "auto" &&
539             language->encoding() != previous_language->encoding()) {
540                 os << "\\inputencoding{"
541                    << language->encoding()->LatexName()
542                    << "}\n";
543                 texrow.newline();
544         }
545
546         switch (style->latextype) {
547         case LATEX_COMMAND:
548                 os << '\\' << style->latexname();
549
550                 // Separate handling of optional argument inset.
551                 if (style->optionalargs == 1) {
552                         InsetOptArg * it = optArgInset(*pit);
553                         if (it)
554                                 it->latexOptional(buf, os, runparams);
555                 }
556                 else
557                         os << style->latexparam();
558                 break;
559         case LATEX_ITEM_ENVIRONMENT:
560         case LATEX_LIST_ENVIRONMENT:
561                 os << "\\item ";
562                 break;
563         case LATEX_BIB_ENVIRONMENT:
564                 // ignore this, the inset will write itself
565                 break;
566         default:
567                 break;
568         }
569
570         os << everypar;
571         bool need_par = pit->simpleTeXOnePar(buf, bparams,
572                                              outerFont(pit, paragraphs),
573                                              os, texrow, runparams);
574
575         // Make sure that \\par is done with the font of the last
576         // character if this has another size as the default.
577         // This is necessary because LaTeX (and LyX on the screen)
578         // calculates the space between the baselines according
579         // to this font. (Matthias)
580         //
581         // Is this really needed ? (Dekel)
582         // We do not need to use to change the font for the last paragraph
583         // or for a command.
584         LyXFont const outerfont(outerFont(pit, paragraphs));
585
586         LyXFont const font =
587                 (pit->empty()
588                  ? pit->getLayoutFont(bparams, outerfont)
589                  : pit->getFont(bparams, pit->size() - 1, outerfont));
590
591         bool is_command = style->isCommand();
592
593         if (style->resfont.size() != font.size()
594             && boost::next(pit) != paragraphs.end()
595             && !is_command) {
596                 if (!need_par)
597                         os << '{';
598                 os << "\\" << font.latexSize() << " \\par}";
599         } else if (need_par) {
600                 os << "\\par}";
601         } else if (is_command)
602                 os << '}';
603
604         switch (style->latextype) {
605         case LATEX_ITEM_ENVIRONMENT:
606         case LATEX_LIST_ENVIRONMENT:
607                 if (boost::next(pit) != paragraphs.end()
608                     && (pit->params().depth() < boost::next(pit)->params().depth())) {
609                         os << '\n';
610                         texrow.newline();
611                 }
612                 break;
613         case LATEX_ENVIRONMENT:
614                 // if its the last paragraph of the current environment
615                 // skip it otherwise fall through
616                 if (boost::next(pit) != paragraphs.end()
617                     && (boost::next(pit)->layout() != pit->layout()
618                         || boost::next(pit)->params().depth() != pit->params().depth()))
619                         break;
620                 // fall through possible
621         default:
622                 // we don't need it for the last paragraph!!!
623                 if (boost::next(pit) != paragraphs.end()) {
624                         os << '\n';
625                         texrow.newline();
626                 }
627         }
628
629         if ((in == 0) || !in->forceDefaultParagraphs(in)) {
630                 further_blank_line = false;
631                 if (pit->params().lineBottom()) {
632                         os << "\\lyxline{\\" << font.latexSize() << '}';
633                         further_blank_line = true;
634                 }
635
636                 if (pit->params().spaceBottom().kind() != VSpace::NONE) {
637                         os << pit->params().spaceBottom().asLatexCommand(bparams);
638                         further_blank_line = true;
639                 }
640
641                 if (pit->params().pagebreakBottom()) {
642                         os << "\\newpage";
643                         further_blank_line = true;
644                 }
645
646                 if (further_blank_line) {
647                         os << '\n';
648                         texrow.newline();
649                 }
650
651                 if (!pit->params().spacing().isDefault()
652                         && (boost::next(pit) == paragraphs.end()|| !boost::next(pit)->hasSameLayout(*pit))) {
653                         os << pit->params().spacing().writeEnvirEnd() << '\n';
654                         texrow.newline();
655                 }
656         }
657
658         // we don't need it for the last paragraph!!!
659         if (boost::next(pit) != paragraphs.end()) {
660                 os << '\n';
661                 texrow.newline();
662         } else {
663                 // Since \selectlanguage write the language to the aux file,
664                 // we need to reset the language at the end of footnote or
665                 // float.
666
667                 if (language->babel() != doc_language->babel()) {
668                         if (lyxrc.language_command_end.empty())
669                                 os << subst(lyxrc.language_command_begin,
670                                             "$$lang",
671                                             doc_language->babel())
672                                    << endl;
673                         else
674                                 os << subst(lyxrc.language_command_end,
675                                             "$$lang",
676                                             language->babel())
677                                    << endl;
678                         texrow.newline();
679                 }
680         }
681
682         lyxerr[Debug::LATEX] << "TeXOnePar...done " << &*boost::next(pit) << endl;
683         return ++pit;
684 }
685
686 } // anon namespace
687
688
689 //
690 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
691 //
692 void latexParagraphs(Buffer const * buf,
693                      ParagraphList const & paragraphs,
694                      ostream & os,
695                      TexRow & texrow,
696                      LatexRunParams const & runparams,
697                      string const & everypar)
698 {
699         bool was_title = false;
700         bool already_title = false;
701         LyXTextClass const & tclass = buf->params.getLyXTextClass();
702         ParagraphList::iterator par = paragraphs.begin();
703         ParagraphList::iterator endpar = paragraphs.end();
704
705         // if only_body
706         while (par != endpar) {
707                 Inset * in = par->inInset();
708                 // well we have to check if we are in an inset with unlimited
709                 // length (all in one row) if that is true then we don't allow
710                 // any special options in the paragraph and also we don't allow
711                 // any environment other then "Standard" to be valid!
712                 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
713                         LyXLayout_ptr const & layout = par->layout();
714
715                         if (layout->intitle) {
716                                 if (already_title) {
717                                         lyxerr <<"Error in latexParagraphs: You"
718                                                 " should not mix title layouts"
719                                                 " with normal ones." << endl;
720                                 } else if (!was_title) {
721                                         was_title = true;
722                                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
723                                                 os << "\\begin{"
724                                                     << tclass.titlename()
725                                                     << "}\n";
726                                                 texrow.newline();
727                                         }
728                                 }
729                         } else if (was_title && !already_title) {
730                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
731                                         os << "\\end{" << tclass.titlename()
732                                             << "}\n";
733                                 }
734                                 else {
735                                         os << "\\" << tclass.titlename()
736                                             << "\n";
737                                 }
738                                 texrow.newline();
739                                 already_title = true;
740                                 was_title = false;
741                         }
742
743                         if (layout->is_environment) {
744                                 par = TeXOnePar(buf, paragraphs, par, os, texrow,
745                                                 runparams, everypar);
746                         } else if (layout->isEnvironment() ||
747                                 !par->params().leftIndent().zero())
748                         {
749                                 par = TeXEnvironment(buf, paragraphs, par, os,
750                                                      texrow, runparams);
751                         } else {
752                                 par = TeXOnePar(buf, paragraphs, par, os, texrow,
753                                                 runparams, everypar);
754                         }
755                 } else {
756                         par = TeXOnePar(buf, paragraphs, par, os, texrow,
757                                         runparams, everypar);
758                 }
759         }
760         // It might be that we only have a title in this document
761         if (was_title && !already_title) {
762                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
763                         os << "\\end{" << tclass.titlename()
764                             << "}\n";
765                 }
766                 else {
767                         os << "\\" << tclass.titlename()
768                             << "\n";
769                                 }
770                 texrow.newline();
771         }
772 }
773
774
775 namespace {
776
777 int readParToken(Buffer & buf, Paragraph & par, LyXLex & lex, string const & token)
778 {
779         static LyXFont font;
780         static Change change;
781
782         BufferParams const & bp = buf.params;
783
784         if (token[0] != '\\') {
785                 string::const_iterator cit = token.begin();
786                 for (; cit != token.end(); ++cit) {
787                         par.insertChar(par.size(), (*cit), font, change);
788                 }
789         } else if (token == "\\layout") {
790                 lex.eatLine();
791                 string layoutname = lex.getString();
792
793                 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
794                 change = Change();
795
796                 LyXTextClass const & tclass = bp.getLyXTextClass();
797
798                 if (layoutname.empty()) {
799                         layoutname = tclass.defaultLayoutName();
800                 }
801
802                 bool hasLayout = tclass.hasLayout(layoutname);
803
804                 if (!hasLayout) {
805                         lyxerr << "Layout '" << layoutname << "' does not"
806                                << " exist in textclass '" << tclass.name()
807                                << "'." << endl;
808                         lyxerr << "Trying to use default layout instead."
809                                << endl;
810                         layoutname = tclass.defaultLayoutName();
811                 }
812
813 #ifdef USE_CAPTION
814                 // The is the compability reading of layout caption.
815                 if (compare_ascii_no_case(layoutname, "caption") == 0) {
816                         // We expect that the par we are now working on is
817                         // really inside a InsetText inside a InsetFloat.
818                         // We also know that captions can only be
819                         // one paragraph. (Lgb)
820
821                         // We should now read until the next "\layout"
822                         // is reached.
823                         // This is probably not good enough, what if the
824                         // caption is the last par in the document (Lgb)
825                         istream & ist = lex.getStream();
826                         stringstream ss;
827                         string line;
828                         int begin = 0;
829                         while (true) {
830                                 getline(ist, line);
831                                 if (prefixIs(line, "\\layout")) {
832                                         lex.pushToken(line);
833                                         break;
834                                 }
835                                 if (prefixIs(line, "\\begin_inset"))
836                                         ++begin;
837                                 if (prefixIs(line, "\\end_inset")) {
838                                         if (begin)
839                                                 --begin;
840                                         else {
841                                                 lex.pushToken(line);
842                                                 break;
843                                         }
844                                 }
845
846                                 ss << line << '\n';
847                         }
848
849                         // Now we should have the whole layout in ss
850                         // we should now be able to give this to the
851                         // caption inset.
852                         ss << "\\end_inset\n";
853
854                         // This seems like a bug in stringstream.
855                         // We really should be able to use ss
856                         // directly. (Lgb)
857                         istringstream is(ss.str());
858                         LyXLex tmplex(0, 0);
859                         tmplex.setStream(is);
860                         Inset * inset = new InsetCaption;
861                         inset->Read(this, tmplex);
862                         par.insertInset(pos, inset, font);
863                         ++pos;
864                 } else {
865 #endif
866                         par.layout(bp.getLyXTextClass()[layoutname]);
867
868                         // Test whether the layout is obsolete.
869                         LyXLayout_ptr const & layout = par.layout();
870                         if (!layout->obsoleted_by().empty())
871                                 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
872
873                         par.params().read(lex);
874 #if USE_CAPTION
875                 }
876 #endif
877
878         } else if (token == "\\end_inset") {
879                 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
880                        << "Missing \\begin_inset?.\n";
881                 // Simply ignore this. The insets do not have
882                 // to read this.
883                 // But insets should read it, it is a part of
884                 // the inset isn't it? Lgb.
885         } else if (token == "\\begin_inset") {
886                 Inset * i = readInset(lex, buf);
887                 par.insertInset(par.size(), i, font, change);
888         } else if (token == "\\family") {
889                 lex.next();
890                 font.setLyXFamily(lex.getString());
891         } else if (token == "\\series") {
892                 lex.next();
893                 font.setLyXSeries(lex.getString());
894         } else if (token == "\\shape") {
895                 lex.next();
896                 font.setLyXShape(lex.getString());
897         } else if (token == "\\size") {
898                 lex.next();
899                 font.setLyXSize(lex.getString());
900         } else if (token == "\\lang") {
901                 lex.next();
902                 string const tok = lex.getString();
903                 Language const * lang = languages.getLanguage(tok);
904                 if (lang) {
905                         font.setLanguage(lang);
906                 } else {
907                         font.setLanguage(bp.language);
908                         lex.printError("Unknown language `$$Token'");
909                 }
910         } else if (token == "\\numeric") {
911                 lex.next();
912                 font.setNumber(font.setLyXMisc(lex.getString()));
913         } else if (token == "\\emph") {
914                 lex.next();
915                 font.setEmph(font.setLyXMisc(lex.getString()));
916         } else if (token == "\\bar") {
917                 lex.next();
918                 string const tok = lex.getString();
919
920                 if (tok == "under")
921                         font.setUnderbar(LyXFont::ON);
922                 else if (tok == "no")
923                         font.setUnderbar(LyXFont::OFF);
924                 else if (tok == "default")
925                         font.setUnderbar(LyXFont::INHERIT);
926                 else
927                         lex.printError("Unknown bar font flag "
928                                        "`$$Token'");
929         } else if (token == "\\noun") {
930                 lex.next();
931                 font.setNoun(font.setLyXMisc(lex.getString()));
932         } else if (token == "\\color") {
933                 lex.next();
934                 font.setLyXColor(lex.getString());
935         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
936                 LyXLayout_ptr const & layout = par.layout();
937
938                 // Insets don't make sense in a free-spacing context! ---Kayvan
939                 if (layout->free_spacing || par.isFreeSpacing()) {
940                         if (token == "\\InsetSpace")
941                                 par.insertChar(par.size(), ' ', font, change);
942                         else if (lex.isOK()) {
943                                 lex.next();
944                                 string const next_token = lex.getString();
945                                 if (next_token == "\\-")
946                                         par.insertChar(par.size(), '-', font, change);
947                                 else {
948                                         lex.printError("Token `$$Token' "
949                                                        "is in free space "
950                                                        "paragraph layout!");
951                                 }
952                         }
953                 } else {
954                         Inset * inset = 0;
955                         if (token == "\\SpecialChar" )
956                                 inset = new InsetSpecialChar;
957                         else
958                                 inset = new InsetSpace;
959                         inset->read(&buf, lex);
960                         par.insertInset(par.size(), inset, font, change);
961                 }
962         } else if (token == "\\i") {
963                 Inset * inset = new InsetLatexAccent;
964                 inset->read(&buf, lex);
965                 par.insertInset(par.size(), inset, font, change);
966         } else if (token == "\\backslash") {
967                 par.insertChar(par.size(), '\\', font, change);
968         } else if (token == "\\newline") {
969                 Inset * inset = new InsetNewline;
970                 inset->read(&buf, lex);
971                 par.insertInset(par.size(), inset, font, change);
972         } else if (token == "\\LyXTable") {
973                 Inset * inset = new InsetTabular(buf);
974                 inset->read(&buf, lex);
975                 par.insertInset(par.size(), inset, font, change);
976         } else if (token == "\\bibitem") {
977                 InsetCommandParams p("bibitem", "dummy");
978                 InsetBibitem * inset = new InsetBibitem(p);
979                 inset->read(&buf, lex);
980                 par.insertInset(par.size(), inset, font, change);
981         } else if (token == "\\hfill") {
982                 par.insertInset(par.size(), new InsetHFill(), font, change);
983         } else if (token == "\\change_unchanged") {
984                 // Hack ! Needed for empty paragraphs :/
985                 // FIXME: is it still ??
986                 if (!par.size())
987                         par.cleanChanges();
988                 change = Change(Change::UNCHANGED);
989         } else if (token == "\\change_inserted") {
990                 lex.nextToken();
991                 istringstream is(STRCONV(lex.getString()));
992                 int aid;
993                 lyx::time_type ct;
994                 is >> aid >> ct;
995                 change = Change(Change::INSERTED, bp.author_map[aid], ct);
996         } else if (token == "\\change_deleted") {
997                 lex.nextToken();
998                 istringstream is(STRCONV(lex.getString()));
999                 int aid;
1000                 lyx::time_type ct;
1001                 is >> aid >> ct;
1002                 change = Change(Change::DELETED, bp.author_map[aid], ct);
1003         } else {
1004                 lex.eatLine();
1005                 string const s = bformat(_("Unknown token: %1$s %2$s\n"),
1006                         token, lex.getString());
1007                 // we can do this here this way because we're actually reading
1008                 // the buffer and don't care about LyXText right now.
1009                 par.insertInset(par.size(), new InsetError(s), font);
1010                 return 1;
1011         }
1012         return 0;
1013 }
1014
1015 }
1016
1017
1018 int readParagraph(Buffer & buf, Paragraph & par, LyXLex & lex)
1019 {
1020         int unknown = 0;
1021
1022         lex.nextToken();
1023         string token = lex.getString();
1024
1025         while (lex.isOK()) {
1026
1027                 unknown += readParToken(buf, par, lex, token);
1028
1029                 lex.nextToken();
1030                 token = lex.getString();
1031
1032                 if (token.empty())
1033                         continue;
1034
1035                 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
1036                                       << token << '\'' << endl;
1037
1038                 // reached the next paragraph. FIXME: really we should
1039                 // change the file format to indicate the end of a par
1040                 // clearly, but for now, this hack will do
1041                 if (token == "\\layout" || token == "\\the_end"
1042                     || token == "\\end_inset" || token == "\\begin_deeper"
1043                     || token == "\\end_deeper") {
1044                         lex.pushToken(token);
1045                         break;
1046                 }
1047         }
1048
1049         return unknown;
1050 }
1051
1052
1053 LyXFont const outerFont(ParagraphList::iterator pit,
1054                         ParagraphList const & plist)
1055 {
1056         Paragraph::depth_type par_depth = pit->getDepth();
1057         LyXFont tmpfont(LyXFont::ALL_INHERIT);
1058
1059         // Resolve against environment font information
1060         while (pit != plist.end() &&
1061                par_depth && !tmpfont.resolved()) {
1062                 pit = outerHook(pit, plist);
1063                 if (pit != plist.end()) {
1064                         tmpfont.realize(pit->layout()->font);
1065                         par_depth = pit->getDepth();
1066                 }
1067         }
1068
1069         return tmpfont;
1070 }
1071
1072
1073 LyXFont const realizeFont(LyXFont const & font,
1074                           BufferParams const & params)
1075 {
1076         LyXTextClass const & tclass = params.getLyXTextClass();
1077         LyXFont tmpfont(font);
1078         tmpfont.realize(tclass.defaultfont());
1079         return tmpfont;
1080 }