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