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