]> git.lyx.org Git - lyx.git/blob - src/paragraph.C
Lots of changes for update of TextInsets, still some problems!
[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-2000 The LyX Team. 
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef __GNUG__
14 #pragma implementation "lyxparagraph.h"
15 #endif
16
17 #include <algorithm>
18 #include <fstream>
19 #include <csignal>
20
21 #include "lyxparagraph.h"
22 #include "support/textutils.h"
23 #include "lyxrc.h"
24 #include "layout.h"
25 #include "tex-strings.h"
26 #include "bufferparams.h"
27 #include "support/FileInfo.h"
28 #include "support/LAssert.h"
29 #include "debug.h"
30 #include "LaTeXFeatures.h"
31 #include "insets/insetinclude.h"
32 #include "insets/insetbib.h"
33 #include "insets/insettext.h"
34 #include "support/filetools.h"
35 #include "lyx_gui_misc.h"
36 #include "texrow.h"
37 #include "support/lyxmanip.h"
38 #include "BufferView.h"
39
40 using std::ostream;
41 using std::endl;
42 using std::fstream;
43 using std::ios;
44 using std::lower_bound;
45 using std::upper_bound;
46 using std::reverse;
47
48 int tex_code_break_column = 72;  // needs non-zero initialization. set later.
49 // this is a bad idea, but how can LyXParagraph find its buffer to get
50 // parameters? (JMarc)
51 extern BufferView * current_view;
52 extern string bibitemWidest(Painter &);
53
54 // this is a minibuffer
55 static char minibuffer_char;
56 static LyXFont minibuffer_font;
57 static Inset * minibuffer_inset;
58
59
60 // Initialization of the counter for the paragraph id's,
61 // declared in lyxparagraph.h
62 unsigned int LyXParagraph::paragraph_id = 0;
63
64
65 LyXParagraph::LyXParagraph()
66 {
67         text.reserve(500); // is this number too big?
68
69         for (int i = 0; i < 10; ++i) setCounter(i , 0);
70         appendix = false;
71         enumdepth = 0;
72         itemdepth = 0;
73         next = 0;
74         previous = 0;
75 #ifndef NEW_INSETS
76         footnoteflag = LyXParagraph::NO_FOOTNOTE;
77         footnotekind = LyXParagraph::FOOTNOTE; // should not be needed
78 #endif
79         align = LYX_ALIGN_BLOCK;
80
81 #ifndef NEW_TABULAR
82         /* table stuff -- begin*/ 
83         table = 0;
84         /* table stuff -- end*/
85 #endif
86         inset_owner = 0;
87         id_ = paragraph_id++;
88         bibkey = 0; // ale970302
89         Clear();
90 }
91
92
93 // This konstruktor inserts the new paragraph in a list.
94 LyXParagraph::LyXParagraph(LyXParagraph * par)
95 {
96         text.reserve(500);
97         par->text.resize(par->text.size());
98
99         for (int i = 0; i < 10; ++i) setCounter(i, 0);
100         appendix = false;
101         enumdepth = 0;
102         itemdepth = 0;
103         // double linked list begin
104         next = par->next;
105         if (next)
106                 next->previous = this;
107         previous = par;
108         previous->next = this;
109         // end
110 #ifndef NEW_INSETS
111         footnoteflag = LyXParagraph::NO_FOOTNOTE;
112         footnotekind = LyXParagraph::FOOTNOTE;
113 #endif
114 #ifndef NEW_TABULAR
115         /* table stuff -- begin*/ 
116         table = 0;
117         /* table stuff -- end*/
118 #endif
119         inset_owner = 0;
120         id_ = paragraph_id++;
121
122         bibkey = 0; // ale970302        
123     
124         Clear();
125 }
126
127
128 void LyXParagraph::writeFile(Buffer const * buf, ostream & os,
129                              BufferParams const & params,
130                              char footflag, char dth) const
131 {
132         LyXFont font1, font2;
133         int column = 0;
134         int h = 0;
135         char c = 0;
136
137         if (footnoteflag != LyXParagraph::NO_FOOTNOTE
138             || !previous
139             || previous->footnoteflag == LyXParagraph::NO_FOOTNOTE) {
140                 
141                 // The beginning or the end of a footnote environment?
142                 if (footflag != footnoteflag) {
143                         footflag = footnoteflag;
144                         if (footflag) {
145                                 os << "\n\\begin_float "
146                                    << string_footnotekinds[footnotekind]
147                                    << " ";
148                         } else {
149                                 os << "\n\\end_float ";
150                         }
151                 }
152
153                 // The beginning or end of a deeper (i.e. nested) area?
154                 if (dth != depth) {
155                         if (depth > dth) {
156                                 while (depth > dth) {
157                                         os << "\n\\begin_deeper ";
158                                         ++dth;
159                                 }
160                         } else {
161                                 while (depth < dth) {
162                                         os << "\n\\end_deeper ";
163                                         --dth;
164                                 }
165                         }
166                 }
167
168                 // First write the layout
169                 os << "\n\\layout "
170                    << textclasslist.NameOfLayout(params.textclass, layout)
171                    << "\n";
172
173                 // Maybe some vertical spaces.
174                 if (added_space_top.kind() != VSpace::NONE)
175                         os << "\\added_space_top "
176                            << added_space_top.asLyXCommand() << " ";
177                 if (added_space_bottom.kind() != VSpace::NONE)
178                         os << "\\added_space_bottom "
179                            << added_space_bottom.asLyXCommand() << " ";
180
181                 // Maybe the paragraph has special spacing
182                 spacing.writeFile(os, true);
183                 
184                 // The labelwidth string used in lists.
185                 if (!labelwidthstring.empty())
186                         os << "\\labelwidthstring "
187                            << labelwidthstring << '\n';
188
189                 // Lines above or below?
190                 if (line_top)
191                         os << "\\line_top ";
192                 if (line_bottom)
193                         os << "\\line_bottom ";
194
195                 // Pagebreaks above or below?
196                 if (pagebreak_top)
197                         os << "\\pagebreak_top ";
198                 if (pagebreak_bottom)
199                         os << "\\pagebreak_bottom ";
200                         
201                 // Start of appendix?
202                 if (start_of_appendix)
203                         os << "\\start_of_appendix ";
204
205                 // Noindent?
206                 if (noindent)
207                         os << "\\noindent ";
208                         
209                 // Alignment?
210                 if (align != LYX_ALIGN_LAYOUT) {
211                         switch (align) {
212                         case LYX_ALIGN_LEFT: h = 1; break;
213                         case LYX_ALIGN_RIGHT: h = 2; break;
214                         case LYX_ALIGN_CENTER: h = 3; break;
215                         default: h = 0; break;
216                         }
217                         os << "\\align " << string_align[h] << " ";
218                 }
219                 if (pextra_type != PEXTRA_NONE) {
220                         os << "\\pextra_type " << pextra_type;
221                         if (pextra_type == PEXTRA_MINIPAGE) {
222                                 os << " \\pextra_alignment "
223                                    << pextra_alignment;
224                                 if (pextra_hfill)
225                                         os << " \\pextra_hfill "
226                                            << pextra_hfill;
227                                 if (pextra_start_minipage)
228                                         os << " \\pextra_start_minipage "
229                                            << pextra_start_minipage;
230                         }
231                         if (!pextra_width.empty()) {
232                                 os << " \\pextra_width "
233                                    << VSpace(pextra_width).asLyXCommand();
234                         } else if (!pextra_widthp.empty()) {
235                                 os << " \\pextra_widthp "
236                                    << pextra_widthp;
237                         }
238                         os << '\n';
239                 }
240         } else {
241                 // Dummy layout. This means that a footnote ended.
242                 os << "\n\\end_float ";
243                 footflag = LyXParagraph::NO_FOOTNOTE;
244         }
245 #ifndef NEW_TABULAR     
246         // It might be a table.
247         if (table){
248                 os << "\\LyXTable\n";
249                 table->Write(os);
250         }
251 #endif
252         // bibitem  ale970302
253         if (bibkey)
254                 bibkey->Write(buf, os);
255
256         font1 = LyXFont(LyXFont::ALL_INHERIT,params.language_info);
257
258         column = 0;
259         for (size_type i = 0; i < size(); ++i) {
260                 if (!i) {
261                         os << "\n";
262                         column = 0;
263                 }
264                 
265                 // Write font changes
266                 font2 = GetFontSettings(params, i);
267                 if (font2 != font1) {
268                         font2.lyxWriteChanges(font1, os);
269                         column = 0;
270                         font1 = font2;
271                 }
272
273                 c = GetChar(i);
274                 switch (c) {
275                 case META_INSET:
276                 {
277                         Inset const * inset = GetInset(i);
278                         if (inset)
279                                 if (inset->DirectWrite()) {
280                                         // international char, let it write
281                                         // code directly so it's shorter in
282                                         // the file
283                                         inset->Write(buf, os);
284                                 } else {
285                                         os << "\n\\begin_inset ";
286                                         inset->Write(buf, os);
287                                         os << "\n\\end_inset \n\n";
288                                         column = 0;
289                                 }
290                 }
291                 break;
292                 case META_NEWLINE: 
293                         os << "\n\\newline \n";
294                         column = 0;
295                         break;
296                 case META_HFILL: 
297                         os << "\n\\hfill \n";
298                         column = 0;
299                         break;
300                 case '\\':
301                         os << "\n\\backslash \n";
302                         column = 0;
303                         break;
304                 case '.':
305                         if (i + 1 < size() && GetChar(i + 1) == ' ') {
306                                 os << ".\n";
307                                 column = 0;
308                         } else
309                                 os << ".";
310                         break;
311                 default:
312                         if ((column > 70 && c == ' ')
313                             || column > 79) {
314                                 os << "\n";
315                                 column = 0;
316                         }
317                         // this check is to amend a bug. LyX sometimes
318                         // inserts '\0' this could cause problems.
319                         if (c != '\0')
320                                 os << c;
321                         else
322                                 lyxerr << "ERROR (LyXParagraph::writeFile):"
323                                         " NULL char in structure." << endl;
324                         ++column;
325                         break;
326                 }
327         }
328
329         // now write the next paragraph
330         if (next)
331                 next->writeFile(buf, os, params, footflag, dth);
332 }
333
334
335 void LyXParagraph::validate(LaTeXFeatures & features) const
336 {
337         BufferParams const & params = features.bufferParams();
338         
339         // this will be useful later
340         LyXLayout const & layout =
341                 textclasslist.Style(params.textclass, 
342                                     GetLayout());
343         
344         // check the params.
345         if (line_top || line_bottom)
346                 features.lyxline = true;
347         if (!spacing.isDefault())
348                 features.setspace = true;
349         
350         // then the layouts
351         features.layout[GetLayout()] = true;
352
353         // then the fonts
354         Language const * doc_language = params.language_info;
355         
356         for (FontList::const_iterator cit = fontlist.begin();
357              cit != fontlist.end(); ++cit) {
358                 if ((*cit).font.noun() == LyXFont::ON) {
359                         lyxerr[Debug::LATEX] << "font.noun: "
360                                              << (*cit).font.noun()
361                                              << endl;
362                         features.noun = true;
363                         lyxerr[Debug::LATEX] << "Noun enabled. Font: "
364                                              << (*cit).font.stateText(0)
365                                              << endl;
366                 }
367                 switch ((*cit).font.color()) {
368                 case LColor::none:
369                 case LColor::inherit:
370                 case LColor::ignore:
371                         break;
372                 default:
373                         features.color = true;
374                         lyxerr[Debug::LATEX] << "Color enabled. Font: "
375                                              << (*cit).font.stateText(0)
376                                              << endl;
377                 }
378
379                 Language const * language = (*cit).font.language();
380                 if (language != doc_language) {
381                         features.UsedLanguages.insert(language);
382                         lyxerr[Debug::LATEX] << "Found language "
383                                              << language->lang() << endl;
384                 }
385         }
386
387         // then the insets
388         for (InsetList::const_iterator cit = insetlist.begin();
389              cit != insetlist.end(); ++cit) {
390                 if ((*cit).inset)
391                         (*cit).inset->Validate(features);
392         }
393
394         if (table && table->IsLongTable())
395                 features.longtable = true;
396         if (pextra_type == PEXTRA_INDENT)
397                 features.LyXParagraphIndent = true;
398         if (pextra_type == PEXTRA_FLOATFLT)
399                 features.floatflt = true;
400         if (layout.needprotect 
401             && next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE)
402                 features.NeedLyXFootnoteCode = true;
403         if (params.paragraph_separation == BufferParams::PARSEP_INDENT
404             && pextra_type == LyXParagraph::PEXTRA_MINIPAGE)
405                 features.NeedLyXMinipageIndent = true;
406         if (table && table->NeedRotating())
407                 features.rotating = true;
408         if (footnoteflag != NO_FOOTNOTE && footnotekind == ALGORITHM)
409                 features.algorithm = true;
410 }
411
412
413 // First few functions needed for cut and paste and paragraph breaking.
414 void LyXParagraph::CopyIntoMinibuffer(BufferParams const & bparams,
415                                       LyXParagraph::size_type pos) const
416 {
417         minibuffer_char = GetChar(pos);
418         minibuffer_font = GetFontSettings(bparams, pos);
419         minibuffer_inset = 0;
420         if (minibuffer_char == LyXParagraph::META_INSET) {
421                 if (GetInset(pos)) {
422                         minibuffer_inset = GetInset(pos)->Clone();
423                 } else {
424                         minibuffer_inset = 0;
425                         minibuffer_char = ' ';
426                         // This reflects what GetInset() does (ARRae)
427                 }
428         }
429 }
430
431
432 void LyXParagraph::CutIntoMinibuffer(BufferParams const & bparams,
433                                      LyXParagraph::size_type pos)
434 {
435         minibuffer_char = GetChar(pos);
436         minibuffer_font = GetFontSettings(bparams, pos);
437         minibuffer_inset = 0;
438         if (minibuffer_char == LyXParagraph::META_INSET) {
439                 if (GetInset(pos)) {
440                         minibuffer_inset = GetInset(pos);
441                         // This is a little hack since I want exactly
442                         // the inset, not just a clone. Otherwise
443                         // the inset would be deleted when calling Erase(pos)
444                         // find the entry
445                         InsetList::iterator it = lower_bound(insetlist.begin(),
446                                                              insetlist.end(),
447                                                              pos, matchIT());
448                         if (it != insetlist.end() && (*it).pos == pos)
449                                 (*it).inset = 0;
450                 } else {
451                         minibuffer_inset = 0;
452                         minibuffer_char = ' ';
453                         // This reflects what GetInset() does (ARRae)
454                 }
455
456         }
457
458         // Erase(pos); now the caller is responsible for that.
459 }
460
461
462 bool LyXParagraph::InsertFromMinibuffer(LyXParagraph::size_type pos)
463 {
464         if ((minibuffer_char == LyXParagraph::META_INSET) &&
465             !InsertInsetAllowed(minibuffer_inset))
466                 return false;
467         if (minibuffer_char == LyXParagraph::META_INSET)
468                 InsertInset(pos, minibuffer_inset, minibuffer_font);
469         else
470                 InsertChar(pos, minibuffer_char, minibuffer_font);
471         return true;
472 }
473
474 // end of minibuffer
475
476
477
478 void LyXParagraph::Clear()
479 {
480         line_top = false;
481         line_bottom = false;
482    
483         pagebreak_top = false;
484         pagebreak_bottom = false;
485
486         added_space_top = VSpace(VSpace::NONE);
487         added_space_bottom = VSpace(VSpace::NONE);
488         spacing.set(Spacing::Default);
489         
490         align = LYX_ALIGN_LAYOUT;
491         depth = 0;
492         noindent = false;
493
494         pextra_type = PEXTRA_NONE;
495         pextra_width.erase();
496         pextra_widthp.erase();
497         pextra_alignment = MINIPAGE_ALIGN_TOP;
498         pextra_hfill = false;
499         pextra_start_minipage = false;
500
501         labelstring.erase();
502         labelwidthstring.erase();
503         layout = 0;
504         bibkey = 0;
505         
506         start_of_appendix = false;
507 }
508
509
510 // the destructor removes the new paragraph from the list
511 LyXParagraph::~LyXParagraph()
512 {
513         if (previous)
514                 previous->next = next;
515         if (next)
516                 next->previous = previous;
517
518         for (InsetList::iterator it = insetlist.begin();
519              it != insetlist.end(); ++it) {
520                 delete (*it).inset;
521         }
522 #ifndef NEW_TABULAR
523         /* table stuff -- begin*/ 
524         delete table;
525         /* table stuff -- end*/
526 #endif
527
528         // ale970302
529         delete bibkey;
530         //
531         //lyxerr << "LyXParagraph::paragraph_id = "
532         //       << LyXParagraph::paragraph_id << endl;
533 }
534
535
536 void LyXParagraph::Erase(LyXParagraph::size_type pos)
537 {
538         // > because last is the next unused position, and you can 
539         // use it if you want
540         if (pos > size()) {
541 #ifndef NEW_INSETS
542                 if (next && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
543                         NextAfterFootnote()->Erase(pos - text.size() - 1);
544                 else 
545 #endif
546                         lyxerr.debug() << "ERROR (LyXParagraph::Erase): "
547                                 "position does not exist." << endl;
548                 return;
549         }
550         if (pos < size()) { // last is free for insertation, but should be empty
551                 // if it is an inset, delete the inset entry 
552                 if (text[pos] == LyXParagraph::META_INSET) {
553                         // find the entry
554                         InsetList::iterator it = lower_bound(insetlist.begin(),
555                                                              insetlist.end(),
556                                                              pos, matchIT());
557                         if (it != insetlist.end() && (*it).pos == pos) {
558                                 delete (*it).inset;
559                                 insetlist.erase(it);
560                         }
561                 }
562                 text.erase(text.begin() + pos);
563
564                 // Erase entries in the tables.
565                 FontList::iterator it = lower_bound(fontlist.begin(),
566                                                     fontlist.end(),
567                                                     pos, matchFT());
568                 if (it != fontlist.end() && (*it).pos == pos &&
569                     (pos == 0 || 
570                      (it != fontlist.begin() && (*(it-1)).pos == pos - 1))) {
571                         // If it is a multi-character font
572                         // entry, we just make it smaller
573                         // (see update below), otherwise we
574                         // should delete it.
575                         unsigned int i = it - fontlist.begin();
576                         fontlist.erase(fontlist.begin() + i);
577                         it = fontlist.begin() + i;
578                         if (i > 0 && i < fontlist.size() &&
579                             fontlist[i-1].font == fontlist[i].font) {
580                                 fontlist.erase(fontlist.begin() + i-1);
581                                 it = fontlist.begin() + i-1;
582                         }
583                 }
584
585                 // Update all other entries.
586                 for (; it != fontlist.end(); ++it)
587                         --(*it).pos;
588
589                 // Update the inset table.
590                 for (InsetList::iterator it = upper_bound(insetlist.begin(),
591                                                           insetlist.end(),
592                                                           pos, matchIT());
593                      it != insetlist.end(); ++it)
594                         --(*it).pos;
595         } else {
596                 lyxerr << "ERROR (LyXParagraph::Erase): "
597                         "can't erase non-existant char." << endl;
598         }
599 }
600
601
602 void LyXParagraph::InsertChar(LyXParagraph::size_type pos, char c)
603 {
604         LyXFont f(LyXFont::ALL_INHERIT);
605         InsertChar(pos, c, f);
606 }
607
608
609 void LyXParagraph::InsertChar(LyXParagraph::size_type pos,
610                               char c, LyXFont const & font)
611 {
612         // > because last is the next unused position, and you can 
613         // use it if you want
614         if (pos > size()) {
615 #ifndef NEW_INSETS
616                 if (next
617                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
618                         NextAfterFootnote()->InsertChar(pos - text.size() - 1,
619                                                         c);
620                 else 
621 #endif
622                         lyxerr.debug() << "ERROR (LyXParagraph::InsertChar): "
623                                 "position does not exist." << endl;
624                 return;
625         }
626         text.insert(text.begin() + pos, c);
627         // Update the font table.
628         for (FontList::iterator it = lower_bound(fontlist.begin(),
629                                                  fontlist.end(),
630                                                  pos, matchFT());
631              it != fontlist.end(); ++it)
632                 ++(*it).pos;
633    
634         // Update the inset table.
635         for (InsetList::iterator it = lower_bound(insetlist.begin(),
636                                                   insetlist.end(),
637                                                   pos, matchIT());
638              it != insetlist.end(); ++it)
639                 ++(*it).pos;
640
641         SetFont(pos, font);
642 }
643
644
645 void LyXParagraph::InsertInset(LyXParagraph::size_type pos,
646                                Inset * inset)
647 {
648         LyXFont f(LyXFont::ALL_INHERIT);
649         InsertInset(pos, inset, f);
650 }
651
652
653 void LyXParagraph::InsertInset(LyXParagraph::size_type pos,
654                                Inset * inset, LyXFont const & font)
655 {
656         Assert(inset);
657         
658         // > because last is the next unused position, and you can 
659         // use it if you want
660         if (pos > size()) {
661 #ifndef NEW_INSETS
662                 if (next
663                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
664                         NextAfterFootnote()
665                                 ->InsertInset(pos - text.size() - 1,
666                                               inset, font);
667                 else
668 #endif
669                         lyxerr << "ERROR (LyXParagraph::InsertInset): " 
670                                 "position does not exist: " << pos << endl;
671                 return;
672         }
673         
674         InsertChar(pos, META_INSET, font);
675         Assert(text[pos] == META_INSET);
676         
677         // Add a new entry in the inset table.
678         InsetList::iterator it = lower_bound(insetlist.begin(),
679                                              insetlist.end(),
680                                              pos, matchIT());
681         if (it != insetlist.end() && (*it).pos == pos)
682                 lyxerr << "ERROR (LyXParagraph::InsertInset): "
683                         "there is an inset in position: " << pos << endl;
684         else
685                 insetlist.insert(it, InsetTable(pos, inset));
686         if (inset_owner)
687                 inset->setOwner(inset_owner);
688 }
689
690
691 bool LyXParagraph::InsertInsetAllowed(Inset * inset)
692 {
693         if (inset_owner)
694                 return inset_owner->InsertInsetAllowed(inset);
695         return true;
696 }
697
698
699 Inset * LyXParagraph::GetInset(LyXParagraph::size_type pos)
700 {
701         if (pos >= size()) {
702 #ifndef NEW_INSETS
703                 if (next
704                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
705                         return NextAfterFootnote()
706                                 ->GetInset(pos - text.size() - 1);
707                 else
708 #endif
709                         lyxerr << "ERROR (LyXParagraph::GetInset): "
710                                 "position does not exist: "
711                                << pos << endl;
712                 
713                 return 0;
714         }
715         // Find the inset.
716         InsetList::iterator it = lower_bound(insetlist.begin(),
717                                              insetlist.end(),
718                                              pos, matchIT());
719         if (it != insetlist.end() && (*it).pos == pos)
720                 return (*it).inset;
721
722         lyxerr << "ERROR (LyXParagraph::GetInset): "
723                 "Inset does not exist: " << pos << endl;
724         //::raise(SIGSTOP);
725         
726         // text[pos] = ' '; // WHY!!! does this set the pos to ' '????
727         // Did this commenting out introduce a bug? So far I have not
728         // see any, please enlighten me. (Lgb)
729         // My guess is that since the inset does not exist, we might
730         // as well replace it with a space to prevent craches. (Asger)
731         return 0;
732 }
733
734
735 Inset const * LyXParagraph::GetInset(LyXParagraph::size_type pos) const
736 {
737         if (pos >= size()) {
738 #ifndef NEW_INSETS
739                 if (next
740                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
741                         return NextAfterFootnote()
742                                 ->GetInset(pos - text.size() - 1);
743                 else
744 #endif
745                         lyxerr << "ERROR (LyXParagraph::GetInset): "
746                                 "position does not exist: "
747                                << pos << endl;
748
749                 return 0;
750         }
751         // Find the inset.
752         InsetList::const_iterator cit = lower_bound(insetlist.begin(),
753                                                     insetlist.end(),
754                                                     pos, matchIT());
755         if (cit != insetlist.end() && (*cit).pos == pos)
756                 return (*cit).inset;
757
758         lyxerr << "ERROR (LyXParagraph::GetInset): "
759                 "Inset does not exist: " << pos << endl;
760         //::raise(SIGSTOP);
761         //text[pos] = ' '; // WHY!!! does this set the pos to ' '????
762         // Did this commenting out introduce a bug? So far I have not
763         // see any, please enlighten me. (Lgb)
764         // My guess is that since the inset does not exist, we might
765         // as well replace it with a space to prevent craches. (Asger)
766         return 0;
767 }
768
769
770 // Gets uninstantiated font setting at position.
771 // Optimized after profiling. (Asger)
772 LyXFont LyXParagraph::GetFontSettings(BufferParams const & bparams,
773                                       LyXParagraph::size_type pos) const
774 {
775         if (pos < size()) {
776                 FontList::const_iterator cit = lower_bound(fontlist.begin(),
777                                                     fontlist.end(),
778                                                     pos, matchFT());
779                 if (cit != fontlist.end())
780                         return (*cit).font;
781         }
782         // > because last is the next unused position, and you can 
783         // use it if you want
784         else if (pos > size()) {
785 #ifndef NEW_INSETS
786                 if (next
787                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
788                         return NextAfterFootnote()
789                                 ->GetFontSettings(bparams,
790                                                   pos - text.size() - 1);
791                 else
792 #endif
793                         // Why is it an error to ask for the font of a
794                         // position that does not exist? Would it be
795                         // enough for this to be enabled on debug?
796                         // We want strict error checking, but it's ok to only
797                         // have it when debugging. (Asger)
798                         lyxerr << "ERROR (LyXParagraph::GetFontSettings): "
799                                 "position does not exist. "
800                                << pos << " (" << static_cast<int>(pos)
801                                << ")" << endl;
802         } else if (pos > 0) {
803                 return GetFontSettings(bparams, pos - 1);
804         } else // pos = size() = 0
805                 return LyXFont(LyXFont::ALL_INHERIT, getParLanguage(bparams));
806
807         return LyXFont(LyXFont::ALL_INHERIT);
808 }
809
810 // Gets uninstantiated font setting at position 0
811 LyXFont LyXParagraph::GetFirstFontSettings() const
812 {
813         if (size() > 0) {
814                 if (!fontlist.empty())
815                         return fontlist[0].font;
816         }
817         
818 #ifndef NEW_INSETS
819         else if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) 
820                 return NextAfterFootnote()->GetFirstFontSettings();
821 #endif
822         return LyXFont(LyXFont::ALL_INHERIT);
823 }
824
825
826 // Gets the fully instantiated font at a given position in a paragraph
827 // This is basically the same function as LyXText::GetFont() in text2.C.
828 // The difference is that this one is used for generating the LaTeX file,
829 // and thus cosmetic "improvements" are disallowed: This has to deliver
830 // the true picture of the buffer. (Asger)
831 // If position is -1, we get the layout font of the paragraph.
832 // If position is -2, we get the font of the manual label of the paragraph.
833 LyXFont LyXParagraph::getFont(BufferParams const & bparams,
834                               LyXParagraph::size_type pos) const
835 {
836         LyXFont tmpfont;
837         LyXLayout const & layout =
838                 textclasslist.Style(bparams.textclass, 
839                                     GetLayout());
840         LyXParagraph::size_type main_body = 0;
841         if (layout.labeltype == LABEL_MANUAL)
842                 main_body = BeginningOfMainBody();
843
844         if (pos >= 0) {
845                 LyXFont layoutfont;
846                 if (pos < main_body)
847                         layoutfont = layout.labelfont;
848                 else
849                         layoutfont = layout.font;
850                 tmpfont = GetFontSettings(bparams, pos);
851                 tmpfont.realize(layoutfont);
852         } else {
853                 // process layoutfont for pos == -1 and labelfont for pos < -1
854                 if (pos == -1)
855                         tmpfont = layout.font;
856                 else
857                         tmpfont = layout.labelfont;
858                 tmpfont.setLanguage(getParLanguage(bparams));
859         }
860
861         // check for environment font information
862         char par_depth = GetDepth();
863         LyXParagraph const * par = this;
864         while (par && par_depth && !tmpfont.resolved()) {
865                 par = par->DepthHook(par_depth - 1);
866                 if (par) {
867                         tmpfont.realize(textclasslist.
868                                         Style(bparams.textclass,
869                                               par->GetLayout()).font);
870                         par_depth = par->GetDepth();
871                 }
872         }
873
874         tmpfont.realize(textclasslist
875                         .TextClass(bparams.textclass)
876                         .defaultfont());
877         return tmpfont;
878 }
879
880
881 /// Returns the height of the highest font in range
882 LyXFont::FONT_SIZE
883 LyXParagraph::HighestFontInRange(LyXParagraph::size_type startpos,
884                                  LyXParagraph::size_type endpos) const
885 {
886         LyXFont::FONT_SIZE maxsize = LyXFont::SIZE_TINY;
887         if (fontlist.empty())
888                 return maxsize;
889         
890         FontList::const_iterator end_it = lower_bound(fontlist.begin(),
891                                                       fontlist.end(),
892                                                       endpos, matchFT());
893         if (end_it != fontlist.end())
894                 ++end_it;
895
896         for (FontList::const_iterator cit = lower_bound(fontlist.begin(),
897                                                         fontlist.end(),
898                                                         startpos, matchFT());
899              cit != end_it; ++cit) {
900                 LyXFont::FONT_SIZE size = (*cit).font.size();
901                 if (size > maxsize && size <= LyXFont::SIZE_HUGER)
902                         maxsize = size;
903         }
904         return maxsize;
905 }
906
907
908 char LyXParagraph::GetChar(LyXParagraph::size_type pos)
909 {
910         Assert(pos >= 0);
911
912         if (pos < size()) {
913                 return text[pos];
914         }
915         // > because last is the next unused position, and you can 
916         // use it if you want
917         else if (pos > size()) {
918 #ifndef NEW_INSETS
919                 if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) 
920                         return NextAfterFootnote()
921                                 ->GetChar(pos - text.size() - 1);
922                 else
923 #endif
924                         {
925                         lyxerr << "ERROR (LyXParagraph::GetChar): "
926                                 "position does not exist."
927                                << pos << " (" << static_cast<int>(pos)
928                                << ")\n";
929                         // Assert(false); // This triggers sometimes...
930                         // Why?
931                 }
932                 
933                 return '\0';
934         }
935         
936 #ifndef NEW_INSETS
937         else {
938                 // We should have a footnote environment.
939                 if (!next || next->footnoteflag == LyXParagraph::NO_FOOTNOTE) {
940                         // Notice that LyX does request the
941                         // last char from time to time. (Asger)
942                         //lyxerr << "ERROR (LyXParagraph::GetChar): "
943                         //      "expected footnote." << endl;
944                         return '\0';
945                 }
946                 switch (next->footnotekind) {
947                 case LyXParagraph::FOOTNOTE:
948                         return LyXParagraph::META_FOOTNOTE;
949                 case LyXParagraph::MARGIN:
950                         return LyXParagraph::META_MARGIN;
951                 case LyXParagraph::FIG:
952                 case LyXParagraph::WIDE_FIG:
953                         return LyXParagraph::META_FIG;
954                 case LyXParagraph::TAB:
955                 case LyXParagraph::WIDE_TAB:
956                         return LyXParagraph::META_TAB;
957                 case LyXParagraph::ALGORITHM:
958                         return LyXParagraph::META_ALGORITHM;
959                 }
960                 return '\0'; // to shut up gcc
961         }
962 #endif
963 }
964
965
966 char LyXParagraph::GetChar(LyXParagraph::size_type pos) const
967 {
968         Assert(pos >= 0);
969
970         if (pos < size()) {
971                 return text[pos];
972         }
973         // > because last is the next unused position, and you can 
974         // use it if you want
975         else if (pos > size()) {
976 #ifndef NEW_INSETS
977                 if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) 
978                         return NextAfterFootnote()
979                                 ->GetChar(pos - text.size() - 1);
980                 else
981 #endif
982                         {
983                         lyxerr << "ERROR (LyXParagraph::GetChar const): "
984                                 "position does not exist."
985                                << pos << " (" << static_cast<int>(pos)
986                                << ")\n";
987                         Assert(false);
988                 }
989                 return '\0';
990         }
991 #ifndef NEW_INSETS
992         else {
993                 // We should have a footnote environment.
994                 if (!next || next->footnoteflag == LyXParagraph::NO_FOOTNOTE) {
995                         // Notice that LyX does request the
996                         // last char from time to time. (Asger)
997                         //lyxerr << "ERROR (LyXParagraph::GetChar): "
998                         //      "expected footnote." << endl;
999                         return '\0';
1000                 }
1001                 switch (next->footnotekind) {
1002                 case LyXParagraph::FOOTNOTE:
1003                         return LyXParagraph::META_FOOTNOTE;
1004                 case LyXParagraph::MARGIN:
1005                         return LyXParagraph::META_MARGIN;
1006                 case LyXParagraph::FIG:
1007                 case LyXParagraph::WIDE_FIG:
1008                         return LyXParagraph::META_FIG;
1009                 case LyXParagraph::TAB:
1010                 case LyXParagraph::WIDE_TAB:
1011                         return LyXParagraph::META_TAB;
1012                 case LyXParagraph::ALGORITHM:
1013                         return LyXParagraph::META_ALGORITHM;
1014                 }
1015                 return '\0'; // to shut up gcc
1016         }
1017 #endif
1018 }
1019
1020
1021 // return an string of the current word, and the end of the word in lastpos.
1022 string LyXParagraph::GetWord(LyXParagraph::size_type & lastpos) const
1023 {
1024         Assert(lastpos>=0);
1025
1026         // the current word is defined as starting at the first character
1027         // from the immediate left of lastpospos which meets the definition
1028         // of IsLetter(), continuing to the last character to the right
1029         // of this meeting IsLetter.
1030
1031         string theword;
1032
1033         // grab a word
1034                 
1035         // move back until we have a letter
1036
1037         //there's no real reason to have firstpos & lastpos as
1038         //separate variables as this is written, but maybe someon
1039         // will want to return firstpos in the future.
1040
1041         //since someone might have typed a punctuation first
1042         int firstpos = lastpos;
1043         
1044         while ((firstpos >= 0) && !IsLetter(firstpos))
1045                 --firstpos;
1046
1047         // now find the beginning by looking for a nonletter
1048         
1049         while ((firstpos>= 0) && IsLetter(firstpos))
1050                 --firstpos;
1051
1052         // the above is now pointing to the preceeding non-letter
1053         ++firstpos;
1054         lastpos = firstpos;
1055
1056         // so copy characters into theword  until we get a nonletter
1057         // note that this can easily exceed lastpos, wich means
1058         // that if used in the middle of a word, the whole word
1059         // is included
1060
1061         while (IsLetter(lastpos)) theword += GetChar(lastpos++);
1062         
1063         return theword;
1064
1065 }
1066
1067  
1068 LyXParagraph::size_type LyXParagraph::Last() const
1069 {
1070 #ifndef NEW_INSETS
1071         if (next && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE)
1072                 return text.size() + NextAfterFootnote()->Last() + 1;
1073         // the 1 is the symbol
1074         // for the footnote
1075         else
1076 #endif
1077                 return text.size();
1078 }
1079
1080
1081 LyXParagraph * LyXParagraph::ParFromPos(LyXParagraph::size_type pos)
1082 {
1083         // > because last is the next unused position, and you can 
1084         // use it if you want
1085         if (pos > size()) {
1086 #ifndef NEW_INSETS
1087                 if (next
1088                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
1089                         return NextAfterFootnote()
1090                                 ->ParFromPos(pos - text.size() - 1);
1091                 else
1092 #endif
1093                         lyxerr << "ERROR (LyXParagraph::ParFromPos): "
1094                                 "position does not exist." << endl;
1095                 return this;
1096         } else
1097                 return this;
1098 }
1099
1100
1101 int LyXParagraph::PositionInParFromPos(LyXParagraph::size_type pos) const
1102 {
1103         // > because last is the next unused position, and you can 
1104         // use it if you want
1105         if (pos > size()) {
1106 #ifndef NEW_INSETS
1107                 if (next
1108                     && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) 
1109                         return NextAfterFootnote()
1110                                 ->PositionInParFromPos(pos - text.size() - 1);
1111                 else
1112 #endif
1113                         lyxerr <<
1114                                 "ERROR (LyXParagraph::PositionInParFromPos): "
1115                                 "position does not exist." << endl;
1116                 return pos;
1117         }
1118         else
1119                 return pos;
1120 }
1121
1122
1123 void LyXParagraph::SetFont(LyXParagraph::size_type pos,
1124                            LyXFont const & font)
1125 {
1126         // > because last is the next unused position, and you can 
1127         // use it if you want
1128         if (pos > size()) {
1129 #ifndef NEW_INSETS
1130                 if (next &&
1131                     next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1132                         NextAfterFootnote()->SetFont(pos - text.size() - 1,
1133                                                      font);
1134                 } else
1135 #endif
1136                         lyxerr << "ERROR (LyXParagraph::SetFont): "
1137                                 "position does not exist." << endl;
1138                 
1139                 return;
1140         }
1141
1142         // First, reduce font against layout/label font
1143         // Update: The SetCharFont() routine in text2.C already
1144         // reduces font, so we don't need to do that here. (Asger)
1145         // No need to simplify this because it will disappear
1146         // in a new kernel. (Asger)
1147         // Next search font table
1148
1149         FontList::iterator it = lower_bound(fontlist.begin(),
1150                                             fontlist.end(),
1151                                             pos, matchFT());
1152         unsigned int i = it - fontlist.begin();
1153         bool notfound = it == fontlist.end();
1154
1155         if (!notfound && fontlist[i].font == font)
1156                 return;
1157
1158         bool begin = pos == 0 || notfound ||
1159                 (i > 0 && fontlist[i-1].pos == pos - 1);
1160         // Is position pos is a beginning of a font block?
1161         bool end = !notfound && fontlist[i].pos == pos;
1162         // Is position pos is the end of a font block?
1163         if (begin && end) { // A single char block
1164                 if (i+1 < fontlist.size() &&
1165                     fontlist[i+1].font == font) {
1166                         // Merge the singleton block with the next block
1167                         fontlist.erase(fontlist.begin() + i);
1168                         if (i > 0 && fontlist[i-1].font == font)
1169                                 fontlist.erase(fontlist.begin() + i-1);
1170                 } else if (i > 0 && fontlist[i-1].font == font) {
1171                         // Merge the singleton block with the previous block
1172                         fontlist[i-1].pos = pos;
1173                         fontlist.erase(fontlist.begin() + i);
1174                 } else
1175                         fontlist[i].font = font;
1176         } else if (begin) {
1177                 if (i > 0 && fontlist[i-1].font == font)
1178                         fontlist[i-1].pos = pos;
1179                 else
1180                         fontlist.insert(fontlist.begin() + i,
1181                                         FontTable(pos, font));
1182         } else if (end) {
1183                 fontlist[i].pos = pos - 1;
1184                 if (!(i+1 < fontlist.size() &&
1185                       fontlist[i+1].font == font))
1186                         fontlist.insert(fontlist.begin() + i+1,
1187                                         FontTable(pos, font));
1188         } else { // The general case. The block is splitted into 3 blocks
1189                 fontlist.insert(fontlist.begin() + i, 
1190                                 FontTable(pos - 1, fontlist[i].font));
1191                 fontlist.insert(fontlist.begin() + i+1, FontTable(pos, font));
1192         }
1193 }
1194
1195    
1196 // This function is able to hide closed footnotes.
1197 LyXParagraph * LyXParagraph::Next()
1198 {
1199 #ifndef NEW_INSETS
1200         if (next && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1201                 LyXParagraph * tmp = next;
1202                 while (tmp
1203                        && tmp->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE)
1204                         tmp = tmp->next;
1205                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1206                         return tmp->Next(); /* there can be more than one
1207                                                footnote in a logical
1208                                                paragraph */
1209                 else
1210                         return next;  // This should never happen!
1211         } else
1212 #endif
1213                 return next;
1214 }
1215
1216
1217 LyXParagraph * LyXParagraph::NextAfterFootnote()
1218 {
1219 #ifndef NEW_INSETS
1220         if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
1221                 LyXParagraph * tmp = next;
1222                 while (tmp && tmp->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1223                         tmp = tmp->next;
1224                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1225                         return tmp;   /* there can be more than one footnote
1226                                          in a logical paragraph */
1227                 else
1228                         return next;  // This should never happen!
1229         } else
1230 #endif
1231                 return next;
1232 }
1233
1234
1235 LyXParagraph const * LyXParagraph::NextAfterFootnote() const
1236 {
1237 #ifndef NEW_INSETS
1238         if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
1239                 LyXParagraph * tmp = next;
1240                 while (tmp && tmp->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1241                         tmp = tmp->next;
1242                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1243                         return tmp;   /* there can be more than one footnote
1244                                          in a logical paragraph */
1245                 else
1246                         return next;  // This should never happen!
1247         } else
1248 #endif
1249                 return next;
1250 }
1251
1252
1253 LyXParagraph * LyXParagraph::PreviousBeforeFootnote()
1254 {
1255 #ifndef NEW_INSETS
1256         LyXParagraph * tmp;
1257         if (previous && previous->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
1258                 tmp = previous;
1259                 while (tmp && tmp->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1260                         tmp = tmp->previous;
1261                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1262                         return tmp;    /* there can be more than one footnote
1263                                           in a logical paragraph */
1264                 else
1265                         return previous;  // This should never happen!
1266         } else
1267 #endif
1268                 return previous;
1269 }
1270
1271
1272 LyXParagraph * LyXParagraph::LastPhysicalPar()
1273 {
1274 #ifndef NEW_INSETS
1275         if (footnoteflag != LyXParagraph::NO_FOOTNOTE)
1276                 return this;
1277    
1278         LyXParagraph * tmp = this;
1279         while (tmp->next
1280                && tmp->next->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1281                 tmp = tmp->NextAfterFootnote();
1282    
1283         return tmp;
1284 #else
1285         return this;
1286 #endif
1287 }
1288
1289 LyXParagraph const * LyXParagraph::LastPhysicalPar() const
1290 {
1291 #ifndef NEW_INSETS
1292         if (footnoteflag != LyXParagraph::NO_FOOTNOTE)
1293                 return this;
1294    
1295         LyXParagraph const * tmp = this;
1296         while (tmp->next
1297                && tmp->next->footnoteflag != LyXParagraph::NO_FOOTNOTE)
1298                 tmp = tmp->NextAfterFootnote();
1299    
1300         return tmp;
1301 #else
1302         return this;
1303 #endif
1304 }
1305
1306 LyXParagraph * LyXParagraph::FirstPhysicalPar()
1307 {
1308 #ifndef NEW_INSETS
1309         if (!IsDummy())
1310                 return this;
1311         LyXParagraph * tmppar = this;
1312
1313         while (tmppar &&
1314                (tmppar->IsDummy()
1315                 || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE))
1316                 tmppar = tmppar->previous;
1317    
1318         if (!tmppar) {
1319                 return this;
1320         } else
1321                 return tmppar;
1322 #else
1323         return this;
1324 #endif
1325 }
1326
1327
1328 LyXParagraph const * LyXParagraph::FirstPhysicalPar() const
1329 {
1330 #ifndef NEW_INSETS
1331         if (!IsDummy())
1332                 return this;
1333         LyXParagraph const * tmppar = this;
1334
1335         while (tmppar &&
1336                (tmppar->IsDummy()
1337                 || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE))
1338                 tmppar = tmppar->previous;
1339    
1340         if (!tmppar) {
1341                 return this;
1342         } else
1343                 return tmppar;
1344 #else
1345         return this;
1346 #endif
1347 }
1348
1349
1350 // This function is able to hide closed footnotes.
1351 LyXParagraph * LyXParagraph::Previous()
1352 {
1353         LyXParagraph * tmp = previous;
1354         if (!tmp)
1355                 return tmp;
1356
1357 #ifndef NEW_INSETS
1358         if (tmp->previous
1359             && tmp->previous->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1360                 tmp = tmp->previous;
1361                 while (tmp
1362                        && tmp->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE)
1363                         tmp = tmp->previous;
1364                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1365                         return tmp->next->Previous();   
1366
1367                 else
1368                         return previous; 
1369         } else
1370 #endif
1371                 return previous;
1372 }
1373
1374
1375 // This function is able to hide closed footnotes.
1376 LyXParagraph const * LyXParagraph::Previous() const
1377 {
1378         LyXParagraph * tmp = previous;
1379         if (!tmp)
1380                 return tmp;
1381 #ifndef NEW_INSETS
1382         if (tmp->previous
1383             && tmp->previous->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1384                 tmp = tmp->previous;
1385                 while (tmp
1386                        && tmp->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE)
1387                         tmp = tmp->previous;
1388                 if (tmp && tmp->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE) 
1389                         return tmp->next->Previous();   
1390
1391                 else
1392                         return previous; 
1393         } else
1394 #endif
1395                 return previous;
1396 }
1397
1398
1399 void LyXParagraph::BreakParagraph(BufferParams const & bparams,
1400                                   LyXParagraph::size_type pos,
1401                                   int flag)
1402 {
1403         size_type i, j, pos_end, pos_first;
1404         // create a new paragraph
1405         LyXParagraph * par = ParFromPos(pos);
1406         LyXParagraph * firstpar = FirstPhysicalPar();
1407    
1408         LyXParagraph * tmp = new LyXParagraph(par);
1409
1410 #ifndef NEW_INSETS
1411         tmp->footnoteflag = footnoteflag;
1412         tmp->footnotekind = footnotekind;
1413 #endif
1414         // this is an idea for a more userfriendly layout handling, I will
1415         // see what the users say
1416    
1417         // layout stays the same with latex-environments
1418         if (flag) {
1419                 tmp->SetOnlyLayout(bparams, firstpar->layout);
1420                 tmp->SetLabelWidthString(firstpar->labelwidthstring);
1421         }
1422
1423         if (Last() > pos || !Last() || flag == 2) {
1424                 tmp->SetOnlyLayout(bparams, firstpar->layout);
1425                 tmp->align = firstpar->align;
1426                 tmp->SetLabelWidthString(firstpar->labelwidthstring);
1427       
1428                 tmp->line_bottom = firstpar->line_bottom;
1429                 firstpar->line_bottom = false;
1430                 tmp->pagebreak_bottom = firstpar->pagebreak_bottom;
1431                 firstpar->pagebreak_bottom = false;
1432                 tmp->added_space_bottom = firstpar->added_space_bottom;
1433                 firstpar->added_space_bottom = VSpace(VSpace::NONE);
1434       
1435                 tmp->depth = firstpar->depth;
1436                 tmp->noindent = firstpar->noindent;
1437    
1438                 // copy everything behind the break-position
1439                 // to the new paragraph
1440                 pos_first = 0;
1441                 while (ParFromPos(pos_first) != par)
1442                         ++pos_first;
1443
1444                 pos_end = pos_first + par->text.size() - 1;
1445
1446                 for (i = j = pos; i <= pos_end; ++i) {
1447                         par->CutIntoMinibuffer(bparams, i - pos_first);
1448                         if (tmp->InsertFromMinibuffer(j - pos))
1449                                 ++j;
1450                 }
1451                 tmp->text.resize(tmp->text.size());
1452                 for (i = pos_end; i >= pos; --i)
1453                         par->Erase(i - pos_first);
1454
1455                 par->text.resize(par->text.size());
1456         }
1457
1458         // just an idea of me
1459         if (!pos) {
1460                 tmp->line_top = firstpar->line_top;
1461                 tmp->pagebreak_top = firstpar->pagebreak_top;
1462                 tmp->added_space_top = firstpar->added_space_top;
1463                 tmp->bibkey = firstpar->bibkey;
1464                 firstpar->Clear();
1465                 // layout stays the same with latex-environments
1466                 if (flag) {
1467                         firstpar->SetOnlyLayout(bparams, tmp->layout);
1468                         firstpar->SetLabelWidthString(tmp->labelwidthstring);
1469                         firstpar->depth = tmp->depth;
1470                 }
1471         }
1472 }
1473
1474
1475 void LyXParagraph::MakeSameLayout(LyXParagraph const * par)
1476 {
1477         par = par->FirstPhysicalPar();
1478 #ifndef NEW_INSETS
1479         footnoteflag = par->footnoteflag;
1480         footnotekind = par->footnotekind;
1481 #endif
1482         layout = par->layout;
1483         align = par-> align;
1484         SetLabelWidthString(par->labelwidthstring);
1485
1486         line_bottom = par->line_bottom;
1487         pagebreak_bottom = par->pagebreak_bottom;
1488         added_space_bottom = par->added_space_bottom;
1489
1490         line_top = par->line_top;
1491         pagebreak_top = par->pagebreak_top;
1492         added_space_top = par->added_space_top;
1493
1494         spacing = par->spacing;
1495         
1496         pextra_type = par->pextra_type;
1497         pextra_width = par->pextra_width;
1498         pextra_widthp = par->pextra_widthp;
1499         pextra_alignment = par->pextra_alignment;
1500         pextra_hfill = par->pextra_hfill;
1501         pextra_start_minipage = par->pextra_start_minipage;
1502
1503         noindent = par->noindent;
1504         depth = par->depth;
1505 }
1506
1507
1508 #ifndef NEW_INSETS
1509 LyXParagraph * LyXParagraph::FirstSelfrowPar()
1510 {
1511         LyXParagraph * tmppar = this;
1512         while (tmppar && (
1513                 (tmppar->IsDummy()
1514                  && tmppar->previous->footnoteflag == 
1515                  LyXParagraph::CLOSED_FOOTNOTE)
1516                 || tmppar->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE))
1517                 tmppar = tmppar->previous;
1518    
1519         if (!tmppar)
1520                 return this;  // This should never happen!
1521         else
1522                 return tmppar;
1523 }
1524 #endif
1525
1526
1527 int LyXParagraph::StripLeadingSpaces(LyXTextClassList::size_type tclass) 
1528 {
1529         if (textclasslist.Style(tclass, GetLayout()).free_spacing)
1530                 return 0;
1531         
1532         int i = 0;
1533         if (!IsDummy() && !table){
1534                 while (Last()
1535                        && (IsNewline(0) || IsLineSeparator(0))){
1536                         Erase(0);
1537                         ++i;
1538                 }
1539         }
1540         return i;
1541 }
1542
1543
1544 LyXParagraph * LyXParagraph::Clone() const
1545 {
1546         // create a new paragraph
1547         LyXParagraph * result = new LyXParagraph;
1548    
1549         result->MakeSameLayout(this);
1550
1551         // this is because of the dummy layout of the paragraphs that
1552         // follow footnotes
1553         result->layout = layout;
1554
1555 #ifndef NEW_TABULAR
1556         /* table stuff -- begin*/ 
1557         if (table)
1558                 result->table = table->Clone();
1559         else
1560                 result->table = 0;
1561         /* table stuff -- end*/ 
1562 #endif
1563         result->inset_owner = inset_owner;
1564    
1565         // ale970302
1566         result->bibkey = (bibkey) ? new InsetBibKey(bibkey): 0;
1567                
1568     
1569         // copy everything behind the break-position to the new paragraph
1570
1571         result->text = text;
1572         result->fontlist = fontlist;
1573         result->insetlist = insetlist;
1574         for (InsetList::iterator it = result->insetlist.begin();
1575              it != result->insetlist.end(); ++it)
1576                 (*it).inset = (*it).inset->Clone();
1577         return result;
1578 }
1579
1580
1581 bool LyXParagraph::HasSameLayout(LyXParagraph const * par) const
1582 {
1583         par = par->FirstPhysicalPar();
1584
1585         return (
1586 #ifndef NEW_INSETS
1587                 par->footnoteflag == footnoteflag &&
1588                 par->footnotekind == footnotekind &&
1589 #endif
1590                 par->layout == layout &&
1591
1592                 par->align == align &&
1593
1594                 par->line_bottom == line_bottom &&
1595                 par->pagebreak_bottom == pagebreak_bottom &&
1596                 par->added_space_bottom == added_space_bottom &&
1597
1598                 par->line_top == line_top &&
1599                 par->pagebreak_top == pagebreak_top &&
1600                 par->added_space_top == added_space_top &&
1601
1602                 par->spacing == spacing &&
1603                 
1604                 par->pextra_type == pextra_type &&
1605                 par->pextra_width == pextra_width && 
1606                 par->pextra_widthp == pextra_widthp && 
1607                 par->pextra_alignment == pextra_alignment && 
1608                 par->pextra_hfill == pextra_hfill && 
1609                 par->pextra_start_minipage == pextra_start_minipage && 
1610 #ifndef NEW_TABULAR
1611                 par->table == table && // what means: NO TABLE AT ALL
1612 #endif
1613
1614                 par->noindent == noindent &&
1615                 par->depth == depth);
1616 }
1617
1618
1619 void LyXParagraph::BreakParagraphConservative(BufferParams const & bparams,
1620                                               LyXParagraph::size_type pos)
1621 {
1622         // create a new paragraph
1623         LyXParagraph * par = ParFromPos(pos);
1624
1625         LyXParagraph * tmp = new LyXParagraph(par);
1626    
1627         tmp->MakeSameLayout(par);
1628
1629         // When can pos < Last()?
1630         // I guess pos == Last() is possible.
1631         if (Last() > pos) {
1632                 // copy everything behind the break-position to the new
1633                 // paragraph
1634                 size_type pos_first = 0;
1635                 while (ParFromPos(pos_first) != par)
1636                         ++pos_first;
1637                 size_type pos_end = pos_first + par->text.size() - 1;
1638
1639                 size_type i, j;
1640                 for (i = j = pos; i <= pos_end; ++i) {
1641                         par->CutIntoMinibuffer(bparams, i - pos_first);
1642                         if (tmp->InsertFromMinibuffer(j - pos))
1643                                 ++j;
1644                 }
1645                 tmp->text.resize(tmp->text.size());
1646                 for (size_type i = pos_end; i >= pos; --i)
1647                         par->Erase(i - pos_first);
1648
1649                 par->text.resize(par->text.size());
1650         }
1651 }
1652    
1653
1654 // Be carefull, this does not make any check at all.
1655 void LyXParagraph::PasteParagraph(BufferParams const & bparams)
1656 {
1657         // copy the next paragraph to this one
1658         LyXParagraph * the_next = Next();
1659    
1660         LyXParagraph * firstpar = FirstPhysicalPar();
1661    
1662         // first the DTP-stuff
1663         firstpar->line_bottom = the_next->line_bottom;
1664         firstpar->added_space_bottom = the_next->added_space_bottom;
1665         firstpar->pagebreak_bottom = the_next->pagebreak_bottom;
1666
1667         size_type pos_end = the_next->text.size() - 1;
1668         size_type pos_insert = Last();
1669
1670         // ok, now copy the paragraph
1671         size_type i, j;
1672         for (i = j = 0; i <= pos_end; ++i) {
1673                 the_next->CutIntoMinibuffer(bparams, i);
1674                 if (InsertFromMinibuffer(pos_insert + j))
1675                         ++j;
1676         }
1677    
1678         // delete the next paragraph
1679         LyXParagraph * ppar = the_next->previous;
1680         LyXParagraph * npar = the_next->next;
1681         delete the_next;
1682         ppar->next = npar;
1683 }
1684
1685
1686 #ifndef NEW_INSETS
1687 void LyXParagraph::OpenFootnote(LyXParagraph::size_type pos)
1688 {
1689         LyXParagraph * par = ParFromPos(pos);
1690         par = par->next;
1691         while (par && par->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1692                 par->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
1693                 par = par->next;
1694         }
1695 }
1696
1697
1698 void LyXParagraph::CloseFootnote(LyXParagraph::size_type pos)
1699 {
1700         LyXParagraph * par = ParFromPos(pos);
1701         par = par->next;
1702         while (par && par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
1703                 par->footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
1704                 par = par->next;
1705         }
1706 }
1707 #endif
1708
1709 int LyXParagraph::GetEndLabel(BufferParams const & bparams) const
1710 {
1711         LyXParagraph const * par = this;
1712         int par_depth = GetDepth();
1713         while (par) {
1714                 LyXTextClass::LayoutList::size_type layout = par->GetLayout();
1715                 int endlabeltype =
1716                         textclasslist.Style(bparams.textclass,
1717                                             layout).endlabeltype;
1718                 if (endlabeltype != END_LABEL_NO_LABEL) {
1719                         LyXParagraph const * last = this;
1720                         if( footnoteflag == NO_FOOTNOTE)
1721                                 last = LastPhysicalPar();
1722                         else if (next->footnoteflag == NO_FOOTNOTE)
1723                                 return endlabeltype;
1724
1725                         if (!last || !last->next)
1726                                 return endlabeltype;
1727
1728                         int next_depth = last->next->GetDepth();
1729                         if (par_depth > next_depth ||
1730                             (par_depth == next_depth && layout != last->next->GetLayout() ))
1731                                 return endlabeltype;
1732                         break;
1733                 }
1734                 if (par_depth == 0)
1735                         break;
1736                 par = par->DepthHook(par_depth - 1);
1737                 if (par)
1738                         par_depth = par->GetDepth();
1739         }
1740         return END_LABEL_NO_LABEL;
1741 }
1742
1743
1744 LyXTextClass::size_type LyXParagraph::GetLayout() const
1745 {
1746         return FirstPhysicalPar()->layout;
1747 }
1748
1749
1750 char LyXParagraph::GetDepth() const
1751 {
1752         return FirstPhysicalPar()->depth;
1753 }
1754
1755
1756 char LyXParagraph::GetAlign() const
1757 {
1758         return FirstPhysicalPar()->align;
1759 }
1760
1761
1762 string LyXParagraph::GetLabelstring() const
1763 {
1764         return FirstPhysicalPar()->labelstring;
1765 }
1766
1767
1768 int LyXParagraph::GetFirstCounter(int i) const
1769 {
1770         return FirstPhysicalPar()->counter_[i];
1771 }
1772
1773
1774 // the next two functions are for the manual labels
1775 string LyXParagraph::GetLabelWidthString() const
1776 {
1777         if (!FirstPhysicalPar()->labelwidthstring.empty())
1778                 return FirstPhysicalPar()->labelwidthstring;
1779         else
1780                 return _("Senseless with this layout!");
1781 }
1782
1783
1784 void LyXParagraph::SetLabelWidthString(string const & s)
1785 {
1786         LyXParagraph * par = FirstPhysicalPar();
1787
1788         par->labelwidthstring = s;
1789 }
1790
1791
1792 void LyXParagraph::SetOnlyLayout(BufferParams const & bparams,
1793                                  LyXTextClass::size_type new_layout)
1794 {
1795         LyXParagraph * par = FirstPhysicalPar();
1796         LyXParagraph * ppar = 0;
1797         LyXParagraph * npar = 0;
1798
1799         par->layout = new_layout;
1800 #ifndef NEW_TABULAR
1801         /* table stuff -- begin*/ 
1802         if (table) 
1803                 par->layout = 0;
1804         /* table stuff -- end*/
1805 #endif
1806         if (par->pextra_type == PEXTRA_NONE) {
1807                 if (par->Previous()) {
1808                         ppar = par->Previous()->FirstPhysicalPar();
1809                         while(ppar
1810                               && ppar->Previous()
1811                               && (ppar->depth > par->depth))
1812                                 ppar = ppar->Previous()->FirstPhysicalPar();
1813                 }
1814                 if (par->Next()) {
1815                         npar = par->Next()->NextAfterFootnote();
1816                         while(npar
1817                               && npar->Next()
1818                               && (npar->depth > par->depth))
1819                                 npar = npar->Next()->NextAfterFootnote();
1820                 }
1821                 if (ppar && (ppar->pextra_type != PEXTRA_NONE)) {
1822                         string
1823                                 p1 = ppar->pextra_width,
1824                                 p2 = ppar->pextra_widthp;
1825                         ppar->SetPExtraType(bparams, ppar->pextra_type,
1826                                             p1.c_str(), p2.c_str());
1827                 }
1828                 if ((par->pextra_type == PEXTRA_NONE) &&
1829                     npar && (npar->pextra_type != PEXTRA_NONE)) {
1830                         string
1831                                 p1 = npar->pextra_width,
1832                                 p2 = npar->pextra_widthp;
1833                         npar->SetPExtraType(bparams, npar->pextra_type,
1834                                             p1.c_str(), p2.c_str());
1835                 }
1836         }
1837 }
1838
1839
1840 void LyXParagraph::SetLayout(BufferParams const & bparams,
1841                              LyXTextClass::size_type new_layout)
1842 {
1843         LyXParagraph
1844                 * par = FirstPhysicalPar(),
1845                 * ppar = 0,
1846                 * npar = 0;
1847
1848         par->layout = new_layout;
1849         par->labelwidthstring.erase();
1850         par->align = LYX_ALIGN_LAYOUT;
1851         par->added_space_top = VSpace(VSpace::NONE);
1852         par->added_space_bottom = VSpace(VSpace::NONE);
1853         par->spacing.set(Spacing::Default);
1854
1855 #ifndef NEW_TABULAR
1856         /* table stuff -- begin*/ 
1857         if (table) 
1858                 par->layout = 0;
1859         /* table stuff -- end*/
1860 #endif
1861         if (par->pextra_type == PEXTRA_NONE) {
1862                 if (par->Previous()) {
1863                         ppar = par->Previous()->FirstPhysicalPar();
1864                         while(ppar
1865                               && ppar->Previous()
1866                               && (ppar->depth > par->depth))
1867                                 ppar = ppar->Previous()->FirstPhysicalPar();
1868                 }
1869                 if (par->Next()) {
1870                         npar = par->Next()->NextAfterFootnote();
1871                         while(npar
1872                               && npar->Next()
1873                               && (npar->depth > par->depth))
1874                                 npar = npar->Next()->NextAfterFootnote();
1875                 }
1876                 if (ppar && (ppar->pextra_type != PEXTRA_NONE)) {
1877                         string
1878                                 p1 = ppar->pextra_width,
1879                                 p2 = ppar->pextra_widthp;
1880                         ppar->SetPExtraType(bparams, ppar->pextra_type,
1881                                             p1.c_str(), p2.c_str());
1882                 }
1883                 if ((par->pextra_type == PEXTRA_NONE) &&
1884                     npar && (npar->pextra_type != PEXTRA_NONE)) {
1885                         string
1886                                 p1 = npar->pextra_width,
1887                                 p2 = npar->pextra_widthp;
1888                         npar->SetPExtraType(bparams, npar->pextra_type,
1889                                             p1.c_str(), p2.c_str());
1890                 }
1891         }
1892 }
1893
1894
1895 // if the layout of a paragraph contains a manual label, the beginning of the 
1896 // main body is the beginning of the second word. This is what the par-
1897 // function returns. If the layout does not contain a label, the main
1898 // body always starts with position 0. This differentiation is necessary,
1899 // because there cannot be a newline or a blank <= the beginning of the 
1900 // main body in TeX.
1901
1902 int LyXParagraph::BeginningOfMainBody() const
1903 {
1904         if (FirstPhysicalPar() != this)
1905                 return -1;
1906    
1907         // Unroll the first two cycles of the loop
1908         // and remember the previous character to
1909         // remove unnecessary GetChar() calls
1910         size_type i = 0;
1911         if (i < size()
1912             && GetChar(i) != LyXParagraph::META_NEWLINE
1913                 ) {
1914                 ++i;
1915                 char previous_char = 0, temp = 0; 
1916                 if (i < size()
1917                     && (previous_char = GetChar(i)) != LyXParagraph::META_NEWLINE) {
1918                         // Yes, this  ^ is supposed to be "= " not "=="
1919                         ++i;
1920                         while (i < size()
1921                                && previous_char != ' '
1922                                && (temp = GetChar(i)) != LyXParagraph::META_NEWLINE) {
1923                                 ++i;
1924                                 previous_char = temp;
1925                         }
1926                 }
1927         }
1928
1929         if (i == 0 && i == size() &&
1930             !(footnoteflag == LyXParagraph::NO_FOOTNOTE
1931               && next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE))
1932                 ++i;                           /* the cursor should not jump  
1933                                                 * to the main body if there
1934                                                 * is nothing in! */
1935         return i;
1936 }
1937
1938
1939 LyXParagraph * LyXParagraph::DepthHook(int deth)
1940 {
1941         LyXParagraph * newpar = this;
1942         if (deth < 0)
1943                 return 0;
1944    
1945         do {
1946                 newpar = newpar->FirstPhysicalPar()->Previous();
1947         } while (newpar && newpar->GetDepth() > deth
1948                  && newpar->footnoteflag == footnoteflag);
1949    
1950         if (!newpar) {
1951                 if (Previous() || GetDepth())
1952                         lyxerr << "ERROR (LyXParagraph::DepthHook): "
1953                                 "no hook." << endl;
1954                 newpar = this;
1955         }
1956         return newpar->FirstPhysicalPar();
1957 }
1958
1959
1960 LyXParagraph const * LyXParagraph::DepthHook(int deth) const
1961 {
1962         LyXParagraph const * newpar = this;
1963         if (deth < 0)
1964                 return 0;
1965    
1966         do {
1967                 newpar = newpar->FirstPhysicalPar()->Previous();
1968         } while (newpar && newpar->GetDepth() > deth
1969                  && newpar->footnoteflag == footnoteflag);
1970    
1971         if (!newpar) {
1972                 if (Previous() || GetDepth())
1973                         lyxerr << "ERROR (LyXParagraph::DepthHook): "
1974                                 "no hook." << endl;
1975                 newpar = this;
1976         }
1977         return newpar->FirstPhysicalPar();
1978 }
1979
1980
1981 int LyXParagraph::AutoDeleteInsets()
1982 {
1983         int count = 0;
1984         InsetList::size_type index = 0;
1985         while (index < insetlist.size()) {
1986                 if (insetlist[index].inset && insetlist[index].inset->AutoDelete()) {
1987                         Erase(insetlist[index].pos); 
1988                         // Erase() calls to insetlist.erase(&insetlist[index])
1989                         // so index shouldn't be increased.
1990                         ++count;
1991                 } else
1992                         ++index;
1993         }
1994         return count;
1995 }
1996
1997
1998 LyXParagraph::inset_iterator LyXParagraph::InsetIterator(LyXParagraph::size_type pos)
1999 {
2000         InsetList::iterator it = lower_bound(insetlist.begin(),
2001                                              insetlist.end(),
2002                                              pos, matchIT());
2003         return inset_iterator(it);
2004 }
2005
2006
2007 // returns -1 if inset not found
2008 int LyXParagraph::GetPositionOfInset(Inset * inset) const
2009 {
2010         // Find the entry.
2011         // We could use lower_bound here too, we just need to add
2012         // the approp. operator() to matchIT (and change the name
2013         // of that struct). Code would then be:
2014         // InsetList::const_iterator cit = lower_bound(insetlist.begin(),
2015         //                                             insetlist.end(),
2016         //                                             inset, matchIT());
2017         // if ((*cit).inset == inset) {
2018         //         return (*cit).pos;
2019         // }
2020         for (InsetList::const_iterator cit = insetlist.begin();
2021              cit != insetlist.end(); ++cit) {
2022                 if ((*cit).inset == inset) {
2023                         return (*cit).pos;
2024                 }
2025         }
2026         // Think about footnotes.
2027         if (footnoteflag == LyXParagraph::NO_FOOTNOTE 
2028             && next && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
2029                 int further = 
2030                         NextAfterFootnote()->GetPositionOfInset(inset);
2031                 if (further != -1)
2032                         return text.size() + 1 + further;
2033         }
2034         return -1;
2035 }
2036
2037
2038 LyXParagraph * LyXParagraph::TeXOnePar(Buffer const * buf,
2039                                        BufferParams const & bparams,
2040                                        ostream & os, TexRow & texrow,
2041                                        bool moving_arg, 
2042                                        ostream & foot,
2043                                        TexRow & foot_texrow,
2044                                        int & foot_count)
2045 {
2046         lyxerr[Debug::LATEX] << "TeXOnePar...     " << this << endl;
2047         LyXLayout const & style =
2048                 textclasslist.Style(bparams.textclass,
2049                                     layout);
2050
2051         bool further_blank_line = false;
2052         if (IsDummy())
2053                 lyxerr << "ERROR (LyXParagraph::TeXOnePar) is dummy." << endl;
2054
2055         if (start_of_appendix) {
2056                 os << "\\appendix\n";
2057                 texrow.newline();
2058         }
2059
2060         if (!spacing.isDefault()
2061             && (!Previous() || !Previous()->HasSameLayout(this))) {
2062                 os << spacing.writeEnvirBegin() << "\n";
2063                 texrow.newline();
2064         }
2065         
2066         if (tex_code_break_column && style.isCommand()){
2067                 os << '\n';
2068                 texrow.newline();
2069         }
2070
2071         if (pagebreak_top) {
2072                 os << "\\newpage";
2073                 further_blank_line = true;
2074         }
2075         if (added_space_top.kind() != VSpace::NONE) {
2076                 os << added_space_top.asLatexCommand(bparams);
2077                 further_blank_line = true;
2078         }
2079       
2080         if (line_top) {
2081                 os << "\\lyxline{\\" << getFont(bparams, 0).latexSize() << '}'
2082                    << "\\vspace{-1\\parskip}";
2083                 further_blank_line = true;
2084         }
2085
2086         if (further_blank_line){
2087                 os << '\n';
2088                 texrow.newline();
2089         }
2090
2091         Language const * language = getParLanguage(bparams);
2092         Language const * doc_language = bparams.language_info;
2093         if (language != doc_language &&
2094             (!previous || previous->getParLanguage(bparams) != language)) {
2095                 os << subst(lyxrc.language_command_begin, "$$lang",
2096                             language->lang())
2097                    << endl;
2098                 texrow.newline();
2099         }
2100         
2101         switch (style.latextype) {
2102         case LATEX_COMMAND:
2103                 os << '\\'
2104                    << style.latexname()
2105                    << style.latexparam();
2106                 break;
2107         case LATEX_ITEM_ENVIRONMENT:
2108                 if (bibkey) {
2109                         bibkey->Latex(buf, os, false, false);
2110                 } else
2111                         os << "\\item ";
2112                 break;
2113         case LATEX_LIST_ENVIRONMENT:
2114                 os << "\\item ";
2115                 break;
2116         default:
2117                 break;
2118         }
2119
2120         bool need_par = SimpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
2121  
2122 #ifndef NEW_INSETS
2123         // Spit out footnotes
2124         LyXParagraph * par = next;
2125         if (lyxrc.rtl_support) {
2126                 if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE
2127                     && next->footnoteflag != footnoteflag) {
2128                         LyXParagraph * p = 0;
2129                         bool is_rtl = (size() > 0) 
2130                                 ? GetFontSettings(bparams,
2131                                                   size()-1).isRightToLeft()
2132                                 : language->RightToLeft();
2133                         if ( (p = NextAfterFootnote()) != 0 &&
2134                              p->size() > 0 &&
2135                              p->GetFontSettings(bparams, 0).isRightToLeft() != is_rtl)
2136                                 is_rtl = getParLanguage(bparams)->RightToLeft();
2137                         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE
2138                                && par->footnoteflag != footnoteflag) {
2139                                 par = par->TeXFootnote(buf, bparams,
2140                                                        os, texrow, foot,
2141                                                        foot_texrow, foot_count,
2142                                                        is_rtl);
2143                                 par->SimpleTeXOnePar(buf, bparams,
2144                                                      os, texrow, moving_arg);
2145                                 is_rtl = (par->size() > 0)
2146                                         ? par->GetFontSettings(bparams,
2147                                                                par->size()-1).isRightToLeft()
2148                                         : language->RightToLeft();
2149                                 if (par->next &&
2150                                     par->next->footnoteflag != LyXParagraph::NO_FOOTNOTE &&
2151                                     (p = par->NextAfterFootnote()) != 0 &&
2152                                     p->size() > 0 &&
2153                                     p->GetFontSettings(bparams, 0).isRightToLeft() != is_rtl)
2154                                         is_rtl = language->RightToLeft();
2155                                 par = par->next;
2156                         }
2157                 }
2158         } else {
2159                 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE
2160                        && par->footnoteflag != footnoteflag) {
2161                         par = par->TeXFootnote(buf, bparams,
2162                                                os, texrow,
2163                                                foot, foot_texrow, foot_count,
2164                                                false);
2165                         par->SimpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
2166                         par = par->next;
2167                 }
2168         }
2169 #endif
2170
2171         // Make sure that \\par is done with the font of the last
2172         // character if this has another size as the default.
2173         // This is necessary because LaTeX (and LyX on the screen)
2174         // calculates the space between the baselines according
2175         // to this font. (Matthias)
2176         LyXFont font = getFont(bparams, Last() - 1);
2177         if (need_par) {
2178                 if (style.resfont.size() != font.size()) {
2179                         os << '\\'
2180                            << font.latexSize()
2181                            << ' ';
2182                 }
2183                 os << "\\par}";
2184         } else if (textclasslist.Style(bparams.textclass,
2185                                        GetLayout()).isCommand()) {
2186                 if (style.resfont.size() != font.size()) {
2187                         os << '\\'
2188                            << font.latexSize()
2189                            << ' ';
2190                 }
2191                 os << '}';
2192         } else if (style.resfont.size() != font.size()){
2193                 os << "{\\" << font.latexSize() << " \\par}";
2194         }
2195
2196         if (language != doc_language &&
2197             (!par
2198              || (footnoteflag != NO_FOOTNOTE && par->footnoteflag != footnoteflag)
2199              || par->getParLanguage(bparams) != language)) {
2200                 os << endl 
2201                    << subst(lyxrc.language_command_end, "$$lang",
2202                             doc_language->lang());
2203         }
2204         
2205         switch (style.latextype) {
2206         case LATEX_ITEM_ENVIRONMENT:
2207         case LATEX_LIST_ENVIRONMENT:
2208                 if (par && (depth < par->depth)) {
2209                         os << '\n';
2210                         texrow.newline();
2211                 }
2212                 break;
2213         case LATEX_ENVIRONMENT:
2214                 // if its the last paragraph of the current environment
2215                 // skip it otherwise fall through
2216                 if (par
2217                     && (par->layout != layout
2218                         || par->depth != depth
2219                         || par->pextra_type != pextra_type))
2220                         break;
2221         default:
2222                 // we don't need it for the last paragraph!!!
2223                 if (next && !(footnoteflag != LyXParagraph::NO_FOOTNOTE
2224                       && footnotekind != LyXParagraph::FOOTNOTE
2225                       && footnotekind != LyXParagraph::MARGIN
2226                       && (table
2227                           || (par
2228                               && par->table)))) {
2229                         // don't insert this if we would be adding it
2230                         // before or after a table in a float.  This 
2231                         // little trick is needed in order to allow
2232                         // use of tables in \subfigures or \subtables.
2233                         os << '\n';
2234                         texrow.newline();
2235                 }
2236         }
2237         
2238         further_blank_line = false;
2239         if (line_bottom) {
2240                 os << "\\lyxline{\\" << getFont(bparams, Last() - 1).latexSize() << '}';
2241                 further_blank_line = true;
2242         }
2243
2244         if (added_space_bottom.kind() != VSpace::NONE) {
2245                 os << added_space_bottom.asLatexCommand(bparams);
2246                 further_blank_line = true;
2247         }
2248       
2249         if (pagebreak_bottom) {
2250                 os << "\\newpage";
2251                 further_blank_line = true;
2252         }
2253
2254         if (further_blank_line){
2255                 os << '\n';
2256                 texrow.newline();
2257         }
2258
2259         if (!spacing.isDefault()
2260             && (!par || !par->HasSameLayout(this))) {
2261                 os << spacing.writeEnvirEnd() << "\n";
2262                 texrow.newline();
2263         }
2264         
2265         // we don't need it for the last paragraph!!!
2266         if (next && !(footnoteflag != LyXParagraph::NO_FOOTNOTE && par &&
2267               par->footnoteflag == LyXParagraph::NO_FOOTNOTE)) {
2268                 os << '\n';
2269                 texrow.newline();
2270         }
2271
2272         lyxerr[Debug::LATEX] << "TeXOnePar...done " << par << endl;
2273         return par;
2274 }
2275
2276
2277 // This one spits out the text of the paragraph
2278 bool LyXParagraph::SimpleTeXOnePar(Buffer const * buf,
2279                                    BufferParams const & bparams,
2280                                    ostream & os, TexRow & texrow,
2281                                    bool moving_arg)
2282 {
2283         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...     " << this << endl;
2284
2285 #ifndef NEW_TABULAR
2286         if (table)
2287                 return SimpleTeXOneTablePar(buf, bparams, os, texrow);
2288 #endif
2289
2290         bool return_value = false;
2291
2292         LyXLayout const & style =
2293                 textclasslist.Style(bparams.textclass,
2294                                     GetLayout());
2295         LyXFont basefont, last_font;
2296
2297         // Maybe we have to create a optional argument.
2298         size_type main_body;
2299         if (style.labeltype != LABEL_MANUAL)
2300                 main_body = 0;
2301         else
2302                 main_body = BeginningOfMainBody();
2303
2304         if (main_body > 0) {
2305                 os << '[';
2306                 basefont = getFont(bparams, -2); // Get label font
2307         } else {
2308                 basefont = getFont(bparams, -1); // Get layout font
2309         }
2310
2311         int column = 0;
2312
2313         if (main_body >= 0
2314             && !text.size()
2315             && !IsDummy()) {
2316                 if (style.isCommand()) {
2317                         os << '{';
2318                         ++column;
2319                 } else if (align != LYX_ALIGN_LAYOUT) {
2320                         os << '{';
2321                         ++column;
2322                         return_value = true;
2323                 }
2324         }
2325
2326         moving_arg |= style.needprotect;
2327  
2328         // Which font is currently active?
2329         LyXFont running_font(basefont);
2330         // Do we have an open font change?
2331         bool open_font = false;
2332
2333         texrow.start(this, 0);
2334
2335         for (size_type i = 0; i < size(); ++i) {
2336                 ++column;
2337                 // First char in paragraph or after label?
2338                 if (i == main_body && !IsDummy()) {
2339                         if (main_body > 0) {
2340                                 if (open_font) {
2341                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
2342                                         open_font = false;
2343                                 }
2344                                 basefont = getFont(bparams, -1); // Now use the layout font
2345                                 running_font = basefont;
2346                                 os << ']';
2347                                 ++column;
2348                         }
2349                         if (style.isCommand()) {
2350                                 os << '{';
2351                                 ++column;
2352                         } else if (align != LYX_ALIGN_LAYOUT) {
2353                                 os << "{\\par";
2354                                 column += 4;
2355                                 return_value = true;
2356                         }
2357
2358                         if (noindent) {
2359                                 os << "\\noindent ";
2360                                 column += 10;
2361                         }
2362                         switch (align) {
2363                         case LYX_ALIGN_NONE:
2364                         case LYX_ALIGN_BLOCK:
2365                         case LYX_ALIGN_LAYOUT:
2366                         case LYX_ALIGN_SPECIAL:
2367                                 break;
2368                         case LYX_ALIGN_LEFT:
2369                                 if (getParLanguage(bparams)->lang() != "hebrew") {
2370                                         os << "\\raggedright ";
2371                                         column+= 13;
2372                                 } else {
2373                                         os << "\\raggedleft ";
2374                                         column+= 12;
2375                                 }
2376                                 break;
2377                         case LYX_ALIGN_RIGHT:
2378                                 if (getParLanguage(bparams)->lang() != "hebrew") {
2379                                         os << "\\raggedleft ";
2380                                         column+= 12;
2381                                 } else {
2382                                         os << "\\raggedright ";
2383                                         column+= 13;
2384                                 }
2385                                 break;
2386                         case LYX_ALIGN_CENTER:
2387                                 os << "\\centering ";
2388                                 column+= 11;
2389                                 break;
2390                         }        
2391                 }
2392
2393                 int c = GetChar(i);
2394
2395                 // Fully instantiated font
2396                 LyXFont font = getFont(bparams, i);
2397                 LyXParagraph * p = 0;
2398                 if (i == 0 && previous && 
2399                     previous->footnoteflag != LyXParagraph::NO_FOOTNOTE &&
2400                     (p = PreviousBeforeFootnote()) != 0)
2401                         last_font = p->getFont(bparams, p->size()-1);
2402                 else
2403                         last_font = running_font;
2404
2405                 // Spaces at end of font change are simulated to be
2406                 // outside font change, i.e. we write "\textXX{text} "
2407                 // rather than "\textXX{text }". (Asger)
2408                 if (open_font && c == ' ' && i <= size() - 2 
2409                     && !getFont(bparams, i + 1).equalExceptLatex(running_font) 
2410                     && !getFont(bparams, i + 1).equalExceptLatex(font)) {
2411                         font = getFont(bparams, i + 1);
2412                 }
2413                 // We end font definition before blanks
2414                 if (!font.equalExceptLatex(running_font) && open_font) {
2415                         column += running_font.latexWriteEndChanges(os,
2416                                                                     basefont,
2417                                                                     (i == main_body-1) ? basefont : font);
2418                         running_font = basefont;
2419                         open_font = false;
2420                 }
2421
2422                 // Blanks are printed before start of fontswitch
2423                 if (c == ' ') {
2424                         // Do not print the separation of the optional argument
2425                         if (i != main_body - 1) {
2426                                 SimpleTeXBlanks(os, texrow, i,
2427                                                 column, font, style);
2428                         }
2429                 }
2430
2431                 // Do we need to change font?
2432                 if (!font.equalExceptLatex(running_font)
2433                     && i != main_body-1) {
2434                         column += font.latexWriteStartChanges(os, basefont,
2435                                                               last_font);
2436                         running_font = font;
2437                         open_font = true;
2438                 }
2439
2440                 if (c == LyXParagraph::META_NEWLINE) {
2441                         // newlines are handled differently here than
2442                         // the default in SimpleTeXSpecialChars().
2443                         if (!style.newline_allowed
2444                             || font.latex() == LyXFont::ON) {
2445                                 os << '\n';
2446                         } else {
2447                                 if (open_font) {
2448                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
2449                                         open_font = false;
2450                                 }
2451                                 basefont = getFont(bparams, -1);
2452                                 running_font = basefont;
2453                                 if (font.family() == 
2454                                     LyXFont::TYPEWRITER_FAMILY) {
2455                                         os << "~";
2456                                 }
2457                                 if (moving_arg)
2458                                         os << "\\protect ";
2459                                 os << "\\\\\n";
2460                         }
2461                         texrow.newline();
2462                         texrow.start(this, i + 1);
2463                         column = 0;
2464                 } else {
2465                         SimpleTeXSpecialChars(buf, bparams,
2466                                               os, texrow, moving_arg,
2467                                               font, running_font, basefont,
2468                                               open_font, style, i, column, c);
2469                 }
2470         }
2471
2472         // If we have an open font definition, we have to close it
2473         if (open_font) {
2474                 LyXParagraph * p = 0;
2475                 if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE
2476                     && (p =  NextAfterFootnote()) != 0)
2477                         running_font.latexWriteEndChanges(os, basefont,
2478                                                           p->getFont(bparams, 0));
2479                 else
2480                         running_font.latexWriteEndChanges(os, basefont, basefont);
2481         }
2482
2483         // Needed if there is an optional argument but no contents.
2484         if (main_body > 0 && main_body == size()) {
2485                 os << "]~";
2486                 return_value = false;
2487         }
2488
2489         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...done " << this << endl;
2490         return return_value;
2491 }
2492
2493
2494 // This one spits out the text of a table paragraph
2495 bool LyXParagraph::SimpleTeXOneTablePar(Buffer const * buf,
2496                                         BufferParams const & bparams,
2497                                         ostream & os, TexRow & texrow)
2498 {
2499         lyxerr[Debug::LATEX] << "SimpleTeXOneTablePar...     " << this << endl;
2500    
2501         bool return_value = false;
2502
2503         LyXLayout const & style = 
2504                 textclasslist.Style(bparams.textclass, GetLayout());
2505  
2506         int column = 0;
2507         if (!IsDummy()) { // it is dummy if it is in a float!!!
2508                 if (style.isCommand()) {
2509                         os << '{';
2510                         ++column;
2511                 } else if (align != LYX_ALIGN_LAYOUT) {
2512                         os << '{';
2513                         ++column;
2514                         return_value = true;
2515                 }
2516                 if (noindent) {
2517                         os << "\\noindent ";
2518                         column += 10;
2519                 }
2520                 switch (align) {
2521                 case LYX_ALIGN_NONE:
2522                 case LYX_ALIGN_BLOCK:
2523                 case LYX_ALIGN_LAYOUT:
2524                 case LYX_ALIGN_SPECIAL: break;
2525                 case LYX_ALIGN_LEFT:
2526                         os << "\\raggedright ";
2527                         column+= 13;
2528                         break;
2529                 case LYX_ALIGN_RIGHT:
2530                         os << "\\raggedleft ";
2531                         column+= 12;
2532                         break;
2533                 case LYX_ALIGN_CENTER:
2534                         os << "\\centering ";
2535                         column+= 11;
2536                         break;
2537                 }
2538         }
2539
2540         LyXFont basefont = getFont(bparams, -1); // Get layout font
2541         // Which font is currently active?
2542         LyXFont running_font = basefont;
2543         LyXFont last_font;
2544         // Do we have an open font change?
2545         bool open_font = false;
2546         int current_cell_number = -1;
2547         int tmp = table->TexEndOfCell(os, current_cell_number);
2548         for (; tmp > 0 ; --tmp)
2549                 texrow.newline();
2550         
2551         texrow.start(this, 0);
2552
2553         bool is_rtl = getParLanguage(bparams)->RightToLeft();
2554         bool first_in_cell = true;
2555                 
2556         for (size_type i = 0; i < size(); ++i) {
2557                 char c = GetChar(i);
2558                 if (table->IsContRow(current_cell_number + 1)) {
2559                         if (c == LyXParagraph::META_NEWLINE)
2560                                 ++current_cell_number;
2561                         continue;
2562                 }
2563                 ++column;
2564
2565                 if (first_in_cell && is_rtl) {
2566                         os << "\\R{";
2567                         column += 3;
2568                         first_in_cell = false;
2569                 }
2570
2571                 // Fully instantiated font
2572                 LyXFont font = getFont(bparams, i);
2573                 last_font = running_font;
2574
2575                 // Spaces at end of font change are simulated to be
2576                 // outside font change.
2577                 // i.e. we write "\textXX{text} " rather than
2578                 // "\textXX{text }". (Asger)
2579                 if (open_font && c == ' ' && i <= size() - 2
2580                     && getFont(bparams, i + 1) != running_font
2581                     && getFont(bparams, i + 1) != font) {
2582                         font = getFont(bparams, i + 1);
2583                 }
2584
2585                 // We end font definition before blanks
2586                 if (font != running_font && open_font) {
2587                         column += running_font.latexWriteEndChanges(os,
2588                                                                     basefont,
2589                                                                     font);
2590                         running_font = basefont;
2591                         open_font = false;
2592                 }
2593                 // Blanks are printed before start of fontswitch
2594                 if (c == ' '){
2595                         SimpleTeXBlanks(os, texrow, i, column, font, style);
2596                 }
2597                 // Do we need to change font?
2598                 if (font != running_font) {
2599                         column += font.latexWriteStartChanges(os, basefont,
2600                                                               last_font);
2601                         running_font = font;
2602                         open_font = true;
2603                 }
2604                 // Do we need to turn on LaTeX mode?
2605                 if (font.latex() != running_font.latex()) {
2606                         if (font.latex() == LyXFont::ON
2607                             && style.needprotect) {
2608                                 os << "\\protect ";
2609                                 column += 9;
2610                         }
2611                 }
2612                 if (c == LyXParagraph::META_NEWLINE) {
2613                         // special case for inside a table
2614                         // different from default case in
2615                         // SimpleTeXSpecialChars()
2616                         if (open_font) {
2617                                 column += running_font
2618                                         .latexWriteEndChanges(os, basefont,
2619                                                               basefont);
2620                                 open_font = false;
2621                         }
2622                         basefont = getFont(bparams, -1);
2623                         running_font = basefont;
2624                         ++current_cell_number;
2625                         if (table->CellHasContRow(current_cell_number) >= 0) {
2626                                 TeXContTableRows(buf, bparams, os, i + 1,
2627                                                  current_cell_number,
2628                                                  column, texrow);
2629                         }
2630                         if (is_rtl && !first_in_cell) {
2631                                 os << "}";
2632                                 first_in_cell = true;
2633                         }
2634
2635                         // if this cell follow only ContRows till end don't
2636                         // put the EndOfCell because it is put after the
2637                         // for(...)
2638                         if (table->ShouldBeVeryLastCell(current_cell_number)) {
2639                                 --current_cell_number;
2640                                 break;
2641                         }
2642                         int tmp = table->TexEndOfCell(os,
2643                                                       current_cell_number);
2644                         if (tmp > 0) {
2645                                 column = 0;
2646                         } else if (tmp < 0) {
2647                                 tmp = -tmp;
2648                         }
2649                         for (; tmp--;) {
2650                                 texrow.newline();
2651                         }
2652                         texrow.start(this, i + 1);
2653                 } else {
2654                         SimpleTeXSpecialChars(buf, bparams,
2655                                               os, texrow, false,
2656                                               font, running_font, basefont,
2657                                               open_font, style, i, column, c);
2658                 }
2659         }
2660
2661         // If we have an open font definition, we have to close it
2662         if (open_font) {
2663                 running_font.latexWriteEndChanges(os, basefont, basefont);
2664         }
2665         ++current_cell_number;
2666         if (is_rtl && !first_in_cell)
2667                 os << "}";
2668         tmp = table->TexEndOfCell(os, current_cell_number);
2669         for (; tmp > 0; --tmp)
2670                 texrow.newline();
2671         lyxerr[Debug::LATEX] << "SimpleTeXOneTablePar...done " << this << endl;
2672         return return_value;
2673 }
2674
2675
2676 // This one spits out the text off ContRows in tables
2677 bool LyXParagraph::TeXContTableRows(Buffer const * buf,
2678                                     BufferParams const & bparams,
2679                                     ostream & os,
2680                                     LyXParagraph::size_type i,
2681                                     int current_cell_number,
2682                                     int & column, TexRow & texrow)
2683 {
2684         lyxerr[Debug::LATEX] << "TeXContTableRows...     " << this << endl;
2685         if (!table)
2686                 return false;
2687     
2688         bool return_value = false;
2689         LyXLayout const & style =
2690                 textclasslist.Style(bparams.textclass,
2691                                     GetLayout());
2692         LyXFont basefont = getFont(bparams, -1); // Get layout font
2693         LyXFont last_font;
2694         // Which font is currently active?
2695         LyXFont running_font = basefont;
2696         // Do we have an open font change?
2697         bool open_font = false;
2698
2699         size_type lastpos = i;
2700         int cell = table->CellHasContRow(current_cell_number);
2701         ++current_cell_number;
2702         char c;
2703         while(cell >= 0) {
2704                 // first find the right position
2705                 i = lastpos;
2706                 for (; (i < size()) && (current_cell_number<cell); ++i) {
2707                         c = GetChar(i);
2708                         if (c == LyXParagraph::META_NEWLINE)
2709                                 ++current_cell_number;
2710                 }
2711                 lastpos = i;
2712                 c = GetChar(i);
2713                 if (table->Linebreaks(table->FirstVirtualCell(cell))) {
2714                         os << " \\\\\n";
2715                         texrow.newline();
2716                         column = 0;
2717                 } else if ((c != ' ') && (c != LyXParagraph::META_NEWLINE)) {
2718                         os << ' ';
2719                 }
2720
2721                 for (; i < size()
2722                              && (c = GetChar(i)) != LyXParagraph::META_NEWLINE;
2723                      ++i) {
2724                         ++column;
2725
2726                         // Fully instantiated font
2727                         LyXFont font = getFont(bparams, i);
2728                         last_font = running_font;
2729
2730                         // Spaces at end of font change are simulated to
2731                         // be outside font change. i.e. we write
2732                         // "\textXX{text} " rather than "\textXX{text }".
2733                         // (Asger)
2734                         if (open_font && c == ' ' && i <= size() - 2 
2735                             && getFont(bparams, i + 1) != running_font
2736                             && getFont(bparams, i + 1) != font) {
2737                                 font = getFont(bparams, i + 1);
2738                         }
2739
2740                         // We end font definition before blanks
2741                         if (font != running_font && open_font) {
2742                                 column += running_font.latexWriteEndChanges(os, basefont, font);
2743                                 running_font = basefont;
2744                                 open_font = false;
2745                         }
2746                         // Blanks are printed before start of fontswitch
2747                         if (c == ' '){
2748                                 SimpleTeXBlanks(os, texrow, i,
2749                                                 column, font, style);
2750                         }
2751                         // Do we need to change font?
2752                         if (font != running_font) {
2753                                 column +=
2754                                         font.latexWriteStartChanges(os,
2755                                                                     basefont,
2756                                                                     last_font);
2757                                 running_font = font;
2758                                 open_font = true;
2759                         }
2760                         // Do we need to turn on LaTeX mode?
2761                         if (font.latex() != running_font.latex()) {
2762                                 if (font.latex() == LyXFont::ON
2763                                     && style.needprotect) {
2764                                         os << "\\protect ";
2765                                         column += 9;
2766                                 }
2767                         }
2768                         SimpleTeXSpecialChars(buf, bparams,
2769                                               os, texrow, false, font,
2770                                               running_font, basefont,
2771                                               open_font, style, i, column, c);
2772                 }
2773                 // If we have an open font definition, we have to close it
2774                 if (open_font) {
2775                         running_font.latexWriteEndChanges(os, basefont,
2776                                                           basefont);
2777                         open_font = false;
2778                 }
2779                 basefont = getFont(bparams, -1);
2780                 running_font = basefont;
2781                 cell = table->CellHasContRow(current_cell_number);
2782         }
2783         lyxerr[Debug::LATEX] << "TeXContTableRows...done " << this << endl;
2784         return return_value;
2785 }
2786
2787
2788 bool LyXParagraph::linuxDocConvertChar(char c, string & sgml_string)
2789 {
2790         bool retval = false;
2791         switch (c) {
2792         case LyXParagraph::META_HFILL:
2793                 sgml_string.erase();
2794                 break;
2795         case LyXParagraph::META_NEWLINE:
2796                 sgml_string = '\n';
2797                 break;
2798         case '&': 
2799                 sgml_string = "&amp;";
2800                 break;
2801         case '<': 
2802                 sgml_string = "&lt;"; 
2803                 break;
2804         case '>':
2805                 sgml_string = "&gt;"; 
2806                 break;
2807         case '$': 
2808                 sgml_string = "&dollar;"; 
2809                 break;
2810         case '#': 
2811                 sgml_string = "&num;";
2812                 break;
2813         case '%': 
2814                 sgml_string = "&percnt;";
2815                 break;
2816         case '[': 
2817                 sgml_string = "&lsqb;";
2818                 break;
2819         case ']': 
2820                 sgml_string = "&rsqb;";
2821                 break;
2822         case '{': 
2823                 sgml_string = "&lcub;";
2824                 break;
2825         case '}': 
2826                 sgml_string = "&rcub;";
2827                 break;
2828         case '~': 
2829                 sgml_string = "&tilde;";
2830                 break;
2831         case '"': 
2832                 sgml_string = "&quot;";
2833                 break;
2834         case '\\': 
2835                 sgml_string = "&bsol;";
2836                 break;
2837         case ' ':
2838                 retval = true;
2839                 sgml_string = ' ';
2840                 break;
2841         case '\0': // Ignore :-)
2842                 sgml_string.erase();
2843                 break;
2844         default:
2845                 sgml_string = c;
2846                 break;
2847         }
2848         return retval;
2849 }
2850
2851
2852 void LyXParagraph::SimpleDocBookOneTablePar(Buffer const * buffer, 
2853                                             ostream & os, string & extra,
2854                                             int & desc_on, int depth) 
2855 {
2856         BufferParams const & bparams = buffer->params;
2857         if (!table) return;
2858         lyxerr[Debug::LATEX] << "SimpleDocbookOneTablePar... " << this << endl;
2859         int column = 0;
2860         LyXFont font1, font2;
2861         char c;
2862         Inset * inset;
2863         size_type main_body;
2864         bool emph_flag = false;
2865         
2866         LyXLayout const & style =
2867                 textclasslist.Style(bparams.textclass,
2868                                     GetLayout());
2869         
2870         if (style.labeltype != LABEL_MANUAL)
2871                 main_body = 0;
2872         else
2873                 main_body = BeginningOfMainBody();
2874         
2875         // Gets paragraph main font.
2876         if (main_body > 0)
2877                 font1 = style.labelfont;
2878         else
2879                 font1 = style.font;
2880         
2881         int char_line_count = depth;
2882         os << newlineAndDepth(depth);
2883         if (footnoteflag == LyXParagraph::NO_FOOTNOTE) {
2884                 os << "<INFORMALTABLE>"
2885                    << newlineAndDepth(++depth);
2886         }
2887         int current_cell_number = -1;
2888         int tmp = table->DocBookEndOfCell(os, current_cell_number, depth);
2889         
2890         // Parsing main loop.
2891         for (size_type i = 0; i < size(); ++i) {
2892                 c = GetChar(i);
2893                 if (table->IsContRow(current_cell_number+1)) {
2894                         if (c == LyXParagraph::META_NEWLINE)
2895                                 ++current_cell_number;
2896                         continue;
2897                 }
2898                 ++column;
2899                 
2900                 // Fully instantiated font
2901                 font2 = getFont(bparams, i);
2902                 
2903                 // Handle <emphasis> tag.
2904                 if (font1.emph() != font2.emph() && i) {
2905                         if (font2.emph() == LyXFont::ON) {
2906                                 os << "<emphasis>";
2907                                 emph_flag= true;
2908                         } else if (emph_flag) {
2909                                 os << "</emphasis>";
2910                                 emph_flag= false;
2911                         }
2912                 }
2913                 if (c == LyXParagraph::META_NEWLINE) {
2914                         // We have only to control for emphasis open here!
2915                         if (emph_flag) {
2916                                 os << "</emphasis>";
2917                                 emph_flag= false;
2918                         }
2919                         font1 = font2 = getFont(bparams, -1);
2920                         ++current_cell_number;
2921                         if (table->CellHasContRow(current_cell_number) >= 0) {
2922                                 DocBookContTableRows(buffer,
2923                                                      os, extra, desc_on, i + 1,
2924                                                      current_cell_number,
2925                                                      column);
2926                         }
2927                         // if this cell follow only ContRows till end don't
2928                         // put the EndOfCell because it is put after the
2929                         // for(...)
2930                         if (table->ShouldBeVeryLastCell(current_cell_number)) {
2931                                 --current_cell_number;
2932                                 break;
2933                         }
2934                         tmp = table->DocBookEndOfCell(os,
2935                                                       current_cell_number,
2936                                                       depth);
2937                         
2938                         if (tmp > 0)
2939                                 column = 0;
2940                 } else if (c == LyXParagraph::META_INSET) {
2941                         inset = GetInset(i);
2942 #ifdef HAVE_SSTREAM
2943                         std::ostringstream ost;
2944                         inset->DocBook(buffer, ost);
2945                         string tmp_out = ost.str().c_str();
2946 #else
2947                         ostrstream ost;
2948                         inset->DocBook(buffer, ost);
2949                         ost << '\0';
2950                         char * ctmp = ost.str();
2951                         string tmp_out(ctmp);
2952                         delete [] ctmp;
2953 #endif
2954                         //
2955                         // This code needs some explanation:
2956                         // Two insets are treated specially
2957                         //   label if it is the first element in a
2958                         //   command paragraph
2959                         //         desc_on == 3
2960                         //   graphics inside tables or figure floats
2961                         //   can't go on
2962                         //   title (the equivalente in latex for this
2963                         //   case is caption
2964                         //   and title should come first
2965                         //         desc_on == 4
2966                         //
2967                         if(desc_on != 3 || i != 0) {
2968                                 if(tmp_out[0] == '@') {
2969                                         if(desc_on == 4)
2970                                                 extra += frontStrip(tmp_out,
2971                                                                     '@');
2972                                         else
2973                                                 os << frontStrip(tmp_out,
2974                                                                  '@');
2975                                 } else
2976                                         os << tmp_out;
2977                         }
2978                 } else if (font2.latex() == LyXFont::ON) {
2979                         // "TeX"-Mode on == > SGML-Mode on.
2980                         if (c != '\0')
2981                                 os << c;
2982                         ++char_line_count;
2983                 } else {
2984                         string sgml_string;
2985                         if (linuxDocConvertChar(c, sgml_string) 
2986                             && !style.free_spacing) {
2987                                 // in freespacing mode, spaces are
2988                                 // non-breaking characters
2989                                 // char is ' '
2990                                 if (desc_on == 1) {
2991                                         ++char_line_count;
2992                                         os << '\n'
2993                                            << "</term><listitem><para>";
2994                                         desc_on = 2;
2995                                 } else  {
2996                                         os << c;
2997                                 }
2998                         } else {
2999                                 os << sgml_string;
3000                         }
3001                 }
3002                 font1 = font2;
3003         }
3004         
3005         // Needed if there is an optional argument but no contents.
3006         if (main_body > 0 && main_body == size()) {
3007                 font1 = style.font;
3008         }
3009
3010         if (emph_flag) {
3011                 os << "</emphasis>";
3012         }
3013         
3014         ++current_cell_number;
3015         tmp = table->DocBookEndOfCell(os, current_cell_number, depth);
3016         // Resets description flag correctly.
3017         switch(desc_on){
3018         case 1:
3019                 // <term> not closed...
3020                 os << "</term>";
3021                 break;
3022         }
3023         if (footnoteflag == LyXParagraph::NO_FOOTNOTE)
3024                 os << "</INFORMALTABLE>";
3025         os << '\n';
3026         lyxerr[Debug::LATEX] << "SimpleDocbookOneTablePar...done "
3027                              << this << endl;
3028 }
3029
3030
3031 void LyXParagraph::DocBookContTableRows(Buffer const * buffer,
3032                                         ostream & os, string & extra,
3033                                         int & desc_on,
3034                                         LyXParagraph::size_type i,
3035                                         int current_cell_number, int &column) 
3036
3037 {
3038         if (!table) return;
3039
3040         BufferParams const & bparams = buffer->params;
3041         
3042         lyxerr[Debug::LATEX] << "DocBookContTableRows... " << this << endl;
3043
3044         LyXFont font2;
3045         char c;
3046         Inset * inset;
3047         //string emph = "emphasis";
3048         bool emph_flag = false;
3049         int char_line_count = 0;
3050         
3051         LyXLayout const & style =
3052                 textclasslist.Style(bparams.textclass,
3053                                     GetLayout());
3054         
3055         size_type main_body;
3056         if (style.labeltype != LABEL_MANUAL)
3057                 main_body = 0;
3058         else
3059                 main_body = BeginningOfMainBody();
3060         
3061         // Gets paragraph main font.
3062         LyXFont font1;
3063         if (main_body > 0)
3064                 font1 = style.labelfont;
3065         else
3066                 font1 = style.font;
3067         
3068         size_type lastpos = i;
3069         int cell = table->CellHasContRow(current_cell_number);
3070         ++current_cell_number;
3071         while(cell >= 0) {
3072                 // first find the right position
3073                 i = lastpos;
3074                 for (; i < size() && current_cell_number < cell; ++i) {
3075                         c = GetChar(i);
3076                         if (c == LyXParagraph::META_NEWLINE)
3077                                 ++current_cell_number;
3078                 }
3079                 lastpos = i;
3080                 c = GetChar(i);
3081                 // I don't know how to handle this so I comment it
3082                 // for the moment (Jug)
3083 //             if (table->Linebreaks(table->FirstVirtualCell(cell))) {
3084 //                     file += " \\\\\n";
3085 //                     column = 0;
3086 //             } else
3087                 if ((c != ' ') && (c != LyXParagraph::META_NEWLINE)) {
3088                         os << ' ';
3089                 }
3090
3091                 for (; i < size()
3092                              && (c = GetChar(i)) != LyXParagraph::META_NEWLINE;
3093                      ++i) {
3094                         ++column;
3095                         
3096                         // Fully instantiated font
3097                         font2 = getFont(bparams, i);
3098                         
3099                         // Handle <emphasis> tag.
3100                         if (font1.emph() != font2.emph() && i) {
3101                                 if (font2.emph() == LyXFont::ON) {
3102                                         os << "<emphasis>";
3103                                         emph_flag= true;
3104                                 } else if (emph_flag) {
3105                                         os << "</emphasis>";
3106                                         emph_flag= false;
3107                                 }
3108                         }
3109                         if (c == LyXParagraph::META_INSET) {
3110                                 inset = GetInset(i);
3111 #ifdef HAVE_SSTREAM
3112                                 std::ostringstream ost;
3113                                 inset->DocBook(buffer, ost);
3114                                 string tmp_out = ost.str().c_str();
3115 #else
3116                                 ostrstream ost;
3117                                 inset->DocBook(buffer, ost);
3118                                 ost << '\0';
3119                                 char * ctmp = ost.str();
3120                                 string tmp_out(ctmp);
3121                                 delete [] ctmp;
3122 #endif
3123                                 //
3124                                 // This code needs some explanation:
3125                                 // Two insets are treated specially
3126                                 //   label if it is the first element in a
3127                                 //   command paragraph
3128                                 //       desc_on == 3
3129                                 //   graphics inside tables or figure floats
3130                                 //   can't go on title (the equivalente in
3131                                 //   latex for this case is caption and title
3132                                 //   should come first
3133                                 //       desc_on == 4
3134                                 //
3135                                 if(desc_on != 3 || i != 0) {
3136                                         if(tmp_out[0] == '@') {
3137                                                 if(desc_on == 4)
3138                                                         extra += frontStrip(tmp_out, '@');
3139                                                 else
3140                                                         os << frontStrip(tmp_out, '@');
3141                                         } else
3142                                                 os << tmp_out;
3143                                 }
3144                         } else if (font2.latex() == LyXFont::ON) {
3145                                 // "TeX"-Mode on == > SGML-Mode on.
3146                                 if (c!= '\0')
3147                                         os << c;
3148                                 ++char_line_count;
3149                         } else {
3150                                 string sgml_string;
3151                                 if (linuxDocConvertChar(c, sgml_string) 
3152                                     && !style.free_spacing) {
3153                                         // in freespacing mode, spaces are
3154                                         // non-breaking characters
3155                                         // char is ' '
3156                                         if (desc_on == 1) {
3157                                                 ++char_line_count;
3158                                                 os << '\n'
3159                                                    << "</term><listitem><para>";
3160                                                 desc_on = 2;
3161                                         } else  {
3162                                                 os << c;
3163                                         }
3164                                 } else {
3165                                         os << sgml_string;
3166                                 }
3167                         }
3168                 }
3169                 // we have only to control for emphasis open here!
3170                 if (emph_flag) {
3171                         os << "</emphasis>";
3172                         emph_flag= false;
3173                 }
3174                 font1 = font2 = getFont(bparams, -1);
3175                 cell = table->CellHasContRow(current_cell_number);
3176         }
3177         lyxerr[Debug::LATEX] << "DocBookContTableRows...done " << this << endl;
3178 }
3179
3180
3181 void LyXParagraph::SimpleTeXBlanks(ostream & os, TexRow & texrow,
3182                                    LyXParagraph::size_type const i,
3183                                    int & column, LyXFont const & font,
3184                                    LyXLayout const & style)
3185 {
3186         if (column > tex_code_break_column
3187             && i 
3188             && GetChar(i - 1) != ' '
3189             && (i < size() - 1)
3190             // In LaTeX mode, we don't want to
3191             // break lines since some commands
3192             // do not like this
3193             && ! (font.latex() == LyXFont::ON)
3194             // same in FreeSpacing mode
3195             && !style.free_spacing
3196             // In typewriter mode, we want to avoid 
3197             // ! . ? : at the end of a line
3198             && !(font.family() == LyXFont::TYPEWRITER_FAMILY
3199                  && (GetChar(i-1) == '.'
3200                      || GetChar(i-1) == '?' 
3201                      || GetChar(i-1) == ':'
3202                      || GetChar(i-1) == '!'))) {
3203                 if (tex_code_break_column == 0) {
3204                         // in batchmode we need LaTeX to still
3205                         // see it as a space not as an extra '\n'
3206                         os << " %\n";
3207                 } else {
3208                         os << '\n';
3209                 }
3210                 texrow.newline();
3211                 texrow.start(this, i + 1);
3212                 column = 0;
3213         } else if (font.latex() == LyXFont::OFF) {
3214                 if (style.free_spacing) {
3215                         os << '~';
3216                 } else {
3217                         os << ' ';
3218                 }
3219         }
3220 }
3221
3222
3223 void LyXParagraph::SimpleTeXSpecialChars(Buffer const * buf,
3224                                          BufferParams const & bparams,
3225                                          ostream & os, TexRow & texrow,
3226                                          bool moving_arg,
3227                                          LyXFont & font,
3228                                          LyXFont & running_font,
3229                                          LyXFont & basefont,
3230                                          bool & open_font,
3231                                          LyXLayout const & style,
3232                                          LyXParagraph::size_type & i,
3233                                          int & column, char const c)
3234 {
3235         // Two major modes:  LaTeX or plain
3236         // Handle here those cases common to both modes
3237         // and then split to handle the two modes separately.
3238         switch (c) {
3239         case LyXParagraph::META_INSET: {
3240                 Inset * inset = GetInset(i);
3241                 if (inset) {
3242                         bool close = false;
3243                         int len = os.tellp();
3244                         if ((inset->LyxCode() == Inset::GRAPHICS_CODE
3245                              || inset->LyxCode() == Inset::MATH_CODE
3246                              || inset->LyxCode() == Inset::URL_CODE)
3247                             && running_font.isRightToLeft()) {
3248                                 os << "\\L{";
3249                                 close = true;
3250                         }
3251
3252                         int tmp = inset->Latex(buf, os, moving_arg,
3253                                                style.free_spacing);
3254
3255                         if (close)
3256                                 os << "}";
3257
3258                         if (tmp) {
3259                                 column = 0;
3260                         } else {
3261                                 column += os.tellp() - len;
3262                         }
3263                         for (; tmp--;) {
3264                                 texrow.newline();
3265                         }
3266                 }
3267         }
3268         break;
3269
3270         case LyXParagraph::META_NEWLINE:
3271                 if (open_font) {
3272                         column += running_font.latexWriteEndChanges(os,
3273                                                                     basefont,
3274                                                                     basefont);
3275                         open_font = false;
3276                 }
3277                 basefont = getFont(bparams, -1);
3278                 running_font = basefont;
3279                 break;
3280
3281         case LyXParagraph::META_HFILL: 
3282                 os << "\\hfill{}";
3283                 column += 7;
3284                 break;
3285
3286         default:
3287                 // And now for the special cases within each mode
3288                 // Are we in LaTeX mode?
3289                 if (font.latex() == LyXFont::ON) {
3290                         // at present we only have one option
3291                         // but I'll leave it as a switch statement
3292                         // so its simpler to extend. (ARRae)
3293                         switch (c) {
3294                         default:
3295                                 // make sure that we will not print
3296                                 // error generating chars to the tex
3297                                 // file. This test would not be needed
3298                                 // if it were done in the buffer
3299                                 // itself.
3300                                 if (c != '\0') {
3301                                         os << c;
3302                                 }
3303                                 break;
3304                         }
3305                 } else {
3306                         // Plain mode (i.e. not LaTeX)
3307                         switch (c) {
3308                         case '\\': 
3309                                 os << "\\textbackslash{}";
3310                                 column += 15;
3311                                 break;
3312                 
3313                         case '°': case '±': case '²': case '³':  
3314                         case '×': case '÷': case '¹': case 'ª':
3315                         case 'º': case '¬': case 'µ':
3316                                 if (bparams.inputenc == "latin1") {
3317                                         os << "\\ensuremath{"
3318                                            << c
3319                                            << '}';
3320                                         column += 13;
3321                                 } else {
3322                                         os << c;
3323                                 }
3324                                 break;
3325
3326                         case '|': case '<': case '>':
3327                                 // In T1 encoding, these characters exist
3328                                 if (lyxrc.fontenc == "T1") {
3329                                         os << c;
3330                                         //... but we should avoid ligatures
3331                                         if ((c == '>' || c == '<')
3332                                             && i <= size() - 2
3333                                             && GetChar(i + 1) == c){
3334                                                 os << "\\textcompwordmark{}";
3335                                                 column += 19;
3336                                         }
3337                                         break;
3338                                 }
3339                                 // Typewriter font also has them
3340                                 if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
3341                                         os << c;
3342                                         break;
3343                                 } 
3344                                 // Otherwise, we use what LaTeX
3345                                 // provides us.
3346                                 switch(c) {
3347                                 case '<':
3348                                         os << "\\textless{}";
3349                                         column += 10;
3350                                         break;
3351                                 case '>':
3352                                         os << "\\textgreater{}";
3353                                         column += 13;
3354                                         break;
3355                                 case '|':
3356                                         os << "\\textbar{}";
3357                                         column += 9;
3358                                         break;
3359                                 }
3360                                 break;
3361
3362                         case '-': // "--" in Typewriter mode -> "-{}-"
3363                                 if (i <= size() - 2
3364                                     && GetChar(i + 1) == '-'
3365                                     && font.family() == LyXFont::TYPEWRITER_FAMILY) {
3366                                         os << "-{}";
3367                                         column += 2;
3368                                 } else {
3369                                         os << '-';
3370                                 }
3371                                 break;
3372
3373                         case '\"': 
3374                                 os << "\\char`\\\"{}";
3375                                 column += 9;
3376                                 break;
3377
3378                         case '£':
3379                                 if (bparams.inputenc == "default") {
3380                                         os << "\\pounds{}";
3381                                         column += 8;
3382                                 } else {
3383                                         os << c;
3384                                 }
3385                                 break;
3386
3387                         case '$': case '&':
3388                         case '%': case '#': case '{':
3389                         case '}': case '_':
3390                                 os << '\\' << c;
3391                                 column += 1;
3392                                 break;
3393
3394                         case '~':
3395                                 os << "\\textasciitilde{}";
3396                                 column += 16;
3397                                 break;
3398
3399                         case '^':
3400                                 os << "\\textasciicircum{}";
3401                                 column += 17;
3402                                 break;
3403
3404                         case '*': case '[': case ']':
3405                                 // avoid being mistaken for optional arguments
3406                                 os << '{' << c << '}';
3407                                 column += 2;
3408                                 break;
3409
3410                         case ' ':
3411                                 // Blanks are printed before font switching.
3412                                 // Sure? I am not! (try nice-latex)
3413                                 // I am sure it's correct. LyX might be smarter
3414                                 // in the future, but for now, nothing wrong is
3415                                 // written. (Asger)
3416                                 break;
3417
3418                         default:
3419                                 /* idea for labels --- begin*/
3420                                 // Check for "LyX"
3421                                 if (c ==  'L'
3422                                     && i <= size() - 3
3423                                     && font.family() != LyXFont::TYPEWRITER_FAMILY
3424                                     && GetChar(i + 1) == 'y'
3425                                     && GetChar(i + 2) == 'X') {
3426                                         os << "\\LyX{}";
3427                                         i += 2;
3428                                         column += 5;
3429                                 }
3430                                 // Check for "TeX"
3431                                 else if (c == 'T'
3432                                          && i <= size() - 3
3433                                          && font.family() != LyXFont::TYPEWRITER_FAMILY
3434                                          && GetChar(i + 1) == 'e'
3435                                          && GetChar(i + 2) == 'X') {
3436                                         os << "\\TeX{}";
3437                                         i += 2;
3438                                         column += 5;
3439                                 }
3440                                 // Check for "LaTeX2e"
3441                                 else if (c == 'L'
3442                                          && i <= size() - 7
3443                                          && font.family() != LyXFont::TYPEWRITER_FAMILY
3444                                          && GetChar(i + 1) == 'a'
3445                                          && GetChar(i + 2) == 'T'
3446                                          && GetChar(i + 3) == 'e'
3447                                          && GetChar(i + 4) == 'X'
3448                                          && GetChar(i + 5) == '2'
3449                                          && GetChar(i + 6) == 'e') {
3450                                         os << "\\LaTeXe{}";
3451                                         i += 6;
3452                                         column += 8;
3453                                 }
3454                                 // Check for "LaTeX"
3455                                 else if (c == 'L'
3456                                          && i <= size() - 5
3457                                          && font.family() != LyXFont::TYPEWRITER_FAMILY
3458                                          && GetChar(i + 1) == 'a'
3459                                          && GetChar(i + 2) == 'T'
3460                                          && GetChar(i + 3) == 'e'
3461                                          && GetChar(i + 4) == 'X') {
3462                                         os << "\\LaTeX{}";
3463                                         i += 4;
3464                                         column += 7;
3465                                         /* idea for labels --- end*/ 
3466                                 } else if (c != '\0') {
3467                                         os << c;
3468                                 }
3469                                 break;
3470                         }
3471                 }
3472         }
3473 }
3474
3475
3476 LyXParagraph * LyXParagraph::TeXDeeper(Buffer const * buf,
3477                                        BufferParams const & bparams,
3478                                        ostream & os, TexRow & texrow,
3479                                        ostream & foot,
3480                                        TexRow & foot_texrow,
3481                                        int & foot_count)
3482 {
3483         lyxerr[Debug::LATEX] << "TeXDeeper...     " << this << endl;
3484         LyXParagraph * par = this;
3485
3486         while (par &&
3487                (par->depth == depth) &&
3488                (par->footnoteflag == footnoteflag)) {
3489                 if (par->IsDummy())
3490                         lyxerr << "ERROR (LyXParagraph::TeXDeeper)" << endl;
3491                 if (textclasslist.Style(bparams.textclass, 
3492                                         par->layout).isEnvironment()
3493                     || par->pextra_type != PEXTRA_NONE) {
3494                         par = par->TeXEnvironment(buf, bparams,
3495                                                   os, texrow,
3496                                                   foot, foot_texrow,
3497                                                   foot_count);
3498                 } else {
3499                         par = par->TeXOnePar(buf, bparams,
3500                                              os, texrow, false,
3501                                              foot, foot_texrow,
3502                                              foot_count);
3503                 }
3504         }
3505         lyxerr[Debug::LATEX] << "TeXDeeper...done " << par << endl;
3506
3507         return par;
3508 }
3509
3510
3511 LyXParagraph * LyXParagraph::TeXEnvironment(Buffer const * buf,
3512                                             BufferParams const & bparams,
3513                                             ostream & os, TexRow & texrow,
3514                                             ostream & foot,
3515                                             TexRow & foot_texrow,
3516                                             int & foot_count)
3517 {
3518         bool eindent_open = false;
3519         bool foot_this_level = false;
3520         // flags when footnotetext should be appended to file.
3521         static bool minipage_open = false;
3522         static int minipage_open_depth = 0;
3523         char par_sep = bparams.paragraph_separation;
3524     
3525         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << this << endl;
3526         if (IsDummy())
3527                 lyxerr << "ERROR (LyXParagraph::TeXEnvironment)" << endl;
3528
3529         LyXLayout const & style =
3530                 textclasslist.Style(bparams.textclass,
3531                                     layout);
3532        
3533         if (pextra_type == PEXTRA_INDENT) {
3534                 if (!pextra_width.empty()) {
3535                         os << "\\begin{LyXParagraphIndent}{"
3536                            << pextra_width << "}\n";
3537                 } else {
3538                         //float ib = atof(pextra_widthp.c_str())/100;
3539                         // string can't handle floats at present (971109)
3540                         // so I'll do a conversion by hand knowing that
3541                         // the limits are 0.0 to 1.0. ARRae.
3542                         os << "\\begin{LyXParagraphIndent}{";
3543                         switch (pextra_widthp.length()) {
3544                         case 3:
3545                                 os << "1.00";
3546                                 break;
3547                         case 2:
3548                                 os << "0."
3549                                    << pextra_widthp;
3550                                 break;
3551                         case 1:
3552                                 os << "0.0"
3553                                    << pextra_widthp;
3554                         }
3555                         os << "\\columnwidth}\n";
3556                 }
3557                 texrow.newline();
3558                 eindent_open = true;
3559         }
3560         if ((pextra_type == PEXTRA_MINIPAGE) && !minipage_open) {
3561                 if (pextra_hfill && Previous() &&
3562                     (Previous()->pextra_type == PEXTRA_MINIPAGE)) {
3563                         os << "\\hfill{}\n";
3564                         texrow.newline();
3565                 }
3566                 if (par_sep == BufferParams::PARSEP_INDENT) {
3567                         os << "{\\setlength\\parindent{0pt}\n";
3568                         texrow.newline();
3569                 }
3570                 os << "\\begin{minipage}";
3571                 switch(pextra_alignment) {
3572                 case MINIPAGE_ALIGN_TOP:
3573                         os << "[t]";
3574                         break;
3575                 case MINIPAGE_ALIGN_MIDDLE:
3576                         os << "[m]";
3577                         break;
3578                 case MINIPAGE_ALIGN_BOTTOM:
3579                         os << "[b]";
3580                         break;
3581                 }
3582                 if (!pextra_width.empty()) {
3583                         os << '{' << pextra_width << "}\n";
3584                 } else {
3585                         //float ib = atof(par->pextra_width.c_str())/100;
3586                         // string can't handle floats at present
3587                         // so I'll do a conversion by hand knowing that
3588                         // the limits are 0.0 to 1.0. ARRae.
3589                         os << '{';
3590                         switch (pextra_widthp.length()) {
3591                         case 3:
3592                                 os << "1.00";
3593                                 break;
3594                         case 2:
3595                                 os << "0."
3596                                    << pextra_widthp;
3597                                 break;
3598                         case 1:
3599                                 os << "0.0"
3600                                    << pextra_widthp;
3601                         }
3602                         os << "\\columnwidth}\n";
3603                 }
3604                 texrow.newline();
3605                 if (par_sep == BufferParams::PARSEP_INDENT) {
3606                         os << "\\setlength\\parindent{\\LyXMinipageIndent}\n";
3607                         texrow.newline();
3608                 }
3609                 minipage_open = true;
3610                 minipage_open_depth = depth;
3611         }
3612
3613 #ifdef WITH_WARNINGS
3614 #warning Define FANCY_FOOTNOTE_CODE to re-enable Allan footnote code
3615         //I disabled it because it breaks when lists span on several
3616         //pages (JMarc)
3617 #endif
3618         if (style.isEnvironment()){
3619                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
3620 #ifdef FANCY_FOOTNOTE_CODE
3621                         if (foot_count < 0) {
3622                                 // flag that footnote[mark][text] should be
3623                                 // used for any footnotes from now on
3624                                 foot_count = 0;
3625                                 foot_this_level = true;
3626                         }
3627 #endif
3628                         os << "\\begin{" << style.latexname() << "}{"
3629                            << labelwidthstring << "}\n";
3630                 } else if (style.labeltype == LABEL_BIBLIO) {
3631                         // ale970405
3632                         os << "\\begin{" << style.latexname() << "}{"
3633                            <<  bibitemWidest(current_view->painter())
3634                            << "}\n";
3635                 } else if (style.latextype == LATEX_ITEM_ENVIRONMENT) {
3636 #ifdef FANCY_FOOTNOTE_CODE
3637                         if (foot_count < 0) {
3638                                 // flag that footnote[mark][text] should be
3639                                 // used for any footnotes from now on
3640                                 foot_count = 0;
3641                                 foot_this_level = true;
3642                         }
3643 #endif
3644                         os << "\\begin{" << style.latexname() << '}'
3645                            << style.latexparam() << '\n';
3646                 } else 
3647                         os << "\\begin{" << style.latexname() << '}'
3648                            << style.latexparam() << '\n';
3649                 texrow.newline();
3650         }
3651         LyXParagraph * par = this;
3652         do {
3653                 par = par->TeXOnePar(buf, bparams,
3654                                      os, texrow, false,
3655                                      foot, foot_texrow, foot_count);
3656
3657                 if (minipage_open && par && !style.isEnvironment() &&
3658                     (par->pextra_type == PEXTRA_MINIPAGE) &&
3659                     par->pextra_start_minipage) {
3660                         os << "\\end{minipage}\n";
3661                         texrow.newline();
3662                         if (par_sep == BufferParams::PARSEP_INDENT) {
3663                                 os << "}\n";
3664                                 texrow.newline();
3665                         }
3666                         minipage_open = false;
3667                 }
3668                 if (par && par->depth > depth) {
3669                         if (textclasslist.Style(bparams.textclass,
3670                                                 par->layout).isParagraph()
3671                             && !par->table
3672                             // Thinko!
3673                             // How to handle this? (Lgb)
3674                             //&& !suffixIs(os, "\n\n")
3675                                 ) {
3676                                 // There should be at least one '\n' already
3677                                 // but we need there to be two for Standard 
3678                                 // paragraphs that are depth-increment'ed to be
3679                                 // output correctly.  However, tables can
3680                                 // also be paragraphs so don't adjust them.
3681                                 // ARRae
3682                                 // Thinkee:
3683                                 // Will it ever harm to have one '\n' too
3684                                 // many? i.e. that we sometimes will have
3685                                 // three in a row. (Lgb)
3686                                 os << '\n';
3687                                 texrow.newline();
3688                         }
3689                         par = par->TeXDeeper(buf, bparams, os, texrow,
3690                                              foot, foot_texrow, foot_count);
3691                 }
3692                 if (par && par->layout == layout && par->depth == depth &&
3693                     (par->pextra_type == PEXTRA_MINIPAGE) && !minipage_open) {
3694                         if (par->pextra_hfill && par->Previous() &&
3695                             (par->Previous()->pextra_type == PEXTRA_MINIPAGE)){
3696                                 os << "\\hfill{}\n";
3697                                 texrow.newline();
3698                         }
3699                         if (par_sep == BufferParams::PARSEP_INDENT) {
3700                                 os << "{\\setlength\\parindent{0pt}\n";
3701                                 texrow.newline();
3702                         }
3703                         os << "\\begin{minipage}";
3704                         switch(par->pextra_alignment) {
3705                         case MINIPAGE_ALIGN_TOP:
3706                                 os << "[t]";
3707                                 break;
3708                         case MINIPAGE_ALIGN_MIDDLE:
3709                                 os << "[m]";
3710                                 break;
3711                         case MINIPAGE_ALIGN_BOTTOM:
3712                                 os << "[b]";
3713                                 break;
3714                         }
3715                         if (!par->pextra_width.empty()) {
3716                                 os << '{' << par->pextra_width << "}\n";
3717                         } else {
3718                                 //float ib = atof(par->pextra_widthp.c_str())/100;
3719                                 // string can't handle floats at present
3720                                 // so I'll do a conversion by hand knowing that
3721                                 // the limits are 0.0 to 1.0. ARRae.
3722                                 os << '{';
3723                                 switch (par->pextra_widthp.length()) {
3724                                 case 3:
3725                                         os << "1.00";
3726                                         break;
3727                                 case 2:
3728                                         os << "0." << par->pextra_widthp;
3729                                         break;
3730                                 case 1:
3731                                         os << "0.0" << par->pextra_widthp;
3732                                 }
3733                                 os << "\\columnwidth}\n";
3734                         }
3735                         texrow.newline();
3736                         if (par_sep == BufferParams::PARSEP_INDENT) {
3737                                 os << "\\setlength\\parindent{\\LyXMinipageIndent}\n";
3738                                 texrow.newline();
3739                         }
3740                         minipage_open = true;
3741                         minipage_open_depth = par->depth;
3742                 }
3743         } while (par
3744                  && par->layout == layout
3745                  && par->depth == depth
3746                  && par->pextra_type == pextra_type
3747                  && par->footnoteflag == footnoteflag);
3748  
3749         if (style.isEnvironment()) {
3750                 os << "\\end{" << style.latexname() << '}';
3751                 // maybe this should go after the minipage closes?
3752                 if (foot_this_level) {
3753                         if (foot_count >= 1) {
3754                                 if (foot_count > 1) {
3755                                         os << "\\addtocounter{footnote}{-"
3756                                            << foot_count - 1
3757                                            << '}';
3758                                 }
3759                                 os << foot;
3760                                 texrow += foot_texrow;
3761                                 foot.clear();
3762                                 foot_texrow.reset();
3763                                 foot_count = 0;
3764                         }
3765                 }
3766         }
3767         if (minipage_open && (minipage_open_depth == depth) &&
3768             (!par || par->pextra_start_minipage ||
3769              par->pextra_type != PEXTRA_MINIPAGE)) {
3770                 os << "\\end{minipage}\n";
3771                 texrow.newline();
3772                 if (par_sep == BufferParams::PARSEP_INDENT) {
3773                         os << "}\n";
3774                         texrow.newline();
3775                 }
3776                 if (par && par->pextra_type != PEXTRA_MINIPAGE) {
3777                         os << "\\medskip\n\n";
3778                         texrow.newline();
3779                         texrow.newline();
3780                 }
3781                 minipage_open = false;
3782         }
3783         if (eindent_open) {
3784                 os << "\\end{LyXParagraphIndent}\n";
3785                 texrow.newline();
3786         }
3787         if (!(par && (par->pextra_type == PEXTRA_MINIPAGE) 
3788               && par->pextra_hfill)) {
3789                 os << '\n';
3790                 texrow.newline();
3791         }
3792         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << par << endl;
3793         return par;  // ale970302
3794 }
3795
3796
3797 #ifndef NEW_INSETS
3798 LyXParagraph * LyXParagraph::TeXFootnote(Buffer const * buf,
3799                                          BufferParams const & bparams,
3800                                          ostream & os, TexRow & texrow,
3801                                          ostream & foot, TexRow & foot_texrow,
3802                                          int & foot_count,
3803                                          bool parent_is_rtl)
3804 {
3805         lyxerr[Debug::LATEX] << "TeXFootnote...  " << this << endl;
3806         if (footnoteflag == LyXParagraph::NO_FOOTNOTE)
3807                 lyxerr << "ERROR (LyXParagraph::TeXFootnote): "
3808                         "No footnote!" << endl;
3809
3810         LyXParagraph * par = this;
3811         LyXLayout const & style =
3812                 textclasslist.Style(bparams.textclass, 
3813                                     previous->GetLayout());
3814         
3815         if (style.needprotect && footnotekind != LyXParagraph::FOOTNOTE){
3816                 lyxerr << "ERROR (LyXParagraph::TeXFootnote): "
3817                         "Float other than footnote in command"
3818                         " with moving argument is illegal" << endl;
3819         }
3820
3821         if (footnotekind != LyXParagraph::FOOTNOTE
3822             && footnotekind != LyXParagraph::MARGIN
3823             && os.tellp()
3824             // Thinko
3825             // How to solve this?
3826             //&& !suffixIs(file, '\n')
3827                 ) {
3828                 // we need to ensure that real floats like tables and figures
3829                 // have their \begin{} on a new line otherwise we can get
3830                 // incorrect results when using the endfloat.sty package
3831                 // especially if two floats follow one another.  ARRae 981022
3832                 // NOTE: if the file is length 0 it must have just been
3833                 //       written out so we assume it ended with a '\n'
3834                 // Thinkee:
3835                 // As far as I can see there is never any harm in writing
3836                 // a '\n' too much. Please tell me if I am wrong. (Lgb)
3837                 os << '\n';
3838                 texrow.newline();
3839         }
3840
3841         bool moving_arg = false;
3842         bool need_closing = false;
3843         bool is_rtl = isRightToLeftPar(bparams);
3844
3845         if (is_rtl != parent_is_rtl) {
3846                 if (is_rtl)
3847                         os << "\\R{";
3848                 else
3849                         os << "\\L{";
3850                 need_closing = true;
3851         }
3852         
3853         //BufferParams * params = &current_view->buffer()->params;
3854         bool footer_in_body = true;
3855         switch (footnotekind) {
3856         case LyXParagraph::FOOTNOTE:
3857                 if (style.intitle) {
3858                         os << "\\thanks{\n";
3859                         footer_in_body = false;
3860                         moving_arg = true;
3861                 } else {
3862                         if (foot_count == -1) {
3863                                 // we're at depth 0 so we can use:
3864                                 os << "\\footnote{%\n";
3865                                 footer_in_body = false;
3866                         } else {
3867                                 os << "\\footnotemark{}%\n";
3868                                 if (foot_count) {
3869                                         // we only need this when there are
3870                                         // multiple footnotes
3871                                         os << "\\stepcounter{footnote}";
3872                                 }
3873                                 os << "\\footnotetext{%\n";
3874                                 foot_texrow.start(this, 0);
3875                                 foot_texrow.newline();
3876                                 ++foot_count;
3877                         }
3878                 }
3879                 break;
3880         case LyXParagraph::MARGIN:
3881                 os << "\\marginpar{\n";
3882                 break;
3883         case LyXParagraph::FIG:
3884                 if (pextra_type == PEXTRA_FLOATFLT
3885                     && (!pextra_width.empty()
3886                         || !pextra_widthp.empty())) {
3887                         if (!pextra_width.empty())
3888                                 os << "\\begin{floatingfigure}{"
3889                                    << pextra_width << "}\n";
3890                         else
3891                                 os << "\\begin{floatingfigure}{"
3892                                    << atoi(pextra_widthp.c_str())/100.0
3893                                    << "\\textwidth}\n";
3894                 } else {
3895                         os << "\\begin{figure}";
3896                         if (!bparams.float_placement.empty()) { 
3897                                 os << '[' << bparams.float_placement << "]\n";
3898                         } else {
3899                                 os << '\n';
3900                         }
3901                 }
3902                 break;
3903         case LyXParagraph::TAB:
3904                 os << "\\begin{table}";
3905                 if (!bparams.float_placement.empty()) { 
3906                         os << '[' << bparams.float_placement << "]\n";
3907                 } else {
3908                         os << '\n';
3909                 }
3910                 break;
3911         case LyXParagraph::WIDE_FIG:
3912                 os << "\\begin{figure*}";
3913                 if (!bparams.float_placement.empty()) { 
3914                         os << '[' << bparams.float_placement << "]\n";
3915                 } else {
3916                         os << '\n';
3917                 }
3918                 break;
3919         case LyXParagraph::WIDE_TAB:
3920                 os << "\\begin{table*}";
3921                 if (!bparams.float_placement.empty()) { 
3922                         os << '[' << bparams.float_placement << "]\n";
3923                 } else {
3924                         os << '\n';
3925                 }
3926                 break;
3927         case LyXParagraph::ALGORITHM:
3928                 os << "\\begin{algorithm}\n";
3929                 break;
3930         }
3931         texrow.newline();
3932    
3933         if (footnotekind != LyXParagraph::FOOTNOTE
3934             || !footer_in_body) {
3935                 // Process text for all floats except footnotes in body
3936                 do {
3937                         LyXLayout const & style =
3938                                 textclasslist
3939                                 .Style(bparams.textclass, par->layout);
3940                         if (par->IsDummy())
3941                                 lyxerr << "ERROR (LyXParagraph::TeXFootnote)"
3942                                        << endl;
3943                         if (style.isEnvironment()
3944                             || par->pextra_type == PEXTRA_MINIPAGE) { /* && !minipage_open ?? */
3945                                 // Allows the use of minipages within float
3946                                 // environments. Shouldn't be circular because
3947                                 // we don't support footnotes inside
3948                                 // floats (yet). ARRae
3949                                 par = par->TeXEnvironment(buf, bparams, os,
3950                                                           texrow,
3951                                                           foot, foot_texrow,
3952                                                           foot_count);
3953                         } else {
3954                                 par = par->TeXOnePar(buf, bparams,
3955                                                      os, texrow, moving_arg,
3956                                                      foot, foot_texrow,
3957                                                      foot_count);
3958                         }
3959                         
3960                         if (par && !par->IsDummy() && par->depth > depth) {
3961                                 par = par->TeXDeeper(buf, bparams, os, texrow,
3962                                                      foot, foot_texrow,
3963                                                      foot_count);
3964                         }
3965                 } while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE);
3966         } else {
3967                 // process footnotes > depth 0 or in environments separately
3968                 // NOTE: Currently don't support footnotes within footnotes
3969                 //       even though that is possible using the \footnotemark
3970 #ifdef HAVE_SSTREAM
3971                 std::ostringstream dummy;
3972 #else
3973                 ostrstream dummy;
3974 #endif
3975                 TexRow dummy_texrow;
3976                 int dummy_count = 0;
3977                 do {
3978                         LyXLayout const & style =
3979                                 textclasslist
3980                                 .Style(bparams.textclass, par->layout);
3981                         if (par->IsDummy())
3982                                 lyxerr << "ERROR (LyXParagraph::TeXFootnote)"
3983                                        << endl;
3984                         if (style.isEnvironment()
3985                             || par->pextra_type == PEXTRA_MINIPAGE) { /* && !minipage_open ?? */
3986                                 // Allows the use of minipages within float
3987                                 // environments. Shouldn't be circular because
3988                                 // we don't support footnotes inside
3989                                 // floats (yet). ARRae
3990                                 par = par->TeXEnvironment(buf, bparams,
3991                                                           foot, foot_texrow,
3992                                                           dummy, dummy_texrow,
3993                                                           dummy_count);
3994                         } else {
3995                                 par = par->TeXOnePar(buf, bparams,
3996                                                      foot, foot_texrow,
3997                                                      moving_arg,
3998                                                      dummy, dummy_texrow,
3999                                                      dummy_count);
4000                         }
4001
4002                         if (par && !par->IsDummy() && par->depth > depth) {
4003                                 par = par->TeXDeeper(buf, bparams,
4004                                                      foot, foot_texrow,
4005                                                      dummy, dummy_texrow,
4006                                                      dummy_count);
4007                         }
4008                 } while (par
4009                          && par->footnoteflag != LyXParagraph::NO_FOOTNOTE);
4010                 if (dummy_count) {
4011                         lyxerr << "ERROR (LyXParagraph::TeXFootnote): "
4012                                 "Footnote in a Footnote -- not supported"
4013                                << endl;
4014                 }
4015 #ifndef HAVE_OSTREAM
4016                 delete [] dummy.str();
4017 #endif
4018         }
4019
4020         switch (footnotekind) {
4021         case LyXParagraph::FOOTNOTE:
4022                 if (footer_in_body) {
4023                         // This helps tell which of the multiple
4024                         // footnotetexts an error was in.
4025                         foot << "}%\n";
4026                         foot_texrow.newline();
4027                 } else {
4028                         os << '}';
4029                 }
4030                 break;
4031         case LyXParagraph::MARGIN:
4032                 os << '}';
4033                 break;
4034         case LyXParagraph::FIG:
4035                 if (pextra_type == PEXTRA_FLOATFLT
4036                     && (!pextra_width.empty()
4037                         || !pextra_widthp.empty()))
4038                         os << "\\end{floatingfigure}";
4039                 else
4040                         os << "\\end{figure}";
4041                 break;
4042         case LyXParagraph::TAB:
4043                 os << "\\end{table}";
4044                 break;
4045         case LyXParagraph::WIDE_FIG:
4046                 os << "\\end{figure*}";
4047                 break;
4048         case LyXParagraph::WIDE_TAB:
4049                 os << "\\end{table*}";
4050                 break;
4051         case LyXParagraph::ALGORITHM:
4052                 os << "\\end{algorithm}";
4053                 break;
4054         }
4055
4056         if (need_closing)
4057                 os << "}";
4058
4059         if (footnotekind != LyXParagraph::FOOTNOTE
4060             && footnotekind != LyXParagraph::MARGIN) {
4061                 // we need to ensure that real floats like tables and figures
4062                 // have their \end{} on a line of their own otherwise we can
4063                 // get incorrect results when using the endfloat.sty package.
4064                 os << "\n";
4065                 texrow.newline();
4066         }
4067
4068         lyxerr[Debug::LATEX] << "TeXFootnote...done " << par->next << endl;
4069         return par;
4070 }
4071
4072
4073 bool LyXParagraph::IsDummy() const
4074 {
4075         return (footnoteflag == LyXParagraph::NO_FOOTNOTE && previous
4076                 && previous->footnoteflag != LyXParagraph::NO_FOOTNOTE);
4077 }
4078 #endif
4079
4080 void LyXParagraph::SetPExtraType(BufferParams const & bparams,
4081                                  int type, char const * width,
4082                                  char const * widthp)
4083 {
4084         pextra_type = type;
4085         pextra_width = width;
4086         pextra_widthp = widthp;
4087
4088         if (textclasslist.Style(bparams.textclass, 
4089                                 layout).isEnvironment()) {
4090                 LyXParagraph
4091                         * par = this,
4092                         * ppar = par;
4093
4094                 while (par && (par->layout == layout)
4095                        && (par->depth == depth)) {
4096                         ppar = par;
4097                         par = par->Previous();
4098                         if (par)
4099                                 par = par->FirstPhysicalPar();
4100                         while (par && par->depth > depth) {
4101                                 par = par->Previous();
4102                                 if (par)
4103                                         par = par->FirstPhysicalPar();
4104                         }
4105                 }
4106                 par = ppar;
4107                 while (par && (par->layout == layout)
4108                        && (par->depth == depth)) {
4109                         par->pextra_type = type;
4110                         par->pextra_width = width;
4111                         par->pextra_widthp = widthp;
4112                         par = par->NextAfterFootnote();
4113                         if (par && (par->depth > depth))
4114                                 par->SetPExtraType(bparams,
4115                                                    type, width, widthp);
4116                         while (par && ((par->depth > depth) || par->IsDummy()))
4117                                 par = par->NextAfterFootnote();
4118                 }
4119         }
4120 }
4121
4122
4123 void LyXParagraph::UnsetPExtraType(BufferParams const & bparams)
4124 {
4125         if (pextra_type == PEXTRA_NONE)
4126                 return;
4127     
4128         pextra_type = PEXTRA_NONE;
4129         pextra_width.erase();
4130         pextra_widthp.erase();
4131
4132         if (textclasslist.Style(bparams.textclass, 
4133                                 layout).isEnvironment()) {
4134                 LyXParagraph
4135                         * par = this,
4136                         * ppar = par;
4137
4138                 while (par && (par->layout == layout)
4139                        && (par->depth == depth)) {
4140                         ppar = par;
4141                         par = par->Previous();
4142                         if (par)
4143                                 par = par->FirstPhysicalPar();
4144                         while (par && par->depth > depth) {
4145                                 par = par->Previous();
4146                                 if (par)
4147                                         par = par->FirstPhysicalPar();
4148                         }
4149                 }
4150                 par = ppar;
4151                 while (par && (par->layout == layout)
4152                        && (par->depth == depth)) {
4153                         par->pextra_type = PEXTRA_NONE;
4154                         par->pextra_width.erase();
4155                         par->pextra_widthp.erase();
4156                         par = par->NextAfterFootnote();
4157                         if (par && (par->depth > depth))
4158                                 par->UnsetPExtraType(bparams);
4159                         while (par && ((par->depth > depth) || par->IsDummy()))
4160                                 par = par->NextAfterFootnote();
4161                 }
4162         }
4163 }
4164
4165
4166 bool LyXParagraph::IsHfill(size_type pos) const
4167 {
4168         return IsHfillChar(GetChar(pos));
4169 }
4170
4171
4172 bool LyXParagraph::IsInset(size_type pos) const
4173 {
4174         return IsInsetChar(GetChar(pos));
4175 }
4176
4177
4178 bool LyXParagraph::IsFloat(size_type pos) const
4179 {
4180         return IsFloatChar(GetChar(pos));
4181 }
4182
4183
4184 bool LyXParagraph::IsNewline(size_type pos) const
4185 {
4186         return pos >= 0 && IsNewlineChar(GetChar(pos));
4187 }
4188
4189
4190 bool LyXParagraph::IsSeparator(size_type pos) const
4191 {
4192         return IsSeparatorChar(GetChar(pos));
4193 }
4194
4195
4196 bool LyXParagraph::IsLineSeparator(size_type pos) const
4197 {
4198         return IsLineSeparatorChar(GetChar(pos));
4199 }
4200
4201
4202 bool LyXParagraph::IsKomma(size_type pos) const
4203 {
4204         return IsKommaChar(GetChar(pos));
4205 }
4206
4207
4208 /// Used by the spellchecker
4209 bool LyXParagraph::IsLetter(LyXParagraph::size_type pos) const
4210 {
4211         unsigned char c = GetChar(pos);
4212         if (IsLetterChar(c))
4213                 return true;
4214         // '\0' is not a letter, allthough every string contains "" (below)
4215         if( c == '\0')
4216                 return false;
4217         // We want to pass the ' and escape chars to ispell
4218         string extra = lyxrc.isp_esc_chars + '\'';
4219         char ch[2];
4220         ch[0] = c;
4221         ch[1] = 0;
4222         return contains(extra, ch);
4223 }
4224  
4225  
4226 bool LyXParagraph::IsWord(size_type pos ) const
4227 {
4228         return IsWordChar(GetChar(pos)) ;
4229 }
4230
4231
4232 Language const *
4233 LyXParagraph::getParLanguage(BufferParams const & bparams) const 
4234 {
4235         if (IsDummy())
4236                 return FirstPhysicalPar()->getParLanguage(bparams);
4237         else if (size() > 0)
4238 #ifndef NEW_TABULAR
4239                 if (!table)
4240 #endif
4241                         return GetFirstFontSettings().language();
4242 #ifndef NEW_TABULAR
4243                 else {
4244                         for (size_type pos = 0; pos < size(); ++pos)
4245                                 if (IsNewline(pos))
4246                                         return GetFontSettings(bparams, pos).language();
4247                         return GetFirstFontSettings().language();
4248                 }
4249 #endif
4250         else if (previous)
4251                 return previous->getParLanguage(bparams);
4252         else
4253                 return bparams.language_info;
4254 }
4255
4256
4257 bool LyXParagraph::isRightToLeftPar(BufferParams const & bparams) const
4258 {
4259         return lyxrc.rtl_support && !table
4260                 && getParLanguage(bparams)->RightToLeft();
4261 }
4262
4263
4264 void LyXParagraph::ChangeLanguage(BufferParams const & bparams,
4265                                   Language const * from, Language const * to)
4266 {
4267         for(size_type i = 0; i < size(); ++i) {
4268                 LyXFont font = GetFontSettings(bparams, i);
4269                 if (font.language() == from) {
4270                         font.setLanguage(to);
4271                         SetFont(i, font);
4272                 }
4273         }
4274 }
4275
4276
4277 bool LyXParagraph::isMultiLingual(BufferParams const & bparams)
4278 {
4279         Language const * doc_language =
4280                 bparams.language_info;
4281         for(size_type i = 0; i < size(); ++i) {
4282                 LyXFont font = GetFontSettings(bparams, i);
4283                 if (font.language() != doc_language)
4284                         return true;
4285         }
4286         return false;
4287 }
4288
4289
4290 // Convert the paragraph to a string.
4291 // Used for building the table of contents
4292 string LyXParagraph::String(Buffer const * buffer, bool label)
4293 {
4294         BufferParams const & bparams = buffer->params;
4295         string s;
4296         if (label && !IsDummy() && !labelstring.empty())
4297                 s += labelstring + ' ';
4298         string::size_type len = s.size();
4299
4300         for (LyXParagraph::size_type i = 0; i < size(); ++i) {
4301                 unsigned char c = GetChar(i);
4302                 if (IsPrintable(c))
4303                         s += c;
4304                 else if (c == META_INSET &&
4305                          GetInset(i)->LyxCode() == Inset::MATH_CODE) {
4306 #ifdef HAVE_SSTREAM
4307                         std::ostringstream ost;
4308                         GetInset(i)->Ascii(buffer, ost);
4309 #else
4310                         ostrstream ost;
4311                         GetInset(i)->Ascii(buffer, ost);
4312                         ost << '\0';
4313 #endif
4314                         s += subst(ost.str(),'\n',' ');
4315                 }
4316         }
4317
4318 #ifndef NEW_INSETS
4319         if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE 
4320             && footnoteflag == LyXParagraph::NO_FOOTNOTE)
4321                 s += NextAfterFootnote()->String(buffer, false);
4322
4323         if (!IsDummy())
4324 #endif
4325                 {
4326                 if (isRightToLeftPar(bparams))
4327                         reverse(s.begin() + len,s.end());
4328         }
4329         return s;
4330 }
4331
4332
4333 string LyXParagraph::String(Buffer const * buffer, 
4334                             LyXParagraph::size_type beg,
4335                             LyXParagraph::size_type end)
4336 {
4337         string s;
4338         int actcell = 0;
4339         int cell = 1;
4340 #ifndef NEW_TABULAR
4341         if (table)
4342                 for (LyXParagraph::size_type i = 0; i < beg; ++i)
4343                         if (IsNewline(i)) {
4344                                 if (cell >= table->NumberOfCellsInRow(actcell))
4345                                         cell = 1;
4346                                 else
4347                                         ++cell;
4348                                 ++actcell;
4349                         }
4350 #endif
4351         
4352         if (beg == 0 && !IsDummy() && !labelstring.empty())
4353                 s += labelstring + ' ';
4354
4355         for (LyXParagraph::size_type i = beg; i < end; ++i) {
4356                 unsigned char c = GetChar(i);
4357                 if (IsPrintable(c))
4358                         s += c;
4359                 else if (c == META_INSET) {
4360 #ifdef HAVE_SSTREAM
4361                         std::ostringstream ost;
4362                         GetInset(i)->Ascii(buffer, ost);
4363 #else
4364                         ostrstream ost;
4365                         GetInset(i)->Ascii(buffer, ost);
4366                         ost << '\0';
4367 #endif
4368                         s += ost.str();
4369                 } else if (table && IsNewlineChar(c)) {
4370                         if (cell >= table->NumberOfCellsInRow(actcell)) {
4371                                 s += '\n';
4372                                 cell = 1;
4373                         } else {
4374                                 s += ' ';
4375                                 ++cell;
4376                         }
4377                         ++actcell;
4378                 }
4379         }
4380
4381         //if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE)
4382         //      s += NextAfterFootnote()->String(false);
4383
4384         return s;
4385 }
4386
4387
4388 void LyXParagraph::SetInsetOwner(Inset *i)
4389 {
4390         inset_owner = i;
4391         for (InsetList::const_iterator cit = insetlist.begin();
4392              cit != insetlist.end(); ++cit) {
4393                 if ((*cit).inset)
4394                         (*cit).inset->setOwner(i);
4395         }
4396 }
4397
4398
4399 void LyXParagraph::deleteInsetsLyXText(BufferView * bv)
4400 {
4401         // then the insets
4402         for (InsetList::const_iterator cit = insetlist.begin();
4403              cit != insetlist.end(); ++cit) {
4404                 if ((*cit).inset) {
4405                         if ((*cit).inset->IsTextInset()) {
4406                                 static_cast<UpdatableInset *>
4407                                         ((*cit).inset)->deleteLyXText(bv);
4408                         }
4409                 }
4410         }
4411 }