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