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