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