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