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