]> git.lyx.org Git - lyx.git/blob - src/paragraph.C
643289168cd8125bfbcb31ce137607c0ee413a42
[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) const
665 {
666         LyXFont::FONT_SIZE maxsize = LyXFont::SIZE_TINY;
667         if (pimpl_->fontlist.empty())
668                 return maxsize;
669
670         Pimpl::FontTable end_search(endpos, LyXFont());
671         Pimpl::FontList::const_iterator end_it =
672                 lower_bound(pimpl_->fontlist.begin(),
673                             pimpl_->fontlist.end(),
674                             end_search, Pimpl::matchFT());
675         if (end_it != pimpl_->fontlist.end())
676                 ++end_it;
677
678         Pimpl::FontTable start_search(startpos, LyXFont());
679         for (Pimpl::FontList::const_iterator cit =
680                         lower_bound(pimpl_->fontlist.begin(),
681                                     pimpl_->fontlist.end(),
682                                     start_search, Pimpl::matchFT());
683              cit != end_it; ++cit)
684         {
685                 LyXFont::FONT_SIZE size = cit->font().size();
686                 if (size > maxsize && size <= LyXFont::SIZE_HUGER)
687                         maxsize = size;
688         }
689         return maxsize;
690 }
691
692
693 Paragraph::value_type
694 Paragraph::getUChar(BufferParams const & bparams,
695                        Paragraph::size_type pos) const
696 {
697         value_type c = getChar(pos);
698         if (!lyxrc.rtl_support)
699                 return c;
700
701         value_type uc = c;
702         switch (c) {
703         case '(':
704                 uc = ')';
705                 break;
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         }
728         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
729                 return uc;
730         else
731                 return c;
732 }
733
734
735 void Paragraph::setFont(Paragraph::size_type pos,
736                            LyXFont const & font)
737 {
738         lyx::Assert(pos <= size());
739
740         // First, reduce font against layout/label font
741         // Update: The SetCharFont() routine in text2.C already
742         // reduces font, so we don't need to do that here. (Asger)
743         // No need to simplify this because it will disappear
744         // in a new kernel. (Asger)
745         // Next search font table
746
747         Pimpl::FontTable search_font(pos, LyXFont());
748         Pimpl::FontList::iterator it = lower_bound(pimpl_->fontlist.begin(),
749                                             pimpl_->fontlist.end(),
750                                             search_font, Pimpl::matchFT());
751         unsigned int i = it - pimpl_->fontlist.begin();
752         bool notfound = it == pimpl_->fontlist.end();
753
754         if (!notfound && pimpl_->fontlist[i].font() == font)
755                 return;
756
757         bool begin = pos == 0 || notfound ||
758                 (i > 0 && pimpl_->fontlist[i-1].pos() == pos - 1);
759         // Is position pos is a beginning of a font block?
760         bool end = !notfound && pimpl_->fontlist[i].pos() == pos;
761         // Is position pos is the end of a font block?
762         if (begin && end) { // A single char block
763                 if (i + 1 < pimpl_->fontlist.size() &&
764                     pimpl_->fontlist[i + 1].font() == font) {
765                         // Merge the singleton block with the next block
766                         pimpl_->fontlist.erase(pimpl_->fontlist.begin() + i);
767                         if (i > 0 && pimpl_->fontlist[i - 1].font() == font)
768                                 pimpl_->fontlist.erase(pimpl_->fontlist.begin() + i-1);
769                 } else if (i > 0 && pimpl_->fontlist[i - 1].font() == font) {
770                         // Merge the singleton block with the previous block
771                         pimpl_->fontlist[i - 1].pos(pos);
772                         pimpl_->fontlist.erase(pimpl_->fontlist.begin() + i);
773                 } else
774                         pimpl_->fontlist[i].font(font);
775         } else if (begin) {
776                 if (i > 0 && pimpl_->fontlist[i - 1].font() == font)
777                         pimpl_->fontlist[i - 1].pos(pos);
778                 else
779                         pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i,
780                                         Pimpl::FontTable(pos, font));
781         } else if (end) {
782                 pimpl_->fontlist[i].pos(pos - 1);
783                 if (!(i + 1 < pimpl_->fontlist.size() &&
784                       pimpl_->fontlist[i + 1].font() == font))
785                         pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i + 1,
786                                         Pimpl::FontTable(pos, font));
787         } else { // The general case. The block is splitted into 3 blocks
788                 pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i, 
789                                 Pimpl::FontTable(pos - 1, pimpl_->fontlist[i].font()));
790                 pimpl_->fontlist.insert(pimpl_->fontlist.begin() + i + 1,
791                                 Pimpl::FontTable(pos, font));
792         }
793 }
794
795
796
797 void Paragraph::next(Paragraph * p)
798 {
799         next_ = p;
800 }
801
802
803 // This function is able to hide closed footnotes.
804 Paragraph * Paragraph::next()
805 {
806         return next_;
807 }
808
809
810 Paragraph const * Paragraph::next() const
811 {
812         return next_;
813 }
814
815
816 void Paragraph::previous(Paragraph * p)
817 {
818         previous_ = p;
819 }
820
821
822 // This function is able to hide closed footnotes.
823 Paragraph * Paragraph::previous()
824 {
825         return previous_;
826 }
827
828
829 // This function is able to hide closed footnotes.
830 Paragraph const * Paragraph::previous() const
831 {
832         return previous_;
833 }
834
835
836 void Paragraph::breakParagraph(BufferParams const & bparams,
837                                   Paragraph::size_type pos,
838                                   int flag)
839 {
840         // create a new paragraph
841         Paragraph * tmp = new Paragraph(this);
842         // remember to set the inset_owner
843         tmp->setInsetOwner(inInset());
844         
845         // this is an idea for a more userfriendly layout handling, I will
846         // see what the users say
847         
848         // layout stays the same with latex-environments
849         if (flag) {
850                 tmp->setOnlyLayout(layout);
851                 tmp->setLabelWidthString(params().labelWidthString());
852         }
853         
854         if (size() > pos || !size() || flag == 2) {
855                 tmp->setOnlyLayout(layout);
856                 tmp->params().align(params().align());
857                 tmp->setLabelWidthString(params().labelWidthString());
858                 
859                 tmp->params().lineBottom(params().lineBottom());
860                 params().lineBottom(false);
861                 tmp->params().pagebreakBottom(params().pagebreakBottom());
862                 params().pagebreakBottom(false);
863                 tmp->params().spaceBottom(params().spaceBottom());
864                 params().spaceBottom(VSpace(VSpace::NONE));
865                 
866                 tmp->params().depth(params().depth());
867                 tmp->params().noindent(params().noindent());
868                 
869                 // copy everything behind the break-position
870                 // to the new paragraph
871                 size_type pos_end = pimpl_->size() - 1;
872                 size_type i = pos;
873                 size_type j = pos;
874                 for (; i <= pos_end; ++i) {
875                         cutIntoMinibuffer(bparams, i);
876                         if (tmp->insertFromMinibuffer(j - pos))
877                                 ++j;
878                 }
879                 for (i = pos_end; i >= pos; --i) {
880                         erase(i);
881                 }
882         }
883         
884         // just an idea of me
885         if (!pos) {
886                 tmp->params().lineTop(params().lineTop());
887                 tmp->params().pagebreakTop(params().pagebreakTop());
888                 tmp->params().spaceTop(params().spaceTop());
889                 tmp->bibkey = bibkey;
890                 clear();
891                 // layout stays the same with latex-environments
892                 if (flag) {
893                         setOnlyLayout(tmp->layout);
894                         setLabelWidthString(tmp->params().labelWidthString());
895                         params().depth(tmp->params().depth());
896                 }
897         }
898 }
899         
900
901 void Paragraph::makeSameLayout(Paragraph const * par)
902 {
903         layout = par->layout;
904         // move to pimpl?
905         params() = par->params();
906 }
907
908
909 int Paragraph::stripLeadingSpaces(LyXTextClassList::size_type tclass) 
910 {
911         if (textclasslist.Style(tclass, getLayout()).free_spacing)
912                 return 0;
913         
914         int i = 0;
915         while (size()
916                && (isNewline(0) || isLineSeparator(0))){
917                 erase(0);
918                 ++i;
919         }
920
921         return i;
922 }
923
924
925 bool Paragraph::hasSameLayout(Paragraph const * par) const
926 {
927         return 
928                 par->layout == layout &&
929                 params().sameLayout(par->params());
930 }
931
932
933 void Paragraph::breakParagraphConservative(BufferParams const & bparams,
934                                            Paragraph::size_type pos)
935 {
936         // create a new paragraph
937         Paragraph * tmp = new Paragraph(this);
938         tmp->makeSameLayout(this);
939
940         // When can pos > Last()?
941         // I guess pos == Last() is possible.
942         if (size() > pos) {
943                 // copy everything behind the break-position to the new
944                 // paragraph
945                 size_type pos_end = pimpl_->size() - 1;
946
947                 //size_type i = pos;
948                 //size_type j = pos;
949                 for (size_type i = pos, j = pos; i <= pos_end; ++i) {
950                         cutIntoMinibuffer(bparams, i);
951                         if (tmp->insertFromMinibuffer(j - pos))
952                                 ++j;
953                 }
954                 
955                 for (size_type k = pos_end; k >= pos; --k) {
956                         erase(k);
957                 }
958         }
959 }
960    
961
962 // Be carefull, this does not make any check at all.
963 // This method has wrong name, it combined this par with the next par.
964 // In that sense it is the reverse of break paragraph. (Lgb)
965 void Paragraph::pasteParagraph(BufferParams const & bparams)
966 {
967         // copy the next paragraph to this one
968         Paragraph * the_next = next();
969    
970         // first the DTP-stuff
971         params().lineBottom(the_next->params().lineBottom());
972         params().spaceBottom(the_next->params().spaceBottom());
973         params().pagebreakBottom(the_next->params().pagebreakBottom());
974
975         size_type pos_end = the_next->pimpl_->size() - 1;
976         size_type pos_insert = size();
977
978         // ok, now copy the paragraph
979         for (size_type i = 0, j = 0; i <= pos_end; ++i) {
980                 the_next->cutIntoMinibuffer(bparams, i);
981                 if (insertFromMinibuffer(pos_insert + j))
982                         ++j;
983         }
984    
985         // delete the next paragraph
986         Paragraph * ppar = the_next->previous_;
987         Paragraph * npar = the_next->next_;
988         delete the_next;
989         ppar->next(npar);
990 }
991
992
993 int Paragraph::getEndLabel(BufferParams const & bparams) const
994 {
995         Paragraph const * par = this;
996         depth_type par_depth = getDepth();
997         while (par) {
998                 LyXTextClass::LayoutList::size_type layout = par->getLayout();
999                 int const endlabeltype =
1000                         textclasslist.Style(bparams.textclass,
1001                                             layout).endlabeltype;
1002                 if (endlabeltype != END_LABEL_NO_LABEL) {
1003                         if (!next_)
1004                                 return endlabeltype;
1005
1006                         depth_type const next_depth = next_->getDepth();
1007                         if (par_depth > next_depth ||
1008                             (par_depth == next_depth
1009                              && layout != next_->getLayout()))
1010                                 return endlabeltype;
1011                         break;
1012                 }
1013                 if (par_depth == 0)
1014                         break;
1015                 par = par->outerHook();
1016                 if (par)
1017                         par_depth = par->getDepth();
1018         }
1019         return END_LABEL_NO_LABEL;
1020 }
1021
1022
1023 Paragraph::depth_type Paragraph::getDepth() const
1024 {
1025         return params().depth();
1026 }
1027
1028
1029 char Paragraph::getAlign() const
1030 {
1031         return params().align();
1032 }
1033
1034
1035 string const & Paragraph::getLabelstring() const
1036 {
1037         return params().labelString();
1038 }
1039
1040
1041 int Paragraph::getFirstCounter(int i) const
1042 {
1043         return pimpl_->counter_[i];
1044 }
1045
1046
1047 // the next two functions are for the manual labels
1048 string const Paragraph::getLabelWidthString() const
1049 {
1050         if (!params().labelWidthString().empty())
1051                 return params().labelWidthString();
1052         else
1053                 return _("Senseless with this layout!");
1054 }
1055
1056
1057 void Paragraph::setLabelWidthString(string const & s)
1058 {
1059         params().labelWidthString(s);
1060 }
1061
1062
1063 void Paragraph::setOnlyLayout(LyXTextClass::size_type new_layout)
1064 {
1065         layout = new_layout;
1066 }
1067
1068
1069 void Paragraph::setLayout(LyXTextClass::size_type new_layout)
1070 {
1071         layout = new_layout;
1072         params().labelWidthString(string());
1073         params().align(LYX_ALIGN_LAYOUT);
1074         params().spaceTop(VSpace(VSpace::NONE));
1075         params().spaceBottom(VSpace(VSpace::NONE));
1076         params().spacing(Spacing(Spacing::Default));
1077 }
1078
1079
1080 // if the layout of a paragraph contains a manual label, the beginning of the 
1081 // main body is the beginning of the second word. This is what the par-
1082 // function returns. If the layout does not contain a label, the main
1083 // body always starts with position 0. This differentiation is necessary,
1084 // because there cannot be a newline or a blank <= the beginning of the 
1085 // main body in TeX.
1086
1087 int Paragraph::beginningOfMainBody() const
1088 {
1089         // Unroll the first two cycles of the loop
1090         // and remember the previous character to
1091         // remove unnecessary GetChar() calls
1092         size_type i = 0;
1093         if (i < size()
1094             && getChar(i) != Paragraph::META_NEWLINE) {
1095                 ++i;
1096                 char previous_char = 0;
1097                 char temp = 0; 
1098                 if (i < size()
1099                     && (previous_char = getChar(i)) != Paragraph::META_NEWLINE) {
1100                         // Yes, this  ^ is supposed to be "= " not "=="
1101                         ++i;
1102                         while (i < size()
1103                                && previous_char != ' '
1104                                && (temp = getChar(i)) != Paragraph::META_NEWLINE) {
1105                                 ++i;
1106                                 previous_char = temp;
1107                         }
1108                 }
1109         }
1110
1111         return i;
1112 }
1113
1114
1115 Paragraph * Paragraph::depthHook(depth_type depth)
1116 {
1117         Paragraph * newpar = this;
1118   
1119         do {
1120                 newpar = newpar->previous();
1121         } while (newpar && newpar->getDepth() > depth);
1122    
1123         if (!newpar) {
1124                 if (previous() || getDepth())
1125                         lyxerr << "ERROR (Paragraph::DepthHook): "
1126                                 "no hook." << endl;
1127                 newpar = this;
1128         }
1129
1130         return newpar;
1131 }
1132
1133
1134 Paragraph const * Paragraph::depthHook(depth_type depth) const
1135 {
1136         Paragraph const * newpar = this;
1137    
1138         do {
1139                 newpar = newpar->previous();
1140         } while (newpar && newpar->getDepth() > depth);
1141    
1142         if (!newpar) {
1143                 if (previous() || getDepth())
1144                         lyxerr << "ERROR (Paragraph::DepthHook): "
1145                                 "no hook." << endl;
1146                 newpar = this;
1147         }
1148
1149         return newpar;
1150 }
1151
1152 Paragraph * Paragraph::outerHook()
1153 {
1154         if(!getDepth())
1155                 return 0;
1156         return depthHook(depth_type(getDepth() - 1));
1157 }
1158
1159 Paragraph const * Paragraph::outerHook() const
1160 {
1161         if(!getDepth())
1162                 return 0;
1163         return depthHook(depth_type(getDepth() - 1));
1164 }
1165
1166 int Paragraph::autoDeleteInsets()
1167 {
1168         int count = 0;
1169         InsetList::size_type index = 0;
1170         while (index < insetlist.size()) {
1171                 if (insetlist[index].inset && insetlist[index].inset->autoDelete()) {
1172                         erase(insetlist[index].pos); 
1173                         // Erase() calls to insetlist.erase(&insetlist[index])
1174                         // so index shouldn't be increased.
1175                         ++count;
1176                 } else
1177                         ++index;
1178         }
1179         return count;
1180 }
1181
1182
1183 Paragraph::inset_iterator
1184 Paragraph::InsetIterator(Paragraph::size_type pos)
1185 {
1186         InsetTable search_inset(pos, 0);
1187         InsetList::iterator it = lower_bound(insetlist.begin(),
1188                                              insetlist.end(),
1189                                              search_inset, Pimpl::matchIT());
1190         return inset_iterator(it);
1191 }
1192
1193
1194 // returns -1 if inset not found
1195 int Paragraph::getPositionOfInset(Inset * inset) const
1196 {
1197         // Find the entry.
1198         for (InsetList::const_iterator cit = insetlist.begin();
1199              cit != insetlist.end(); ++cit) {
1200                 if (cit->inset == inset) {
1201                         return cit->pos;
1202                 }
1203         }
1204         if (inset == bibkey)
1205                 return 0;
1206
1207         return -1;
1208 }
1209
1210
1211 Paragraph * Paragraph::TeXOnePar(Buffer const * buf,
1212                                        BufferParams const & bparams,
1213                                        ostream & os, TexRow & texrow,
1214                                        bool moving_arg)
1215 {
1216         lyxerr[Debug::LATEX] << "TeXOnePar...     " << this << endl;
1217         LyXLayout const & style =
1218                 textclasslist.Style(bparams.textclass,
1219                                     layout);
1220
1221         bool further_blank_line = false;
1222
1223         if (params().startOfAppendix()) {
1224                 os << "\\appendix\n";
1225                 texrow.newline();
1226         }
1227
1228         if (!params().spacing().isDefault()
1229             && (!previous() || !previous()->hasSameLayout(this))) {
1230                 os << params().spacing().writeEnvirBegin() << "\n";
1231                 texrow.newline();
1232         }
1233         
1234         if (tex_code_break_column && style.isCommand()){
1235                 os << '\n';
1236                 texrow.newline();
1237         }
1238
1239         if (params().pagebreakTop()) {
1240                 os << "\\newpage";
1241                 further_blank_line = true;
1242         }
1243         if (params().spaceTop().kind() != VSpace::NONE) {
1244                 os << params().spaceTop().asLatexCommand(bparams);
1245                 further_blank_line = true;
1246         }
1247       
1248         if (params().lineTop()) {
1249                 os << "\\lyxline{\\" << getFont(bparams, 0).latexSize() << '}'
1250                    << "\\vspace{-1\\parskip}";
1251                 further_blank_line = true;
1252         }
1253
1254         if (further_blank_line){
1255                 os << '\n';
1256                 texrow.newline();
1257         }
1258
1259         Language const * language = getParLanguage(bparams);
1260         Language const * doc_language = bparams.language;
1261         Language const * previous_language = previous_
1262                 ? previous_->getParLanguage(bparams) : doc_language;
1263         if (language == ignore_language || language == inherit_language)
1264                 lyxerr << "1:" << language->lang() << endl;
1265         if (language->babel() != doc_language->babel() &&
1266             language->babel() != previous_language->babel()) {
1267                 os << subst(lyxrc.language_command_begin, "$$lang",
1268                             language->babel())
1269                    << endl;
1270                 texrow.newline();
1271         }
1272
1273         if (bparams.inputenc == "auto" &&
1274             language->encoding() != previous_language->encoding())
1275         {
1276                 os << "\\inputencoding{"
1277                    << language->encoding()->LatexName()
1278                    << "}" << endl;
1279                 texrow.newline();
1280         }
1281
1282         switch (style.latextype) {
1283         case LATEX_COMMAND:
1284                 os << '\\'
1285                    << style.latexname()
1286                    << style.latexparam();
1287                 break;
1288         case LATEX_ITEM_ENVIRONMENT:
1289                 if (bibkey) {
1290                         bibkey->latex(buf, os, false, false);
1291                 } else
1292                         os << "\\item ";
1293                 break;
1294         case LATEX_LIST_ENVIRONMENT:
1295                 os << "\\item ";
1296                 break;
1297         default:
1298                 break;
1299         }
1300
1301         bool need_par = simpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
1302  
1303         // Make sure that \\par is done with the font of the last
1304         // character if this has another size as the default.
1305         // This is necessary because LaTeX (and LyX on the screen)
1306         // calculates the space between the baselines according
1307         // to this font. (Matthias)
1308         //
1309         // Is this really needed ? (Dekel)
1310         // We do not need to use to change the font for the last paragraph
1311         // or for a command.
1312         LyXFont font = getFont(bparams, size() - 1);
1313
1314         bool is_command = textclasslist.Style(bparams.textclass,
1315                                               getLayout()).isCommand();
1316         if (style.resfont.size() != font.size() && next_ && !is_command) {
1317                 if (!need_par)
1318                         os << "{";
1319                 os << "\\" << font.latexSize() << " \\par}";
1320         } else if (need_par) {
1321                 os << "\\par}";
1322         } else if (is_command)
1323                 os << "}";
1324
1325         if (language->babel() != doc_language->babel() &&
1326             (!next_ ||
1327              next_->getParLanguage(bparams)->babel() != language->babel()))
1328         {
1329                 os << endl 
1330                    << subst(lyxrc.language_command_end, "$$lang",
1331                             doc_language->babel());
1332         }
1333         
1334         switch (style.latextype) {
1335         case LATEX_ITEM_ENVIRONMENT:
1336         case LATEX_LIST_ENVIRONMENT:
1337                 if (next_ && (params().depth() < next_->params().depth())) {
1338                         os << '\n';
1339                         texrow.newline();
1340                 }
1341                 break;
1342         case LATEX_ENVIRONMENT:
1343                 // if its the last paragraph of the current environment
1344                 // skip it otherwise fall through
1345                 if (next_
1346                     && (next_->layout != layout
1347                         || next_->params().depth() != params().depth()))
1348                         break;
1349         default:
1350                 // we don't need it for the last paragraph!!!
1351                 // or for tables in floats
1352                 //   -- effectively creates a \par where there isn't one which
1353                 //      breaks a \subfigure or \subtable.
1354                 if (next_) {
1355                         os << '\n';
1356                         texrow.newline();
1357                 }
1358         }
1359         
1360         further_blank_line = false;
1361         if (params().lineBottom()) {
1362                 os << "\\lyxline{\\" << getFont(bparams,
1363                                                 size() - 1).latexSize() << '}';
1364                 further_blank_line = true;
1365         }
1366
1367         if (params().spaceBottom().kind() != VSpace::NONE) {
1368                 os << params().spaceBottom().asLatexCommand(bparams);
1369                 further_blank_line = true;
1370         }
1371       
1372         if (params().pagebreakBottom()) {
1373                 os << "\\newpage";
1374                 further_blank_line = true;
1375         }
1376
1377         if (further_blank_line){
1378                 os << '\n';
1379                 texrow.newline();
1380         }
1381
1382         if (!params().spacing().isDefault()
1383             && (!next_ || !next_->hasSameLayout(this))) {
1384                 os << params().spacing().writeEnvirEnd() << "\n";
1385                 texrow.newline();
1386         }
1387         
1388         // we don't need it for the last paragraph!!!
1389         if (next_) {
1390                 os << '\n';
1391                 texrow.newline();
1392         }
1393
1394         lyxerr[Debug::LATEX] << "TeXOnePar...done " << next_ << endl;
1395         return next_;
1396 }
1397
1398
1399 // This one spits out the text of the paragraph
1400 bool Paragraph::simpleTeXOnePar(Buffer const * buf,
1401                                    BufferParams const & bparams,
1402                                    ostream & os, TexRow & texrow,
1403                                    bool moving_arg)
1404 {
1405         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...     " << this << endl;
1406
1407         bool return_value = false;
1408
1409         LyXLayout const & style =
1410                 textclasslist.Style(bparams.textclass,
1411                                     getLayout());
1412         LyXFont basefont;
1413
1414         // Maybe we have to create a optional argument.
1415         size_type main_body;
1416         if (style.labeltype != LABEL_MANUAL)
1417                 main_body = 0;
1418         else
1419                 main_body = beginningOfMainBody();
1420
1421         int column = 0;
1422
1423         if (main_body > 0) {
1424                 os << '[';
1425                 ++column;
1426                 basefont = getFont(bparams, -2); // Get label font
1427         } else {
1428                 basefont = getFont(bparams, -1); // Get layout font
1429         }
1430
1431         if (main_body >= 0
1432             && !pimpl_->size()) {
1433                 if (style.isCommand()) {
1434                         os << '{';
1435                         ++column;
1436                 }
1437         }
1438
1439         moving_arg |= style.needprotect;
1440  
1441         // Which font is currently active?
1442         LyXFont running_font(basefont);
1443         // Do we have an open font change?
1444         bool open_font = false;
1445
1446         texrow.start(this, 0);
1447
1448         for (size_type i = 0; i < size(); ++i) {
1449                 ++column;
1450                 // First char in paragraph or after label?
1451                 if (i == main_body) {
1452                         if (main_body > 0) {
1453                                 if (open_font) {
1454                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1455                                         open_font = false;
1456                                 }
1457                                 basefont = getFont(bparams, -1); // Now use the layout font
1458                                 running_font = basefont;
1459                                 os << ']';
1460                                 ++column;
1461                         }
1462                         if (style.isCommand()) {
1463                                 os << '{';
1464                                 ++column;
1465                         }
1466
1467                         if (params().noindent()) {
1468                                 os << "\\noindent ";
1469                                 column += 10;
1470                         }
1471                         switch (params().align()) {
1472                         case LYX_ALIGN_NONE:
1473                         case LYX_ALIGN_BLOCK:
1474                         case LYX_ALIGN_LAYOUT:
1475                         case LYX_ALIGN_SPECIAL:
1476                                 break;
1477                         case LYX_ALIGN_LEFT:
1478                                 if (getParLanguage(bparams)->babel() != "hebrew") {
1479                                         os << "\\begin{flushleft}";
1480                                         column+= 17;
1481                                 } else {
1482                                         os << "\\begin{flushright}";
1483                                         column+= 18;
1484                                 }
1485                                 break;
1486                         case LYX_ALIGN_RIGHT:
1487                                 if (getParLanguage(bparams)->babel() != "hebrew") {
1488                                         os << "\\begin{flushright}";
1489                                         column+= 18;
1490                                 } else {
1491                                         os << "\\begin{flushleft}";
1492                                         column+= 17;
1493                                 }
1494                                 break;
1495                         case LYX_ALIGN_CENTER:
1496                                 os << "\\begin{center}";
1497                                 column+= 14;
1498                                 break;
1499                         }        
1500                 }
1501
1502                 value_type c = getChar(i);
1503
1504                 // Fully instantiated font
1505                 LyXFont font = getFont(bparams, i);
1506
1507                 LyXFont last_font = running_font;
1508
1509                 // Spaces at end of font change are simulated to be
1510                 // outside font change, i.e. we write "\textXX{text} "
1511                 // rather than "\textXX{text }". (Asger)
1512                 if (open_font && c == ' ' && i <= size() - 2 
1513                     && !getFont(bparams, i + 1).equalExceptLatex(running_font) 
1514                     && !getFont(bparams, i + 1).equalExceptLatex(font)) {
1515                         font = getFont(bparams, i + 1);
1516                 }
1517                 // We end font definition before blanks
1518                 if (!font.equalExceptLatex(running_font) && open_font) {
1519                         column += running_font.latexWriteEndChanges(os,
1520                                                                     basefont,
1521                                                                     (i == main_body-1) ? basefont : font);
1522                         running_font = basefont;
1523                         open_font = false;
1524                 }
1525
1526                 // Blanks are printed before start of fontswitch
1527                 if (c == ' ') {
1528                         // Do not print the separation of the optional argument
1529                         if (i != main_body - 1) {
1530                                 pimpl_->simpleTeXBlanks(os, texrow, i,
1531                                                        column, font, style);
1532                         }
1533                 }
1534
1535                 // Do we need to change font?
1536                 if (!font.equalExceptLatex(running_font)
1537                     && i != main_body-1) {
1538                         column += font.latexWriteStartChanges(os, basefont,
1539                                                               last_font);
1540                         running_font = font;
1541                         open_font = true;
1542                 }
1543
1544                 if (c == Paragraph::META_NEWLINE) {
1545                         // newlines are handled differently here than
1546                         // the default in SimpleTeXSpecialChars().
1547                         if (!style.newline_allowed
1548 #ifndef NO_LATEX
1549                             || font.latex() == LyXFont::ON
1550 #endif
1551                                 ) {
1552                                 os << '\n';
1553                         } else {
1554                                 if (open_font) {
1555                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
1556                                         open_font = false;
1557                                 }
1558                                 basefont = getFont(bparams, -1);
1559                                 running_font = basefont;
1560                                 if (font.family() == 
1561                                     LyXFont::TYPEWRITER_FAMILY) {
1562                                         os << "~";
1563                                 }
1564                                 if (moving_arg)
1565                                         os << "\\protect ";
1566                                 os << "\\\\\n";
1567                         }
1568                         texrow.newline();
1569                         texrow.start(this, i + 1);
1570                         column = 0;
1571                 } else {
1572                         pimpl_->simpleTeXSpecialChars(buf, bparams,
1573                                                       os, texrow, moving_arg,
1574                                                       font, running_font, 
1575                                                       basefont, open_font, 
1576                                                       style, i, column, c);
1577                 }
1578         }
1579
1580         // If we have an open font definition, we have to close it
1581         if (open_font) {
1582 #ifdef FIXED_LANGUAGE_END_DETECTION
1583                 if (next_) {
1584                         running_font
1585                                 .latexWriteEndChanges(os, basefont,
1586                                                       next_->getFont(bparams,
1587                                                       0));
1588                 } else {
1589                         running_font.latexWriteEndChanges(os, basefont,
1590                                                           basefont);
1591                 }
1592 #else
1593 #ifdef WITH_WARNINGS
1594 #warning For now we ALWAYS have to close the foreign font settings if they are
1595 #warning there as we start another \selectlanguage with the next paragraph if
1596 #warning we are in need of this. This should be fixed sometime (Jug)
1597 #endif
1598                 running_font.latexWriteEndChanges(os, basefont,  basefont);
1599 #endif
1600         }
1601
1602         // Needed if there is an optional argument but no contents.
1603         if (main_body > 0 && main_body == size()) {
1604                 os << "]~";
1605                 return_value = false;
1606         }
1607
1608         switch (params().align()) {
1609         case LYX_ALIGN_NONE:
1610         case LYX_ALIGN_BLOCK:
1611         case LYX_ALIGN_LAYOUT:
1612         case LYX_ALIGN_SPECIAL:
1613                 break;
1614         case LYX_ALIGN_LEFT:
1615                 if (getParLanguage(bparams)->babel() != "hebrew") {
1616                         os << "\\end{flushleft}";
1617                         column+= 15;
1618                 } else {
1619                         os << "\\end{flushright}";
1620                         column+= 16;
1621                 }
1622                 break;
1623         case LYX_ALIGN_RIGHT:
1624                 if (getParLanguage(bparams)->babel() != "hebrew") {
1625                         os << "\\end{flushright}";
1626                         column+= 16;
1627                 } else {
1628                         os << "\\end{flushleft}";
1629                         column+= 15;
1630                 }
1631                 break;
1632         case LYX_ALIGN_CENTER:
1633                 os << "\\end{center}";
1634                 column+= 12;
1635                 break;
1636         }        
1637
1638         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...done " << this << endl;
1639         return return_value;
1640 }
1641
1642
1643 bool Paragraph::linuxDocConvertChar(char c, string & sgml_string)
1644 {
1645         bool retval = false;
1646         switch (c) {
1647         case Paragraph::META_HFILL:
1648                 sgml_string.erase();
1649                 break;
1650         case Paragraph::META_NEWLINE:
1651                 sgml_string = '\n';
1652                 break;
1653         case '&': 
1654                 sgml_string = "&amp;";
1655                 break;
1656         case '<': 
1657                 sgml_string = "&lt;"; 
1658                 break;
1659         case '>':
1660                 sgml_string = "&gt;"; 
1661                 break;
1662         case '$': 
1663                 sgml_string = "&dollar;"; 
1664                 break;
1665         case '#': 
1666                 sgml_string = "&num;";
1667                 break;
1668         case '%': 
1669                 sgml_string = "&percnt;";
1670                 break;
1671         case '[': 
1672                 sgml_string = "&lsqb;";
1673                 break;
1674         case ']': 
1675                 sgml_string = "&rsqb;";
1676                 break;
1677         case '{': 
1678                 sgml_string = "&lcub;";
1679                 break;
1680         case '}': 
1681                 sgml_string = "&rcub;";
1682                 break;
1683         case '~': 
1684                 sgml_string = "&tilde;";
1685                 break;
1686         case '"': 
1687                 sgml_string = "&quot;";
1688                 break;
1689         case '\\': 
1690                 sgml_string = "&bsol;";
1691                 break;
1692         case ' ':
1693                 retval = true;
1694                 sgml_string = ' ';
1695                 break;
1696         case '\0': // Ignore :-)
1697                 sgml_string.erase();
1698                 break;
1699         default:
1700                 sgml_string = c;
1701                 break;
1702         }
1703         return retval;
1704 }
1705
1706
1707 Paragraph * Paragraph::TeXEnvironment(Buffer const * buf,
1708                                             BufferParams const & bparams,
1709                                             ostream & os, TexRow & texrow)
1710 {
1711         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << this << endl;
1712
1713         LyXLayout const & style =
1714                 textclasslist.Style(bparams.textclass,
1715                                     layout);
1716
1717         if (style.isEnvironment()){
1718                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
1719                         os << "\\begin{" << style.latexname() << "}{"
1720                            << params().labelWidthString() << "}\n";
1721                 } else if (style.labeltype == LABEL_BIBLIO) {
1722                         // ale970405
1723                         os << "\\begin{" << style.latexname() << "}{"
1724                            <<  bibitemWidest(buf)
1725                            << "}\n";
1726                 } else if (style.latextype == LATEX_ITEM_ENVIRONMENT) {
1727                         os << "\\begin{" << style.latexname() << '}'
1728                            << style.latexparam() << '\n';
1729                 } else 
1730                         os << "\\begin{" << style.latexname() << '}'
1731                            << style.latexparam() << '\n';
1732                 texrow.newline();
1733         }
1734         Paragraph * par = this;
1735         do {
1736                 par = par->TeXOnePar(buf, bparams,
1737                                      os, texrow, false);
1738
1739                 if (par && par->params().depth() > params().depth()) {
1740                         if (textclasslist.Style(bparams.textclass,
1741                                                 par->layout).isParagraph()
1742                             // Thinko!
1743                             // How to handle this? (Lgb)
1744                             //&& !suffixIs(os, "\n\n")
1745                                 ) {
1746                                 // There should be at least one '\n' already
1747                                 // but we need there to be two for Standard 
1748                                 // paragraphs that are depth-increment'ed to be
1749                                 // output correctly.  However, tables can
1750                                 // also be paragraphs so don't adjust them.
1751                                 // ARRae
1752                                 // Thinkee:
1753                                 // Will it ever harm to have one '\n' too
1754                                 // many? i.e. that we sometimes will have
1755                                 // three in a row. (Lgb)
1756                                 os << '\n';
1757                                 texrow.newline();
1758                         }
1759                         par = par->pimpl_->TeXDeeper(buf, bparams, os, texrow);
1760                 }
1761         } while (par
1762                  && par->layout == layout
1763                  && par->params().depth() == params().depth());
1764  
1765         if (style.isEnvironment()) {
1766                 os << "\\end{" << style.latexname() << "}\n";
1767         }
1768
1769         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << par << endl;
1770         return par;  // ale970302
1771 }
1772
1773
1774 bool Paragraph::isHfill(size_type pos) const
1775 {
1776         return IsHfillChar(getChar(pos));
1777 }
1778
1779
1780 bool Paragraph::isInset(size_type pos) const
1781 {
1782         return IsInsetChar(getChar(pos));
1783 }
1784
1785
1786 bool Paragraph::isNewline(size_type pos) const
1787 {
1788         return pos >= 0 && IsNewlineChar(getChar(pos));
1789 }
1790
1791
1792 bool Paragraph::isSeparator(size_type pos) const
1793 {
1794         return IsSeparatorChar(getChar(pos));
1795 }
1796
1797
1798 bool Paragraph::isLineSeparator(size_type pos) const
1799 {
1800         return IsLineSeparatorChar(getChar(pos));
1801 }
1802
1803
1804 bool Paragraph::isKomma(size_type pos) const
1805 {
1806         return IsKommaChar(getChar(pos));
1807 }
1808
1809
1810 /// Used by the spellchecker
1811 bool Paragraph::isLetter(Paragraph::size_type pos) const
1812 {
1813         value_type const c = getChar(pos);
1814         if (IsLetterChar(c))
1815                 return true;
1816         // '\0' is not a letter, allthough every string contains "" (below)
1817         if (c == '\0')
1818                 return false;
1819         // We want to pass the ' and escape chars to ispell
1820         string const extra = lyxrc.isp_esc_chars + '\'';
1821         char ch[2] = { c, 0 };
1822         return contains(extra, ch);
1823 }
1824  
1825  
1826 bool Paragraph::isWord(size_type pos ) const
1827 {
1828         return IsWordChar(getChar(pos)) ;
1829 }
1830
1831
1832 Language const *
1833 Paragraph::getParLanguage(BufferParams const & bparams) const 
1834 {
1835         if (size() > 0) {
1836                 Language const * lang = getFirstFontSettings().language();
1837 #warning We should make this somewhat better, any ideas? (Jug)
1838                 if (lang == inherit_language || lang == ignore_language)
1839                         lang = bparams.language;
1840                 return lang;
1841         } else if (previous_)
1842                 return previous_->getParLanguage(bparams);
1843         else
1844                 return bparams.language;
1845 }
1846
1847
1848 bool Paragraph::isRightToLeftPar(BufferParams const & bparams) const
1849 {
1850         return lyxrc.rtl_support
1851                 && getParLanguage(bparams)->RightToLeft();
1852 }
1853
1854
1855 void Paragraph::changeLanguage(BufferParams const & bparams,
1856                                   Language const * from, Language const * to)
1857 {
1858         for (size_type i = 0; i < size(); ++i) {
1859                 LyXFont font = getFontSettings(bparams, i);
1860                 if (font.language() == from) {
1861                         font.setLanguage(to);
1862                         setFont(i, font);
1863                 }
1864         }
1865 }
1866
1867
1868 bool Paragraph::isMultiLingual(BufferParams const & bparams)
1869 {
1870         Language const * doc_language = bparams.language;
1871         for (Pimpl::FontList::const_iterator cit = pimpl_->fontlist.begin();
1872              cit != pimpl_->fontlist.end(); ++cit)
1873                 if (cit->font().language() != inherit_language &&
1874                         cit->font().language() != ignore_language &&
1875                         cit->font().language() != doc_language)
1876                         return true;
1877         return false;
1878 }
1879
1880
1881 // Convert the paragraph to a string.
1882 // Used for building the table of contents
1883 string const Paragraph::asString(Buffer const * buffer, bool label)
1884 {
1885         BufferParams const & bparams = buffer->params;
1886         string s;
1887         if (label && !params().labelString().empty())
1888                 s += params().labelString() + ' ';
1889         string::size_type const len = s.size();
1890
1891         for (Paragraph::size_type i = 0; i < size(); ++i) {
1892                 value_type c = getChar(i);
1893                 if (IsPrintable(c))
1894                         s += c;
1895                 else if (c == META_INSET &&
1896                          getInset(i)->lyxCode() == Inset::MATH_CODE) {
1897                         ostringstream ost;
1898                         getInset(i)->ascii(buffer, ost);
1899                         s += subst(ost.str().c_str(),'\n',' ');
1900                 }
1901         }
1902
1903         if (isRightToLeftPar(bparams))
1904                 reverse(s.begin() + len,s.end());
1905
1906         return s;
1907 }
1908
1909
1910 string const Paragraph::asString(Buffer const * buffer, 
1911                             Paragraph::size_type beg,
1912                             Paragraph::size_type end)
1913 {
1914         ostringstream ost;
1915
1916         if (beg == 0 && !params().labelString().empty())
1917                 ost << params().labelString() << ' ';
1918
1919         for (Paragraph::size_type i = beg; i < end; ++i) {
1920                 value_type const c = getUChar(buffer->params, i);
1921                 if (IsPrintable(c))
1922                         ost << c;
1923                 else if (c == META_INSET) {
1924                         getInset(i)->ascii(buffer, ost);
1925                 }
1926         }
1927
1928         return ost.str().c_str();
1929 }
1930
1931
1932 void Paragraph::setInsetOwner(Inset * i)
1933 {
1934         pimpl_->inset_owner = i;
1935         for (InsetList::const_iterator cit = insetlist.begin();
1936              cit != insetlist.end(); ++cit) {
1937                 if (cit->inset)
1938                         cit->inset->setOwner(i);
1939         }
1940 }
1941
1942
1943 void Paragraph::deleteInsetsLyXText(BufferView * bv)
1944 {
1945         // then the insets
1946         for (InsetList::const_iterator cit = insetlist.begin();
1947              cit != insetlist.end(); ++cit) {
1948                 if (cit->inset) {
1949                         if (cit->inset->isTextInset()) {
1950                                 static_cast<UpdatableInset *>
1951                                         (cit->inset)->deleteLyXText(bv, true);
1952                         }
1953                 }
1954         }
1955 }
1956
1957
1958 void Paragraph::resizeInsetsLyXText(BufferView * bv)
1959 {
1960         // then the insets
1961         for (InsetList::const_iterator cit = insetlist.begin();
1962              cit != insetlist.end(); ++cit) {
1963                 if (cit->inset) {
1964                         if (cit->inset->isTextInset()) {
1965                                 static_cast<UpdatableInset *>
1966                                         (cit->inset)->resizeLyXText(bv, true);
1967                         }
1968                 }
1969         }
1970 }
1971
1972
1973 void Paragraph::setContentsFromPar(Paragraph * par)
1974 {
1975         pimpl_->setContentsFromPar(par);
1976 }
1977
1978
1979 Paragraph::size_type Paragraph::size() const
1980 {
1981         return pimpl_->size();
1982 }
1983
1984
1985 Paragraph::value_type
1986 Paragraph::getChar(Paragraph::size_type pos) const
1987 {
1988         return pimpl_->getChar(pos);
1989 }
1990
1991
1992 int Paragraph::id() const
1993 {
1994         return pimpl_->id_;
1995 }
1996
1997
1998 void  Paragraph::id(int id_arg)
1999 {
2000         pimpl_->id_ = id_arg;
2001 }
2002
2003
2004 LyXTextClass::LayoutList::size_type Paragraph::getLayout() const
2005 {
2006         return layout;
2007 }
2008
2009
2010 bool Paragraph::isFirstInSequence() const
2011 {
2012         Paragraph const * dhook = depthHook(getDepth());
2013         return (dhook == this
2014                 || dhook->getLayout() != getLayout()
2015                 || dhook->getDepth() != getDepth());
2016 }
2017
2018
2019 Inset * Paragraph::inInset() const
2020 {
2021         return pimpl_->inset_owner;
2022 }
2023
2024
2025 void Paragraph::clearContents()
2026 {
2027         pimpl_->clear();
2028 }
2029
2030
2031 void Paragraph::setCounter(int i, int v)
2032 {
2033         pimpl_->counter_[i] = v;
2034 }
2035
2036
2037 int Paragraph::getCounter(int i) const
2038 {
2039         return pimpl_->counter_[i];
2040 }
2041
2042
2043 void Paragraph::incCounter(int i)
2044 {
2045         pimpl_->counter_[i]++;
2046 }
2047
2048
2049 void Paragraph::setChar(size_type pos, value_type c)
2050 {
2051         pimpl_->setChar(pos, c);
2052 }
2053
2054
2055 Paragraph::inset_iterator::inset_iterator(Paragraph::InsetList::iterator const & iter)
2056  : it(iter) 
2057 {}
2058
2059
2060 Paragraph::inset_iterator Paragraph::inset_iterator_begin()
2061 {
2062         return inset_iterator(insetlist.begin());
2063 }
2064
2065
2066 Paragraph::inset_iterator Paragraph::inset_iterator_end()
2067 {
2068         return inset_iterator(insetlist.end());
2069 }
2070
2071
2072 ParagraphParameters & Paragraph::params()
2073 {
2074         return pimpl_->params;
2075 }
2076
2077
2078 ParagraphParameters const & Paragraph::params() const
2079 {
2080         return pimpl_->params;
2081 }
2082
2083
2084 Paragraph * Paragraph::getParFromID(int id) const
2085 {
2086         return pimpl_->getParFromID(id);
2087 }