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