]> git.lyx.org Git - lyx.git/blob - src/paragraph_funcs.C
The "I want this in now" patch.
[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 "latexrunparams.h"
19 #include "debug.h"
20 #include "gettext.h"
21 #include "language.h"
22 #include "encoding.h"
23 #include "lyxrc.h"
24 #include "lyxlex.h"
25 #include "factory.h"
26 #include "Lsstream.h"
27 #include "support/lstrings.h"
28 #include "insets/insetoptarg.h"
29 #include "insets/insetcommandparams.h"
30 #include "insets/insetbibitem.h"
31 #include "insets/insetspace.h"
32 #include "insets/insetspecialchar.h"
33 #include "insets/insetlatexaccent.h"
34 #include "insets/insettabular.h"
35 #include "insets/insethfill.h"
36 #include "insets/inseterror.h"
37 #include "insets/insetnewline.h"
38
39 extern string bibitemWidest(Buffer const *);
40
41 using lyx::pos_type;
42 //using lyx::layout_type;
43 using std::endl;
44 using std::ostream;
45
46
47 void breakParagraph(BufferParams const & bparams,
48                     ParagraphList & paragraphs,
49                     ParagraphList::iterator par,
50                     pos_type pos,
51                     int flag)
52 {
53         // create a new paragraph, and insert into the list
54         ParagraphList::iterator tmp = paragraphs.insert(boost::next(par),
55                                                         new Paragraph);
56
57         // without doing that we get a crash when typing <Return> at the
58         // end of a paragraph
59         tmp->layout(bparams.getLyXTextClass().defaultLayout());
60         // remember to set the inset_owner
61         tmp->setInsetOwner(par->inInset());
62
63         if (bparams.tracking_changes)
64                 tmp->trackChanges();
65
66         // this is an idea for a more userfriendly layout handling, I will
67         // see what the users say
68
69         // layout stays the same with latex-environments
70         if (flag) {
71                 tmp->layout(par->layout());
72                 tmp->setLabelWidthString(par->params().labelWidthString());
73         }
74
75         bool const isempty = (par->layout()->keepempty && par->empty());
76
77         if (!isempty && (par->size() > pos || par->empty() || flag == 2)) {
78                 tmp->layout(par->layout());
79                 tmp->params().align(par->params().align());
80                 tmp->setLabelWidthString(par->params().labelWidthString());
81
82                 tmp->params().lineBottom(par->params().lineBottom());
83                 par->params().lineBottom(false);
84                 tmp->params().pagebreakBottom(par->params().pagebreakBottom());
85                 par->params().pagebreakBottom(false);
86                 tmp->params().spaceBottom(par->params().spaceBottom());
87                 par->params().spaceBottom(VSpace(VSpace::NONE));
88
89                 tmp->params().depth(par->params().depth());
90                 tmp->params().noindent(par->params().noindent());
91
92                 // copy everything behind the break-position
93                 // to the new paragraph
94
95 #ifdef WITH_WARNINGS
96 #warning this seems wrong
97 #endif
98                 /* FIXME: if !keepempty, empty() == true, then we reach
99                  * here with size() == 0. So pos_end becomes - 1. Why
100                  * doesn't this cause problems ???
101                  */
102                 pos_type pos_end = par->size() - 1;
103                 pos_type i = pos;
104                 pos_type j = pos;
105
106                 for (; i <= pos_end; ++i) {
107                         Change::Type change(par->lookupChange(i));
108                         par->cutIntoMinibuffer(bparams, i);
109                         if (tmp->insertFromMinibuffer(j - pos)) {
110                                 tmp->setChange(j - pos, change);
111                                 ++j;
112                         }
113                 }
114                 for (i = pos_end; i >= pos; --i) {
115                         par->eraseIntern(i);
116                 }
117         }
118
119         if (pos)
120                 return;
121
122         tmp->params().lineTop(par->params().lineTop());
123         tmp->params().pagebreakTop(par->params().pagebreakTop());
124         tmp->params().spaceTop(par->params().spaceTop());
125         par->params().clear();
126
127         par->layout(bparams.getLyXTextClass().defaultLayout());
128
129         // layout stays the same with latex-environments
130         if (flag) {
131                 par->layout(tmp->layout());
132                 par->setLabelWidthString(tmp->params().labelWidthString());
133                 par->params().depth(tmp->params().depth());
134         }
135
136         // subtle, but needed to get empty pars working right
137         if (bparams.tracking_changes) {
138                 if (!par->size()) {
139                         par->cleanChanges();
140                 } else if (!tmp->size()) {
141                         tmp->cleanChanges();
142                 }
143         }
144 }
145
146
147 void breakParagraphConservative(BufferParams const & bparams,
148                                 ParagraphList & paragraphs,
149                                 ParagraphList::iterator par,
150                                 pos_type pos)
151 {
152         // create a new paragraph
153         ParagraphList::iterator tmp = paragraphs.insert(boost::next(par),
154                                                         new Paragraph);
155         tmp->makeSameLayout(*par);
156
157         // When can pos > size()?
158         // I guess pos == size() is possible.
159         if (par->size() > pos) {
160                 // copy everything behind the break-position to the new
161                 // paragraph
162                 pos_type pos_end = par->size() - 1;
163
164                 for (pos_type i = pos, j = pos; i <= pos_end; ++i) {
165                         par->cutIntoMinibuffer(bparams, i);
166                         if (tmp->insertFromMinibuffer(j - pos))
167                                 ++j;
168                 }
169
170                 for (pos_type k = pos_end; k >= pos; --k) {
171                         par->erase(k);
172                 }
173         }
174 }
175
176
177 void mergeParagraph(BufferParams const & bparams,
178                     ParagraphList & paragraphs,
179                     ParagraphList::iterator par)
180 {
181         ParagraphList::iterator the_next = boost::next(par);
182
183         // first the DTP-stuff
184         par->params().lineBottom(the_next->params().lineBottom());
185         par->params().spaceBottom(the_next->params().spaceBottom());
186         par->params().pagebreakBottom(the_next->params().pagebreakBottom());
187
188         pos_type pos_end = the_next->size() - 1;
189         pos_type pos_insert = par->size();
190
191         // ok, now copy the paragraph
192         for (pos_type i = 0, j = 0; i <= pos_end; ++i) {
193                 the_next->cutIntoMinibuffer(bparams, i);
194                 if (par->insertFromMinibuffer(pos_insert + j))
195                         ++j;
196         }
197
198         paragraphs.erase(the_next);
199 }
200
201
202 ParagraphList::iterator depthHook(ParagraphList::iterator pit,
203                                   ParagraphList const & plist,
204                                   Paragraph::depth_type depth)
205 {
206         ParagraphList::iterator newpit = pit;
207         ParagraphList::iterator beg = plist.begin();
208
209         if (newpit != beg)
210                 --newpit;
211
212         while (newpit !=  beg && newpit->getDepth() > depth) {
213                 --newpit;
214         }
215
216         if (newpit->getDepth() > depth)
217                 return pit;
218
219         return newpit;
220 }
221
222
223 ParagraphList::iterator outerHook(ParagraphList::iterator pit,
224                                   ParagraphList const & plist)
225 {
226         if (!pit->getDepth())
227                 return plist.end();
228         return depthHook(pit, plist,
229                          Paragraph::depth_type(pit->getDepth() - 1));
230 }
231
232
233 bool isFirstInSequence(ParagraphList::iterator pit,
234                        ParagraphList const & plist)
235 {
236         ParagraphList::iterator dhook = depthHook(pit, plist, pit->getDepth());
237         return (dhook == pit
238                 || dhook->layout() != pit->layout()
239                 || dhook->getDepth() != pit->getDepth());
240 }
241
242
243 int getEndLabel(ParagraphList::iterator p, ParagraphList const & plist)
244 {
245         ParagraphList::iterator pit = p;
246         Paragraph::depth_type par_depth = p->getDepth();
247         while (pit != plist.end()) {
248                 LyXLayout_ptr const & layout = pit->layout();
249                 int const endlabeltype = layout->endlabeltype;
250
251                 if (endlabeltype != END_LABEL_NO_LABEL) {
252                         if (boost::next(p) == plist.end())
253                                 return endlabeltype;
254
255                         Paragraph::depth_type const next_depth = boost::next(p)->getDepth();
256                         if (par_depth > next_depth ||
257                             (par_depth == next_depth &&
258                              layout != boost::next(p)->layout()))
259                                 return endlabeltype;
260                         break;
261                 }
262                 if (par_depth == 0)
263                         break;
264                 pit = outerHook(pit, plist);
265                 if (pit != plist.end())
266                         par_depth = pit->getDepth();
267         }
268         return END_LABEL_NO_LABEL;
269 }
270
271
272 namespace {
273
274 ParagraphList::iterator
275 TeXEnvironment(Buffer const * buf,
276                ParagraphList const & paragraphs,
277                ParagraphList::iterator pit,
278                ostream & os, TexRow & texrow,
279                LatexRunParams const & runparams);
280
281 ParagraphList::iterator
282 TeXOnePar(Buffer const * buf,
283           ParagraphList const & paragraphs,
284           ParagraphList::iterator pit,
285           ostream & os, TexRow & texrow,
286           LatexRunParams const & runparams,
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           string const & everypar)
448 {
449         lyxerr[Debug::LATEX] << "TeXOnePar...     " << &*pit << " '" << everypar
450 << "'" << endl;
451         BufferParams const & bparams = buf->params;
452
453         Inset const * in = pit->inInset();
454         bool further_blank_line = false;
455         LyXLayout_ptr style;
456
457         // well we have to check if we are in an inset with unlimited
458         // lenght (all in one row) if that is true then we don't allow
459         // any special options in the paragraph and also we don't allow
460         // any environment other then "Standard" to be valid!
461         if ((in == 0) || !in->forceDefaultParagraphs(in)) {
462                 style = pit->layout();
463
464                 if (pit->params().startOfAppendix()) {
465                         os << "\\appendix\n";
466                         texrow.newline();
467                 }
468
469                 if (!pit->params().spacing().isDefault()
470                         && (pit == paragraphs.begin() || !boost::prior(pit)->hasSameLayout(*pit))) {
471                         os << pit->params().spacing().writeEnvirBegin() << '\n';
472                         texrow.newline();
473                 }
474
475                 if (style->isCommand()) {
476                         os << '\n';
477                         texrow.newline();
478                 }
479
480                 if (pit->params().pagebreakTop()) {
481                         os << "\\newpage";
482                         further_blank_line = true;
483                 }
484                 if (pit->params().spaceTop().kind() != VSpace::NONE) {
485                         os << pit->params().spaceTop().asLatexCommand(bparams);
486                         further_blank_line = true;
487                 }
488
489                 if (pit->params().lineTop()) {
490                         os << "\\lyxline{\\"
491                            << pit->getFont(bparams, 0, outerFont(pit, paragraphs)).latexSize()
492                            << '}'
493                            << "\\vspace{-1\\parskip}";
494                         further_blank_line = true;
495                 }
496
497                 if (further_blank_line) {
498                         os << '\n';
499                         texrow.newline();
500                 }
501         } else {
502                 style = bparams.getLyXTextClass().defaultLayout();
503         }
504
505         Language const * language = pit->getParLanguage(bparams);
506         Language const * doc_language = bparams.language;
507         Language const * previous_language =
508                 (pit != paragraphs.begin())
509                 ? boost::prior(pit)->getParLanguage(bparams)
510                 : doc_language;
511
512         if (language->babel() != previous_language->babel()
513             // check if we already put language command in TeXEnvironment()
514             && !(style->isEnvironment()
515                  && (pit == paragraphs.begin() ||
516                      (boost::prior(pit)->layout() != pit->layout() &&
517                       boost::prior(pit)->getDepth() <= pit->getDepth())
518                      || boost::prior(pit)->getDepth() < pit->getDepth())))
519         {
520                 if (!lyxrc.language_command_end.empty() &&
521                     previous_language->babel() != doc_language->babel())
522                 {
523                         os << subst(lyxrc.language_command_end, "$$lang",
524                                     previous_language->babel())
525                            << endl;
526                         texrow.newline();
527                 }
528
529                 if (lyxrc.language_command_end.empty() ||
530                     language->babel() != doc_language->babel())
531                 {
532                         os << subst(lyxrc.language_command_begin, "$$lang",
533                                     language->babel())
534                            << endl;
535                         texrow.newline();
536                 }
537         }
538
539         if (bparams.inputenc == "auto" &&
540             language->encoding() != previous_language->encoding()) {
541                 os << "\\inputencoding{"
542                    << language->encoding()->LatexName()
543                    << "}\n";
544                 texrow.newline();
545         }
546
547         switch (style->latextype) {
548         case LATEX_COMMAND:
549                 os << '\\' << style->latexname();
550
551                 // Separate handling of optional argument inset.
552                 if (style->optionalargs == 1) {
553                         InsetOptArg * it = optArgInset(*pit);
554                         if (it)
555                                 it->latexOptional(buf, os, runparams,
556                                                   false);
557                 }
558                 else
559                         os << style->latexparam();
560                 break;
561         case LATEX_ITEM_ENVIRONMENT:
562         case LATEX_LIST_ENVIRONMENT:
563                 os << "\\item ";
564                 break;
565         case LATEX_BIB_ENVIRONMENT:
566                 // ignore this, the inset will write itself
567                 break;
568         default:
569                 break;
570         }
571
572         os << everypar;
573         bool need_par = pit->simpleTeXOnePar(buf, bparams,
574                                              outerFont(pit, paragraphs),
575                                              os, texrow, runparams,
576                                              runparams.fragile);
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                      string const & everypar)
701 {
702         bool was_title = false;
703         bool already_title = false;
704         LyXTextClass const & tclass = buf->params.getLyXTextClass();
705         ParagraphList::iterator par = paragraphs.begin();
706         ParagraphList::iterator endpar = paragraphs.end();
707
708         // if only_body
709         while (par != endpar) {
710                 Inset * in = par->inInset();
711                 // well we have to check if we are in an inset with unlimited
712                 // length (all in one row) if that is true then we don't allow
713                 // any special options in the paragraph and also we don't allow
714                 // any environment other then "Standard" to be valid!
715                 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
716                         LyXLayout_ptr const & layout = par->layout();
717
718                         if (layout->intitle) {
719                                 if (already_title) {
720                                         lyxerr <<"Error in latexParagraphs: You"
721                                                 " should not mix title layouts"
722                                                 " with normal ones." << endl;
723                                 } else if (!was_title) {
724                                         was_title = true;
725                                         if (tclass.titletype() == TITLE_ENVIRONMENT) {
726                                                 os << "\\begin{"
727                                                     << tclass.titlename()
728                                                     << "}\n";
729                                                 texrow.newline();
730                                         }
731                                 }
732                         } else if (was_title && !already_title) {
733                                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
734                                         os << "\\end{" << tclass.titlename()
735                                             << "}\n";
736                                 }
737                                 else {
738                                         os << "\\" << tclass.titlename()
739                                             << "\n";
740                                 }
741                                 texrow.newline();
742                                 already_title = true;
743                                 was_title = false;
744                         }
745
746                         if (layout->is_environment) {
747                                 par = TeXOnePar(buf, paragraphs, par, os, texrow,
748                                                 runparams, everypar);
749                         } else if (layout->isEnvironment() ||
750                                 !par->params().leftIndent().zero())
751                         {
752                                 par = TeXEnvironment(buf, paragraphs, par, os,
753                                                      texrow, runparams);
754                         } else {
755                                 par = TeXOnePar(buf, paragraphs, par, os, texrow,
756                                                 runparams, everypar);
757                         }
758                 } else {
759                         par = TeXOnePar(buf, paragraphs, par, os, texrow,
760                                         runparams, everypar);
761                 }
762         }
763         // It might be that we only have a title in this document
764         if (was_title && !already_title) {
765                 if (tclass.titletype() == TITLE_ENVIRONMENT) {
766                         os << "\\end{" << tclass.titlename()
767                             << "}\n";
768                 }
769                 else {
770                         os << "\\" << tclass.titlename()
771                             << "\n";
772                                 }
773                 texrow.newline();
774         }
775 }
776
777
778 namespace {
779
780 int readParToken(Buffer & buf, Paragraph & par, LyXLex & lex, string const & token)
781 {
782         static LyXFont font;
783         static Change change;
784
785         BufferParams const & bp = buf.params;
786
787         if (token[0] != '\\') {
788                 string::const_iterator cit = token.begin();
789                 for (; cit != token.end(); ++cit) {
790                         par.insertChar(par.size(), (*cit), font, change);
791                 }
792         } else if (token == "\\layout") {
793                 lex.eatLine();
794                 string layoutname = lex.getString();
795
796                 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
797                 change = Change();
798
799                 LyXTextClass const & tclass = bp.getLyXTextClass();
800
801                 if (layoutname.empty()) {
802                         layoutname = tclass.defaultLayoutName();
803                 }
804
805                 bool hasLayout = tclass.hasLayout(layoutname);
806
807                 if (!hasLayout) {
808                         lyxerr << "Layout '" << layoutname << "' does not"
809                                << " exist in textclass '" << tclass.name()
810                                << "'." << endl;
811                         lyxerr << "Trying to use default layout instead."
812                                << endl;
813                         layoutname = tclass.defaultLayoutName();
814                 }
815
816 #ifdef USE_CAPTION
817                 // The is the compability reading of layout caption.
818                 if (compare_ascii_no_case(layoutname, "caption") == 0) {
819                         // We expect that the par we are now working on is
820                         // really inside a InsetText inside a InsetFloat.
821                         // We also know that captions can only be
822                         // one paragraph. (Lgb)
823
824                         // We should now read until the next "\layout"
825                         // is reached.
826                         // This is probably not good enough, what if the
827                         // caption is the last par in the document (Lgb)
828                         istream & ist = lex.getStream();
829                         stringstream ss;
830                         string line;
831                         int begin = 0;
832                         while (true) {
833                                 getline(ist, line);
834                                 if (prefixIs(line, "\\layout")) {
835                                         lex.pushToken(line);
836                                         break;
837                                 }
838                                 if (prefixIs(line, "\\begin_inset"))
839                                         ++begin;
840                                 if (prefixIs(line, "\\end_inset")) {
841                                         if (begin)
842                                                 --begin;
843                                         else {
844                                                 lex.pushToken(line);
845                                                 break;
846                                         }
847                                 }
848
849                                 ss << line << '\n';
850                         }
851
852                         // Now we should have the whole layout in ss
853                         // we should now be able to give this to the
854                         // caption inset.
855                         ss << "\\end_inset\n";
856
857                         // This seems like a bug in stringstream.
858                         // We really should be able to use ss
859                         // directly. (Lgb)
860                         istringstream is(ss.str());
861                         LyXLex tmplex(0, 0);
862                         tmplex.setStream(is);
863                         Inset * inset = new InsetCaption;
864                         inset->Read(this, tmplex);
865                         par.insertInset(pos, inset, font);
866                         ++pos;
867                 } else {
868 #endif
869                         par.layout(bp.getLyXTextClass()[layoutname]);
870
871                         // Test whether the layout is obsolete.
872                         LyXLayout_ptr const & layout = par.layout();
873                         if (!layout->obsoleted_by().empty())
874                                 par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
875
876                         par.params().read(lex);
877 #if USE_CAPTION
878                 }
879 #endif
880
881         } else if (token == "\\end_inset") {
882                 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
883                        << "Missing \\begin_inset?.\n";
884                 // Simply ignore this. The insets do not have
885                 // to read this.
886                 // But insets should read it, it is a part of
887                 // the inset isn't it? Lgb.
888         } else if (token == "\\begin_inset") {
889                 Inset * i = readInset(lex, buf);
890                 par.insertInset(par.size(), i, font, change);
891         } else if (token == "\\family") {
892                 lex.next();
893                 font.setLyXFamily(lex.getString());
894         } else if (token == "\\series") {
895                 lex.next();
896                 font.setLyXSeries(lex.getString());
897         } else if (token == "\\shape") {
898                 lex.next();
899                 font.setLyXShape(lex.getString());
900         } else if (token == "\\size") {
901                 lex.next();
902                 font.setLyXSize(lex.getString());
903         } else if (token == "\\lang") {
904                 lex.next();
905                 string const tok = lex.getString();
906                 Language const * lang = languages.getLanguage(tok);
907                 if (lang) {
908                         font.setLanguage(lang);
909                 } else {
910                         font.setLanguage(bp.language);
911                         lex.printError("Unknown language `$$Token'");
912                 }
913         } else if (token == "\\numeric") {
914                 lex.next();
915                 font.setNumber(font.setLyXMisc(lex.getString()));
916         } else if (token == "\\emph") {
917                 lex.next();
918                 font.setEmph(font.setLyXMisc(lex.getString()));
919         } else if (token == "\\bar") {
920                 lex.next();
921                 string const tok = lex.getString();
922
923                 if (tok == "under")
924                         font.setUnderbar(LyXFont::ON);
925                 else if (tok == "no")
926                         font.setUnderbar(LyXFont::OFF);
927                 else if (tok == "default")
928                         font.setUnderbar(LyXFont::INHERIT);
929                 else
930                         lex.printError("Unknown bar font flag "
931                                        "`$$Token'");
932         } else if (token == "\\noun") {
933                 lex.next();
934                 font.setNoun(font.setLyXMisc(lex.getString()));
935         } else if (token == "\\color") {
936                 lex.next();
937                 font.setLyXColor(lex.getString());
938         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
939                 LyXLayout_ptr const & layout = par.layout();
940
941                 // Insets don't make sense in a free-spacing context! ---Kayvan
942                 if (layout->free_spacing || par.isFreeSpacing()) {
943                         if (token == "\\InsetSpace")
944                                 par.insertChar(par.size(), ' ', font, change);
945                         else if (lex.isOK()) {
946                                 lex.next();
947                                 string const next_token = lex.getString();
948                                 if (next_token == "\\-")
949                                         par.insertChar(par.size(), '-', font, change);
950                                 else {
951                                         lex.printError("Token `$$Token' "
952                                                        "is in free space "
953                                                        "paragraph layout!");
954                                 }
955                         }
956                 } else {
957                         Inset * inset = 0;
958                         if (token == "\\SpecialChar" )
959                                 inset = new InsetSpecialChar;
960                         else
961                                 inset = new InsetSpace;
962                         inset->read(&buf, lex);
963                         par.insertInset(par.size(), inset, font, change);
964                 }
965         } else if (token == "\\i") {
966                 Inset * inset = new InsetLatexAccent;
967                 inset->read(&buf, lex);
968                 par.insertInset(par.size(), inset, font, change);
969         } else if (token == "\\backslash") {
970                 par.insertChar(par.size(), '\\', font, change);
971         } else if (token == "\\newline") {
972                 Inset * inset = new InsetNewline;
973                 inset->read(&buf, lex);
974                 par.insertInset(par.size(), inset, font, change);
975         } else if (token == "\\LyXTable") {
976                 Inset * inset = new InsetTabular(buf);
977                 inset->read(&buf, lex);
978                 par.insertInset(par.size(), inset, font, change);
979         } else if (token == "\\bibitem") {
980                 InsetCommandParams p("bibitem", "dummy");
981                 InsetBibitem * inset = new InsetBibitem(p);
982                 inset->read(&buf, lex);
983                 par.insertInset(par.size(), inset, font, change);
984         } else if (token == "\\hfill") {
985                 par.insertInset(par.size(), new InsetHFill(), font, change);
986         } else if (token == "\\change_unchanged") {
987                 // Hack ! Needed for empty paragraphs :/
988                 // FIXME: is it still ??
989                 if (!par.size())
990                         par.cleanChanges();
991                 change = Change(Change::UNCHANGED);
992         } else if (token == "\\change_inserted") {
993                 lex.nextToken();
994                 istringstream is(STRCONV(lex.getString()));
995                 int aid;
996                 lyx::time_type ct;
997                 is >> aid >> ct;
998                 change = Change(Change::INSERTED, bp.author_map[aid], ct);
999         } else if (token == "\\change_deleted") {
1000                 lex.nextToken();
1001                 istringstream is(STRCONV(lex.getString()));
1002                 int aid;
1003                 lyx::time_type ct;
1004                 is >> aid >> ct;
1005                 change = Change(Change::DELETED, bp.author_map[aid], ct);
1006         } else {
1007                 lex.eatLine();
1008                 string const s = bformat(_("Unknown token: %1$s %2$s\n"),
1009                         token, lex.getString());
1010                 // we can do this here this way because we're actually reading
1011                 // the buffer and don't care about LyXText right now.
1012                 par.insertInset(par.size(), new InsetError(s), font);
1013                 return 1;
1014         }
1015         return 0;
1016 }
1017
1018 }
1019
1020
1021 int readParagraph(Buffer & buf, Paragraph & par, LyXLex & lex)
1022 {
1023         int unknown = 0;
1024
1025         lex.nextToken();
1026         string token = lex.getString();
1027
1028         while (lex.isOK()) {
1029
1030                 unknown += readParToken(buf, par, lex, token);
1031
1032                 lex.nextToken();
1033                 token = lex.getString();
1034
1035                 if (token.empty())
1036                         continue;
1037
1038                 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
1039                                       << token << '\'' << endl;
1040
1041                 // reached the next paragraph. FIXME: really we should
1042                 // change the file format to indicate the end of a par
1043                 // clearly, but for now, this hack will do
1044                 if (token == "\\layout" || token == "\\the_end"
1045                     || token == "\\end_inset" || token == "\\begin_deeper"
1046                     || token == "\\end_deeper") {
1047                         lex.pushToken(token);
1048                         break;
1049                 }
1050         }
1051
1052         return unknown;
1053 }
1054
1055
1056 LyXFont const outerFont(ParagraphList::iterator pit,
1057                         ParagraphList const & plist)
1058 {
1059         Paragraph::depth_type par_depth = pit->getDepth();
1060         LyXFont tmpfont(LyXFont::ALL_INHERIT);
1061
1062         // Resolve against environment font information
1063         while (pit != plist.end() &&
1064                par_depth && !tmpfont.resolved()) {
1065                 pit = outerHook(pit, plist);
1066                 if (pit != plist.end()) {
1067                         tmpfont.realize(pit->layout()->font);
1068                         par_depth = pit->getDepth();
1069                 }
1070         }
1071
1072         return tmpfont;
1073 }
1074
1075
1076 LyXFont const realizeFont(LyXFont const & font,
1077                           BufferParams const & params)
1078 {
1079         LyXTextClass const & tclass = params.getLyXTextClass();
1080         LyXFont tmpfont(font);
1081         tmpfont.realize(tclass.defaultfont());
1082         return tmpfont;
1083 }