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