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