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