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