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