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