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