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