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