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