]> git.lyx.org Git - lyx.git/blob - src/paragraph.C
fix the <...> delimiters
[lyx.git] / src / paragraph.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef __GNUG__
14 #pragma implementation
15 #endif
16
17 #include "paragraph.h"
18 #include "paragraph_pimpl.h"
19 #include "lyxrc.h"
20 #include "layout.h"
21 #include "language.h"
22 #include "tex-strings.h"
23 #include "buffer.h"
24 #include "bufferparams.h"
25 #include "debug.h"
26 #include "LaTeXFeatures.h"
27 #include "texrow.h"
28 #include "BufferView.h"
29 #include "encoding.h"
30 #include "ParameterStruct.h"
31 #include "gettext.h"
32 #include "lyxtextclasslist.h"
33
34 #include "insets/insetinclude.h"
35 #include "insets/insetbib.h"
36 #include "insets/insettext.h"
37
38 #include "support/filetools.h"
39 #include "support/lstrings.h"
40 #include "support/lyxmanip.h"
41 #include "support/FileInfo.h"
42 #include "support/LAssert.h"
43 #include "support/textutils.h"
44
45 #include <algorithm>
46 #include <fstream>
47 #include <csignal>
48
49 using std::ostream;
50 using std::endl;
51 using std::fstream;
52 using std::ios;
53 using std::lower_bound;
54 using std::upper_bound;
55 using std::reverse;
56
57 using lyx::pos_type;
58
59 int tex_code_break_column = 72;  // needs non-zero initialization. set later.
60 // this is a bad idea, but how can Paragraph find its buffer to get
61 // parameters? (JMarc)
62
63 extern string bibitemWidest(Buffer const *);
64
65 // this is a minibuffer
66
67 namespace {
68
69 char minibuffer_char;
70 LyXFont minibuffer_font;
71 Inset * minibuffer_inset;
72
73 } // namespace anon
74
75
76 extern BufferView * current_view;
77
78
79 Paragraph::Paragraph()
80         : pimpl_(new Paragraph::Pimpl(this))
81 {
82         for (int i = 0; i < 10; ++i)
83                 setCounter(i, 0);
84         next_ = 0;
85         previous_ = 0;
86         enumdepth = 0;
87         itemdepth = 0;
88         bibkey = 0; // ale970302
89         params().clear();
90 }
91
92
93 // This constructor inserts the new paragraph in a list.
94 Paragraph::Paragraph(Paragraph * par)
95         : pimpl_(new Paragraph::Pimpl(this))
96 {
97         for (int i = 0; i < 10; ++i)
98                 setCounter(i, 0);
99         enumdepth = 0;
100         itemdepth = 0;
101
102         // double linked list begin
103         next_ = par->next_;
104         if (next_)
105                 next_->previous_ = this;
106         previous_ = par;
107         previous_->next_ = this;
108         // end
109
110         bibkey = 0; // ale970302
111         params().clear();
112 }
113
114
115 Paragraph::Paragraph(Paragraph const & lp, bool same_ids)
116         : pimpl_(new Paragraph::Pimpl(*lp.pimpl_, this, same_ids))
117 {
118         for (int i = 0; i < 10; ++i)
119                 setCounter(i, 0);
120         enumdepth = 0;
121         itemdepth = 0;
122         next_     = 0;
123         previous_ = 0;
124
125         // this is because of the dummy layout of the paragraphs that
126         // follow footnotes
127         layout_ = lp.layout();
128
129         // ale970302
130         if (lp.bibkey) {
131                 bibkey = static_cast<InsetBibKey *>
132                         (lp.bibkey->clone(*current_view->buffer()));
133         } else {
134                 bibkey = 0;
135         }
136
137         // copy everything behind the break-position to the new paragraph
138         insetlist = lp.insetlist;
139         for (InsetList::iterator it = insetlist.begin();
140              it != insetlist.end(); ++it)
141         {
142                 it->inset = it->inset->clone(*current_view->buffer(), same_ids);
143                 // tell the new inset who is the boss now
144                 it->inset->parOwner(this);
145         }
146 }
147
148
149 // the destructor removes the new paragraph from the list
150 Paragraph::~Paragraph()
151 {
152         if (previous_)
153                 previous_->next_ = next_;
154         if (next_)
155                 next_->previous_ = previous_;
156
157         for (InsetList::iterator it = insetlist.begin();
158              it != insetlist.end(); ++it) {
159                 delete it->inset;
160         }
161
162         // ale970302
163         delete bibkey;
164
165         delete pimpl_;
166         //
167         //lyxerr << "Paragraph::paragraph_id = "
168         //       << Paragraph::paragraph_id << endl;
169 }
170
171
172 void Paragraph::writeFile(Buffer const * buf, ostream & os,
173                           BufferParams const & bparams,
174                           depth_type dth) const
175 {
176         // The beginning or end of a deeper (i.e. nested) area?
177         if (dth != params().depth()) {
178                 if (params().depth() > dth) {
179                         while (params().depth() > dth) {
180                                 os << "\n\\begin_deeper ";
181                                 ++dth;
182                         }
183                 } else {
184                         while (params().depth() < dth) {
185                                 os << "\n\\end_deeper ";
186                                 --dth;
187                         }
188                 }
189         }
190
191         // First write the layout
192         os << "\n\\layout " << layout()->name() << "\n";
193
194         // Maybe some vertical spaces.
195         if (params().spaceTop().kind() != VSpace::NONE)
196                 os << "\\added_space_top "
197                    << params().spaceTop().asLyXCommand() << " ";
198         if (params().spaceBottom().kind() != VSpace::NONE)
199                 os << "\\added_space_bottom "
200                    << params().spaceBottom().asLyXCommand() << " ";
201
202         // Maybe the paragraph has special spacing
203         params().spacing().writeFile(os, true);
204
205         // The labelwidth string used in lists.
206         if (!params().labelWidthString().empty())
207                 os << "\\labelwidthstring "
208                    << params().labelWidthString() << '\n';
209
210         // Lines above or below?
211         if (params().lineTop())
212                 os << "\\line_top ";
213         if (params().lineBottom())
214                 os << "\\line_bottom ";
215
216         // Pagebreaks above or below?
217         if (params().pagebreakTop())
218                 os << "\\pagebreak_top ";
219         if (params().pagebreakBottom())
220                 os << "\\pagebreak_bottom ";
221
222         // Start of appendix?
223         if (params().startOfAppendix())
224                 os << "\\start_of_appendix ";
225
226         // Noindent?
227         if (params().noindent())
228                 os << "\\noindent ";
229
230         // Do we have a manual left indent?
231         if (!params().leftIndent().zero())
232                 os << "\\leftindent " << params().leftIndent().asString() << " ";
233
234         // Alignment?
235         if (params().align() != LYX_ALIGN_LAYOUT) {
236                 int h = 0;
237                 switch (params().align()) {
238                 case LYX_ALIGN_LEFT: h = 1; break;
239                 case LYX_ALIGN_RIGHT: h = 2; break;
240                 case LYX_ALIGN_CENTER: h = 3; break;
241                 default: h = 0; break;
242                 }
243                 os << "\\align " << string_align[h] << " ";
244         }
245
246         // bibitem  ale970302
247         if (bibkey)
248                 bibkey->write(buf, os);
249
250         LyXFont font1(LyXFont::ALL_INHERIT, bparams.language);
251
252         int column = 0;
253         for (pos_type i = 0; i < size(); ++i) {
254                 if (!i) {
255                         os << "\n";
256                         column = 0;
257                 }
258
259                 // Write font changes
260                 LyXFont font2 = getFontSettings(bparams, i);
261                 if (font2 != font1) {
262 #ifndef INHERIT_LANGUAGE
263                         font2.lyxWriteChanges(font1, os);
264 #else
265                         font2.lyxWriteChanges(font1, bparams.language, os);
266 #endif
267                         column = 0;
268                         font1 = font2;
269                 }
270
271                 value_type const c = getChar(i);
272                 switch (c) {
273                 case META_INSET:
274                 {
275                         Inset const * inset = getInset(i);
276                         if (inset)
277                                 if (inset->directWrite()) {
278                                         // international char, let it write
279                                         // code directly so it's shorter in
280                                         // the file
281                                         inset->write(buf, os);
282                                 } else {
283                                         os << "\n\\begin_inset ";
284                                         inset->write(buf, os);
285                                         os << "\n\\end_inset \n\n";
286                                         column = 0;
287                                 }
288                 }
289                 break;
290                 case META_NEWLINE:
291                         os << "\n\\newline \n";
292                         column = 0;
293                         break;
294                 case META_HFILL:
295                         os << "\n\\hfill \n";
296                         column = 0;
297                         break;
298                 case '\\':
299                         os << "\n\\backslash \n";
300                         column = 0;
301                         break;
302                 case '.':
303                         if (i + 1 < size() && getChar(i + 1) == ' ') {
304                                 os << ".\n";
305                                 column = 0;
306                         } else
307                                 os << ".";
308                         break;
309                 default:
310                         if ((column > 70 && c == ' ')
311                             || column > 79) {
312                                 os << "\n";
313                                 column = 0;
314                         }
315                         // this check is to amend a bug. LyX sometimes
316                         // inserts '\0' this could cause problems.
317                         if (c != '\0')
318                                 os << c;
319                         else
320                                 lyxerr << "ERROR (Paragraph::writeFile):"
321                                         " NULL char in structure." << endl;
322                         ++column;
323                         break;
324                 }
325         }
326
327         // now write the next paragraph
328         if (next_)
329                 next_->writeFile(buf, os, bparams, dth);
330 }
331
332
333 void Paragraph::validate(LaTeXFeatures & features) const
334 {
335         BufferParams const & bparams = features.bufferParams();
336
337         // check the params.
338         if (params().lineTop() || params().lineBottom())
339                 features.require("lyxline");
340         if (!params().spacing().isDefault())
341                 features.require("setspace");
342
343         // then the layouts
344         features.useLayout(layout()->name());
345
346         // then the fonts
347         Language const * doc_language = bparams.language;
348
349         Pimpl::FontList::const_iterator fcit = pimpl_->fontlist.begin();
350         Pimpl::FontList::const_iterator fend = pimpl_->fontlist.end();
351         for (; fcit != fend; ++fcit) {
352                 if (fcit->font().noun() == LyXFont::ON) {
353                         lyxerr[Debug::LATEX] << "font.noun: "
354                                              << fcit->font().noun()
355                                              << endl;
356                         features.require("noun");
357                         lyxerr[Debug::LATEX] << "Noun enabled. Font: "
358                                              << fcit->font().stateText(0)
359                                              << endl;
360                 }
361                 switch (fcit->font().color()) {
362                 case LColor::none:
363                 case LColor::inherit:
364                 case LColor::ignore:
365                         // probably we should put here all interface colors used for
366                         // font displaying! For now I just add this ones I know of (Jug)
367                 case LColor::latex:
368                 case LColor::note:
369                         break;
370                 default:
371                         features.require("color");
372                         lyxerr[Debug::LATEX] << "Color enabled. Font: "
373                                              << fcit->font().stateText(0)
374                                              << endl;
375                 }
376
377                 Language const * language = fcit->font().language();
378                 if (language->babel() != doc_language->babel() &&
379                     language != ignore_language &&
380 #ifdef INHERIT_LANGUAGE
381                     language != inherit_language &&
382 #endif
383                     language != latex_language)
384                 {
385                         features.useLanguage(language);
386                         lyxerr[Debug::LATEX] << "Found language "
387                                              << language->babel() << endl;
388                 }
389         }
390
391         if (!params().leftIndent().zero())
392                 features.require("ParagraphLeftIndent");
393
394         // then the insets
395         LyXLayout_ptr const & lout = layout();
396
397         InsetList::const_iterator icit = insetlist.begin();
398         InsetList::const_iterator iend = insetlist.end();
399         for (; icit != iend; ++icit) {
400                 if (icit->inset) {
401                         icit->inset->validate(features);
402                         if (lout->needprotect &&
403                             icit->inset->lyxCode() == Inset::FOOT_CODE)
404                                 features.require("NeedLyXFootnoteCode");
405                 }
406         }
407 }
408
409
410 // First few functions needed for cut and paste and paragraph breaking.
411 void Paragraph::copyIntoMinibuffer(Buffer const & buffer, pos_type pos) const
412 {
413         BufferParams bparams = buffer.params;
414
415         minibuffer_char = getChar(pos);
416         minibuffer_font = getFontSettings(bparams, pos);
417         minibuffer_inset = 0;
418         if (minibuffer_char == Paragraph::META_INSET) {
419                 if (getInset(pos)) {
420                         minibuffer_inset = getInset(pos)->clone(buffer);
421                 } else {
422                         minibuffer_inset = 0;
423                         minibuffer_char = ' ';
424                         // This reflects what GetInset() does (ARRae)
425                 }
426         }
427 }
428
429
430 void Paragraph::cutIntoMinibuffer(BufferParams const & bparams, pos_type pos)
431 {
432         minibuffer_char = getChar(pos);
433         minibuffer_font = getFontSettings(bparams, pos);
434         minibuffer_inset = 0;
435         if (minibuffer_char == Paragraph::META_INSET) {
436                 if (getInset(pos)) {
437                         minibuffer_inset = getInset(pos);
438                         // This is a little hack since I want exactly
439                         // the inset, not just a clone. Otherwise
440                         // the inset would be deleted when calling Erase(pos)
441                         // find the entry
442                         InsetList::iterator it = insetlist.begin();
443                         InsetList::iterator end = insetlist.end();
444                         for (; it != end; ++it) {
445                                 if (it->pos == pos)
446                                         break;
447                         }
448
449                         if (it != end && it->pos == pos)
450                                 it->inset = 0;
451                         // the inset is not in a paragraph anymore
452                         minibuffer_inset->parOwner(0);
453                 } else {
454                         minibuffer_inset = 0;
455                         minibuffer_char = ' ';
456                         // This reflects what GetInset() does (ARRae)
457                 }
458
459         }
460
461         // Erase(pos); now the caller is responsible for that.
462 }
463
464
465 bool Paragraph::insertFromMinibuffer(pos_type pos)
466 {
467         if (minibuffer_char == Paragraph::META_INSET) {
468                 if (!insetAllowed(minibuffer_inset->lyxCode())) {
469                         return false;
470                 }
471                 insertInset(pos, minibuffer_inset, minibuffer_font);
472         } else {
473                 LyXFont f = minibuffer_font;
474                 if (!checkInsertChar(f)) {
475                         return false;
476                 }
477                 insertChar(pos, minibuffer_char, f);
478         }
479         return true;
480 }
481
482 // end of minibuffer
483
484
485 void Paragraph::erase(pos_type pos)
486 {
487         pimpl_->erase(pos);
488 }
489
490
491 bool Paragraph::checkInsertChar(LyXFont & font)
492 {
493         if (pimpl_->inset_owner)
494                 return pimpl_->inset_owner->checkInsertChar(font);
495         return true;
496 }
497
498
499 void Paragraph::insertChar(pos_type pos, Paragraph::value_type c)
500 {
501         LyXFont const f(LyXFont::ALL_INHERIT);
502         insertChar(pos, c, f);
503 }
504
505
506 void Paragraph::insertChar(pos_type pos, Paragraph::value_type c,
507                            LyXFont const & font)
508 {
509         pimpl_->insertChar(pos, c, font);
510 }
511
512
513 void Paragraph::insertInset(pos_type pos, Inset * inset)
514 {
515         LyXFont const f(LyXFont::ALL_INHERIT);
516         insertInset(pos, inset, f);
517 }
518
519
520 void Paragraph::insertInset(pos_type pos, Inset * inset, LyXFont const & font)
521 {
522         pimpl_->insertInset(pos, inset, font);
523 }
524
525
526 bool Paragraph::insetAllowed(Inset::Code code)
527 {
528         //lyxerr << "Paragraph::InsertInsetAllowed" << endl;
529
530         if (pimpl_->inset_owner)
531                 return pimpl_->inset_owner->insetAllowed(code);
532         return true;
533 }
534
535
536 Inset * Paragraph::getInset(pos_type pos)
537 {
538         lyx::Assert(pos < size());
539
540         // Find the inset.
541         InsetList::iterator it = insetlist.begin();
542         InsetList::iterator end = insetlist.end();
543         for (; it != end; ++it) {
544                 if (it->pos == pos)
545                         break;
546         }
547
548         if (it != end && it->pos == pos)
549                 return it->inset;
550
551         lyxerr << "ERROR (Paragraph::getInset): "
552                << "Inset does not exist: " << pos << endl;
553         //::raise(SIGSTOP);
554
555         // text[pos] = ' '; // WHY!!! does this set the pos to ' '????
556         // Did this commenting out introduce a bug? So far I have not
557         // see any, please enlighten me. (Lgb)
558         // My guess is that since the inset does not exist, we might
559         // as well replace it with a space to prevent craches. (Asger)
560         return 0;
561 }
562
563
564 Inset const * Paragraph::getInset(pos_type pos) const
565 {
566         lyx::Assert(pos < size());
567
568         // Find the inset.
569         InsetList::const_iterator cit = insetlist.begin();
570         InsetList::const_iterator end = insetlist.end();
571         for (; cit != end; ++cit) {
572                 if (cit->pos == pos)
573                         break;
574         }
575
576         if (cit != end && cit->pos == pos)
577                 return cit->inset;
578
579         lyxerr << "ERROR (Paragraph::getInset): "
580                << "Inset does not exist: " << pos << endl;
581         //::raise(SIGSTOP);
582         //text[pos] = ' '; // WHY!!! does this set the pos to ' '????
583         // Did this commenting out introduce a bug? So far I have not
584         // see any, please enlighten me. (Lgb)
585         // My guess is that since the inset does not exist, we might
586         // as well replace it with a space to prevent craches. (Asger)
587         return 0;
588 }
589
590
591 // Gets uninstantiated font setting at position.
592 LyXFont const Paragraph::getFontSettings(BufferParams const & bparams,
593                                          pos_type pos) const
594 {
595         lyx::Assert(pos <= size());
596
597         Pimpl::FontList::const_iterator cit = pimpl_->fontlist.begin();
598         Pimpl::FontList::const_iterator end = pimpl_->fontlist.end();
599         for (; cit != end; ++cit) {
600                 if (cit->pos() >= pos)
601                         break;
602         }
603
604         LyXFont retfont;
605         if (cit != end) {
606                 retfont = cit->font();
607         } else if (pos == size() && size()) {
608                 retfont = getFontSettings(bparams, pos - 1);
609         } else
610                 retfont = LyXFont(LyXFont::ALL_INHERIT, getParLanguage(bparams));
611 #ifdef INHERIT_LANGUAGE
612         if (retfont.language() == inherit_language)
613                 retfont.setLanguage(bparams.language);
614 #endif
615
616         return retfont;
617 }
618
619
620 // Gets uninstantiated font setting at position 0
621 LyXFont const Paragraph::getFirstFontSettings() const
622 {
623         if (size() > 0 && !pimpl_->fontlist.empty())
624                 return pimpl_->fontlist[0].font();
625
626         return LyXFont(LyXFont::ALL_INHERIT);
627 }
628
629
630 // Gets the fully instantiated font at a given position in a paragraph
631 // This is basically the same function as LyXText::GetFont() in text2.C.
632 // The difference is that this one is used for generating the LaTeX file,
633 // and thus cosmetic "improvements" are disallowed: This has to deliver
634 // the true picture of the buffer. (Asger)
635 // If position is -1, we get the layout font of the paragraph.
636 // If position is -2, we get the font of the manual label of the paragraph.
637 LyXFont const Paragraph::getFont(BufferParams const & bparams,
638                                  pos_type pos) const
639 {
640         lyx::Assert(pos >= 0);
641
642         LyXLayout_ptr const & lout = layout();
643
644         pos_type main_body = 0;
645         if (lout->labeltype == LABEL_MANUAL)
646                 main_body = beginningOfMainBody();
647
648         LyXFont layoutfont;
649         if (pos < main_body)
650                 layoutfont = lout->labelfont;
651         else
652                 layoutfont = lout->font;
653
654         LyXFont tmpfont = getFontSettings(bparams, pos);
655 #ifndef INHERIT_LANGUAGE
656         tmpfont.realize(layoutfont);
657 #else
658         tmpfont.realize(layoutfont, bparams.language);
659 #endif
660
661         return pimpl_->realizeFont(tmpfont, bparams);
662 }
663
664
665 LyXFont const Paragraph::getLabelFont(BufferParams const & bparams) const
666 {
667         LyXLayout_ptr const & lout = layout();
668
669         LyXFont tmpfont = lout->labelfont;
670         tmpfont.setLanguage(getParLanguage(bparams));
671
672         return pimpl_->realizeFont(tmpfont, bparams);
673 }
674
675
676 LyXFont const Paragraph::getLayoutFont(BufferParams const & bparams) const
677 {
678         LyXLayout_ptr const & lout = layout();
679
680         LyXFont tmpfont = lout->font;
681         tmpfont.setLanguage(getParLanguage(bparams));
682
683         return pimpl_->realizeFont(tmpfont, bparams);
684 }
685
686
687 /// Returns the height of the highest font in range
688 LyXFont::FONT_SIZE
689 Paragraph::highestFontInRange(pos_type startpos, pos_type endpos,
690                               LyXFont::FONT_SIZE const def_size) const
691 {
692         if (pimpl_->fontlist.empty())
693                 return def_size;
694
695         Pimpl::FontList::const_iterator end_it = pimpl_->fontlist.begin();
696         Pimpl::FontList::const_iterator end = pimpl_->fontlist.end();
697         for (; end_it != end; ++end_it) {
698                 if (end_it->pos() >= endpos)
699                         break;
700         }
701
702         if (end_it != end)
703                 ++end_it;
704
705         Pimpl::FontList::const_iterator cit = pimpl_->fontlist.begin();
706         for (; cit != end; ++cit) {
707                 if (cit->pos() >= startpos)
708                         break;
709         }
710
711         LyXFont::FONT_SIZE maxsize = LyXFont::SIZE_TINY;
712         for (; cit != end_it; ++cit) {
713                 LyXFont::FONT_SIZE size = cit->font().size();
714                 if (size == LyXFont::INHERIT_SIZE)
715                         size = def_size;
716                 if (size > maxsize && size <= LyXFont::SIZE_HUGER)
717                         maxsize = size;
718         }
719         return maxsize;
720 }
721
722
723 Paragraph::value_type
724 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
725 {
726         value_type c = getChar(pos);
727         if (!lyxrc.rtl_support)
728                 return c;
729
730         value_type uc = c;
731         switch (c) {
732         case '(':
733                 uc = ')';
734                 break;
735         case ')':
736                 uc = '(';
737                 break;
738         case '[':
739                 uc = ']';
740                 break;
741         case ']':
742                 uc = '[';
743                 break;
744         case '{':
745                 uc = '}';
746                 break;
747         case '}':
748                 uc = '{';
749                 break;
750         case '<':
751                 uc = '>';
752                 break;
753         case '>':
754                 uc = '<';
755                 break;
756         }
757         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
758                 return uc;
759         else
760                 return c;
761 }
762
763
764 void Paragraph::setFont(pos_type pos, LyXFont const & font)
765 {
766         lyx::Assert(pos <= size());
767
768         // First, reduce font against layout/label font
769         // Update: The SetCharFont() routine in text2.C already
770         // reduces font, so we don't need to do that here. (Asger)
771         // No need to simplify this because it will disappear
772         // in a new kernel. (Asger)
773         // Next search font table
774
775         Pimpl::FontList::iterator beg = pimpl_->fontlist.begin();
776         Pimpl::FontList::iterator it = beg;
777         Pimpl::FontList::iterator endit = pimpl_->fontlist.end();
778         for (; it != endit; ++it) {
779                 if (it->pos() >= pos)
780                         break;
781         }
782         unsigned int i = std::distance(beg, it);
783         bool notfound = (it == endit);
784
785         if (!notfound && pimpl_->fontlist[i].font() == font)
786                 return;
787
788         bool begin = pos == 0 || notfound ||
789                 (i > 0 && pimpl_->fontlist[i - 1].pos() == pos - 1);
790         // Is position pos is a beginning of a font block?
791         bool end = !notfound && pimpl_->fontlist[i].pos() == pos;
792         // Is position pos is the end of a font block?
793         if (begin && end) { // A single char block
794                 if (i + 1 < pimpl_->fontlist.size() &&
795                     pimpl_->fontlist[i + 1].font() == font) {
796                         // Merge the singleton block with the next block
797                         pimpl_->fontlist.erase(pimpl_->fontlist.begin() + i);
798                         if (i > 0 && pimpl_->fontlist[i - 1].font() == font)
799                                 pimpl_->fontlist.erase(pimpl_->fontlist.begin() + i-1);
800                 } else if (i > 0 && pimpl_->fontlist[i - 1].font() == font) {
801                         // Merge the singleton block with the previous block
802                         pimpl_->fontlist[i - 1].pos(pos);
803                         pimpl_->fontlist.erase(pimpl_->fontlist.begin() + i);
804                 } else
805                         pimpl_->fontlist[i].font(font);
806         } else if (begin) {
807                 if (i > 0 && pimpl_->fontlist[i - 1].font() == font)
808                         pimpl_->fontlist[i - 1].pos(pos);
809                 else
810                         pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i,
811                                         Pimpl::FontTable(pos, font));
812         } else if (end) {
813                 pimpl_->fontlist[i].pos(pos - 1);
814                 if (!(i + 1 < pimpl_->fontlist.size() &&
815                       pimpl_->fontlist[i + 1].font() == font))
816                         pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i + 1,
817                                         Pimpl::FontTable(pos, font));
818         } else { // The general case. The block is splitted into 3 blocks
819                 pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i,
820                                 Pimpl::FontTable(pos - 1, pimpl_->fontlist[i].font()));
821                 pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i + 1,
822                                 Pimpl::FontTable(pos, font));
823         }
824 }
825
826
827
828 void Paragraph::next(Paragraph * p)
829 {
830         next_ = p;
831 }
832
833
834 // This function is able to hide closed footnotes.
835 Paragraph * Paragraph::next()
836 {
837         return next_;
838 }
839
840
841 Paragraph const * Paragraph::next() const
842 {
843         return next_;
844 }
845
846
847 void Paragraph::previous(Paragraph * p)
848 {
849         previous_ = p;
850 }
851
852
853 // This function is able to hide closed footnotes.
854 Paragraph * Paragraph::previous()
855 {
856         return previous_;
857 }
858
859
860 // This function is able to hide closed footnotes.
861 Paragraph const * Paragraph::previous() const
862 {
863         return previous_;
864 }
865
866
867 void Paragraph::breakParagraph(BufferParams const & bparams,
868                                   pos_type pos,
869                                   int flag)
870 {
871         // create a new paragraph
872         Paragraph * tmp = new Paragraph(this);
873         tmp->layout(textclasslist[bparams.textclass].defaultLayout());
874         // remember to set the inset_owner
875         tmp->setInsetOwner(inInset());
876
877         // this is an idea for a more userfriendly layout handling, I will
878         // see what the users say
879
880         // layout stays the same with latex-environments
881         if (flag) {
882                 tmp->layout(layout());
883                 tmp->setLabelWidthString(params().labelWidthString());
884         }
885
886         bool isempty = (layout()->keepempty && !size());
887
888         if (!isempty && (size() > pos || !size() || flag == 2)) {
889                 tmp->layout(layout());
890                 tmp->params().align(params().align());
891                 tmp->setLabelWidthString(params().labelWidthString());
892
893                 tmp->params().lineBottom(params().lineBottom());
894                 params().lineBottom(false);
895                 tmp->params().pagebreakBottom(params().pagebreakBottom());
896                 params().pagebreakBottom(false);
897                 tmp->params().spaceBottom(params().spaceBottom());
898                 params().spaceBottom(VSpace(VSpace::NONE));
899
900                 tmp->params().depth(params().depth());
901                 tmp->params().noindent(params().noindent());
902
903                 // copy everything behind the break-position
904                 // to the new paragraph
905                 pos_type pos_end = size() - 1;
906                 pos_type i = pos;
907                 pos_type j = pos;
908                 for (; i <= pos_end; ++i) {
909                         cutIntoMinibuffer(bparams, i);
910                         if (tmp->insertFromMinibuffer(j - pos))
911                                 ++j;
912                 }
913                 for (i = pos_end; i >= pos; --i) {
914                         erase(i);
915                 }
916         }
917
918         // just an idea of me
919         if (!isempty && !pos) {
920                 tmp->params().lineTop(params().lineTop());
921                 tmp->params().pagebreakTop(params().pagebreakTop());
922                 tmp->params().spaceTop(params().spaceTop());
923                 tmp->bibkey = bibkey;
924
925                 bibkey = 0;
926                 params().clear();
927
928                 layout(textclasslist[bparams.textclass].defaultLayout());
929
930                 // layout stays the same with latex-environments
931                 if (flag) {
932                         layout(tmp->layout());
933                         setLabelWidthString(tmp->params().labelWidthString());
934                         params().depth(tmp->params().depth());
935                 }
936         }
937 }
938
939
940 void Paragraph::makeSameLayout(Paragraph const * par)
941 {
942         layout(par->layout());
943         // move to pimpl?
944         params() = par->params();
945 }
946
947
948 int Paragraph::stripLeadingSpaces()
949 {
950         if (layout()->free_spacing ||
951             isFreeSpacing()) {
952                 return 0;
953         }
954
955         int i = 0;
956         while (size() && (isNewline(0) || isLineSeparator(0))) {
957                 erase(0);
958                 ++i;
959         }
960
961         return i;
962 }
963
964
965 bool Paragraph::hasSameLayout(Paragraph const * par) const
966 {
967         return
968                 par->layout() == layout() &&
969                 params().sameLayout(par->params());
970 }
971
972
973 void Paragraph::breakParagraphConservative(BufferParams const & bparams,
974                                            pos_type pos)
975 {
976         // create a new paragraph
977         Paragraph * tmp = new Paragraph(this);
978         tmp->makeSameLayout(this);
979
980         // When can pos > Last()?
981         // I guess pos == Last() is possible.
982         if (size() > pos) {
983                 // copy everything behind the break-position to the new
984                 // paragraph
985                 pos_type pos_end = size() - 1;
986
987                 //pos_type i = pos;
988                 //pos_type j = pos;
989                 for (pos_type i = pos, j = pos; i <= pos_end; ++i) {
990                         cutIntoMinibuffer(bparams, i);
991                         if (tmp->insertFromMinibuffer(j - pos))
992                                 ++j;
993                 }
994
995                 for (pos_type k = pos_end; k >= pos; --k) {
996                         erase(k);
997                 }
998         }
999 }
1000
1001
1002 // Be carefull, this does not make any check at all.
1003 // This method has wrong name, it combined this par with the next par.
1004 // In that sense it is the reverse of break paragraph. (Lgb)
1005 void Paragraph::pasteParagraph(BufferParams const & bparams)
1006 {
1007         // copy the next paragraph to this one
1008         Paragraph * the_next = next();
1009
1010         // first the DTP-stuff
1011         params().lineBottom(the_next->params().lineBottom());
1012         params().spaceBottom(the_next->params().spaceBottom());
1013         params().pagebreakBottom(the_next->params().pagebreakBottom());
1014
1015         pos_type pos_end = the_next->pimpl_->size() - 1;
1016         pos_type pos_insert = size();
1017
1018         // ok, now copy the paragraph
1019         for (pos_type i = 0, j = 0; i <= pos_end; ++i) {
1020                 the_next->cutIntoMinibuffer(bparams, i);
1021                 if (insertFromMinibuffer(pos_insert + j))
1022                         ++j;
1023         }
1024
1025         // delete the next paragraph
1026         Paragraph * ppar = the_next->previous_;
1027         Paragraph * npar = the_next->next_;
1028         delete the_next;
1029         ppar->next(npar);
1030 }
1031
1032
1033 int Paragraph::getEndLabel() const
1034 {
1035         Paragraph const * par = this;
1036         depth_type par_depth = getDepth();
1037         while (par) {
1038                 LyXLayout_ptr const & layout = par->layout();
1039                 int const endlabeltype = layout->endlabeltype;
1040
1041                 if (endlabeltype != END_LABEL_NO_LABEL) {
1042                         if (!next_)
1043                                 return endlabeltype;
1044
1045                         depth_type const next_depth = next_->getDepth();
1046                         if (par_depth > next_depth ||
1047                             (par_depth == next_depth
1048                              && layout != next_->layout()))
1049                                 return endlabeltype;
1050                         break;
1051                 }
1052                 if (par_depth == 0)
1053                         break;
1054                 par = par->outerHook();
1055                 if (par)
1056                         par_depth = par->getDepth();
1057         }
1058         return END_LABEL_NO_LABEL;
1059 }
1060
1061
1062 Paragraph::depth_type Paragraph::getDepth() const
1063 {
1064         return params().depth();
1065 }
1066
1067
1068 Paragraph::depth_type Paragraph::getMaxDepthAfter() const
1069 {
1070         bool const isenv = layout()->isEnvironment();
1071
1072         if (isenv)
1073                 return params().depth() + 1;
1074         else
1075                 return params().depth();
1076
1077 }
1078
1079 char Paragraph::getAlign() const
1080 {
1081         return params().align();
1082 }
1083
1084
1085 string const & Paragraph::getLabelstring() const
1086 {
1087         return params().labelString();
1088 }
1089
1090
1091 int Paragraph::getFirstCounter(int i) const
1092 {
1093         return pimpl_->counter_[i];
1094 }
1095
1096
1097 // the next two functions are for the manual labels
1098 string const Paragraph::getLabelWidthString() const
1099 {
1100         if (!params().labelWidthString().empty())
1101                 return params().labelWidthString();
1102         else
1103                 return _("Senseless with this layout!");
1104 }
1105
1106
1107 void Paragraph::setLabelWidthString(string const & s)
1108 {
1109         params().labelWidthString(s);
1110 }
1111
1112
1113 void Paragraph::applyLayout(LyXLayout_ptr const & new_layout)
1114 {
1115         layout(new_layout);
1116         params().labelWidthString(string());
1117         params().align(LYX_ALIGN_LAYOUT);
1118         params().spaceTop(VSpace(VSpace::NONE));
1119         params().spaceBottom(VSpace(VSpace::NONE));
1120         params().spacing(Spacing(Spacing::Default));
1121 }
1122
1123
1124 // if the layout of a paragraph contains a manual label, the beginning of the
1125 // main body is the beginning of the second word. This is what the par-
1126 // function returns. If the layout does not contain a label, the main
1127 // body always starts with position 0. This differentiation is necessary,
1128 // because there cannot be a newline or a blank <= the beginning of the
1129 // main body in TeX.
1130
1131 int Paragraph::beginningOfMainBody() const
1132 {
1133         // Unroll the first two cycles of the loop
1134         // and remember the previous character to
1135         // remove unnecessary GetChar() calls
1136         pos_type i = 0;
1137         if (i < size() && getChar(i) != Paragraph::META_NEWLINE) {
1138                 ++i;
1139                 char previous_char = 0;
1140                 char temp = 0;
1141                 if (i < size()
1142                     && (previous_char = getChar(i)) != Paragraph::META_NEWLINE) {
1143                         // Yes, this  ^ is supposed to be "= " not "=="
1144                         ++i;
1145                         while (i < size()
1146                                && previous_char != ' '
1147                                && (temp = getChar(i)) != Paragraph::META_NEWLINE) {
1148                                 ++i;
1149                                 previous_char = temp;
1150                         }
1151                 }
1152         }
1153
1154         return i;
1155 }
1156
1157
1158 Paragraph * Paragraph::depthHook(depth_type depth)
1159 {
1160         Paragraph * newpar = this;
1161
1162         do {
1163                 newpar = newpar->previous();
1164         } while (newpar && newpar->getDepth() > depth);
1165
1166         if (!newpar) {
1167                 if (previous() || getDepth())
1168                         lyxerr << "ERROR (Paragraph::DepthHook): "
1169                                 "no hook." << endl;
1170                 newpar = this;
1171         }
1172
1173         return newpar;
1174 }
1175
1176
1177 Paragraph const * Paragraph::depthHook(depth_type depth) const
1178 {
1179         Paragraph const * newpar = this;
1180
1181         do {
1182                 newpar = newpar->previous();
1183         } while (newpar && newpar->getDepth() > depth);
1184
1185         if (!newpar) {
1186                 if (previous() || getDepth())
1187                         lyxerr << "ERROR (Paragraph::DepthHook): "
1188                                 "no hook." << endl;
1189                 newpar = this;
1190         }
1191
1192         return newpar;
1193 }
1194
1195 Paragraph * Paragraph::outerHook()
1196 {
1197         if (!getDepth())
1198                 return 0;
1199         return depthHook(depth_type(getDepth() - 1));
1200 }
1201
1202 Paragraph const * Paragraph::outerHook() const
1203 {
1204         if (!getDepth())
1205                 return 0;
1206         return depthHook(depth_type(getDepth() - 1));
1207 }
1208
1209
1210 Paragraph::inset_iterator
1211 Paragraph::InsetIterator(pos_type pos)
1212 {
1213         InsetList::iterator it = insetlist.begin();
1214         InsetList::iterator end = insetlist.end();
1215         for (; it != end; ++it) {
1216                 if (it->pos >= pos)
1217                         break;
1218         }
1219
1220         return inset_iterator(it);
1221 }
1222
1223
1224 // returns -1 if inset not found
1225 int Paragraph::getPositionOfInset(Inset const * inset) const
1226 {
1227         // Find the entry.
1228         InsetList::const_iterator cit = insetlist.begin();
1229         InsetList::const_iterator end = insetlist.end();
1230         for (; cit != end; ++cit) {
1231                 if (cit->inset == inset) {
1232                         return cit->pos;
1233                 }
1234         }
1235         if (inset == bibkey)
1236                 return 0;
1237
1238         return -1;
1239 }
1240
1241
1242 Paragraph * Paragraph::TeXOnePar(Buffer const * buf,
1243                                  BufferParams const & bparams,
1244                                  ostream & os, TexRow & texrow,
1245                                  bool moving_arg)
1246 {
1247         lyxerr[Debug::LATEX] << "TeXOnePar...     " << this << endl;
1248         Inset const * in = inInset();
1249         bool further_blank_line = false;
1250         LyXLayout_ptr style;
1251
1252         // well we have to check if we are in an inset with unlimited
1253         // lenght (all in one row) if that is true then we don't allow
1254         // any special options in the paragraph and also we don't allow
1255         // any environment other then "Standard" to be valid!
1256         if ((in == 0) || !in->forceDefaultParagraphs(in)) {
1257                 style = layout();
1258
1259                 if (params().startOfAppendix()) {
1260                         os << "\\appendix\n";
1261                         texrow.newline();
1262                 }
1263
1264                 if (!params().spacing().isDefault()
1265                         && (!previous() || !previous()->hasSameLayout(this))) {
1266                         os << params().spacing().writeEnvirBegin() << "\n";
1267                         texrow.newline();
1268                 }
1269
1270                 if (tex_code_break_column && style->isCommand()) {
1271                         os << '\n';
1272                         texrow.newline();
1273                 }
1274
1275                 if (params().pagebreakTop()) {
1276                         os << "\\newpage";
1277                         further_blank_line = true;
1278                 }
1279                 if (params().spaceTop().kind() != VSpace::NONE) {
1280                         os << params().spaceTop().asLatexCommand(bparams);
1281                         further_blank_line = true;
1282                 }
1283
1284                 if (params().lineTop()) {
1285                         os << "\\lyxline{\\" << getFont(bparams, 0).latexSize() << '}'
1286                            << "\\vspace{-1\\parskip}";
1287                         further_blank_line = true;
1288                 }
1289
1290                 if (further_blank_line) {
1291                         os << '\n';
1292                         texrow.newline();
1293                 }
1294         } else {
1295                 style = textclasslist[bparams.textclass].defaultLayout();
1296         }
1297
1298         Language const * language = getParLanguage(bparams);
1299         Language const * doc_language = bparams.language;
1300         Language const * previous_language = previous()
1301                 ? previous()->getParLanguage(bparams) : doc_language;
1302
1303         if (language->babel() != previous_language->babel()
1304             // check if we already put language command in TeXEnvironment()
1305             && !(style->isEnvironment()
1306                  && (!previous() || previous()->layout() != layout() ||
1307                          previous()->params().depth() != params().depth())))
1308         {
1309                 if (!lyxrc.language_command_end.empty() &&
1310                     previous_language->babel() != doc_language->babel())
1311                 {
1312                         os << subst(lyxrc.language_command_end, "$$lang",
1313                                     previous_language->babel())
1314                            << endl;
1315                         texrow.newline();
1316                 }
1317
1318                 if (lyxrc.language_command_end.empty() ||
1319                     language->babel() != doc_language->babel())
1320                 {
1321                         os << subst(lyxrc.language_command_begin, "$$lang",
1322                                     language->babel())
1323                            << endl;
1324                         texrow.newline();
1325                 }
1326         }
1327
1328         if (bparams.inputenc == "auto" &&
1329             language->encoding() != previous_language->encoding()) {
1330                 os << "\\inputencoding{"
1331                    << language->encoding()->LatexName()
1332                    << "}" << endl;
1333                 texrow.newline();
1334         }
1335
1336         switch (style->latextype) {
1337         case LATEX_COMMAND:
1338                 os << '\\'
1339                    << style->latexname()
1340                    << style->latexparam();
1341                 break;
1342         case LATEX_ITEM_ENVIRONMENT:
1343                 if (bibkey) {
1344                         bibkey->latex(buf, os, false, false);
1345                 } else
1346                         os << "\\item ";
1347                 break;
1348         case LATEX_LIST_ENVIRONMENT:
1349                 os << "\\item ";
1350                 break;
1351         default:
1352                 break;
1353         }
1354
1355         bool need_par = simpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
1356
1357         // Make sure that \\par is done with the font of the last
1358         // character if this has another size as the default.
1359         // This is necessary because LaTeX (and LyX on the screen)
1360         // calculates the space between the baselines according
1361         // to this font. (Matthias)
1362         //
1363         // Is this really needed ? (Dekel)
1364         // We do not need to use to change the font for the last paragraph
1365         // or for a command.
1366         LyXFont const font =
1367                 (size() == 0
1368                  ? getLayoutFont(bparams) : getFont(bparams, size() - 1));
1369
1370         bool is_command = style->isCommand();
1371
1372         if (style->resfont.size() != font.size() && next_ && !is_command) {
1373                 if (!need_par)
1374                         os << "{";
1375                 os << "\\" << font.latexSize() << " \\par}";
1376         } else if (need_par) {
1377                 os << "\\par}";
1378         } else if (is_command)
1379                 os << "}";
1380
1381         switch (style->latextype) {
1382         case LATEX_ITEM_ENVIRONMENT:
1383         case LATEX_LIST_ENVIRONMENT:
1384                 if (next_ && (params().depth() < next_->params().depth())) {
1385                         os << '\n';
1386                         texrow.newline();
1387                 }
1388                 break;
1389         case LATEX_ENVIRONMENT:
1390                 // if its the last paragraph of the current environment
1391                 // skip it otherwise fall through
1392                 if (next_
1393                     && (next_->layout() != layout()
1394                         || next_->params().depth() != params().depth()))
1395                         break;
1396                 // fall through possible
1397         default:
1398                 // we don't need it for the last paragraph!!!
1399                 if (next_) {
1400                         os << '\n';
1401                         texrow.newline();
1402                 }
1403         }
1404
1405         if ((in == 0) || !in->forceDefaultParagraphs(in)) {
1406                 further_blank_line = false;
1407                 if (params().lineBottom()) {
1408                         os << "\\lyxline{\\" << font.latexSize() << '}';
1409                         further_blank_line = true;
1410                 }
1411
1412                 if (params().spaceBottom().kind() != VSpace::NONE) {
1413                         os << params().spaceBottom().asLatexCommand(bparams);
1414                         further_blank_line = true;
1415                 }
1416
1417                 if (params().pagebreakBottom()) {
1418                         os << "\\newpage";
1419                         further_blank_line = true;
1420                 }
1421
1422                 if (further_blank_line) {
1423                         os << '\n';
1424                         texrow.newline();
1425                 }
1426
1427                 if (!params().spacing().isDefault()
1428                         && (!next_ || !next_->hasSameLayout(this))) {
1429                         os << params().spacing().writeEnvirEnd() << "\n";
1430                         texrow.newline();
1431                 }
1432         }
1433
1434         // we don't need it for the last paragraph!!!
1435         if (next_) {
1436                 os << '\n';
1437                 texrow.newline();
1438         } else {
1439                 // Since \selectlanguage write the language to the aux file,
1440                 // we need to reset the language at the end of footnote or
1441                 // float.
1442
1443                 if (language->babel() != doc_language->babel()) {
1444                         if (lyxrc.language_command_end.empty())
1445                                 os << subst(lyxrc.language_command_begin,
1446                                             "$$lang",
1447                                             doc_language->babel())
1448                                    << endl;
1449                         else
1450                                 os << subst(lyxrc.language_command_end,
1451                                             "$$lang",
1452                                             language->babel())
1453                                    << endl;
1454                         texrow.newline();
1455                 }
1456         }
1457
1458         lyxerr[Debug::LATEX] << "TeXOnePar...done " << next_ << endl;
1459         return next_;
1460 }
1461
1462 // This could go to ParagraphParameters if we want to
1463 int Paragraph::startTeXParParams(BufferParams const & bparams,
1464                                  ostream & os) const
1465 {
1466         int column = 0;
1467
1468         if (params().noindent()) {
1469                 os << "\\noindent ";
1470                 column += 10;
1471         }
1472
1473         switch (params().align()) {
1474         case LYX_ALIGN_NONE:
1475         case LYX_ALIGN_BLOCK:
1476         case LYX_ALIGN_LAYOUT:
1477         case LYX_ALIGN_SPECIAL:
1478                 break;
1479         case LYX_ALIGN_LEFT:
1480                 if (getParLanguage(bparams)->babel() != "hebrew") {
1481                         os << "\\begin{flushleft}";
1482                         column += 17;
1483                 } else {
1484                         os << "\\begin{flushright}";
1485                         column += 18;
1486                 }
1487                 break;
1488         case LYX_ALIGN_RIGHT:
1489                 if (getParLanguage(bparams)->babel() != "hebrew") {
1490                         os << "\\begin{flushright}";
1491                         column += 18;
1492                 } else {
1493                         os << "\\begin{flushleft}";
1494                         column += 17;
1495                 }
1496                 break;
1497         case LYX_ALIGN_CENTER:
1498                 os << "\\begin{center}";
1499                 column += 14;
1500                 break;
1501         }
1502
1503         return column;
1504 }
1505
1506 // This could go to ParagraphParameters if we want to
1507 int Paragraph::endTeXParParams(BufferParams const & bparams,
1508                                ostream & os) const
1509 {
1510         int column = 0;
1511
1512         switch (params().align()) {
1513         case LYX_ALIGN_NONE:
1514         case LYX_ALIGN_BLOCK:
1515         case LYX_ALIGN_LAYOUT:
1516         case LYX_ALIGN_SPECIAL:
1517                 break;
1518         case LYX_ALIGN_LEFT:
1519                 if (getParLanguage(bparams)->babel() != "hebrew") {
1520                         os << "\\end{flushleft}";
1521                         column = 15;
1522                 } else {
1523                         os << "\\end{flushright}";
1524                         column = 16;
1525                 }
1526                 break;
1527         case LYX_ALIGN_RIGHT:
1528                 if (getParLanguage(bparams)->babel() != "hebrew") {
1529                         os << "\\end{flushright}";
1530                         column+= 16;
1531                 } else {
1532                         os << "\\end{flushleft}";
1533                         column = 15;
1534                 }
1535                 break;
1536         case LYX_ALIGN_CENTER:
1537                 os << "\\end{center}";
1538                 column = 12;
1539                 break;
1540         }
1541         return column;
1542 }
1543
1544
1545 // This one spits out the text of the paragraph
1546 bool Paragraph::simpleTeXOnePar(Buffer const * buf,
1547                                 BufferParams const & bparams,
1548                                 ostream & os, TexRow & texrow,
1549                                 bool moving_arg)
1550 {
1551         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...     " << this << endl;
1552
1553         bool return_value = false;
1554
1555         LyXLayout_ptr style;
1556
1557         // well we have to check if we are in an inset with unlimited
1558         // lenght (all in one row) if that is true then we don't allow
1559         // any special options in the paragraph and also we don't allow
1560         // any environment other then "Standard" to be valid!
1561         bool asdefault =
1562                 (inInset() && inInset()->forceDefaultParagraphs(inInset()));
1563
1564         if (asdefault) {
1565                 style = textclasslist[bparams.textclass].defaultLayout();
1566         } else {
1567                 style = layout();
1568         }
1569
1570         LyXFont basefont;
1571
1572         // Maybe we have to create a optional argument.
1573         pos_type main_body;
1574         if (style->labeltype != LABEL_MANUAL)
1575                 main_body = 0;
1576         else
1577                 main_body = beginningOfMainBody();
1578
1579         int column = 0;
1580
1581         if (main_body > 0) {
1582                 os << '[';
1583                 ++column;
1584                 basefont = getLabelFont(bparams);
1585         } else {
1586                 basefont = getLayoutFont(bparams);
1587         }
1588
1589         moving_arg |= style->needprotect;
1590
1591         // Which font is currently active?
1592         LyXFont running_font(basefont);
1593         // Do we have an open font change?
1594         bool open_font = false;
1595
1596         texrow.start(this, 0);
1597
1598         // if the paragraph is empty, the loop will not be entered at all
1599         if (!size()) {
1600                 if (style->isCommand()) {
1601                         os << '{';
1602                         ++column;
1603                 }
1604                 if (!asdefault)
1605                         column += startTeXParParams(bparams, os);
1606
1607         }
1608
1609         for (pos_type i = 0; i < size(); ++i) {
1610                 ++column;
1611                 // First char in paragraph or after label?
1612                 if (i == main_body) {
1613                         if (main_body > 0) {
1614                                 if (open_font) {
1615                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1616                                         open_font = false;
1617                                 }
1618                                 basefont = getLayoutFont(bparams);
1619                                 running_font = basefont;
1620                                 os << ']';
1621                                 ++column;
1622                         }
1623                         if (style->isCommand()) {
1624                                 os << '{';
1625                                 ++column;
1626                         }
1627
1628                         if (!asdefault)
1629                                 column += startTeXParParams(bparams, os);
1630                 }
1631
1632                 value_type c = getChar(i);
1633
1634                 // Fully instantiated font
1635                 LyXFont font = getFont(bparams, i);
1636
1637                 LyXFont const last_font = running_font;
1638
1639                 // Spaces at end of font change are simulated to be
1640                 // outside font change, i.e. we write "\textXX{text} "
1641                 // rather than "\textXX{text }". (Asger)
1642                 if (open_font && c == ' ' && i <= size() - 2) {
1643                         LyXFont const & next_font = getFont(bparams, i + 1);
1644                         if (next_font != running_font
1645                             && next_font != font) {
1646                                 font = next_font;
1647                         }
1648                 }
1649
1650                 // We end font definition before blanks
1651                 if (open_font &&
1652                     (font != running_font ||
1653                      font.language() != running_font.language()))
1654                 {
1655                         column += running_font.latexWriteEndChanges(os,
1656                                                                     basefont,
1657                                                                     (i == main_body-1) ? basefont : font);
1658                         running_font = basefont;
1659                         open_font = false;
1660                 }
1661
1662                 // Blanks are printed before start of fontswitch
1663                 if (c == ' ') {
1664                         // Do not print the separation of the optional argument
1665                         if (i != main_body - 1) {
1666                                 pimpl_->simpleTeXBlanks(os, texrow, i,
1667                                                        column, font, *style);
1668                         }
1669                 }
1670
1671                 // Do we need to change font?
1672                 if ((font != running_font ||
1673                      font.language() != running_font.language()) &&
1674                         i != main_body - 1)
1675                 {
1676                         column += font.latexWriteStartChanges(os, basefont,
1677                                                               last_font);
1678                         running_font = font;
1679                         open_font = true;
1680                 }
1681
1682                 if (c == Paragraph::META_NEWLINE) {
1683                         // newlines are handled differently here than
1684                         // the default in SimpleTeXSpecialChars().
1685                         if (!style->newline_allowed) {
1686                                 os << '\n';
1687                         } else {
1688                                 if (open_font) {
1689                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1690                                         open_font = false;
1691                                 }
1692                                 basefont = getLayoutFont(bparams);
1693                                 running_font = basefont;
1694                                 if (font.family() ==
1695                                     LyXFont::TYPEWRITER_FAMILY) {
1696                                         os << "~";
1697                                 }
1698                                 if (moving_arg)
1699                                         os << "\\protect ";
1700
1701                                 os << "\\\\\n";
1702                         }
1703                         texrow.newline();
1704                         texrow.start(this, i + 1);
1705                         column = 0;
1706                 } else {
1707                         pimpl_->simpleTeXSpecialChars(buf, bparams,
1708                                                       os, texrow, moving_arg,
1709                                                       font, running_font,
1710                                                       basefont, open_font,
1711                                                       *style, i, column, c);
1712                 }
1713         }
1714
1715         // If we have an open font definition, we have to close it
1716         if (open_font) {
1717 #ifdef FIXED_LANGUAGE_END_DETECTION
1718                 if (next_) {
1719                         running_font
1720                                 .latexWriteEndChanges(os, basefont,
1721                                                       next_->getFont(bparams,
1722                                                       0));
1723                 } else {
1724                         running_font.latexWriteEndChanges(os, basefont,
1725                                                           basefont);
1726                 }
1727 #else
1728 #ifdef WITH_WARNINGS
1729 //#warning For now we ALWAYS have to close the foreign font settings if they are
1730 //#warning there as we start another \selectlanguage with the next paragraph if
1731 //#warning we are in need of this. This should be fixed sometime (Jug)
1732 #endif
1733                 running_font.latexWriteEndChanges(os, basefont,  basefont);
1734 #endif
1735         }
1736
1737         // Needed if there is an optional argument but no contents.
1738         if (main_body > 0 && main_body == size()) {
1739                 os << "]~";
1740                 return_value = false;
1741         }
1742
1743         if (!asdefault) {
1744                 column += endTeXParParams(bparams, os);
1745         }
1746
1747         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...done " << this << endl;
1748         return return_value;
1749 }
1750
1751
1752 bool Paragraph::sgmlConvertChar(char c, string & sgml_string)
1753 {
1754         bool retval = false;
1755         switch (c) {
1756         case Paragraph::META_HFILL:
1757                 sgml_string.erase();
1758                 break;
1759         case Paragraph::META_NEWLINE:
1760                 sgml_string = '\n';
1761                 break;
1762         case '&':
1763                 sgml_string = "&amp;";
1764                 break;
1765         case '<':
1766                 sgml_string = "&lt;";
1767                 break;
1768         case '>':
1769                 sgml_string = "&gt;";
1770                 break;
1771         case '$':
1772                 sgml_string = "&dollar;";
1773                 break;
1774         case '#':
1775                 sgml_string = "&num;";
1776                 break;
1777         case '%':
1778                 sgml_string = "&percnt;";
1779                 break;
1780         case '[':
1781                 sgml_string = "&lsqb;";
1782                 break;
1783         case ']':
1784                 sgml_string = "&rsqb;";
1785                 break;
1786         case '{':
1787                 sgml_string = "&lcub;";
1788                 break;
1789         case '}':
1790                 sgml_string = "&rcub;";
1791                 break;
1792         case '~':
1793                 sgml_string = "&tilde;";
1794                 break;
1795         case '"':
1796                 sgml_string = "&quot;";
1797                 break;
1798         case '\\':
1799                 sgml_string = "&bsol;";
1800                 break;
1801         case ' ':
1802                 retval = true;
1803                 sgml_string = ' ';
1804                 break;
1805         case '\0': // Ignore :-)
1806                 sgml_string.erase();
1807                 break;
1808         default:
1809                 sgml_string = c;
1810                 break;
1811         }
1812         return retval;
1813 }
1814
1815
1816 Paragraph * Paragraph::TeXEnvironment(Buffer const * buf,
1817                                             BufferParams const & bparams,
1818                                             ostream & os, TexRow & texrow)
1819 {
1820         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << this << endl;
1821
1822         LyXLayout_ptr const & style = layout();
1823
1824         Language const * language = getParLanguage(bparams);
1825         Language const * doc_language = bparams.language;
1826         Language const * previous_language = previous_
1827                 ? previous_->getParLanguage(bparams) : doc_language;
1828         if (language->babel() != previous_language->babel()) {
1829
1830                 if (!lyxrc.language_command_end.empty() &&
1831                     previous_language->babel() != doc_language->babel()) {
1832                         os << subst(lyxrc.language_command_end, "$$lang",
1833                                     previous_language->babel())
1834                            << endl;
1835                         texrow.newline();
1836                 }
1837
1838                 if (lyxrc.language_command_end.empty() ||
1839                     language->babel() != doc_language->babel()) {
1840                         os << subst(lyxrc.language_command_begin, "$$lang",
1841                                     language->babel())
1842                            << endl;
1843                         texrow.newline();
1844                 }
1845         }
1846
1847         bool leftindent_open = false;
1848         if (!params().leftIndent().zero()) {
1849                 os << "\\begin{LyXParagraphLeftIndent}{" <<
1850                         params().leftIndent().asLatexString() << "}\n";
1851                 texrow.newline();
1852                 leftindent_open = true;
1853         }
1854
1855         if (style->isEnvironment()) {
1856                 if (style->latextype == LATEX_LIST_ENVIRONMENT) {
1857                         os << "\\begin{" << style->latexname() << "}{"
1858                            << params().labelWidthString() << "}\n";
1859                 } else if (style->labeltype == LABEL_BIBLIO) {
1860                         // ale970405
1861                         os << "\\begin{" << style->latexname() << "}{"
1862                            <<  bibitemWidest(buf)
1863                            << "}\n";
1864                 } else if (style->latextype == LATEX_ITEM_ENVIRONMENT) {
1865                         os << "\\begin{" << style->latexname() << '}'
1866                            << style->latexparam() << '\n';
1867                 } else
1868                         os << "\\begin{" << style->latexname() << '}'
1869                            << style->latexparam() << '\n';
1870                 texrow.newline();
1871         }
1872         Paragraph * par = this;
1873         do {
1874                 par = par->TeXOnePar(buf, bparams, os, texrow, false);
1875
1876                 if (par && par->params().depth() > params().depth()) {
1877                             if (par->layout()->isParagraph()) {
1878
1879                             // Thinko!
1880                             // How to handle this? (Lgb)
1881                             //&& !suffixIs(os, "\n\n")
1882                                     //) {
1883                                 // There should be at least one '\n' already
1884                                 // but we need there to be two for Standard
1885                                 // paragraphs that are depth-increment'ed to be
1886                                 // output correctly.  However, tables can
1887                                 // also be paragraphs so don't adjust them.
1888                                 // ARRae
1889                                 // Thinkee:
1890                                 // Will it ever harm to have one '\n' too
1891                                 // many? i.e. that we sometimes will have
1892                                 // three in a row. (Lgb)
1893                                 os << '\n';
1894                                 texrow.newline();
1895                         }
1896                         par = par->pimpl_->TeXDeeper(buf, bparams, os, texrow);
1897                 }
1898         } while (par
1899                  && par->layout() == layout()
1900                  && par->params().depth() == params().depth()
1901                  && par->params().leftIndent() == params().leftIndent());
1902
1903         if (style->isEnvironment()) {
1904                 os << "\\end{" << style->latexname() << "}\n";
1905                 texrow.newline();
1906         }
1907
1908         if (leftindent_open) {
1909                 os << "\\end{LyXParagraphLeftIndent}\n";
1910                 texrow.newline();
1911         }
1912
1913         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << par << endl;
1914         return par;  // ale970302
1915 }
1916
1917
1918 bool Paragraph::isHfill(pos_type pos) const
1919 {
1920         return IsHfillChar(getChar(pos));
1921 }
1922
1923
1924 bool Paragraph::isInset(pos_type pos) const
1925 {
1926         return IsInsetChar(getChar(pos));
1927 }
1928
1929
1930 bool Paragraph::isNewline(pos_type pos) const
1931 {
1932         return pos >= 0 && IsNewlineChar(getChar(pos));
1933 }
1934
1935
1936 bool Paragraph::isSeparator(pos_type pos) const
1937 {
1938         return IsSeparatorChar(getChar(pos));
1939 }
1940
1941
1942 bool Paragraph::isLineSeparator(pos_type pos) const
1943 {
1944         value_type const c = getChar(pos);
1945         return IsLineSeparatorChar(c)
1946                 || (IsInsetChar(c) && getInset(pos) &&
1947                 getInset(pos)->isLineSeparator());
1948 }
1949
1950
1951 bool Paragraph::isKomma(pos_type pos) const
1952 {
1953         return IsKommaChar(getChar(pos));
1954 }
1955
1956
1957 /// Used by the spellchecker
1958 bool Paragraph::isLetter(pos_type pos) const
1959 {
1960         value_type const c = getChar(pos);
1961         if (IsLetterChar(c))
1962                 return true;
1963         if (isInset(pos))
1964                 return getInset(pos)->isLetter();
1965         // We want to pass the ' and escape chars to ispell
1966         string const extra = lyxrc.isp_esc_chars + '\'';
1967         return contains(extra, c);
1968 }
1969
1970
1971 bool Paragraph::isWord(pos_type pos) const
1972 {
1973         return IsWordChar(getChar(pos)) ;
1974 }
1975
1976
1977 Language const *
1978 Paragraph::getParLanguage(BufferParams const & bparams) const
1979 {
1980         if (size() > 0) {
1981 #ifndef INHERIT_LANGUAGE
1982                 return getFirstFontSettings().language();
1983 #else
1984                 Language const * lang = getFirstFontSettings().language();
1985 #ifdef WITH_WARNINGS
1986 #warning We should make this somewhat better, any ideas? (Jug)
1987 #endif
1988                 if (lang == inherit_language || lang == ignore_language)
1989                         lang = bparams.language;
1990                 return lang;
1991 #endif
1992         } else if (previous_)
1993                 return previous_->getParLanguage(bparams);
1994         else
1995                 return bparams.language;
1996 }
1997
1998
1999 bool Paragraph::isRightToLeftPar(BufferParams const & bparams) const
2000 {
2001         return lyxrc.rtl_support
2002                 && getParLanguage(bparams)->RightToLeft()
2003                 && !(inInset() && inInset()->owner() &&
2004                      inInset()->owner()->lyxCode() == Inset::ERT_CODE);
2005 }
2006
2007
2008 void Paragraph::changeLanguage(BufferParams const & bparams,
2009                                   Language const * from, Language const * to)
2010 {
2011         for (pos_type i = 0; i < size(); ++i) {
2012                 LyXFont font = getFontSettings(bparams, i);
2013                 if (font.language() == from) {
2014                         font.setLanguage(to);
2015                         setFont(i, font);
2016                 }
2017         }
2018 }
2019
2020
2021 bool Paragraph::isMultiLingual(BufferParams const & bparams)
2022 {
2023         Language const * doc_language = bparams.language;
2024         Pimpl::FontList::const_iterator cit = pimpl_->fontlist.begin();
2025         Pimpl::FontList::const_iterator end = pimpl_->fontlist.end();
2026
2027         for (; cit != end; ++cit)
2028                 if (cit->font().language() != ignore_language &&
2029                     cit->font().language() != latex_language &&
2030 #ifdef INHERIT_LANGUAGE
2031                         cit->font().language() != inherit_language &&
2032 #endif
2033                         cit->font().language() != doc_language)
2034                         return true;
2035         return false;
2036 }
2037
2038
2039 // Convert the paragraph to a string.
2040 // Used for building the table of contents
2041 string const Paragraph::asString(Buffer const * buffer, bool label)
2042 {
2043         BufferParams const & bparams = buffer->params;
2044         string s;
2045         if (label && !params().labelString().empty())
2046                 s += params().labelString() + ' ';
2047         string::size_type const len = s.size();
2048
2049         for (pos_type i = 0; i < size(); ++i) {
2050                 value_type c = getChar(i);
2051                 if (IsPrintable(c))
2052                         s += c;
2053                 else if (c == META_INSET &&
2054                          getInset(i)->lyxCode() == Inset::MATH_CODE) {
2055                         ostringstream ost;
2056                         getInset(i)->ascii(buffer, ost);
2057                         s += subst(ost.str().c_str(),'\n',' ');
2058                 }
2059         }
2060
2061         if (isRightToLeftPar(bparams))
2062                 reverse(s.begin() + len,s.end());
2063
2064         return s;
2065 }
2066
2067
2068 string const Paragraph::asString(Buffer const * buffer,
2069                                  pos_type beg, pos_type end, bool label)
2070 {
2071         ostringstream ost;
2072
2073         if (beg == 0 && label && !params().labelString().empty())
2074                 ost << params().labelString() << ' ';
2075
2076         for (pos_type i = beg; i < end; ++i) {
2077                 value_type const c = getUChar(buffer->params, i);
2078                 if (IsPrintable(c))
2079                         ost << c;
2080                 else if (c == META_NEWLINE)
2081                         ost << '\n';
2082                 else if (c == META_HFILL)
2083                         ost << '\t';
2084                 else if (c == META_INSET) {
2085                         getInset(i)->ascii(buffer, ost);
2086                 }
2087         }
2088
2089         return ost.str().c_str();
2090 }
2091
2092
2093 void Paragraph::setInsetOwner(Inset * i)
2094 {
2095         pimpl_->inset_owner = i;
2096         InsetList::const_iterator cit = insetlist.begin();
2097         InsetList::const_iterator end = insetlist.end();
2098         for (; cit != end; ++cit) {
2099                 if (cit->inset)
2100                         cit->inset->setOwner(i);
2101         }
2102 }
2103
2104
2105 void Paragraph::deleteInsetsLyXText(BufferView * bv)
2106 {
2107         // then the insets
2108         InsetList::const_iterator cit = insetlist.begin();
2109         InsetList::const_iterator end = insetlist.end();
2110         for (; cit != end; ++cit) {
2111                 if (cit->inset && cit->inset->isTextInset()) {
2112                         static_cast<UpdatableInset *>
2113                                 (cit->inset)->deleteLyXText(bv, true);
2114                 }
2115         }
2116 }
2117
2118
2119 void Paragraph::resizeInsetsLyXText(BufferView * bv)
2120 {
2121         // then the insets
2122         InsetList::const_iterator cit = insetlist.begin();
2123         InsetList::const_iterator end = insetlist.end();
2124         for (; cit != end; ++cit) {
2125                 if (cit->inset) {
2126                         if (cit->inset->isTextInset()) {
2127                                 static_cast<UpdatableInset *>
2128                                         (cit->inset)->resizeLyXText(bv, true);
2129                         }
2130                 }
2131         }
2132 }
2133
2134
2135 void Paragraph::setContentsFromPar(Paragraph * par)
2136 {
2137         pimpl_->setContentsFromPar(par);
2138 }
2139
2140
2141 lyx::pos_type Paragraph::size() const
2142 {
2143         return pimpl_->size();
2144 }
2145
2146
2147 Paragraph::value_type Paragraph::getChar(pos_type pos) const
2148 {
2149         return pimpl_->getChar(pos);
2150 }
2151
2152
2153 int Paragraph::id() const
2154 {
2155         return pimpl_->id_;
2156 }
2157
2158
2159 void  Paragraph::id(int id_arg)
2160 {
2161         pimpl_->id_ = id_arg;
2162 }
2163
2164
2165 LyXLayout_ptr const & Paragraph::layout() const
2166 {
2167         return layout_;
2168 }
2169
2170
2171 void Paragraph::layout(LyXLayout_ptr const & new_layout)
2172 {
2173         layout_ = new_layout;
2174 }
2175
2176
2177 bool Paragraph::isFirstInSequence() const
2178 {
2179         Paragraph const * dhook = depthHook(getDepth());
2180         return (dhook == this
2181                 || dhook->layout() != layout()
2182                 || dhook->getDepth() != getDepth());
2183 }
2184
2185
2186 Inset * Paragraph::inInset() const
2187 {
2188         return pimpl_->inset_owner;
2189 }
2190
2191
2192 void Paragraph::clearContents()
2193 {
2194         pimpl_->clear();
2195 }
2196
2197
2198 void Paragraph::setCounter(int i, int v)
2199 {
2200         pimpl_->counter_[i] = v;
2201 }
2202
2203
2204 int Paragraph::getCounter(int i) const
2205 {
2206         return pimpl_->counter_[i];
2207 }
2208
2209
2210 void Paragraph::incCounter(int i)
2211 {
2212         pimpl_->counter_[i]++;
2213 }
2214
2215
2216 void Paragraph::setChar(pos_type pos, value_type c)
2217 {
2218         pimpl_->setChar(pos, c);
2219 }
2220
2221
2222 Paragraph::inset_iterator::inset_iterator(Paragraph::InsetList::iterator const & iter)
2223  : it(iter)
2224 {}
2225
2226
2227 Paragraph::inset_iterator Paragraph::inset_iterator_begin()
2228 {
2229         return inset_iterator(insetlist.begin());
2230 }
2231
2232
2233 Paragraph::inset_iterator Paragraph::inset_iterator_end()
2234 {
2235         return inset_iterator(insetlist.end());
2236 }
2237
2238
2239 ParagraphParameters & Paragraph::params()
2240 {
2241         return pimpl_->params;
2242 }
2243
2244
2245 ParagraphParameters const & Paragraph::params() const
2246 {
2247         return pimpl_->params;
2248 }
2249
2250
2251 Paragraph * Paragraph::getParFromID(int id) const
2252 {
2253         return pimpl_->getParFromID(id);
2254 }
2255
2256
2257 bool Paragraph::isFreeSpacing() const
2258 {
2259         // for now we just need this, later should we need this in some
2260         // other way we can always add a function to Inset::() too.
2261         if (pimpl_->inset_owner && pimpl_->inset_owner->owner())
2262                 return (pimpl_->inset_owner->owner()->lyxCode() == Inset::ERT_CODE);
2263         return false;
2264 }