]> git.lyx.org Git - lyx.git/blob - src/paragraph.C
some more changes
[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, bool moving_arg) 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         case LYX_ALIGN_RIGHT:
1481         case LYX_ALIGN_CENTER:
1482                 if (moving_arg) {
1483                         os << "\\protect";
1484                         column = 8;
1485                 }
1486                 break;
1487         }
1488         
1489         switch (params().align()) {
1490         case LYX_ALIGN_NONE:
1491         case LYX_ALIGN_BLOCK:
1492         case LYX_ALIGN_LAYOUT:
1493         case LYX_ALIGN_SPECIAL:
1494                 break;
1495         case LYX_ALIGN_LEFT:
1496                 if (getParLanguage(bparams)->babel() != "hebrew") {
1497                         os << "\\begin{flushleft}";
1498                         column += 17;
1499                 } else {
1500                         os << "\\begin{flushright}";
1501                         column += 18;
1502                 }
1503                 break;
1504         case LYX_ALIGN_RIGHT:
1505                 if (getParLanguage(bparams)->babel() != "hebrew") {
1506                         os << "\\begin{flushright}";
1507                         column += 18;
1508                 } else {
1509                         os << "\\begin{flushleft}";
1510                         column += 17;
1511                 }
1512                 break;
1513         case LYX_ALIGN_CENTER:
1514                 os << "\\begin{center}";
1515                 column += 14;
1516                 break;
1517         }
1518
1519         return column;
1520 }
1521
1522 // This could go to ParagraphParameters if we want to
1523 int Paragraph::endTeXParParams(BufferParams const & bparams,
1524                                ostream & os, bool moving_arg) const
1525 {
1526         int column = 0;
1527
1528         switch (params().align()) {
1529         case LYX_ALIGN_NONE:
1530         case LYX_ALIGN_BLOCK:
1531         case LYX_ALIGN_LAYOUT:
1532         case LYX_ALIGN_SPECIAL:
1533                 break;
1534         case LYX_ALIGN_LEFT:
1535         case LYX_ALIGN_RIGHT:
1536         case LYX_ALIGN_CENTER:
1537                 if (moving_arg) {
1538                         os << "\\protect";
1539                         column = 8;
1540                 }
1541                 break;
1542         }
1543         
1544         switch (params().align()) {
1545         case LYX_ALIGN_NONE:
1546         case LYX_ALIGN_BLOCK:
1547         case LYX_ALIGN_LAYOUT:
1548         case LYX_ALIGN_SPECIAL:
1549                 break;
1550         case LYX_ALIGN_LEFT:
1551                 if (getParLanguage(bparams)->babel() != "hebrew") {
1552                         os << "\\end{flushleft}";
1553                         column = 15;
1554                 } else {
1555                         os << "\\end{flushright}";
1556                         column = 16;
1557                 }
1558                 break;
1559         case LYX_ALIGN_RIGHT:
1560                 if (getParLanguage(bparams)->babel() != "hebrew") {
1561                         os << "\\end{flushright}";
1562                         column+= 16;
1563                 } else {
1564                         os << "\\end{flushleft}";
1565                         column = 15;
1566                 }
1567                 break;
1568         case LYX_ALIGN_CENTER:
1569                 os << "\\end{center}";
1570                 column = 12;
1571                 break;
1572         }
1573         return column;
1574 }
1575
1576
1577 // This one spits out the text of the paragraph
1578 bool Paragraph::simpleTeXOnePar(Buffer const * buf,
1579                                 BufferParams const & bparams,
1580                                 ostream & os, TexRow & texrow,
1581                                 bool moving_arg)
1582 {
1583         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...     " << this << endl;
1584
1585         bool return_value = false;
1586
1587         LyXLayout_ptr style;
1588
1589         // well we have to check if we are in an inset with unlimited
1590         // lenght (all in one row) if that is true then we don't allow
1591         // any special options in the paragraph and also we don't allow
1592         // any environment other then "Standard" to be valid!
1593         bool asdefault =
1594                 (inInset() && inInset()->forceDefaultParagraphs(inInset()));
1595
1596         if (asdefault) {
1597                 style = textclasslist[bparams.textclass].defaultLayout();
1598         } else {
1599                 style = layout();
1600         }
1601
1602         LyXFont basefont;
1603
1604         // Maybe we have to create a optional argument.
1605         pos_type main_body;
1606         if (style->labeltype != LABEL_MANUAL)
1607                 main_body = 0;
1608         else
1609                 main_body = beginningOfMainBody();
1610
1611         int column = 0;
1612
1613         if (main_body > 0) {
1614                 os << '[';
1615                 ++column;
1616                 basefont = getLabelFont(bparams);
1617         } else {
1618                 basefont = getLayoutFont(bparams);
1619         }
1620
1621         moving_arg |= style->needprotect;
1622
1623         // Which font is currently active?
1624         LyXFont running_font(basefont);
1625         // Do we have an open font change?
1626         bool open_font = false;
1627
1628         texrow.start(this, 0);
1629
1630         // if the paragraph is empty, the loop will not be entered at all
1631         if (!size()) {
1632                 if (style->isCommand()) {
1633                         os << '{';
1634                         ++column;
1635                 }
1636                 if (!asdefault)
1637                         column += startTeXParParams(bparams, os, moving_arg);
1638
1639         }
1640
1641         for (pos_type i = 0; i < size(); ++i) {
1642                 ++column;
1643                 // First char in paragraph or after label?
1644                 if (i == main_body) {
1645                         if (main_body > 0) {
1646                                 if (open_font) {
1647                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1648                                         open_font = false;
1649                                 }
1650                                 basefont = getLayoutFont(bparams);
1651                                 running_font = basefont;
1652                                 os << ']';
1653                                 ++column;
1654                         }
1655                         if (style->isCommand()) {
1656                                 os << '{';
1657                                 ++column;
1658                         }
1659
1660                         if (!asdefault)
1661                                 column += startTeXParParams(bparams, os,
1662                                                             moving_arg);
1663                 }
1664
1665                 value_type c = getChar(i);
1666
1667                 // Fully instantiated font
1668                 LyXFont font = getFont(bparams, i);
1669
1670                 LyXFont const last_font = running_font;
1671
1672                 // Spaces at end of font change are simulated to be
1673                 // outside font change, i.e. we write "\textXX{text} "
1674                 // rather than "\textXX{text }". (Asger)
1675                 if (open_font && c == ' ' && i <= size() - 2) {
1676                         LyXFont const & next_font = getFont(bparams, i + 1);
1677                         if (next_font != running_font
1678                             && next_font != font) {
1679                                 font = next_font;
1680                         }
1681                 }
1682
1683                 // We end font definition before blanks
1684                 if (open_font &&
1685                     (font != running_font ||
1686                      font.language() != running_font.language()))
1687                 {
1688                         column += running_font.latexWriteEndChanges(os,
1689                                                                     basefont,
1690                                                                     (i == main_body-1) ? basefont : font);
1691                         running_font = basefont;
1692                         open_font = false;
1693                 }
1694
1695                 // Blanks are printed before start of fontswitch
1696                 if (c == ' ') {
1697                         // Do not print the separation of the optional argument
1698                         if (i != main_body - 1) {
1699                                 pimpl_->simpleTeXBlanks(os, texrow, i,
1700                                                        column, font, *style);
1701                         }
1702                 }
1703
1704                 // Do we need to change font?
1705                 if ((font != running_font ||
1706                      font.language() != running_font.language()) &&
1707                         i != main_body - 1)
1708                 {
1709                         column += font.latexWriteStartChanges(os, basefont,
1710                                                               last_font);
1711                         running_font = font;
1712                         open_font = true;
1713                 }
1714
1715                 if (c == Paragraph::META_NEWLINE) {
1716                         // newlines are handled differently here than
1717                         // the default in SimpleTeXSpecialChars().
1718                         if (!style->newline_allowed) {
1719                                 os << '\n';
1720                         } else {
1721                                 if (open_font) {
1722                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1723                                         open_font = false;
1724                                 }
1725                                 basefont = getLayoutFont(bparams);
1726                                 running_font = basefont;
1727                                 if (font.family() ==
1728                                     LyXFont::TYPEWRITER_FAMILY) {
1729                                         os << "~";
1730                                 }
1731                                 if (moving_arg)
1732                                         os << "\\protect ";
1733
1734                                 os << "\\\\\n";
1735                         }
1736                         texrow.newline();
1737                         texrow.start(this, i + 1);
1738                         column = 0;
1739                 } else {
1740                         pimpl_->simpleTeXSpecialChars(buf, bparams,
1741                                                       os, texrow, moving_arg,
1742                                                       font, running_font,
1743                                                       basefont, open_font,
1744                                                       *style, i, column, c);
1745                 }
1746         }
1747
1748         // If we have an open font definition, we have to close it
1749         if (open_font) {
1750 #ifdef FIXED_LANGUAGE_END_DETECTION
1751                 if (next_) {
1752                         running_font
1753                                 .latexWriteEndChanges(os, basefont,
1754                                                       next_->getFont(bparams,
1755                                                       0));
1756                 } else {
1757                         running_font.latexWriteEndChanges(os, basefont,
1758                                                           basefont);
1759                 }
1760 #else
1761 #ifdef WITH_WARNINGS
1762 //#warning For now we ALWAYS have to close the foreign font settings if they are
1763 //#warning there as we start another \selectlanguage with the next paragraph if
1764 //#warning we are in need of this. This should be fixed sometime (Jug)
1765 #endif
1766                 running_font.latexWriteEndChanges(os, basefont,  basefont);
1767 #endif
1768         }
1769
1770         // Needed if there is an optional argument but no contents.
1771         if (main_body > 0 && main_body == size()) {
1772                 os << "]~";
1773                 return_value = false;
1774         }
1775
1776         if (!asdefault) {
1777                 column += endTeXParParams(bparams, os, moving_arg);
1778         }
1779
1780         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...done " << this << endl;
1781         return return_value;
1782 }
1783
1784
1785 bool Paragraph::sgmlConvertChar(char c, string & sgml_string)
1786 {
1787         bool retval = false;
1788         switch (c) {
1789         case Paragraph::META_HFILL:
1790                 sgml_string.erase();
1791                 break;
1792         case Paragraph::META_NEWLINE:
1793                 sgml_string = '\n';
1794                 break;
1795         case '&':
1796                 sgml_string = "&amp;";
1797                 break;
1798         case '<':
1799                 sgml_string = "&lt;";
1800                 break;
1801         case '>':
1802                 sgml_string = "&gt;";
1803                 break;
1804         case '$':
1805                 sgml_string = "&dollar;";
1806                 break;
1807         case '#':
1808                 sgml_string = "&num;";
1809                 break;
1810         case '%':
1811                 sgml_string = "&percnt;";
1812                 break;
1813         case '[':
1814                 sgml_string = "&lsqb;";
1815                 break;
1816         case ']':
1817                 sgml_string = "&rsqb;";
1818                 break;
1819         case '{':
1820                 sgml_string = "&lcub;";
1821                 break;
1822         case '}':
1823                 sgml_string = "&rcub;";
1824                 break;
1825         case '~':
1826                 sgml_string = "&tilde;";
1827                 break;
1828         case '"':
1829                 sgml_string = "&quot;";
1830                 break;
1831         case '\\':
1832                 sgml_string = "&bsol;";
1833                 break;
1834         case ' ':
1835                 retval = true;
1836                 sgml_string = ' ';
1837                 break;
1838         case '\0': // Ignore :-)
1839                 sgml_string.erase();
1840                 break;
1841         default:
1842                 sgml_string = c;
1843                 break;
1844         }
1845         return retval;
1846 }
1847
1848
1849 Paragraph * Paragraph::TeXEnvironment(Buffer const * buf,
1850                                             BufferParams const & bparams,
1851                                             ostream & os, TexRow & texrow)
1852 {
1853         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << this << endl;
1854
1855         LyXLayout_ptr const & style = layout();
1856
1857         Language const * language = getParLanguage(bparams);
1858         Language const * doc_language = bparams.language;
1859         Language const * previous_language = previous_
1860                 ? previous_->getParLanguage(bparams) : doc_language;
1861         if (language->babel() != previous_language->babel()) {
1862
1863                 if (!lyxrc.language_command_end.empty() &&
1864                     previous_language->babel() != doc_language->babel()) {
1865                         os << subst(lyxrc.language_command_end, "$$lang",
1866                                     previous_language->babel())
1867                            << endl;
1868                         texrow.newline();
1869                 }
1870
1871                 if (lyxrc.language_command_end.empty() ||
1872                     language->babel() != doc_language->babel()) {
1873                         os << subst(lyxrc.language_command_begin, "$$lang",
1874                                     language->babel())
1875                            << endl;
1876                         texrow.newline();
1877                 }
1878         }
1879
1880         bool leftindent_open = false;
1881         if (!params().leftIndent().zero()) {
1882                 os << "\\begin{LyXParagraphLeftIndent}{" <<
1883                         params().leftIndent().asLatexString() << "}\n";
1884                 texrow.newline();
1885                 leftindent_open = true;
1886         }
1887
1888         if (style->isEnvironment()) {
1889                 if (style->latextype == LATEX_LIST_ENVIRONMENT) {
1890                         os << "\\begin{" << style->latexname() << "}{"
1891                            << params().labelWidthString() << "}\n";
1892                 } else if (style->labeltype == LABEL_BIBLIO) {
1893                         // ale970405
1894                         os << "\\begin{" << style->latexname() << "}{"
1895                            <<  bibitemWidest(buf)
1896                            << "}\n";
1897                 } else if (style->latextype == LATEX_ITEM_ENVIRONMENT) {
1898                         os << "\\begin{" << style->latexname() << '}'
1899                            << style->latexparam() << '\n';
1900                 } else
1901                         os << "\\begin{" << style->latexname() << '}'
1902                            << style->latexparam() << '\n';
1903                 texrow.newline();
1904         }
1905         Paragraph * par = this;
1906         do {
1907                 par = par->TeXOnePar(buf, bparams, os, texrow, false);
1908
1909                 if (par && par->params().depth() > params().depth()) {
1910                             if (par->layout()->isParagraph()) {
1911
1912                             // Thinko!
1913                             // How to handle this? (Lgb)
1914                             //&& !suffixIs(os, "\n\n")
1915                                     //) {
1916                                 // There should be at least one '\n' already
1917                                 // but we need there to be two for Standard
1918                                 // paragraphs that are depth-increment'ed to be
1919                                 // output correctly.  However, tables can
1920                                 // also be paragraphs so don't adjust them.
1921                                 // ARRae
1922                                 // Thinkee:
1923                                 // Will it ever harm to have one '\n' too
1924                                 // many? i.e. that we sometimes will have
1925                                 // three in a row. (Lgb)
1926                                 os << '\n';
1927                                 texrow.newline();
1928                         }
1929                         par = par->pimpl_->TeXDeeper(buf, bparams, os, texrow);
1930                 }
1931         } while (par
1932                  && par->layout() == layout()
1933                  && par->params().depth() == params().depth()
1934                  && par->params().leftIndent() == params().leftIndent());
1935
1936         if (style->isEnvironment()) {
1937                 os << "\\end{" << style->latexname() << "}\n";
1938                 texrow.newline();
1939         }
1940
1941         if (leftindent_open) {
1942                 os << "\\end{LyXParagraphLeftIndent}\n";
1943                 texrow.newline();
1944         }
1945
1946         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << par << endl;
1947         return par;  // ale970302
1948 }
1949
1950
1951 bool Paragraph::isHfill(pos_type pos) const
1952 {
1953         return IsHfillChar(getChar(pos));
1954 }
1955
1956
1957 bool Paragraph::isInset(pos_type pos) const
1958 {
1959         return IsInsetChar(getChar(pos));
1960 }
1961
1962
1963 bool Paragraph::isNewline(pos_type pos) const
1964 {
1965         return pos >= 0 && IsNewlineChar(getChar(pos));
1966 }
1967
1968
1969 bool Paragraph::isSeparator(pos_type pos) const
1970 {
1971         return IsSeparatorChar(getChar(pos));
1972 }
1973
1974
1975 bool Paragraph::isLineSeparator(pos_type pos) const
1976 {
1977         value_type const c = getChar(pos);
1978         return IsLineSeparatorChar(c)
1979                 || (IsInsetChar(c) && getInset(pos) &&
1980                 getInset(pos)->isLineSeparator());
1981 }
1982
1983
1984 bool Paragraph::isKomma(pos_type pos) const
1985 {
1986         return IsKommaChar(getChar(pos));
1987 }
1988
1989
1990 /// Used by the spellchecker
1991 bool Paragraph::isLetter(pos_type pos) const
1992 {
1993         value_type const c = getChar(pos);
1994         if (IsLetterChar(c))
1995                 return true;
1996         if (isInset(pos))
1997                 return getInset(pos)->isLetter();
1998         // We want to pass the ' and escape chars to ispell
1999         string const extra = lyxrc.isp_esc_chars + '\'';
2000         return contains(extra, c);
2001 }
2002
2003
2004 bool Paragraph::isWord(pos_type pos) const
2005 {
2006         return IsWordChar(getChar(pos)) ;
2007 }
2008
2009
2010 Language const *
2011 Paragraph::getParLanguage(BufferParams const & bparams) const
2012 {
2013         if (size() > 0) {
2014 #ifndef INHERIT_LANGUAGE
2015                 return getFirstFontSettings().language();
2016 #else
2017                 Language const * lang = getFirstFontSettings().language();
2018 #ifdef WITH_WARNINGS
2019 #warning We should make this somewhat better, any ideas? (Jug)
2020 #endif
2021                 if (lang == inherit_language || lang == ignore_language)
2022                         lang = bparams.language;
2023                 return lang;
2024 #endif
2025         } else if (previous_)
2026                 return previous_->getParLanguage(bparams);
2027         else
2028                 return bparams.language;
2029 }
2030
2031
2032 bool Paragraph::isRightToLeftPar(BufferParams const & bparams) const
2033 {
2034         return lyxrc.rtl_support
2035                 && getParLanguage(bparams)->RightToLeft()
2036                 && !(inInset() && inInset()->owner() &&
2037                      inInset()->owner()->lyxCode() == Inset::ERT_CODE);
2038 }
2039
2040
2041 void Paragraph::changeLanguage(BufferParams const & bparams,
2042                                   Language const * from, Language const * to)
2043 {
2044         for (pos_type i = 0; i < size(); ++i) {
2045                 LyXFont font = getFontSettings(bparams, i);
2046                 if (font.language() == from) {
2047                         font.setLanguage(to);
2048                         setFont(i, font);
2049                 }
2050         }
2051 }
2052
2053
2054 bool Paragraph::isMultiLingual(BufferParams const & bparams)
2055 {
2056         Language const * doc_language = bparams.language;
2057         Pimpl::FontList::const_iterator cit = pimpl_->fontlist.begin();
2058         Pimpl::FontList::const_iterator end = pimpl_->fontlist.end();
2059
2060         for (; cit != end; ++cit)
2061                 if (cit->font().language() != ignore_language &&
2062                     cit->font().language() != latex_language &&
2063 #ifdef INHERIT_LANGUAGE
2064                         cit->font().language() != inherit_language &&
2065 #endif
2066                         cit->font().language() != doc_language)
2067                         return true;
2068         return false;
2069 }
2070
2071
2072 // Convert the paragraph to a string.
2073 // Used for building the table of contents
2074 string const Paragraph::asString(Buffer const * buffer, bool label)
2075 {
2076         BufferParams const & bparams = buffer->params;
2077         string s;
2078         if (label && !params().labelString().empty())
2079                 s += params().labelString() + ' ';
2080         string::size_type const len = s.size();
2081
2082         for (pos_type i = 0; i < size(); ++i) {
2083                 value_type c = getChar(i);
2084                 if (IsPrintable(c))
2085                         s += c;
2086                 else if (c == META_INSET &&
2087                          getInset(i)->lyxCode() == Inset::MATH_CODE) {
2088                         ostringstream ost;
2089                         getInset(i)->ascii(buffer, ost);
2090                         s += subst(ost.str().c_str(),'\n',' ');
2091                 }
2092         }
2093
2094         if (isRightToLeftPar(bparams))
2095                 reverse(s.begin() + len,s.end());
2096
2097         return s;
2098 }
2099
2100
2101 string const Paragraph::asString(Buffer const * buffer,
2102                                  pos_type beg, pos_type end, bool label)
2103 {
2104         ostringstream ost;
2105
2106         if (beg == 0 && label && !params().labelString().empty())
2107                 ost << params().labelString() << ' ';
2108
2109         for (pos_type i = beg; i < end; ++i) {
2110                 value_type const c = getUChar(buffer->params, i);
2111                 if (IsPrintable(c))
2112                         ost << c;
2113                 else if (c == META_NEWLINE)
2114                         ost << '\n';
2115                 else if (c == META_HFILL)
2116                         ost << '\t';
2117                 else if (c == META_INSET) {
2118                         getInset(i)->ascii(buffer, ost);
2119                 }
2120         }
2121
2122         return ost.str().c_str();
2123 }
2124
2125
2126 void Paragraph::setInsetOwner(Inset * i)
2127 {
2128         pimpl_->inset_owner = i;
2129         InsetList::const_iterator cit = insetlist.begin();
2130         InsetList::const_iterator end = insetlist.end();
2131         for (; cit != end; ++cit) {
2132                 if (cit->inset)
2133                         cit->inset->setOwner(i);
2134         }
2135 }
2136
2137
2138 void Paragraph::deleteInsetsLyXText(BufferView * bv)
2139 {
2140         // then the insets
2141         InsetList::const_iterator cit = insetlist.begin();
2142         InsetList::const_iterator end = insetlist.end();
2143         for (; cit != end; ++cit) {
2144                 if (cit->inset && cit->inset->isTextInset()) {
2145                         static_cast<UpdatableInset *>
2146                                 (cit->inset)->deleteLyXText(bv, true);
2147                 }
2148         }
2149 }
2150
2151
2152 void Paragraph::resizeInsetsLyXText(BufferView * bv)
2153 {
2154         // then the insets
2155         InsetList::const_iterator cit = insetlist.begin();
2156         InsetList::const_iterator end = insetlist.end();
2157         for (; cit != end; ++cit) {
2158                 if (cit->inset) {
2159                         if (cit->inset->isTextInset()) {
2160                                 static_cast<UpdatableInset *>
2161                                         (cit->inset)->resizeLyXText(bv, true);
2162                         }
2163                 }
2164         }
2165 }
2166
2167
2168 void Paragraph::setContentsFromPar(Paragraph * par)
2169 {
2170         pimpl_->setContentsFromPar(par);
2171 }
2172
2173
2174 lyx::pos_type Paragraph::size() const
2175 {
2176         return pimpl_->size();
2177 }
2178
2179
2180 Paragraph::value_type Paragraph::getChar(pos_type pos) const
2181 {
2182         return pimpl_->getChar(pos);
2183 }
2184
2185
2186 int Paragraph::id() const
2187 {
2188         return pimpl_->id_;
2189 }
2190
2191
2192 void  Paragraph::id(int id_arg)
2193 {
2194         pimpl_->id_ = id_arg;
2195 }
2196
2197
2198 LyXLayout_ptr const & Paragraph::layout() const
2199 {
2200         return layout_;
2201 }
2202
2203
2204 void Paragraph::layout(LyXLayout_ptr const & new_layout)
2205 {
2206         layout_ = new_layout;
2207 }
2208
2209
2210 bool Paragraph::isFirstInSequence() const
2211 {
2212         Paragraph const * dhook = depthHook(getDepth());
2213         return (dhook == this
2214                 || dhook->layout() != layout()
2215                 || dhook->getDepth() != getDepth());
2216 }
2217
2218
2219 Inset * Paragraph::inInset() const
2220 {
2221         return pimpl_->inset_owner;
2222 }
2223
2224
2225 void Paragraph::clearContents()
2226 {
2227         pimpl_->clear();
2228 }
2229
2230
2231 void Paragraph::setCounter(int i, int v)
2232 {
2233         pimpl_->counter_[i] = v;
2234 }
2235
2236
2237 int Paragraph::getCounter(int i) const
2238 {
2239         return pimpl_->counter_[i];
2240 }
2241
2242
2243 void Paragraph::incCounter(int i)
2244 {
2245         pimpl_->counter_[i]++;
2246 }
2247
2248
2249 void Paragraph::setChar(pos_type pos, value_type c)
2250 {
2251         pimpl_->setChar(pos, c);
2252 }
2253
2254
2255 Paragraph::inset_iterator::inset_iterator(Paragraph::InsetList::iterator const & iter)
2256  : it(iter)
2257 {}
2258
2259
2260 Paragraph::inset_iterator Paragraph::inset_iterator_begin()
2261 {
2262         return inset_iterator(insetlist.begin());
2263 }
2264
2265
2266 Paragraph::inset_iterator Paragraph::inset_iterator_end()
2267 {
2268         return inset_iterator(insetlist.end());
2269 }
2270
2271
2272 ParagraphParameters & Paragraph::params()
2273 {
2274         return pimpl_->params;
2275 }
2276
2277
2278 ParagraphParameters const & Paragraph::params() const
2279 {
2280         return pimpl_->params;
2281 }
2282
2283
2284 Paragraph * Paragraph::getParFromID(int id) const
2285 {
2286         return pimpl_->getParFromID(id);
2287 }
2288
2289
2290 bool Paragraph::isFreeSpacing() const
2291 {
2292         // for now we just need this, later should we need this in some
2293         // other way we can always add a function to Inset::() too.
2294         if (pimpl_->inset_owner && pimpl_->inset_owner->owner())
2295                 return (pimpl_->inset_owner->owner()->lyxCode() == Inset::ERT_CODE);
2296         return false;
2297 }