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