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