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