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