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