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