]> git.lyx.org Git - lyx.git/blob - src/paragraph.C
remove lowercase, better layout handling and some variable renameing
[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         tmp->layout(layout());
863         
864         // remember to set the inset_owner
865         tmp->setInsetOwner(inInset());
866         
867         // this is an idea for a more userfriendly layout handling, I will
868         // see what the users say
869         
870         // layout stays the same with latex-environments
871         if (flag) {
872                 tmp->layout(layout());
873                 tmp->setLabelWidthString(params().labelWidthString());
874         }
875         
876         if (size() > pos || !size() || flag == 2) {
877                 tmp->layout(layout());
878                 tmp->params().align(params().align());
879                 tmp->setLabelWidthString(params().labelWidthString());
880                 
881                 tmp->params().lineBottom(params().lineBottom());
882                 params().lineBottom(false);
883                 tmp->params().pagebreakBottom(params().pagebreakBottom());
884                 params().pagebreakBottom(false);
885                 tmp->params().spaceBottom(params().spaceBottom());
886                 params().spaceBottom(VSpace(VSpace::NONE));
887                 
888                 tmp->params().depth(params().depth());
889                 tmp->params().noindent(params().noindent());
890                 
891                 // copy everything behind the break-position
892                 // to the new paragraph
893                 pos_type pos_end = size() - 1;
894                 pos_type i = pos;
895                 pos_type j = pos;
896                 for (; i <= pos_end; ++i) {
897                         cutIntoMinibuffer(bparams, i);
898                         if (tmp->insertFromMinibuffer(j - pos))
899                                 ++j;
900                 }
901                 for (i = pos_end; i >= pos; --i) {
902                         erase(i);
903                 }
904         }
905         
906         // just an idea of me
907         if (!pos) {
908                 tmp->params().lineTop(params().lineTop());
909                 tmp->params().pagebreakTop(params().pagebreakTop());
910                 tmp->params().spaceTop(params().spaceTop());
911                 tmp->bibkey = bibkey;
912                 clear();
913                 // layout stays the same with latex-environments
914                 if (flag) {
915                         layout(tmp->layout());
916                         setLabelWidthString(tmp->params().labelWidthString());
917                         params().depth(tmp->params().depth());
918                 }
919         }
920 }
921         
922
923 void Paragraph::makeSameLayout(Paragraph const * par)
924 {
925         layout(par->layout());
926         // move to pimpl?
927         params() = par->params();
928 }
929
930
931 int Paragraph::stripLeadingSpaces(lyx::textclass_type tclass) 
932 {
933         if (textclasslist[tclass][layout()].free_spacing ||
934             isFreeSpacing()) {
935                 return 0;
936         }
937         
938         int i = 0;
939         while (size() && (isNewline(0) || isLineSeparator(0))) {
940                 erase(0);
941                 ++i;
942         }
943
944         return i;
945 }
946
947
948 bool Paragraph::hasSameLayout(Paragraph const * par) const
949 {
950         return 
951                 par->layout() == layout() &&
952                 params().sameLayout(par->params());
953 }
954
955
956 void Paragraph::breakParagraphConservative(BufferParams const & bparams,
957                                            pos_type pos)
958 {
959         // create a new paragraph
960         Paragraph * tmp = new Paragraph(this);
961         tmp->makeSameLayout(this);
962
963         // When can pos > Last()?
964         // I guess pos == Last() is possible.
965         if (size() > pos) {
966                 // copy everything behind the break-position to the new
967                 // paragraph
968                 pos_type pos_end = size() - 1;
969
970                 //pos_type i = pos;
971                 //pos_type j = pos;
972                 for (pos_type i = pos, j = pos; i <= pos_end; ++i) {
973                         cutIntoMinibuffer(bparams, i);
974                         if (tmp->insertFromMinibuffer(j - pos))
975                                 ++j;
976                 }
977                 
978                 for (pos_type k = pos_end; k >= pos; --k) {
979                         erase(k);
980                 }
981         }
982 }
983
984
985 // Be carefull, this does not make any check at all.
986 // This method has wrong name, it combined this par with the next par.
987 // In that sense it is the reverse of break paragraph. (Lgb)
988 void Paragraph::pasteParagraph(BufferParams const & bparams)
989 {
990         // copy the next paragraph to this one
991         Paragraph * the_next = next();
992
993         // first the DTP-stuff
994         params().lineBottom(the_next->params().lineBottom());
995         params().spaceBottom(the_next->params().spaceBottom());
996         params().pagebreakBottom(the_next->params().pagebreakBottom());
997
998         pos_type pos_end = the_next->pimpl_->size() - 1;
999         pos_type pos_insert = size();
1000
1001         // ok, now copy the paragraph
1002         for (pos_type i = 0, j = 0; i <= pos_end; ++i) {
1003                 the_next->cutIntoMinibuffer(bparams, i);
1004                 if (insertFromMinibuffer(pos_insert + j))
1005                         ++j;
1006         }
1007
1008         // delete the next paragraph
1009         Paragraph * ppar = the_next->previous_;
1010         Paragraph * npar = the_next->next_;
1011         delete the_next;
1012         ppar->next(npar);
1013 }
1014
1015
1016 int Paragraph::getEndLabel(BufferParams const & bparams) const
1017 {
1018         Paragraph const * par = this;
1019         depth_type par_depth = getDepth();
1020         while (par) {
1021                 string const & layout = par->layout();
1022                 int const endlabeltype =
1023                         textclasslist[bparams.textclass][layout].endlabeltype;
1024                 if (endlabeltype != END_LABEL_NO_LABEL) {
1025                         if (!next_)
1026                                 return endlabeltype;
1027
1028                         depth_type const next_depth = next_->getDepth();
1029                         if (par_depth > next_depth ||
1030                             (par_depth == next_depth
1031                              && layout != next_->layout()))
1032                                 return endlabeltype;
1033                         break;
1034                 }
1035                 if (par_depth == 0)
1036                         break;
1037                 par = par->outerHook();
1038                 if (par)
1039                         par_depth = par->getDepth();
1040         }
1041         return END_LABEL_NO_LABEL;
1042 }
1043
1044
1045 Paragraph::depth_type Paragraph::getDepth() const
1046 {
1047         return params().depth();
1048 }
1049
1050
1051 Paragraph::depth_type Paragraph::getMaxDepthAfter(Buffer const * buffer) const
1052 {
1053         bool const isenv = textclasslist[buffer->params.textclass][layout()].isEnvironment();
1054
1055         if (isenv)
1056                 return params().depth() + 1;
1057         else
1058                 return params().depth();
1059
1060 }
1061
1062 char Paragraph::getAlign() const
1063 {
1064         return params().align();
1065 }
1066
1067
1068 string const & Paragraph::getLabelstring() const
1069 {
1070         return params().labelString();
1071 }
1072
1073
1074 int Paragraph::getFirstCounter(int i) const
1075 {
1076         return pimpl_->counter_[i];
1077 }
1078
1079
1080 // the next two functions are for the manual labels
1081 string const Paragraph::getLabelWidthString() const
1082 {
1083         if (!params().labelWidthString().empty())
1084                 return params().labelWidthString();
1085         else
1086                 return _("Senseless with this layout!");
1087 }
1088
1089
1090 void Paragraph::setLabelWidthString(string const & s)
1091 {
1092         params().labelWidthString(s);
1093 }
1094
1095
1096 void Paragraph::applyLayout(string const & new_layout)
1097 {
1098         layout(new_layout);
1099         params().labelWidthString(string());
1100         params().align(LYX_ALIGN_LAYOUT);
1101         params().spaceTop(VSpace(VSpace::NONE));
1102         params().spaceBottom(VSpace(VSpace::NONE));
1103         params().spacing(Spacing(Spacing::Default));
1104 }
1105
1106
1107 // if the layout of a paragraph contains a manual label, the beginning of the 
1108 // main body is the beginning of the second word. This is what the par-
1109 // function returns. If the layout does not contain a label, the main
1110 // body always starts with position 0. This differentiation is necessary,
1111 // because there cannot be a newline or a blank <= the beginning of the 
1112 // main body in TeX.
1113
1114 int Paragraph::beginningOfMainBody() const
1115 {
1116         // Unroll the first two cycles of the loop
1117         // and remember the previous character to
1118         // remove unnecessary GetChar() calls
1119         pos_type i = 0;
1120         if (i < size()
1121             && getChar(i) != Paragraph::META_NEWLINE) {
1122                 ++i;
1123                 char previous_char = 0;
1124                 char temp = 0; 
1125                 if (i < size()
1126                     && (previous_char = getChar(i)) != Paragraph::META_NEWLINE) {
1127                         // Yes, this  ^ is supposed to be "= " not "=="
1128                         ++i;
1129                         while (i < size()
1130                                && previous_char != ' '
1131                                && (temp = getChar(i)) != Paragraph::META_NEWLINE) {
1132                                 ++i;
1133                                 previous_char = temp;
1134                         }
1135                 }
1136         }
1137
1138         return i;
1139 }
1140
1141
1142 Paragraph * Paragraph::depthHook(depth_type depth)
1143 {
1144         Paragraph * newpar = this;
1145
1146         do {
1147                 newpar = newpar->previous();
1148         } while (newpar && newpar->getDepth() > depth);
1149
1150         if (!newpar) {
1151                 if (previous() || getDepth())
1152                         lyxerr << "ERROR (Paragraph::DepthHook): "
1153                                 "no hook." << endl;
1154                 newpar = this;
1155         }
1156
1157         return newpar;
1158 }
1159
1160
1161 Paragraph const * Paragraph::depthHook(depth_type depth) const
1162 {
1163         Paragraph const * newpar = this;
1164
1165         do {
1166                 newpar = newpar->previous();
1167         } while (newpar && newpar->getDepth() > depth);
1168
1169         if (!newpar) {
1170                 if (previous() || getDepth())
1171                         lyxerr << "ERROR (Paragraph::DepthHook): "
1172                                 "no hook." << endl;
1173                 newpar = this;
1174         }
1175
1176         return newpar;
1177 }
1178
1179 Paragraph * Paragraph::outerHook()
1180 {
1181         if (!getDepth())
1182                 return 0;
1183         return depthHook(depth_type(getDepth() - 1));
1184 }
1185
1186 Paragraph const * Paragraph::outerHook() const
1187 {
1188         if (!getDepth())
1189                 return 0;
1190         return depthHook(depth_type(getDepth() - 1));
1191 }
1192
1193
1194 Paragraph::inset_iterator
1195 Paragraph::InsetIterator(pos_type pos)
1196 {
1197         InsetTable search_inset(pos, 0);
1198         InsetList::iterator it = lower_bound(insetlist.begin(),
1199                                              insetlist.end(),
1200                                              search_inset, Pimpl::matchIT());
1201         return inset_iterator(it);
1202 }
1203
1204
1205 // returns -1 if inset not found
1206 int Paragraph::getPositionOfInset(Inset const * inset) const
1207 {
1208         // Find the entry.
1209         for (InsetList::const_iterator cit = insetlist.begin();
1210              cit != insetlist.end(); ++cit) {
1211                 if (cit->inset == inset) {
1212                         return cit->pos;
1213                 }
1214         }
1215         if (inset == bibkey)
1216                 return 0;
1217
1218         return -1;
1219 }
1220
1221
1222 Paragraph * Paragraph::TeXOnePar(Buffer const * buf,
1223                                  BufferParams const & bparams,
1224                                  ostream & os, TexRow & texrow,
1225                                  bool moving_arg)
1226 {
1227         lyxerr[Debug::LATEX] << "TeXOnePar...     " << this << endl;
1228         Inset const * in = inInset();
1229         bool further_blank_line = false;
1230         LyXLayout style;
1231         
1232         // well we have to check if we are in an inset with unlimited
1233         // lenght (all in one row) if that is true then we don't allow
1234         // any special options in the paragraph and also we don't allow
1235         // any environment other then "Standard" to be valid!
1236         if ((in == 0) || !in->forceDefaultParagraphs(in)) {
1237                 style = textclasslist[bparams.textclass][layout()];
1238
1239                 if (params().startOfAppendix()) {
1240                         os << "\\appendix\n";
1241                         texrow.newline();
1242                 }
1243
1244                 if (!params().spacing().isDefault()
1245                         && (!previous() || !previous()->hasSameLayout(this))) {
1246                         os << params().spacing().writeEnvirBegin() << "\n";
1247                         texrow.newline();
1248                 }
1249         
1250                 if (tex_code_break_column && style.isCommand()) {
1251                         os << '\n';
1252                         texrow.newline();
1253                 }
1254
1255                 if (params().pagebreakTop()) {
1256                         os << "\\newpage";
1257                         further_blank_line = true;
1258                 }
1259                 if (params().spaceTop().kind() != VSpace::NONE) {
1260                         os << params().spaceTop().asLatexCommand(bparams);
1261                         further_blank_line = true;
1262                 }
1263
1264                 if (params().lineTop()) {
1265                         os << "\\lyxline{\\" << getFont(bparams, 0).latexSize() << '}'
1266                            << "\\vspace{-1\\parskip}";
1267                         further_blank_line = true;
1268                 }
1269
1270                 if (further_blank_line) {
1271                         os << '\n';
1272                         texrow.newline();
1273                 }
1274         } else {
1275                 style = textclasslist[bparams.textclass].defaultLayout();
1276         }
1277
1278         Language const * language = getParLanguage(bparams);
1279         Language const * doc_language = bparams.language;
1280         Language const * previous_language = previous()
1281                 ? previous()->getParLanguage(bparams) : doc_language;
1282
1283         if (language->babel() != previous_language->babel()
1284             // check if we already put language command in TeXEnvironment()
1285             && !(style.isEnvironment()
1286                  && (!previous() || previous()->layout() != layout() ||
1287                          previous()->params().depth() != params().depth())))
1288         {
1289                 if (!lyxrc.language_command_end.empty() &&
1290                     previous_language->babel() != doc_language->babel())
1291                 {
1292                         os << subst(lyxrc.language_command_end, "$$lang",
1293                                     previous_language->babel())
1294                            << endl;
1295                         texrow.newline();
1296                 }
1297
1298                 if (lyxrc.language_command_end.empty() ||
1299                     language->babel() != doc_language->babel())
1300                 {
1301                         os << subst(lyxrc.language_command_begin, "$$lang",
1302                                     language->babel())
1303                            << endl;
1304                         texrow.newline();
1305                 }
1306         }
1307
1308         if (bparams.inputenc == "auto" &&
1309             language->encoding() != previous_language->encoding()) {
1310                 os << "\\inputencoding{"
1311                    << language->encoding()->LatexName()
1312                    << "}" << endl;
1313                 texrow.newline();
1314         }
1315
1316         switch (style.latextype) {
1317         case LATEX_COMMAND:
1318                 os << '\\'
1319                    << style.latexname()
1320                    << style.latexparam();
1321                 break;
1322         case LATEX_ITEM_ENVIRONMENT:
1323                 if (bibkey) {
1324                         bibkey->latex(buf, os, false, false);
1325                 } else
1326                         os << "\\item ";
1327                 break;
1328         case LATEX_LIST_ENVIRONMENT:
1329                 os << "\\item ";
1330                 break;
1331         default:
1332                 break;
1333         }
1334
1335         bool need_par = simpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
1336  
1337         // Make sure that \\par is done with the font of the last
1338         // character if this has another size as the default.
1339         // This is necessary because LaTeX (and LyX on the screen)
1340         // calculates the space between the baselines according
1341         // to this font. (Matthias)
1342         //
1343         // Is this really needed ? (Dekel)
1344         // We do not need to use to change the font for the last paragraph
1345         // or for a command.
1346         LyXFont const font =
1347                 (size() == 0
1348                  ? getLayoutFont(bparams) : getFont(bparams, size() - 1));
1349
1350         bool is_command = style.isCommand();
1351         
1352         if (style.resfont.size() != font.size() && next_ && !is_command) {
1353                 if (!need_par)
1354                         os << "{";
1355                 os << "\\" << font.latexSize() << " \\par}";
1356         } else if (need_par) {
1357                 os << "\\par}";
1358         } else if (is_command)
1359                 os << "}";
1360
1361         switch (style.latextype) {
1362         case LATEX_ITEM_ENVIRONMENT:
1363         case LATEX_LIST_ENVIRONMENT:
1364                 if (next_ && (params().depth() < next_->params().depth())) {
1365                         os << '\n';
1366                         texrow.newline();
1367                 }
1368                 break;
1369         case LATEX_ENVIRONMENT:
1370                 // if its the last paragraph of the current environment
1371                 // skip it otherwise fall through
1372                 if (next_
1373                     && (next_->layout() != layout()
1374                         || next_->params().depth() != params().depth()))
1375                         break;
1376                 // fall through possible
1377         default:
1378                 // we don't need it for the last paragraph!!!
1379                 if (next_) {
1380                         os << '\n';
1381                         texrow.newline();
1382                 }
1383         }
1384         
1385         if ((in == 0) || !in->forceDefaultParagraphs(in)) {
1386                 further_blank_line = false;
1387                 if (params().lineBottom()) {
1388                         os << "\\lyxline{\\" << font.latexSize() << '}';
1389                         further_blank_line = true;
1390                 }
1391
1392                 if (params().spaceBottom().kind() != VSpace::NONE) {
1393                         os << params().spaceBottom().asLatexCommand(bparams);
1394                         further_blank_line = true;
1395                 }
1396
1397                 if (params().pagebreakBottom()) {
1398                         os << "\\newpage";
1399                         further_blank_line = true;
1400                 }
1401
1402                 if (further_blank_line) {
1403                         os << '\n';
1404                         texrow.newline();
1405                 }
1406
1407                 if (!params().spacing().isDefault()
1408                         && (!next_ || !next_->hasSameLayout(this))) {
1409                         os << params().spacing().writeEnvirEnd() << "\n";
1410                         texrow.newline();
1411                 }
1412         }
1413         
1414         // we don't need it for the last paragraph!!!
1415         if (next_) {
1416                 os << '\n';
1417                 texrow.newline();
1418         } else {
1419                 // Since \selectlanguage write the language to the aux file,
1420                 // we need to reset the language at the end of footnote or
1421                 // float.
1422
1423                 if (language->babel() != doc_language->babel()) {
1424                         if (lyxrc.language_command_end.empty())
1425                                 os << subst(lyxrc.language_command_begin,
1426                                             "$$lang",
1427                                             doc_language->babel())
1428                                    << endl;
1429                         else
1430                                 os << subst(lyxrc.language_command_end,
1431                                             "$$lang",
1432                                             language->babel())
1433                                    << endl;
1434                         texrow.newline();
1435                 }
1436         }
1437
1438         lyxerr[Debug::LATEX] << "TeXOnePar...done " << next_ << endl;
1439         return next_;
1440 }
1441
1442 // This could go to ParagraphParameters if we want to
1443 int Paragraph::startTeXParParams(BufferParams const & bparams,
1444                                  ostream & os) const
1445 {
1446         int column = 0;
1447         
1448         if (params().noindent()) {
1449                 os << "\\noindent ";
1450                 column += 10;
1451         }
1452                         
1453         switch (params().align()) {
1454         case LYX_ALIGN_NONE:
1455         case LYX_ALIGN_BLOCK:
1456         case LYX_ALIGN_LAYOUT:
1457         case LYX_ALIGN_SPECIAL:
1458                 break;
1459         case LYX_ALIGN_LEFT:
1460                 if (getParLanguage(bparams)->babel() != "hebrew") {
1461                         os << "\\begin{flushleft}";
1462                         column += 17;
1463                 } else {
1464                         os << "\\begin{flushright}";
1465                         column += 18;
1466                 }
1467                 break;
1468         case LYX_ALIGN_RIGHT:
1469                 if (getParLanguage(bparams)->babel() != "hebrew") {
1470                         os << "\\begin{flushright}";
1471                         column += 18;
1472                 } else {
1473                         os << "\\begin{flushleft}";
1474                         column += 17;
1475                 }
1476                 break;
1477         case LYX_ALIGN_CENTER:
1478                 os << "\\begin{center}";
1479                 column += 14;
1480                 break;
1481         }
1482         
1483         return column;
1484 }
1485
1486 // This could go to ParagraphParameters if we want to
1487 int Paragraph::endTeXParParams(BufferParams const & bparams,
1488                                ostream & os) const
1489 {
1490         int column = 0;
1491         
1492         switch (params().align()) {
1493         case LYX_ALIGN_NONE:
1494         case LYX_ALIGN_BLOCK:
1495         case LYX_ALIGN_LAYOUT:
1496         case LYX_ALIGN_SPECIAL:
1497                 break;
1498         case LYX_ALIGN_LEFT:
1499                 if (getParLanguage(bparams)->babel() != "hebrew") {
1500                         os << "\\end{flushleft}";
1501                         column = 15;
1502                 } else {
1503                         os << "\\end{flushright}";
1504                         column = 16;
1505                 }
1506                 break;
1507         case LYX_ALIGN_RIGHT:
1508                 if (getParLanguage(bparams)->babel() != "hebrew") {
1509                         os << "\\end{flushright}";
1510                         column+= 16;
1511                 } else {
1512                         os << "\\end{flushleft}";
1513                         column = 15;
1514                 }
1515                 break;
1516         case LYX_ALIGN_CENTER:
1517                 os << "\\end{center}";
1518                 column = 12;
1519                 break;
1520         }
1521         return column;
1522 }
1523
1524
1525 // This one spits out the text of the paragraph
1526 bool Paragraph::simpleTeXOnePar(Buffer const * buf,
1527                                 BufferParams const & bparams,
1528                                 ostream & os, TexRow & texrow,
1529                                 bool moving_arg)
1530 {
1531         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...     " << this << endl;
1532
1533         bool return_value = false;
1534
1535         LyXLayout style;
1536         
1537         // well we have to check if we are in an inset with unlimited
1538         // lenght (all in one row) if that is true then we don't allow
1539         // any special options in the paragraph and also we don't allow
1540         // any environment other then "Standard" to be valid!
1541         bool asdefault =
1542                 (inInset() && inInset()->forceDefaultParagraphs(inInset()));
1543
1544         if (asdefault) {
1545                 style = textclasslist[bparams.textclass].defaultLayout();
1546         } else {
1547                 style = textclasslist[bparams.textclass][layout()];
1548         }
1549         
1550         LyXFont basefont;
1551
1552         // Maybe we have to create a optional argument.
1553         pos_type main_body;
1554         if (style.labeltype != LABEL_MANUAL)
1555                 main_body = 0;
1556         else
1557                 main_body = beginningOfMainBody();
1558
1559         int column = 0;
1560
1561         if (main_body > 0) {
1562                 os << '[';
1563                 ++column;
1564                 basefont = getLabelFont(bparams);
1565         } else {
1566                 basefont = getLayoutFont(bparams);
1567         }
1568
1569         moving_arg |= style.needprotect;
1570  
1571         // Which font is currently active?
1572         LyXFont running_font(basefont);
1573         // Do we have an open font change?
1574         bool open_font = false;
1575
1576         texrow.start(this, 0);
1577
1578         // if the paragraph is empty, the loop will not be entered at all
1579         if (!size()) {
1580                 if (style.isCommand()) {
1581                         os << '{';
1582                         ++column;
1583                 }
1584                 if (!asdefault)
1585                         column += startTeXParParams(bparams, os);
1586
1587         }
1588
1589         for (pos_type i = 0; i < size(); ++i) {
1590                 ++column;
1591                 // First char in paragraph or after label?
1592                 if (i == main_body) {
1593                         if (main_body > 0) {
1594                                 if (open_font) {
1595                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1596                                         open_font = false;
1597                                 }
1598                                 basefont = getLayoutFont(bparams);
1599                                 running_font = basefont;
1600                                 os << ']';
1601                                 ++column;
1602                         }
1603                         if (style.isCommand()) {
1604                                 os << '{';
1605                                 ++column;
1606                         }
1607                         
1608                         if (!asdefault)
1609                                 column += startTeXParParams(bparams, os);
1610                 }
1611                 
1612                 value_type c = getChar(i);
1613
1614                 // Fully instantiated font
1615                 LyXFont font = getFont(bparams, i);
1616
1617                 LyXFont const & last_font = running_font;
1618
1619                 // Spaces at end of font change are simulated to be
1620                 // outside font change, i.e. we write "\textXX{text} "
1621                 // rather than "\textXX{text }". (Asger)
1622                 if (open_font && c == ' ' && i <= size() - 2) {
1623                         LyXFont const & next_font = getFont(bparams, i + 1);
1624                         if (next_font != running_font
1625                             && next_font != font) {
1626                                 font = next_font;
1627                         }
1628                 }
1629                 
1630                 // We end font definition before blanks
1631                 if (font != running_font && open_font) {
1632                         column += running_font.latexWriteEndChanges(os,
1633                                                                     basefont,
1634                                                                     (i == main_body-1) ? basefont : font);
1635                         running_font = basefont;
1636                         open_font = false;
1637                 }
1638
1639                 // Blanks are printed before start of fontswitch
1640                 if (c == ' ') {
1641                         // Do not print the separation of the optional argument
1642                         if (i != main_body - 1) {
1643                                 pimpl_->simpleTeXBlanks(os, texrow, i,
1644                                                        column, font, style);
1645                         }
1646                 }
1647
1648                 // Do we need to change font?
1649                 if (font != running_font && i != main_body - 1) {
1650                         column += font.latexWriteStartChanges(os, basefont,
1651                                                               last_font);
1652                         running_font = font;
1653                         open_font = true;
1654                 }
1655
1656                 if (c == Paragraph::META_NEWLINE) {
1657                         // newlines are handled differently here than
1658                         // the default in SimpleTeXSpecialChars().
1659                         if (!style.newline_allowed) {
1660                                 os << '\n';
1661                         } else {
1662                                 if (open_font) {
1663                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1664                                         open_font = false;
1665                                 }
1666                                 basefont = getLayoutFont(bparams);
1667                                 running_font = basefont;
1668                                 if (font.family() == 
1669                                     LyXFont::TYPEWRITER_FAMILY) {
1670                                         os << "~";
1671                                 }
1672                                 if (moving_arg)
1673                                         os << "\\protect ";
1674                                 os << "\\\\\n";
1675                         }
1676                         texrow.newline();
1677                         texrow.start(this, i + 1);
1678                         column = 0;
1679                 } else {
1680                         pimpl_->simpleTeXSpecialChars(buf, bparams,
1681                                                       os, texrow, moving_arg,
1682                                                       font, running_font, 
1683                                                       basefont, open_font, 
1684                                                       style, i, column, c);
1685                 }
1686         }
1687
1688         // If we have an open font definition, we have to close it
1689         if (open_font) {
1690 #ifdef FIXED_LANGUAGE_END_DETECTION
1691                 if (next_) {
1692                         running_font
1693                                 .latexWriteEndChanges(os, basefont,
1694                                                       next_->getFont(bparams,
1695                                                       0));
1696                 } else {
1697                         running_font.latexWriteEndChanges(os, basefont,
1698                                                           basefont);
1699                 }
1700 #else
1701 #ifdef WITH_WARNINGS
1702 //#warning For now we ALWAYS have to close the foreign font settings if they are
1703 //#warning there as we start another \selectlanguage with the next paragraph if
1704 //#warning we are in need of this. This should be fixed sometime (Jug)
1705 #endif
1706                 running_font.latexWriteEndChanges(os, basefont,  basefont);
1707 #endif
1708         }
1709
1710         // Needed if there is an optional argument but no contents.
1711         if (main_body > 0 && main_body == size()) {
1712                 os << "]~";
1713                 return_value = false;
1714         }
1715
1716         if (!asdefault) {
1717                 column += endTeXParParams(bparams, os);
1718         }
1719
1720         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...done " << this << endl;
1721         return return_value;
1722 }
1723
1724
1725 bool Paragraph::sgmlConvertChar(char c, string & sgml_string)
1726 {
1727         bool retval = false;
1728         switch (c) {
1729         case Paragraph::META_HFILL:
1730                 sgml_string.erase();
1731                 break;
1732         case Paragraph::META_NEWLINE:
1733                 sgml_string = '\n';
1734                 break;
1735         case '&': 
1736                 sgml_string = "&amp;";
1737                 break;
1738         case '<': 
1739                 sgml_string = "&lt;"; 
1740                 break;
1741         case '>':
1742                 sgml_string = "&gt;"; 
1743                 break;
1744         case '$': 
1745                 sgml_string = "&dollar;"; 
1746                 break;
1747         case '#': 
1748                 sgml_string = "&num;";
1749                 break;
1750         case '%': 
1751                 sgml_string = "&percnt;";
1752                 break;
1753         case '[': 
1754                 sgml_string = "&lsqb;";
1755                 break;
1756         case ']': 
1757                 sgml_string = "&rsqb;";
1758                 break;
1759         case '{': 
1760                 sgml_string = "&lcub;";
1761                 break;
1762         case '}': 
1763                 sgml_string = "&rcub;";
1764                 break;
1765         case '~': 
1766                 sgml_string = "&tilde;";
1767                 break;
1768         case '"': 
1769                 sgml_string = "&quot;";
1770                 break;
1771         case '\\': 
1772                 sgml_string = "&bsol;";
1773                 break;
1774         case ' ':
1775                 retval = true;
1776                 sgml_string = ' ';
1777                 break;
1778         case '\0': // Ignore :-)
1779                 sgml_string.erase();
1780                 break;
1781         default:
1782                 sgml_string = c;
1783                 break;
1784         }
1785         return retval;
1786 }
1787
1788
1789 Paragraph * Paragraph::TeXEnvironment(Buffer const * buf,
1790                                             BufferParams const & bparams,
1791                                             ostream & os, TexRow & texrow)
1792 {
1793         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << this << endl;
1794
1795         LyXLayout const & style =
1796                 textclasslist[bparams.textclass][layout()];
1797
1798         Language const * language = getParLanguage(bparams);
1799         Language const * doc_language = bparams.language;
1800         Language const * previous_language = previous_
1801                 ? previous_->getParLanguage(bparams) : doc_language;
1802         if (language->babel() != previous_language->babel()) {
1803
1804                 if (!lyxrc.language_command_end.empty() &&
1805                     previous_language->babel() != doc_language->babel()) {
1806                         os << subst(lyxrc.language_command_end, "$$lang",
1807                                     previous_language->babel())
1808                            << endl;
1809                         texrow.newline();
1810                 }
1811
1812                 if (lyxrc.language_command_end.empty() ||
1813                     language->babel() != doc_language->babel()) {
1814                         os << subst(lyxrc.language_command_begin, "$$lang",
1815                                     language->babel())
1816                            << endl;
1817                         texrow.newline();
1818                 }
1819         }
1820
1821         if (style.isEnvironment()) {
1822                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
1823                         os << "\\begin{" << style.latexname() << "}{"
1824                            << params().labelWidthString() << "}\n";
1825                 } else if (style.labeltype == LABEL_BIBLIO) {
1826                         // ale970405
1827                         os << "\\begin{" << style.latexname() << "}{"
1828                            <<  bibitemWidest(buf)
1829                            << "}\n";
1830                 } else if (style.latextype == LATEX_ITEM_ENVIRONMENT) {
1831                         os << "\\begin{" << style.latexname() << '}'
1832                            << style.latexparam() << '\n';
1833                 } else 
1834                         os << "\\begin{" << style.latexname() << '}'
1835                            << style.latexparam() << '\n';
1836                 texrow.newline();
1837         }
1838         Paragraph * par = this;
1839         do {
1840                 par = par->TeXOnePar(buf, bparams, os, texrow, false);
1841
1842                 if (par && par->params().depth() > params().depth()) {
1843                         if (textclasslist[bparams.textclass][par->layout()].isParagraph()
1844                             // Thinko!
1845                             // How to handle this? (Lgb)
1846                             //&& !suffixIs(os, "\n\n")
1847                                 ) {
1848                                 // There should be at least one '\n' already
1849                                 // but we need there to be two for Standard 
1850                                 // paragraphs that are depth-increment'ed to be
1851                                 // output correctly.  However, tables can
1852                                 // also be paragraphs so don't adjust them.
1853                                 // ARRae
1854                                 // Thinkee:
1855                                 // Will it ever harm to have one '\n' too
1856                                 // many? i.e. that we sometimes will have
1857                                 // three in a row. (Lgb)
1858                                 os << '\n';
1859                                 texrow.newline();
1860                         }
1861                         par = par->pimpl_->TeXDeeper(buf, bparams, os, texrow);
1862                 }
1863         } while (par
1864                  && par->layout() == layout()
1865                  && par->params().depth() == params().depth());
1866  
1867         if (style.isEnvironment()) {
1868                 os << "\\end{" << style.latexname() << "}\n";
1869                 texrow.newline();
1870         }
1871
1872         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << par << endl;
1873         return par;  // ale970302
1874 }
1875
1876
1877 bool Paragraph::isHfill(pos_type pos) const
1878 {
1879         return IsHfillChar(getChar(pos));
1880 }
1881
1882
1883 bool Paragraph::isInset(pos_type pos) const
1884 {
1885         return IsInsetChar(getChar(pos));
1886 }
1887
1888
1889 bool Paragraph::isNewline(pos_type pos) const
1890 {
1891         return pos >= 0 && IsNewlineChar(getChar(pos));
1892 }
1893
1894
1895 bool Paragraph::isSeparator(pos_type pos) const
1896 {
1897         return IsSeparatorChar(getChar(pos));
1898 }
1899
1900
1901 bool Paragraph::isLineSeparator(pos_type pos) const
1902 {
1903         value_type const c = getChar(pos);
1904         return IsLineSeparatorChar(c)
1905                 || (IsInsetChar(c) && getInset(pos)->isLineSeparator());
1906 }
1907
1908
1909 bool Paragraph::isKomma(pos_type pos) const
1910 {
1911         return IsKommaChar(getChar(pos));
1912 }
1913
1914
1915 /// Used by the spellchecker
1916 bool Paragraph::isLetter(pos_type pos) const
1917 {
1918         value_type const c = getChar(pos);
1919         if (IsLetterChar(c))
1920                 return true;
1921         if (isInset(pos)) 
1922                 return getInset(pos)->isLetter();
1923         // We want to pass the ' and escape chars to ispell
1924         string const extra = lyxrc.isp_esc_chars + '\'';
1925         return contains(extra, c);
1926 }
1927  
1928  
1929 bool Paragraph::isWord(pos_type pos) const
1930 {
1931         return IsWordChar(getChar(pos)) ;
1932 }
1933
1934
1935 Language const *
1936 Paragraph::getParLanguage(BufferParams const & bparams) const 
1937 {
1938         if (size() > 0) {
1939 #ifndef INHERIT_LANGUAGE
1940                 return getFirstFontSettings().language();
1941 #else
1942                 Language const * lang = getFirstFontSettings().language();
1943 #ifdef WITH_WARNINGS
1944 #warning We should make this somewhat better, any ideas? (Jug)
1945 #endif
1946                 if (lang == inherit_language || lang == ignore_language)
1947                         lang = bparams.language;
1948                 return lang;
1949 #endif
1950         } else if (previous_)
1951                 return previous_->getParLanguage(bparams);
1952         else
1953                 return bparams.language;
1954 }
1955
1956
1957 bool Paragraph::isRightToLeftPar(BufferParams const & bparams) const
1958 {
1959         return lyxrc.rtl_support
1960                 && getParLanguage(bparams)->RightToLeft();
1961 }
1962
1963
1964 void Paragraph::changeLanguage(BufferParams const & bparams,
1965                                   Language const * from, Language const * to)
1966 {
1967         for (pos_type i = 0; i < size(); ++i) {
1968                 LyXFont font = getFontSettings(bparams, i);
1969                 if (font.language() == from) {
1970                         font.setLanguage(to);
1971                         setFont(i, font);
1972                 }
1973         }
1974 }
1975
1976
1977 bool Paragraph::isMultiLingual(BufferParams const & bparams)
1978 {
1979         Language const * doc_language = bparams.language;
1980         for (Pimpl::FontList::const_iterator cit = pimpl_->fontlist.begin();
1981              cit != pimpl_->fontlist.end(); ++cit)
1982                 if (cit->font().language() != ignore_language &&
1983                     cit->font().language() != latex_language &&
1984 #ifdef INHERIT_LANGUAGE
1985                         cit->font().language() != inherit_language &&
1986 #endif
1987                         cit->font().language() != doc_language)
1988                         return true;
1989         return false;
1990 }
1991
1992
1993 // Convert the paragraph to a string.
1994 // Used for building the table of contents
1995 string const Paragraph::asString(Buffer const * buffer, bool label)
1996 {
1997         BufferParams const & bparams = buffer->params;
1998         string s;
1999         if (label && !params().labelString().empty())
2000                 s += params().labelString() + ' ';
2001         string::size_type const len = s.size();
2002
2003         for (pos_type i = 0; i < size(); ++i) {
2004                 value_type c = getChar(i);
2005                 if (IsPrintable(c))
2006                         s += c;
2007                 else if (c == META_INSET &&
2008                          getInset(i)->lyxCode() == Inset::MATH_CODE) {
2009                         ostringstream ost;
2010                         getInset(i)->ascii(buffer, ost);
2011                         s += subst(ost.str().c_str(),'\n',' ');
2012                 }
2013         }
2014
2015         if (isRightToLeftPar(bparams))
2016                 reverse(s.begin() + len,s.end());
2017
2018         return s;
2019 }
2020
2021
2022 string const Paragraph::asString(Buffer const * buffer, 
2023                                  pos_type beg, pos_type end, bool label)
2024 {
2025         ostringstream ost;
2026
2027         if (beg == 0 && label && !params().labelString().empty())
2028                 ost << params().labelString() << ' ';
2029
2030         for (pos_type i = beg; i < end; ++i) {
2031                 value_type const c = getUChar(buffer->params, i);
2032                 if (IsPrintable(c))
2033                         ost << c;
2034                 else if (c == META_NEWLINE)
2035                         ost << '\n';
2036                 else if (c == META_HFILL)
2037                         ost << '\t'; 
2038                 else if (c == META_INSET) {
2039                         getInset(i)->ascii(buffer, ost);
2040                 }
2041         }
2042
2043         return ost.str().c_str();
2044 }
2045
2046
2047 void Paragraph::setInsetOwner(Inset * i)
2048 {
2049         pimpl_->inset_owner = i;
2050         for (InsetList::const_iterator cit = insetlist.begin();
2051              cit != insetlist.end(); ++cit) {
2052                 if (cit->inset)
2053                         cit->inset->setOwner(i);
2054         }
2055 }
2056
2057
2058 void Paragraph::deleteInsetsLyXText(BufferView * bv)
2059 {
2060         // then the insets
2061         for (InsetList::const_iterator cit = insetlist.begin();
2062              cit != insetlist.end(); ++cit) {
2063                 if (cit->inset) {
2064                         if (cit->inset->isTextInset()) {
2065                                 static_cast<UpdatableInset *>
2066                                         (cit->inset)->deleteLyXText(bv, true);
2067                         }
2068                 }
2069         }
2070 }
2071
2072
2073 void Paragraph::resizeInsetsLyXText(BufferView * bv)
2074 {
2075         // then the insets
2076         for (InsetList::const_iterator cit = insetlist.begin();
2077              cit != insetlist.end(); ++cit)
2078         {
2079                 if (cit->inset) {
2080                         if (cit->inset->isTextInset()) {
2081                                 static_cast<UpdatableInset *>
2082                                         (cit->inset)->resizeLyXText(bv, true);
2083                         }
2084                 }
2085         }
2086 }
2087
2088
2089 void Paragraph::setContentsFromPar(Paragraph * par)
2090 {
2091         pimpl_->setContentsFromPar(par);
2092 }
2093
2094
2095 lyx::pos_type Paragraph::size() const
2096 {
2097         return pimpl_->size();
2098 }
2099
2100
2101 Paragraph::value_type Paragraph::getChar(pos_type pos) const
2102 {
2103         return pimpl_->getChar(pos);
2104 }
2105
2106
2107 int Paragraph::id() const
2108 {
2109         return pimpl_->id_;
2110 }
2111
2112
2113 void  Paragraph::id(int id_arg)
2114 {
2115         pimpl_->id_ = id_arg;
2116 }
2117
2118
2119 string const & Paragraph::layout() const
2120 {
2121         return layout_;
2122 }
2123
2124
2125 void Paragraph::layout(string const & new_layout)
2126 {
2127         layout_ = new_layout;
2128 }
2129
2130
2131 bool Paragraph::isFirstInSequence() const
2132 {
2133         Paragraph const * dhook = depthHook(getDepth());
2134         return (dhook == this
2135                 || dhook->layout() != layout()
2136                 || dhook->getDepth() != getDepth());
2137 }
2138
2139
2140 Inset * Paragraph::inInset() const
2141 {
2142         return pimpl_->inset_owner;
2143 }
2144
2145
2146 void Paragraph::clearContents()
2147 {
2148         pimpl_->clear();
2149 }
2150
2151
2152 void Paragraph::setCounter(int i, int v)
2153 {
2154         pimpl_->counter_[i] = v;
2155 }
2156
2157
2158 int Paragraph::getCounter(int i) const
2159 {
2160         return pimpl_->counter_[i];
2161 }
2162
2163
2164 void Paragraph::incCounter(int i)
2165 {
2166         pimpl_->counter_[i]++;
2167 }
2168
2169
2170 void Paragraph::setChar(pos_type pos, value_type c)
2171 {
2172         pimpl_->setChar(pos, c);
2173 }
2174
2175
2176 Paragraph::inset_iterator::inset_iterator(Paragraph::InsetList::iterator const & iter)
2177  : it(iter) 
2178 {}
2179
2180
2181 Paragraph::inset_iterator Paragraph::inset_iterator_begin()
2182 {
2183         return inset_iterator(insetlist.begin());
2184 }
2185
2186
2187 Paragraph::inset_iterator Paragraph::inset_iterator_end()
2188 {
2189         return inset_iterator(insetlist.end());
2190 }
2191
2192
2193 ParagraphParameters & Paragraph::params()
2194 {
2195         return pimpl_->params;
2196 }
2197
2198
2199 ParagraphParameters const & Paragraph::params() const
2200 {
2201         return pimpl_->params;
2202 }
2203
2204
2205 Paragraph * Paragraph::getParFromID(int id) const
2206 {
2207         return pimpl_->getParFromID(id);
2208 }
2209
2210
2211 bool Paragraph::isFreeSpacing() const
2212 {
2213         // for now we just need this, later should we need this in some
2214         // other way we can always add a function to Inset::() too.
2215         if (pimpl_->inset_owner && pimpl_->inset_owner->owner())
2216                 return (pimpl_->inset_owner->owner()->lyxCode() == Inset::ERT_CODE);
2217         return false;
2218 }