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