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