]> git.lyx.org Git - lyx.git/blob - src/paragraph.C
6fb5e4bd27640a0f8c023d67329d8eb28ff298bb
[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(Buffer const *);
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);
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;
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->babel() != doc_language->babel()) {
372                         features.UsedLanguages.insert(language);
373                         lyxerr[Debug::LATEX] << "Found language "
374                                              << language->babel() << 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(*current_view->buffer());
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 *>
1614                                  (bibkey->Clone(*current_view->buffer()));
1615         else
1616                 result->bibkey = 0;
1617     
1618         // copy everything behind the break-position to the new paragraph
1619
1620         result->text = text;
1621         result->fontlist = fontlist;
1622         result->insetlist = insetlist;
1623         for (InsetList::iterator it = result->insetlist.begin();
1624              it != result->insetlist.end(); ++it)
1625                 (*it).inset = (*it).inset->Clone(*current_view->buffer());
1626         return result;
1627 }
1628
1629
1630 bool LyXParagraph::HasSameLayout(LyXParagraph const * par) const
1631 {
1632 #ifndef NEW_INSETS
1633         par = par->FirstPhysicalPar();
1634 #endif
1635
1636         return (
1637 #ifndef NEW_INSETS
1638                 par->footnoteflag == footnoteflag &&
1639                 par->footnotekind == footnotekind &&
1640 #endif
1641                 par->layout == layout &&
1642
1643                 par->align == align &&
1644
1645                 par->line_bottom == line_bottom &&
1646                 par->pagebreak_bottom == pagebreak_bottom &&
1647                 par->added_space_bottom == added_space_bottom &&
1648
1649                 par->line_top == line_top &&
1650                 par->pagebreak_top == pagebreak_top &&
1651                 par->added_space_top == added_space_top &&
1652
1653                 par->spacing == spacing &&
1654                 
1655                 par->pextra_type == pextra_type &&
1656                 par->pextra_width == pextra_width && 
1657                 par->pextra_widthp == pextra_widthp && 
1658                 par->pextra_alignment == pextra_alignment && 
1659                 par->pextra_hfill == pextra_hfill && 
1660                 par->pextra_start_minipage == pextra_start_minipage && 
1661                 par->noindent == noindent &&
1662                 par->depth == depth);
1663 }
1664
1665
1666 void LyXParagraph::BreakParagraphConservative(BufferParams const & bparams,
1667                                               LyXParagraph::size_type pos)
1668 {
1669 #ifndef NEW_INSETS
1670         // create a new paragraph
1671         LyXParagraph * par = ParFromPos(pos);
1672
1673         LyXParagraph * tmp = new LyXParagraph(par);
1674    
1675         tmp->MakeSameLayout(par);
1676
1677         // When can pos < Last()?
1678         // I guess pos == Last() is possible.
1679         if (Last() > pos) {
1680                 // copy everything behind the break-position to the new
1681                 // paragraph
1682                 size_type pos_first = 0;
1683                 while (ParFromPos(pos_first) != par)
1684                         ++pos_first;
1685                 size_type pos_end = pos_first + par->text.size() - 1;
1686
1687                 size_type i, j;
1688                 for (i = j = pos; i <= pos_end; ++i) {
1689                         par->CutIntoMinibuffer(bparams, i - pos_first);
1690                         if (tmp->InsertFromMinibuffer(j - pos))
1691                                 ++j;
1692                 }
1693                 tmp->text.resize(tmp->text.size());
1694                 for (size_type i = pos_end; i >= pos; --i)
1695                         par->Erase(i - pos_first);
1696
1697                 par->text.resize(par->text.size());
1698         }
1699 #else
1700         // create a new paragraph
1701         LyXParagraph * tmp = new LyXParagraph(this);
1702         tmp->MakeSameLayout(this);
1703
1704         // When can pos > Last()?
1705         // I guess pos == Last() is possible.
1706         if (Last() > pos) {
1707                 // copy everything behind the break-position to the new
1708                 // paragraph
1709                 size_type pos_end = text.size() - 1;
1710
1711                 size_type i, j;
1712                 for (i = j = pos; i <= pos_end; ++i) {
1713                         CutIntoMinibuffer(bparams, i);
1714                         if (tmp->InsertFromMinibuffer(j - pos))
1715                                 ++j;
1716                 }
1717
1718                 tmp->fitToSize();
1719                 
1720                 for (size_type i = pos_end; i >= pos; --i)
1721                         Erase(i);
1722
1723                 fitToSize();
1724         }
1725 #endif
1726 }
1727    
1728
1729 // Be carefull, this does not make any check at all.
1730 // This method has wrong name, it combined this par with the next par.
1731 // In that sense it is the reverse of break paragraph. (Lgb)
1732 void LyXParagraph::PasteParagraph(BufferParams const & bparams)
1733 {
1734         // copy the next paragraph to this one
1735         LyXParagraph * the_next = Next();
1736 #ifndef NEW_INSETS   
1737         LyXParagraph * firstpar = FirstPhysicalPar();
1738 #endif
1739    
1740         // first the DTP-stuff
1741 #ifndef NEW_INSETS
1742         firstpar->line_bottom = the_next->line_bottom;
1743         firstpar->added_space_bottom = the_next->added_space_bottom;
1744         firstpar->pagebreak_bottom = the_next->pagebreak_bottom;
1745 #else
1746         line_bottom = the_next->line_bottom;
1747         added_space_bottom = the_next->added_space_bottom;
1748         pagebreak_bottom = the_next->pagebreak_bottom;
1749 #endif
1750
1751         size_type pos_end = the_next->text.size() - 1;
1752         size_type pos_insert = Last();
1753
1754         // ok, now copy the paragraph
1755         size_type i, j;
1756         for (i = j = 0; i <= pos_end; ++i) {
1757                 the_next->CutIntoMinibuffer(bparams, i);
1758                 if (InsertFromMinibuffer(pos_insert + j))
1759                         ++j;
1760         }
1761    
1762         // delete the next paragraph
1763         LyXParagraph * ppar = the_next->previous;
1764         LyXParagraph * npar = the_next->next;
1765         delete the_next;
1766         ppar->next = npar;
1767 }
1768
1769
1770 #ifndef NEW_INSETS
1771 void LyXParagraph::OpenFootnote(LyXParagraph::size_type pos)
1772 {
1773         LyXParagraph * par = ParFromPos(pos);
1774         par = par->next;
1775         while (par && par->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
1776                 par->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
1777                 par = par->next;
1778         }
1779 }
1780
1781
1782 void LyXParagraph::CloseFootnote(LyXParagraph::size_type pos)
1783 {
1784         LyXParagraph * par = ParFromPos(pos);
1785         par = par->next;
1786         while (par && par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
1787                 par->footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
1788                 par = par->next;
1789         }
1790 }
1791 #endif
1792
1793
1794 int LyXParagraph::GetEndLabel(BufferParams const & bparams) const
1795 {
1796         LyXParagraph const * par = this;
1797         int par_depth = GetDepth();
1798         while (par) {
1799                 LyXTextClass::LayoutList::size_type layout = par->GetLayout();
1800                 int const endlabeltype =
1801                         textclasslist.Style(bparams.textclass,
1802                                             layout).endlabeltype;
1803                 if (endlabeltype != END_LABEL_NO_LABEL) {
1804                         LyXParagraph const * last = this;
1805 #ifndef NEW_INSETS
1806                         if( footnoteflag == NO_FOOTNOTE)
1807                                 last = LastPhysicalPar();
1808                         else if (next->footnoteflag == NO_FOOTNOTE)
1809                                 return endlabeltype;
1810 #else
1811                         last = this;
1812 #endif
1813
1814                         if (!last || !last->next)
1815                                 return endlabeltype;
1816
1817                         int next_depth = last->next->GetDepth();
1818                         if (par_depth > next_depth ||
1819                             (par_depth == next_depth && layout != last->next->GetLayout() ))
1820                                 return endlabeltype;
1821                         break;
1822                 }
1823                 if (par_depth == 0)
1824                         break;
1825                 par = par->DepthHook(par_depth - 1);
1826                 if (par)
1827                         par_depth = par->GetDepth();
1828         }
1829         return END_LABEL_NO_LABEL;
1830 }
1831
1832
1833 LyXTextClass::size_type LyXParagraph::GetLayout() const
1834 {
1835 #ifndef NEW_INSETS
1836         return FirstPhysicalPar()->layout;
1837 #else
1838         return layout;
1839 #endif
1840 }
1841
1842
1843 char LyXParagraph::GetDepth() const
1844 {
1845 #ifndef NEW_INSETS
1846         return FirstPhysicalPar()->depth;
1847 #else
1848         return depth;
1849 #endif
1850 }
1851
1852
1853 char LyXParagraph::GetAlign() const
1854 {
1855 #ifndef NEW_INSETS
1856         return FirstPhysicalPar()->align;
1857 #else
1858         return align;
1859 #endif
1860 }
1861
1862
1863 string const & LyXParagraph::GetLabelstring() const
1864 {
1865 #ifndef NEW_INSETS
1866         return FirstPhysicalPar()->labelstring;
1867 #else
1868         return labelstring;
1869 #endif
1870 }
1871
1872
1873 int LyXParagraph::GetFirstCounter(int i) const
1874 {
1875 #ifndef NEW_INSETS
1876         return FirstPhysicalPar()->counter_[i];
1877 #else
1878         return counter_[i];
1879 #endif
1880 }
1881
1882
1883 // the next two functions are for the manual labels
1884 string const LyXParagraph::GetLabelWidthString() const
1885 {
1886 #ifndef NEW_INSETS
1887         if (!FirstPhysicalPar()->labelwidthstring.empty())
1888                 return FirstPhysicalPar()->labelwidthstring;
1889 #else
1890         if (!labelwidthstring.empty())
1891                 return labelwidthstring;
1892 #endif
1893         else
1894                 return _("Senseless with this layout!");
1895 }
1896
1897
1898 void LyXParagraph::SetLabelWidthString(string const & s)
1899 {
1900 #ifndef NEW_INSETS
1901         LyXParagraph * par = FirstPhysicalPar();
1902
1903         par->labelwidthstring = s;
1904 #else
1905         labelwidthstring = s;
1906 #endif
1907 }
1908
1909
1910 void LyXParagraph::SetOnlyLayout(BufferParams const & bparams,
1911                                  LyXTextClass::size_type new_layout)
1912 {
1913 #ifndef NEW_INSETS
1914         LyXParagraph * par = FirstPhysicalPar();
1915 #else
1916         LyXParagraph * par = this;
1917 #endif
1918         LyXParagraph * ppar = 0;
1919         LyXParagraph * npar = 0;
1920
1921         par->layout = new_layout;
1922
1923         if (par->pextra_type == PEXTRA_NONE) {
1924                 if (par->Previous()) {
1925 #ifndef NEW_INSETS
1926                         ppar = par->Previous()->FirstPhysicalPar();
1927 #else
1928                         ppar = par->Previous();
1929 #endif
1930                         while(ppar
1931                               && ppar->Previous()
1932                               && (ppar->depth > par->depth))
1933 #ifndef NEW_INSETS
1934                                 ppar = ppar->Previous()->FirstPhysicalPar();
1935 #else
1936                         ppar = ppar->Previous();
1937 #endif
1938                 }
1939                 if (par->Next()) {
1940 #ifndef NEW_INSETS
1941                         npar = par->Next()->NextAfterFootnote();
1942 #else
1943                         npar = par->Next();
1944 #endif
1945                         while(npar
1946                               && npar->Next()
1947                               && (npar->depth > par->depth))
1948 #ifndef NEW_INSETS
1949                                 npar = npar->Next()->NextAfterFootnote();
1950 #else
1951                         npar = npar->Next();
1952 #endif
1953                 }
1954                 if (ppar && (ppar->pextra_type != PEXTRA_NONE)) {
1955                         string
1956                                 p1 = ppar->pextra_width,
1957                                 p2 = ppar->pextra_widthp;
1958                         ppar->SetPExtraType(bparams, ppar->pextra_type,
1959                                             p1, p2);
1960                 }
1961                 if ((par->pextra_type == PEXTRA_NONE) &&
1962                     npar && (npar->pextra_type != PEXTRA_NONE)) {
1963                         string
1964                                 p1 = npar->pextra_width,
1965                                 p2 = npar->pextra_widthp;
1966                         npar->SetPExtraType(bparams, npar->pextra_type,
1967                                             p1, p2);
1968                 }
1969         }
1970 }
1971
1972
1973 void LyXParagraph::SetLayout(BufferParams const & bparams,
1974                              LyXTextClass::size_type new_layout)
1975 {
1976         LyXParagraph
1977 #ifndef NEW_INSETS
1978                 * par = FirstPhysicalPar(),
1979 #else
1980                 * par = this,
1981 #endif
1982                 * ppar = 0,
1983                 * npar = 0;
1984
1985         par->layout = new_layout;
1986         par->labelwidthstring.erase();
1987         par->align = LYX_ALIGN_LAYOUT;
1988         par->added_space_top = VSpace(VSpace::NONE);
1989         par->added_space_bottom = VSpace(VSpace::NONE);
1990         par->spacing.set(Spacing::Default);
1991
1992         if (par->pextra_type == PEXTRA_NONE) {
1993                 if (par->Previous()) {
1994 #ifndef NEW_INSETS
1995                         ppar = par->Previous()->FirstPhysicalPar();
1996 #else
1997                         ppar = par->Previous();
1998 #endif
1999                         while(ppar
2000                               && ppar->Previous()
2001                               && (ppar->depth > par->depth))
2002 #ifndef NEW_INSETS
2003                                 ppar = ppar->Previous()->FirstPhysicalPar();
2004 #else
2005                         ppar = ppar->Previous();
2006 #endif
2007                 }
2008                 if (par->Next()) {
2009 #ifndef NEW_INSETS
2010                         npar = par->Next()->NextAfterFootnote();
2011 #else
2012                         npar = par->Next();
2013 #endif
2014                         while(npar
2015                               && npar->Next()
2016                               && (npar->depth > par->depth))
2017 #ifndef NEW_INSETS
2018                                 npar = npar->Next()->NextAfterFootnote();
2019 #else
2020                         npar = npar->Next();
2021 #endif
2022                 }
2023                 if (ppar && (ppar->pextra_type != PEXTRA_NONE)) {
2024                         string
2025                                 p1 = ppar->pextra_width,
2026                                 p2 = ppar->pextra_widthp;
2027                         ppar->SetPExtraType(bparams, ppar->pextra_type,
2028                                             p1, p2);
2029                 }
2030                 if ((par->pextra_type == PEXTRA_NONE) &&
2031                     npar && (npar->pextra_type != PEXTRA_NONE)) {
2032                         string
2033                                 p1 = npar->pextra_width,
2034                                 p2 = npar->pextra_widthp;
2035                         npar->SetPExtraType(bparams, npar->pextra_type,
2036                                             p1, p2);
2037                 }
2038         }
2039 }
2040
2041
2042 // if the layout of a paragraph contains a manual label, the beginning of the 
2043 // main body is the beginning of the second word. This is what the par-
2044 // function returns. If the layout does not contain a label, the main
2045 // body always starts with position 0. This differentiation is necessary,
2046 // because there cannot be a newline or a blank <= the beginning of the 
2047 // main body in TeX.
2048
2049 int LyXParagraph::BeginningOfMainBody() const
2050 {
2051 #ifndef NEW_INSETS
2052         if (FirstPhysicalPar() != this)
2053                 return -1;
2054 #endif
2055         // Unroll the first two cycles of the loop
2056         // and remember the previous character to
2057         // remove unnecessary GetChar() calls
2058         size_type i = 0;
2059         if (i < size()
2060             && GetChar(i) != LyXParagraph::META_NEWLINE
2061                 ) {
2062                 ++i;
2063                 char previous_char = 0, temp = 0; 
2064                 if (i < size()
2065                     && (previous_char = GetChar(i)) != LyXParagraph::META_NEWLINE) {
2066                         // Yes, this  ^ is supposed to be "= " not "=="
2067                         ++i;
2068                         while (i < size()
2069                                && previous_char != ' '
2070                                && (temp = GetChar(i)) != LyXParagraph::META_NEWLINE) {
2071                                 ++i;
2072                                 previous_char = temp;
2073                         }
2074                 }
2075         }
2076
2077 #ifndef NEW_INSETS
2078         if (i == 0 && i == size() &&
2079             !(footnoteflag == LyXParagraph::NO_FOOTNOTE
2080               && next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE))
2081                 ++i;                           /* the cursor should not jump  
2082                                                 * to the main body if there
2083                                                 * is nothing in! */
2084 #endif
2085         return i;
2086 }
2087
2088
2089 LyXParagraph * LyXParagraph::DepthHook(int deth)
2090 {
2091         LyXParagraph * newpar = this;
2092         if (deth < 0)
2093                 return 0;
2094    
2095         do {
2096 #ifndef NEW_INSETS
2097                 newpar = newpar->FirstPhysicalPar()->Previous();
2098 #else
2099                 newpar = newpar->Previous();
2100 #endif
2101         } while (newpar && newpar->GetDepth() > deth
2102 #ifndef NEW_INSETS
2103                  && newpar->footnoteflag == footnoteflag
2104 #endif
2105                 );
2106    
2107         if (!newpar) {
2108                 if (Previous() || GetDepth())
2109                         lyxerr << "ERROR (LyXParagraph::DepthHook): "
2110                                 "no hook." << endl;
2111                 newpar = this;
2112         }
2113 #ifndef NEW_INSETS
2114         return newpar->FirstPhysicalPar();
2115 #else
2116         return newpar;
2117 #endif
2118 }
2119
2120
2121 LyXParagraph const * LyXParagraph::DepthHook(int deth) const
2122 {
2123         LyXParagraph const * newpar = this;
2124         if (deth < 0)
2125                 return 0;
2126    
2127         do {
2128 #ifndef NEW_INSETS
2129                 newpar = newpar->FirstPhysicalPar()->Previous();
2130 #else
2131                 newpar = newpar->Previous();
2132 #endif
2133         } while (newpar && newpar->GetDepth() > deth
2134 #ifndef NEW_INSETS
2135                  && newpar->footnoteflag == footnoteflag
2136 #endif
2137                 );
2138    
2139         if (!newpar) {
2140                 if (Previous() || GetDepth())
2141                         lyxerr << "ERROR (LyXParagraph::DepthHook): "
2142                                 "no hook." << endl;
2143                 newpar = this;
2144         }
2145 #ifndef NEW_INSETS
2146         return newpar->FirstPhysicalPar();
2147 #else
2148         return newpar;
2149 #endif
2150 }
2151
2152
2153 int LyXParagraph::AutoDeleteInsets()
2154 {
2155         int count = 0;
2156         InsetList::size_type index = 0;
2157         while (index < insetlist.size()) {
2158                 if (insetlist[index].inset && insetlist[index].inset->AutoDelete()) {
2159                         Erase(insetlist[index].pos); 
2160                         // Erase() calls to insetlist.erase(&insetlist[index])
2161                         // so index shouldn't be increased.
2162                         ++count;
2163                 } else
2164                         ++index;
2165         }
2166         return count;
2167 }
2168
2169
2170 LyXParagraph::inset_iterator
2171 LyXParagraph::InsetIterator(LyXParagraph::size_type pos)
2172 {
2173         InsetTable search_inset(pos, 0);
2174         InsetList::iterator it = lower_bound(insetlist.begin(),
2175                                              insetlist.end(),
2176                                              search_inset, matchIT());
2177         return inset_iterator(it);
2178 }
2179
2180
2181 // returns -1 if inset not found
2182 int LyXParagraph::GetPositionOfInset(Inset * inset) const
2183 {
2184         // Find the entry.
2185         for (InsetList::const_iterator cit = insetlist.begin();
2186              cit != insetlist.end(); ++cit) {
2187                 if ((*cit).inset == inset) {
2188                         return (*cit).pos;
2189                 }
2190         }
2191 #ifndef NEW_INSETS
2192         // Think about footnotes.
2193         if (footnoteflag == LyXParagraph::NO_FOOTNOTE 
2194             && next && next->footnoteflag == LyXParagraph::CLOSED_FOOTNOTE) {
2195                 int further = 
2196                         NextAfterFootnote()->GetPositionOfInset(inset);
2197                 if (further != -1)
2198                         return text.size() + 1 + further;
2199         }
2200 #endif
2201         return -1;
2202 }
2203
2204
2205 LyXParagraph * LyXParagraph::TeXOnePar(Buffer const * buf,
2206                                        BufferParams const & bparams,
2207                                        ostream & os, TexRow & texrow,
2208                                        bool moving_arg
2209 #ifndef NEW_INSETS
2210                                        , 
2211                                        ostream & foot,
2212                                        TexRow & foot_texrow,
2213                                        int & foot_count
2214 #endif
2215         )
2216 {
2217         lyxerr[Debug::LATEX] << "TeXOnePar...     " << this << endl;
2218         LyXLayout const & style =
2219                 textclasslist.Style(bparams.textclass,
2220                                     layout);
2221
2222         bool further_blank_line = false;
2223 #ifndef NEW_INSETS
2224         if (IsDummy())
2225                 lyxerr << "ERROR (LyXParagraph::TeXOnePar) is dummy." << endl;
2226 #endif
2227
2228         if (start_of_appendix) {
2229                 os << "\\appendix\n";
2230                 texrow.newline();
2231         }
2232
2233         if (!spacing.isDefault()
2234             && (!Previous() || !Previous()->HasSameLayout(this))) {
2235                 os << spacing.writeEnvirBegin() << "\n";
2236                 texrow.newline();
2237         }
2238         
2239         if (tex_code_break_column && style.isCommand()){
2240                 os << '\n';
2241                 texrow.newline();
2242         }
2243
2244         if (pagebreak_top) {
2245                 os << "\\newpage";
2246                 further_blank_line = true;
2247         }
2248         if (added_space_top.kind() != VSpace::NONE) {
2249                 os << added_space_top.asLatexCommand(bparams);
2250                 further_blank_line = true;
2251         }
2252       
2253         if (line_top) {
2254                 os << "\\lyxline{\\" << getFont(bparams, 0).latexSize() << '}'
2255                    << "\\vspace{-1\\parskip}";
2256                 further_blank_line = true;
2257         }
2258
2259         if (further_blank_line){
2260                 os << '\n';
2261                 texrow.newline();
2262         }
2263
2264         Language const * language = getParLanguage(bparams);
2265         Language const * doc_language = bparams.language;
2266         Language const * previous_language = previous
2267                 ? previous->getParLanguage(bparams) : doc_language;
2268         if (language->babel() != doc_language->babel() &&
2269             language->babel() != previous_language->babel()) {
2270                 os << subst(lyxrc.language_command_begin, "$$lang",
2271                             language->babel())
2272                    << endl;
2273                 texrow.newline();
2274         }
2275
2276         if (bparams.inputenc == "auto" &&
2277             language->encoding() != previous_language->encoding()) {
2278                 os << "\\inputencoding{"
2279                    << language->encoding()->LatexName()
2280                    << "}" << endl;
2281                 texrow.newline();
2282         }
2283         
2284         switch (style.latextype) {
2285         case LATEX_COMMAND:
2286                 os << '\\'
2287                    << style.latexname()
2288                    << style.latexparam();
2289                 break;
2290         case LATEX_ITEM_ENVIRONMENT:
2291                 if (bibkey) {
2292                         bibkey->Latex(buf, os, false, false);
2293                 } else
2294                         os << "\\item ";
2295                 break;
2296         case LATEX_LIST_ENVIRONMENT:
2297                 os << "\\item ";
2298                 break;
2299         default:
2300                 break;
2301         }
2302
2303         bool need_par = SimpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
2304  
2305         LyXParagraph * par = next;
2306 #ifndef NEW_INSETS
2307         // Spit out footnotes
2308         if (lyxrc.rtl_support) {
2309                 if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE
2310                     && next->footnoteflag != footnoteflag) {
2311                         LyXParagraph * p = 0;
2312                         bool is_rtl = (size() > 0) 
2313                                 ? GetFontSettings(bparams,
2314                                                   size()-1).isRightToLeft()
2315                                 : language->RightToLeft();
2316                         if ( (p = NextAfterFootnote()) != 0 &&
2317                              p->size() > 0 &&
2318                              p->GetFontSettings(bparams, 0).isRightToLeft() != is_rtl)
2319                                 is_rtl = getParLanguage(bparams)->RightToLeft();
2320                         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE
2321                                && par->footnoteflag != footnoteflag) {
2322                                 par = par->TeXFootnote(buf, bparams,
2323                                                        os, texrow, foot,
2324                                                        foot_texrow, foot_count,
2325                                                        is_rtl);
2326                                 par->SimpleTeXOnePar(buf, bparams,
2327                                                      os, texrow, moving_arg);
2328                                 is_rtl = (par->size() > 0)
2329                                         ? par->GetFontSettings(bparams,
2330                                                                par->size()-1).isRightToLeft()
2331                                         : language->RightToLeft();
2332                                 if (par->next &&
2333                                     par->next->footnoteflag != LyXParagraph::NO_FOOTNOTE &&
2334                                     (p = par->NextAfterFootnote()) != 0 &&
2335                                     p->size() > 0 &&
2336                                     p->GetFontSettings(bparams, 0).isRightToLeft() != is_rtl)
2337                                         is_rtl = language->RightToLeft();
2338                                 par = par->next;
2339                         }
2340                 }
2341         } else {
2342                 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE
2343                        && par->footnoteflag != footnoteflag) {
2344                         par = par->TeXFootnote(buf, bparams,
2345                                                os, texrow,
2346                                                foot, foot_texrow, foot_count,
2347                                                false);
2348                         par->SimpleTeXOnePar(buf, bparams, os, texrow, moving_arg);
2349                         par = par->next;
2350                 }
2351         }
2352 #endif
2353
2354         // Make sure that \\par is done with the font of the last
2355         // character if this has another size as the default.
2356         // This is necessary because LaTeX (and LyX on the screen)
2357         // calculates the space between the baselines according
2358         // to this font. (Matthias)
2359         LyXFont font = getFont(bparams, Last() - 1);
2360         if (need_par && next) {
2361                 if (style.resfont.size() != font.size()) {
2362                         os << '\\'
2363                            << font.latexSize()
2364                            << ' ';
2365                 }
2366                 os << "\\par}";
2367         } else if (textclasslist.Style(bparams.textclass,
2368                                        GetLayout()).isCommand()) {
2369                 if (style.resfont.size() != font.size()) {
2370                         os << '\\'
2371                            << font.latexSize()
2372                            << ' ';
2373                 }
2374                 os << '}';
2375         } else if ((style.resfont.size() != font.size()) && next){
2376                 os << "{\\" << font.latexSize() << " \\par}";
2377         }
2378
2379         if (language->babel() != doc_language->babel() &&
2380             (!par
2381 #ifndef NEW_INSETS
2382              || (footnoteflag != NO_FOOTNOTE && par->footnoteflag != footnoteflag)
2383 #endif
2384              || par->getParLanguage(bparams)->babel() != language->babel())) {
2385                 os << endl 
2386                    << subst(lyxrc.language_command_end, "$$lang",
2387                             doc_language->babel());
2388         }
2389         
2390         switch (style.latextype) {
2391         case LATEX_ITEM_ENVIRONMENT:
2392         case LATEX_LIST_ENVIRONMENT:
2393                 if (par && (depth < par->depth)) {
2394                         os << '\n';
2395                         texrow.newline();
2396                 }
2397                 break;
2398         case LATEX_ENVIRONMENT:
2399                 // if its the last paragraph of the current environment
2400                 // skip it otherwise fall through
2401                 if (par
2402                     && (par->layout != layout
2403                         || par->depth != depth
2404                         || par->pextra_type != pextra_type))
2405                         break;
2406         default:
2407                 // we don't need it for the last paragraph!!!
2408                 if (next) {
2409                         os << '\n';
2410                         texrow.newline();
2411                 }
2412         }
2413         
2414         further_blank_line = false;
2415         if (line_bottom) {
2416                 os << "\\lyxline{\\" << getFont(bparams, Last() - 1).latexSize() << '}';
2417                 further_blank_line = true;
2418         }
2419
2420         if (added_space_bottom.kind() != VSpace::NONE) {
2421                 os << added_space_bottom.asLatexCommand(bparams);
2422                 further_blank_line = true;
2423         }
2424       
2425         if (pagebreak_bottom) {
2426                 os << "\\newpage";
2427                 further_blank_line = true;
2428         }
2429
2430         if (further_blank_line){
2431                 os << '\n';
2432                 texrow.newline();
2433         }
2434
2435         if (!spacing.isDefault()
2436             && (!par || !par->HasSameLayout(this))) {
2437                 os << spacing.writeEnvirEnd() << "\n";
2438                 texrow.newline();
2439         }
2440         
2441         // we don't need it for the last paragraph!!!
2442         if (next
2443 #ifndef NEW_INSETS
2444             && !(footnoteflag != LyXParagraph::NO_FOOTNOTE && par &&
2445               par->footnoteflag == LyXParagraph::NO_FOOTNOTE)
2446 #endif
2447                 ) {
2448                 os << '\n';
2449                 texrow.newline();
2450         }
2451
2452         lyxerr[Debug::LATEX] << "TeXOnePar...done " << par << endl;
2453         return par;
2454 }
2455
2456
2457 // This one spits out the text of the paragraph
2458 bool LyXParagraph::SimpleTeXOnePar(Buffer const * buf,
2459                                    BufferParams const & bparams,
2460                                    ostream & os, TexRow & texrow,
2461                                    bool moving_arg)
2462 {
2463         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...     " << this << endl;
2464
2465         bool return_value = false;
2466
2467         LyXLayout const & style =
2468                 textclasslist.Style(bparams.textclass,
2469                                     GetLayout());
2470         LyXFont basefont, last_font;
2471
2472         // Maybe we have to create a optional argument.
2473         size_type main_body;
2474         if (style.labeltype != LABEL_MANUAL)
2475                 main_body = 0;
2476         else
2477                 main_body = BeginningOfMainBody();
2478
2479         if (main_body > 0) {
2480                 os << '[';
2481                 basefont = getFont(bparams, -2); // Get label font
2482         } else {
2483                 basefont = getFont(bparams, -1); // Get layout font
2484         }
2485
2486         int column = 0;
2487
2488         if (main_body >= 0
2489             && !text.size()
2490 #ifndef NEW_INSETS
2491             && !IsDummy()
2492 #endif
2493                 ) {
2494                 if (style.isCommand()) {
2495                         os << '{';
2496                         ++column;
2497                 } else if (align != LYX_ALIGN_LAYOUT) {
2498                         os << '{';
2499                         ++column;
2500                         return_value = true;
2501                 }
2502         }
2503
2504         moving_arg |= style.needprotect;
2505  
2506         // Which font is currently active?
2507         LyXFont running_font(basefont);
2508         // Do we have an open font change?
2509         bool open_font = false;
2510
2511         texrow.start(this, 0);
2512
2513         for (size_type i = 0; i < size(); ++i) {
2514                 ++column;
2515                 // First char in paragraph or after label?
2516                 if (i == main_body
2517 #ifndef NEW_INSETS
2518                     && !IsDummy()
2519 #endif
2520                         ) {
2521                         if (main_body > 0) {
2522                                 if (open_font) {
2523                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
2524                                         open_font = false;
2525                                 }
2526                                 basefont = getFont(bparams, -1); // Now use the layout font
2527                                 running_font = basefont;
2528                                 os << ']';
2529                                 ++column;
2530                         }
2531                         if (style.isCommand()) {
2532                                 os << '{';
2533                                 ++column;
2534                         } else if (align != LYX_ALIGN_LAYOUT) {
2535                                 os << "{\\par";
2536                                 column += 4;
2537                                 return_value = true;
2538                         }
2539
2540                         if (noindent) {
2541                                 os << "\\noindent ";
2542                                 column += 10;
2543                         }
2544                         switch (align) {
2545                         case LYX_ALIGN_NONE:
2546                         case LYX_ALIGN_BLOCK:
2547                         case LYX_ALIGN_LAYOUT:
2548                         case LYX_ALIGN_SPECIAL:
2549                                 break;
2550                         case LYX_ALIGN_LEFT:
2551                                 if (getParLanguage(bparams)->babel() != "hebrew") {
2552                                         os << "\\raggedright ";
2553                                         column+= 13;
2554                                 } else {
2555                                         os << "\\raggedleft ";
2556                                         column+= 12;
2557                                 }
2558                                 break;
2559                         case LYX_ALIGN_RIGHT:
2560                                 if (getParLanguage(bparams)->babel() != "hebrew") {
2561                                         os << "\\raggedleft ";
2562                                         column+= 12;
2563                                 } else {
2564                                         os << "\\raggedright ";
2565                                         column+= 13;
2566                                 }
2567                                 break;
2568                         case LYX_ALIGN_CENTER:
2569                                 os << "\\centering ";
2570                                 column+= 11;
2571                                 break;
2572                         }        
2573                 }
2574
2575                 value_type c = GetChar(i);
2576
2577                 // Fully instantiated font
2578                 LyXFont font = getFont(bparams, i);
2579 #ifndef NEW_INSETS
2580                 LyXParagraph * p = 0;
2581                 if (i == 0
2582                     && previous && 
2583                     previous->footnoteflag != LyXParagraph::NO_FOOTNOTE &&
2584                     (p = PreviousBeforeFootnote()) != 0)
2585                         last_font = p->getFont(bparams, p->size() - 1);
2586                 else
2587 #endif
2588                         last_font = running_font;
2589
2590                 // Spaces at end of font change are simulated to be
2591                 // outside font change, i.e. we write "\textXX{text} "
2592                 // rather than "\textXX{text }". (Asger)
2593                 if (open_font && c == ' ' && i <= size() - 2 
2594                     && !getFont(bparams, i + 1).equalExceptLatex(running_font) 
2595                     && !getFont(bparams, i + 1).equalExceptLatex(font)) {
2596                         font = getFont(bparams, i + 1);
2597                 }
2598                 // We end font definition before blanks
2599                 if (!font.equalExceptLatex(running_font) && open_font) {
2600                         column += running_font.latexWriteEndChanges(os,
2601                                                                     basefont,
2602                                                                     (i == main_body-1) ? basefont : font);
2603                         running_font = basefont;
2604                         open_font = false;
2605                 }
2606
2607                 // Blanks are printed before start of fontswitch
2608                 if (c == ' ') {
2609                         // Do not print the separation of the optional argument
2610                         if (i != main_body - 1) {
2611                                 SimpleTeXBlanks(os, texrow, i,
2612                                                 column, font, style);
2613                         }
2614                 }
2615
2616                 // Do we need to change font?
2617                 if (!font.equalExceptLatex(running_font)
2618                     && i != main_body-1) {
2619                         column += font.latexWriteStartChanges(os, basefont,
2620                                                               last_font);
2621                         running_font = font;
2622                         open_font = true;
2623                 }
2624
2625                 if (c == LyXParagraph::META_NEWLINE) {
2626                         // newlines are handled differently here than
2627                         // the default in SimpleTeXSpecialChars().
2628                         if (!style.newline_allowed
2629                             || font.latex() == LyXFont::ON) {
2630                                 os << '\n';
2631                         } else {
2632                                 if (open_font) {
2633                                         column += running_font.latexWriteEndChanges(os, basefont, basefont);
2634                                         open_font = false;
2635                                 }
2636                                 basefont = getFont(bparams, -1);
2637                                 running_font = basefont;
2638                                 if (font.family() == 
2639                                     LyXFont::TYPEWRITER_FAMILY) {
2640                                         os << "~";
2641                                 }
2642                                 if (moving_arg)
2643                                         os << "\\protect ";
2644                                 os << "\\\\\n";
2645                         }
2646                         texrow.newline();
2647                         texrow.start(this, i + 1);
2648                         column = 0;
2649                 } else {
2650                         SimpleTeXSpecialChars(buf, bparams,
2651                                               os, texrow, moving_arg,
2652                                               font, running_font, basefont,
2653                                               open_font, style, i, column, c);
2654                 }
2655         }
2656
2657         // If we have an open font definition, we have to close it
2658         if (open_font) {
2659                 LyXParagraph * p = 0;
2660                 if (next
2661 #ifndef NEW_INSETS
2662                     && next->footnoteflag != LyXParagraph::NO_FOOTNOTE
2663                     && (p =  NextAfterFootnote()) != 0
2664 #else
2665                         && (p = next)
2666 #endif
2667                 )
2668                         running_font.latexWriteEndChanges(os, basefont,
2669                                                           p->getFont(bparams, 0));
2670                 else
2671                         running_font.latexWriteEndChanges(os, basefont, basefont);
2672         }
2673
2674         // Needed if there is an optional argument but no contents.
2675         if (main_body > 0 && main_body == size()) {
2676                 os << "]~";
2677                 return_value = false;
2678         }
2679
2680         lyxerr[Debug::LATEX] << "SimpleTeXOnePar...done " << this << endl;
2681         return return_value;
2682 }
2683
2684
2685 bool LyXParagraph::linuxDocConvertChar(char c, string & sgml_string)
2686 {
2687         bool retval = false;
2688         switch (c) {
2689         case LyXParagraph::META_HFILL:
2690                 sgml_string.erase();
2691                 break;
2692         case LyXParagraph::META_NEWLINE:
2693                 sgml_string = '\n';
2694                 break;
2695         case '&': 
2696                 sgml_string = "&amp;";
2697                 break;
2698         case '<': 
2699                 sgml_string = "&lt;"; 
2700                 break;
2701         case '>':
2702                 sgml_string = "&gt;"; 
2703                 break;
2704         case '$': 
2705                 sgml_string = "&dollar;"; 
2706                 break;
2707         case '#': 
2708                 sgml_string = "&num;";
2709                 break;
2710         case '%': 
2711                 sgml_string = "&percnt;";
2712                 break;
2713         case '[': 
2714                 sgml_string = "&lsqb;";
2715                 break;
2716         case ']': 
2717                 sgml_string = "&rsqb;";
2718                 break;
2719         case '{': 
2720                 sgml_string = "&lcub;";
2721                 break;
2722         case '}': 
2723                 sgml_string = "&rcub;";
2724                 break;
2725         case '~': 
2726                 sgml_string = "&tilde;";
2727                 break;
2728         case '"': 
2729                 sgml_string = "&quot;";
2730                 break;
2731         case '\\': 
2732                 sgml_string = "&bsol;";
2733                 break;
2734         case ' ':
2735                 retval = true;
2736                 sgml_string = ' ';
2737                 break;
2738         case '\0': // Ignore :-)
2739                 sgml_string.erase();
2740                 break;
2741         default:
2742                 sgml_string = c;
2743                 break;
2744         }
2745         return retval;
2746 }
2747
2748
2749 void LyXParagraph::SimpleTeXBlanks(ostream & os, TexRow & texrow,
2750                                    LyXParagraph::size_type const i,
2751                                    int & column, LyXFont const & font,
2752                                    LyXLayout const & style)
2753 {
2754         if (column > tex_code_break_column
2755             && i 
2756             && GetChar(i - 1) != ' '
2757             && (i < size() - 1)
2758             // In LaTeX mode, we don't want to
2759             // break lines since some commands
2760             // do not like this
2761             && ! (font.latex() == LyXFont::ON)
2762             // same in FreeSpacing mode
2763             && !style.free_spacing
2764             // In typewriter mode, we want to avoid 
2765             // ! . ? : at the end of a line
2766             && !(font.family() == LyXFont::TYPEWRITER_FAMILY
2767                  && (GetChar(i-1) == '.'
2768                      || GetChar(i-1) == '?' 
2769                      || GetChar(i-1) == ':'
2770                      || GetChar(i-1) == '!'))) {
2771                 if (tex_code_break_column == 0) {
2772                         // in batchmode we need LaTeX to still
2773                         // see it as a space not as an extra '\n'
2774                         os << " %\n";
2775                 } else {
2776                         os << '\n';
2777                 }
2778                 texrow.newline();
2779                 texrow.start(this, i + 1);
2780                 column = 0;
2781         } else if (font.latex() == LyXFont::OFF) {
2782                 if (style.free_spacing) {
2783                         os << '~';
2784                 } else {
2785                         os << ' ';
2786                 }
2787         }
2788 }
2789
2790
2791 void LyXParagraph::SimpleTeXSpecialChars(Buffer const * buf,
2792                                          BufferParams const & bparams,
2793                                          ostream & os, TexRow & texrow,
2794                                          bool moving_arg,
2795                                          LyXFont & font,
2796                                          LyXFont & running_font,
2797                                          LyXFont & basefont,
2798                                          bool & open_font,
2799                                          LyXLayout const & style,
2800                                          LyXParagraph::size_type & i,
2801                                          int & column,
2802                                          LyXParagraph::value_type const c)
2803 {
2804         // Two major modes:  LaTeX or plain
2805         // Handle here those cases common to both modes
2806         // and then split to handle the two modes separately.
2807         switch (c) {
2808         case LyXParagraph::META_INSET: {
2809                 Inset * inset = GetInset(i);
2810                 if (inset) {
2811                         bool close = false;
2812                         int len = os.tellp();
2813                         if ((inset->LyxCode() == Inset::GRAPHICS_CODE
2814                              || inset->LyxCode() == Inset::MATH_CODE
2815                              || inset->LyxCode() == Inset::URL_CODE)
2816                             && running_font.isRightToLeft()) {
2817                                 os << "\\L{";
2818                                 close = true;
2819                         }
2820
2821                         int tmp = inset->Latex(buf, os, moving_arg,
2822                                                style.free_spacing);
2823
2824                         if (close)
2825                                 os << "}";
2826
2827                         if (tmp) {
2828                                 column = 0;
2829                         } else {
2830                                 column += os.tellp() - len;
2831                         }
2832                         for (; tmp--;) {
2833                                 texrow.newline();
2834                         }
2835                 }
2836         }
2837         break;
2838
2839         case LyXParagraph::META_NEWLINE:
2840                 if (open_font) {
2841                         column += running_font.latexWriteEndChanges(os,
2842                                                                     basefont,
2843                                                                     basefont);
2844                         open_font = false;
2845                 }
2846                 basefont = getFont(bparams, -1);
2847                 running_font = basefont;
2848                 break;
2849
2850         case LyXParagraph::META_HFILL: 
2851                 os << "\\hfill{}";
2852                 column += 7;
2853                 break;
2854
2855         default:
2856                 // And now for the special cases within each mode
2857                 // Are we in LaTeX mode?
2858                 if (font.latex() == LyXFont::ON) {
2859                         // at present we only have one option
2860                         // but I'll leave it as a switch statement
2861                         // so its simpler to extend. (ARRae)
2862                         switch (c) {
2863                         default:
2864                                 // make sure that we will not print
2865                                 // error generating chars to the tex
2866                                 // file. This test would not be needed
2867                                 // if it were done in the buffer
2868                                 // itself.
2869                                 if (c != '\0') {
2870                                         os << c;
2871                                 }
2872                                 break;
2873                         }
2874                 } else {
2875                         // Plain mode (i.e. not LaTeX)
2876                         switch (c) {
2877                         case '\\': 
2878                                 os << "\\textbackslash{}";
2879                                 column += 15;
2880                                 break;
2881                 
2882                         case '°': case '±': case '²': case '³':  
2883                         case '×': case '÷': case '¹': case 'ª':
2884                         case 'º': case '¬': case 'µ':
2885                                 if (bparams.inputenc == "latin1" ||
2886                                     (bparams.inputenc == "auto" &&
2887                                      font.language()->encoding()->LatexName()
2888                                      == "latin1")) {
2889                                         os << "\\ensuremath{"
2890                                            << c
2891                                            << '}';
2892                                         column += 13;
2893                                 } else {
2894                                         os << c;
2895                                 }
2896                                 break;
2897
2898                         case '|': case '<': case '>':
2899                                 // In T1 encoding, these characters exist
2900                                 if (lyxrc.fontenc == "T1") {
2901                                         os << c;
2902                                         //... but we should avoid ligatures
2903                                         if ((c == '>' || c == '<')
2904                                             && i <= size() - 2
2905                                             && GetChar(i + 1) == c) {
2906                                                 //os << "\\textcompwordmark{}";
2907                                                 // Jean-Marc, have a look at
2908                                                 // this. I think this works
2909                                                 // equally well:
2910                                                 os << "\\,{}";
2911                                                 // Lgb
2912                                                 column += 19;
2913                                         }
2914                                         break;
2915                                 }
2916                                 // Typewriter font also has them
2917                                 if (font.family() == LyXFont::TYPEWRITER_FAMILY) {
2918                                         os << c;
2919                                         break;
2920                                 } 
2921                                 // Otherwise, we use what LaTeX
2922                                 // provides us.
2923                                 switch(c) {
2924                                 case '<':
2925                                         os << "\\textless{}";
2926                                         column += 10;
2927                                         break;
2928                                 case '>':
2929                                         os << "\\textgreater{}";
2930                                         column += 13;
2931                                         break;
2932                                 case '|':
2933                                         os << "\\textbar{}";
2934                                         column += 9;
2935                                         break;
2936                                 }
2937                                 break;
2938
2939                         case '-': // "--" in Typewriter mode -> "-{}-"
2940                                 if (i <= size() - 2
2941                                     && GetChar(i + 1) == '-'
2942                                     && font.family() == LyXFont::TYPEWRITER_FAMILY) {
2943                                         os << "-{}";
2944                                         column += 2;
2945                                 } else {
2946                                         os << '-';
2947                                 }
2948                                 break;
2949
2950                         case '\"': 
2951                                 os << "\\char`\\\"{}";
2952                                 column += 9;
2953                                 break;
2954
2955                         case '£':
2956                                 if (bparams.inputenc == "default") {
2957                                         os << "\\pounds{}";
2958                                         column += 8;
2959                                 } else {
2960                                         os << c;
2961                                 }
2962                                 break;
2963
2964                         case '$': case '&':
2965                         case '%': case '#': case '{':
2966                         case '}': case '_':
2967                                 os << '\\' << c;
2968                                 column += 1;
2969                                 break;
2970
2971                         case '~':
2972                                 os << "\\textasciitilde{}";
2973                                 column += 16;
2974                                 break;
2975
2976                         case '^':
2977                                 os << "\\textasciicircum{}";
2978                                 column += 17;
2979                                 break;
2980
2981                         case '*': case '[': case ']':
2982                                 // avoid being mistaken for optional arguments
2983                                 os << '{' << c << '}';
2984                                 column += 2;
2985                                 break;
2986
2987                         case ' ':
2988                                 // Blanks are printed before font switching.
2989                                 // Sure? I am not! (try nice-latex)
2990                                 // I am sure it's correct. LyX might be smarter
2991                                 // in the future, but for now, nothing wrong is
2992                                 // written. (Asger)
2993                                 break;
2994
2995                         default:
2996                                 /* idea for labels --- begin*/
2997                                 // Check for "LyX"
2998                                 if (c ==  'L'
2999                                     && i <= size() - 3
3000                                     && font.family() != LyXFont::TYPEWRITER_FAMILY
3001                                     && GetChar(i + 1) == 'y'
3002                                     && GetChar(i + 2) == 'X') {
3003                                         os << "\\LyX{}";
3004                                         i += 2;
3005                                         column += 5;
3006                                 }
3007                                 // Check for "TeX"
3008                                 else if (c == 'T'
3009                                          && i <= size() - 3
3010                                          && font.family() != LyXFont::TYPEWRITER_FAMILY
3011                                          && GetChar(i + 1) == 'e'
3012                                          && GetChar(i + 2) == 'X') {
3013                                         os << "\\TeX{}";
3014                                         i += 2;
3015                                         column += 5;
3016                                 }
3017                                 // Check for "LaTeX2e"
3018                                 else if (c == 'L'
3019                                          && i <= size() - 7
3020                                          && font.family() != LyXFont::TYPEWRITER_FAMILY
3021                                          && GetChar(i + 1) == 'a'
3022                                          && GetChar(i + 2) == 'T'
3023                                          && GetChar(i + 3) == 'e'
3024                                          && GetChar(i + 4) == 'X'
3025                                          && GetChar(i + 5) == '2'
3026                                          && GetChar(i + 6) == 'e') {
3027                                         os << "\\LaTeXe{}";
3028                                         i += 6;
3029                                         column += 8;
3030                                 }
3031                                 // Check for "LaTeX"
3032                                 else if (c == 'L'
3033                                          && i <= size() - 5
3034                                          && font.family() != LyXFont::TYPEWRITER_FAMILY
3035                                          && GetChar(i + 1) == 'a'
3036                                          && GetChar(i + 2) == 'T'
3037                                          && GetChar(i + 3) == 'e'
3038                                          && GetChar(i + 4) == 'X') {
3039                                         os << "\\LaTeX{}";
3040                                         i += 4;
3041                                         column += 7;
3042                                         /* idea for labels --- end*/ 
3043                                 } else if (c != '\0') {
3044                                         os << c;
3045                                 }
3046                                 break;
3047                         }
3048                 }
3049         }
3050 }
3051
3052
3053 LyXParagraph * LyXParagraph::TeXDeeper(Buffer const * buf,
3054                                        BufferParams const & bparams,
3055                                        ostream & os, TexRow & texrow
3056 #ifndef NEW_INSETS
3057                                        ,ostream & foot,
3058                                        TexRow & foot_texrow,
3059                                        int & foot_count
3060 #endif
3061         )
3062 {
3063         lyxerr[Debug::LATEX] << "TeXDeeper...     " << this << endl;
3064         LyXParagraph * par = this;
3065
3066         while (par &&
3067                (par->depth == depth)
3068 #ifndef NEW_INSETS
3069                && (par->footnoteflag == footnoteflag)
3070 #endif
3071                 ) {
3072 #ifndef NEW_INSETS
3073                 if (par->IsDummy())
3074                         lyxerr << "ERROR (LyXParagraph::TeXDeeper)" << endl;
3075 #endif
3076                 if (textclasslist.Style(bparams.textclass, 
3077                                         par->layout).isEnvironment()
3078                     || par->pextra_type != PEXTRA_NONE) {
3079                         par = par->TeXEnvironment(buf, bparams,
3080                                                   os, texrow
3081 #ifndef NEW_INSETS
3082                                                   ,foot, foot_texrow,
3083                                                   foot_count
3084 #endif
3085                                 );
3086                 } else {
3087                         par = par->TeXOnePar(buf, bparams,
3088                                              os, texrow, false
3089 #ifndef NEW_INSETS
3090                                              ,
3091                                              foot, foot_texrow,
3092                                              foot_count
3093 #endif
3094                                 );
3095                 }
3096         }
3097         lyxerr[Debug::LATEX] << "TeXDeeper...done " << par << endl;
3098
3099         return par;
3100 }
3101
3102
3103 LyXParagraph * LyXParagraph::TeXEnvironment(Buffer const * buf,
3104                                             BufferParams const & bparams,
3105                                             ostream & os, TexRow & texrow
3106 #ifndef NEW_INSETS
3107                                             ,ostream & foot,
3108                                             TexRow & foot_texrow,
3109                                             int & foot_count
3110 #endif
3111         )
3112 {
3113         bool eindent_open = false;
3114 #ifndef NEW_INSETS
3115         bool foot_this_level = false;
3116 #endif
3117         // flags when footnotetext should be appended to file.
3118         static bool minipage_open = false;
3119         static int minipage_open_depth = 0;
3120         char par_sep = bparams.paragraph_separation;
3121     
3122         lyxerr[Debug::LATEX] << "TeXEnvironment...     " << this << endl;
3123 #ifndef NEW_INSETS
3124         if (IsDummy())
3125                 lyxerr << "ERROR (LyXParagraph::TeXEnvironment)" << endl;
3126 #endif
3127
3128         LyXLayout const & style =
3129                 textclasslist.Style(bparams.textclass,
3130                                     layout);
3131        
3132         if (pextra_type == PEXTRA_INDENT) {
3133                 if (!pextra_width.empty()) {
3134                         os << "\\begin{LyXParagraphIndent}{"
3135                            << pextra_width << "}\n";
3136                 } else {
3137                         //float ib = atof(pextra_widthp.c_str())/100;
3138                         // string can't handle floats at present (971109)
3139                         // so I'll do a conversion by hand knowing that
3140                         // the limits are 0.0 to 1.0. ARRae.
3141                         os << "\\begin{LyXParagraphIndent}{";
3142                         switch (pextra_widthp.length()) {
3143                         case 3:
3144                                 os << "1.00";
3145                                 break;
3146                         case 2:
3147                                 os << "0."
3148                                    << pextra_widthp;
3149                                 break;
3150                         case 1:
3151                                 os << "0.0"
3152                                    << pextra_widthp;
3153                         }
3154                         os << "\\columnwidth}\n";
3155                 }
3156                 texrow.newline();
3157                 eindent_open = true;
3158         }
3159         if ((pextra_type == PEXTRA_MINIPAGE) && !minipage_open) {
3160                 if (pextra_hfill && Previous() &&
3161                     (Previous()->pextra_type == PEXTRA_MINIPAGE)) {
3162                         os << "\\hfill{}\n";
3163                         texrow.newline();
3164                 }
3165                 if (par_sep == BufferParams::PARSEP_INDENT) {
3166                         os << "{\\setlength\\parindent{0pt}\n";
3167                         texrow.newline();
3168                 }
3169                 os << "\\begin{minipage}";
3170                 switch(pextra_alignment) {
3171                 case MINIPAGE_ALIGN_TOP:
3172                         os << "[t]";
3173                         break;
3174                 case MINIPAGE_ALIGN_MIDDLE:
3175                         os << "[m]";
3176                         break;
3177                 case MINIPAGE_ALIGN_BOTTOM:
3178                         os << "[b]";
3179                         break;
3180                 }
3181                 if (!pextra_width.empty()) {
3182                         os << '{' << pextra_width << "}\n";
3183                 } else {
3184                         //float ib = atof(par->pextra_width.c_str())/100;
3185                         // string can't handle floats at present
3186                         // so I'll do a conversion by hand knowing that
3187                         // the limits are 0.0 to 1.0. ARRae.
3188                         os << '{';
3189                         switch (pextra_widthp.length()) {
3190                         case 3:
3191                                 os << "1.00";
3192                                 break;
3193                         case 2:
3194                                 os << "0."
3195                                    << pextra_widthp;
3196                                 break;
3197                         case 1:
3198                                 os << "0.0"
3199                                    << pextra_widthp;
3200                         }
3201                         os << "\\columnwidth}\n";
3202                 }
3203                 texrow.newline();
3204                 if (par_sep == BufferParams::PARSEP_INDENT) {
3205                         os << "\\setlength\\parindent{\\LyXMinipageIndent}\n";
3206                         texrow.newline();
3207                 }
3208                 minipage_open = true;
3209                 minipage_open_depth = depth;
3210         }
3211
3212 #ifdef WITH_WARNINGS
3213 #warning Define FANCY_FOOTNOTE_CODE to re-enable Allan footnote code
3214         //I disabled it because it breaks when lists span on several
3215         //pages (JMarc)
3216 #endif
3217         if (style.isEnvironment()){
3218                 if (style.latextype == LATEX_LIST_ENVIRONMENT) {
3219 #ifdef FANCY_FOOTNOTE_CODE
3220                         if (foot_count < 0) {
3221                                 // flag that footnote[mark][text] should be
3222                                 // used for any footnotes from now on
3223                                 foot_count = 0;
3224                                 foot_this_level = true;
3225                         }
3226 #endif
3227                         os << "\\begin{" << style.latexname() << "}{"
3228                            << labelwidthstring << "}\n";
3229                 } else if (style.labeltype == LABEL_BIBLIO) {
3230                         // ale970405
3231                         os << "\\begin{" << style.latexname() << "}{"
3232                            <<  bibitemWidest(buf)
3233                            << "}\n";
3234                 } else if (style.latextype == LATEX_ITEM_ENVIRONMENT) {
3235 #ifdef FANCY_FOOTNOTE_CODE
3236                         if (foot_count < 0) {
3237                                 // flag that footnote[mark][text] should be
3238                                 // used for any footnotes from now on
3239                                 foot_count = 0;
3240                                 foot_this_level = true;
3241                         }
3242 #endif
3243                         os << "\\begin{" << style.latexname() << '}'
3244                            << style.latexparam() << '\n';
3245                 } else 
3246                         os << "\\begin{" << style.latexname() << '}'
3247                            << style.latexparam() << '\n';
3248                 texrow.newline();
3249         }
3250         LyXParagraph * par = this;
3251         do {
3252                 par = par->TeXOnePar(buf, bparams,
3253                                      os, texrow, false
3254 #ifndef NEW_INSETS
3255                                      ,
3256                                      foot, foot_texrow, foot_count
3257 #endif
3258                         );
3259
3260                 if (minipage_open && par && !style.isEnvironment() &&
3261                     (par->pextra_type == PEXTRA_MINIPAGE) &&
3262                     par->pextra_start_minipage) {
3263                         os << "\\end{minipage}\n";
3264                         texrow.newline();
3265                         if (par_sep == BufferParams::PARSEP_INDENT) {
3266                                 os << "}\n";
3267                                 texrow.newline();
3268                         }
3269                         minipage_open = false;
3270                 }
3271                 if (par && par->depth > depth) {
3272                         if (textclasslist.Style(bparams.textclass,
3273                                                 par->layout).isParagraph()
3274                             // Thinko!
3275                             // How to handle this? (Lgb)
3276                             //&& !suffixIs(os, "\n\n")
3277                                 ) {
3278                                 // There should be at least one '\n' already
3279                                 // but we need there to be two for Standard 
3280                                 // paragraphs that are depth-increment'ed to be
3281                                 // output correctly.  However, tables can
3282                                 // also be paragraphs so don't adjust them.
3283                                 // ARRae
3284                                 // Thinkee:
3285                                 // Will it ever harm to have one '\n' too
3286                                 // many? i.e. that we sometimes will have
3287                                 // three in a row. (Lgb)
3288                                 os << '\n';
3289                                 texrow.newline();
3290                         }
3291                         par = par->TeXDeeper(buf, bparams, os, texrow
3292 #ifndef NEW_INSETS
3293                                              ,foot, foot_texrow, foot_count
3294 #endif
3295                                 );
3296                 }
3297                 if (par && par->layout == layout && par->depth == depth &&
3298                     (par->pextra_type == PEXTRA_MINIPAGE) && !minipage_open) {
3299                         if (par->pextra_hfill && par->Previous() &&
3300                             (par->Previous()->pextra_type == PEXTRA_MINIPAGE)){
3301                                 os << "\\hfill{}\n";
3302                                 texrow.newline();
3303                         }
3304                         if (par_sep == BufferParams::PARSEP_INDENT) {
3305                                 os << "{\\setlength\\parindent{0pt}\n";
3306                                 texrow.newline();
3307                         }
3308                         os << "\\begin{minipage}";
3309                         switch(par->pextra_alignment) {
3310                         case MINIPAGE_ALIGN_TOP:
3311                                 os << "[t]";
3312                                 break;
3313                         case MINIPAGE_ALIGN_MIDDLE:
3314                                 os << "[m]";
3315                                 break;
3316                         case MINIPAGE_ALIGN_BOTTOM:
3317                                 os << "[b]";
3318                                 break;
3319                         }
3320                         if (!par->pextra_width.empty()) {
3321                                 os << '{' << par->pextra_width << "}\n";
3322                         } else {
3323                                 //float ib = atof(par->pextra_widthp.c_str())/100;
3324                                 // string can't handle floats at present
3325                                 // so I'll do a conversion by hand knowing that
3326                                 // the limits are 0.0 to 1.0. ARRae.
3327                                 os << '{';
3328                                 switch (par->pextra_widthp.length()) {
3329                                 case 3:
3330                                         os << "1.00";
3331                                         break;
3332                                 case 2:
3333                                         os << "0." << par->pextra_widthp;
3334                                         break;
3335                                 case 1:
3336                                         os << "0.0" << par->pextra_widthp;
3337                                 }
3338                                 os << "\\columnwidth}\n";
3339                         }
3340                         texrow.newline();
3341                         if (par_sep == BufferParams::PARSEP_INDENT) {
3342                                 os << "\\setlength\\parindent{\\LyXMinipageIndent}\n";
3343                                 texrow.newline();
3344                         }
3345                         minipage_open = true;
3346                         minipage_open_depth = par->depth;
3347                 }
3348         } while (par
3349                  && par->layout == layout
3350                  && par->depth == depth
3351                  && par->pextra_type == pextra_type
3352 #ifndef NEW_INSETS
3353                  && par->footnoteflag == footnoteflag
3354 #endif
3355                 );
3356  
3357         if (style.isEnvironment()) {
3358                 os << "\\end{" << style.latexname() << '}';
3359 #ifndef NEW_INSETS
3360                 // maybe this should go after the minipage closes?
3361                 if (foot_this_level) {
3362                         if (foot_count >= 1) {
3363                                 if (foot_count > 1) {
3364                                         os << "\\addtocounter{footnote}{-"
3365                                            << foot_count - 1
3366                                            << '}';
3367                                 }
3368                                 os << foot;
3369                                 texrow += foot_texrow;
3370                                 foot.clear();
3371                                 foot_texrow.reset();
3372                                 foot_count = 0;
3373                         }
3374                 }
3375 #endif
3376         }
3377         if (minipage_open && (minipage_open_depth == depth) &&
3378             (!par || par->pextra_start_minipage ||
3379              par->pextra_type != PEXTRA_MINIPAGE)) {
3380                 os << "\\end{minipage}\n";
3381                 texrow.newline();
3382                 if (par_sep == BufferParams::PARSEP_INDENT) {
3383                         os << "}\n";
3384                         texrow.newline();
3385                 }
3386                 if (par && par->pextra_type != PEXTRA_MINIPAGE) {
3387                         os << "\\medskip\n\n";
3388                         texrow.newline();
3389                         texrow.newline();
3390                 }
3391                 minipage_open = false;
3392         }
3393         if (eindent_open) {
3394                 os << "\\end{LyXParagraphIndent}\n";
3395                 texrow.newline();
3396         }
3397         if (!(par && (par->pextra_type == PEXTRA_MINIPAGE) 
3398               && par->pextra_hfill)) {
3399                 os << '\n';
3400                 texrow.newline();
3401         }
3402         lyxerr[Debug::LATEX] << "TeXEnvironment...done " << par << endl;
3403         return par;  // ale970302
3404 }
3405
3406
3407 #ifndef NEW_INSETS
3408 LyXParagraph * LyXParagraph::TeXFootnote(Buffer const * buf,
3409                                          BufferParams const & bparams,
3410                                          ostream & os, TexRow & texrow,
3411                                          ostream & foot, TexRow & foot_texrow,
3412                                          int & foot_count,
3413                                          bool parent_is_rtl)
3414 {
3415         lyxerr[Debug::LATEX] << "TeXFootnote...  " << this << endl;
3416         if (footnoteflag == LyXParagraph::NO_FOOTNOTE)
3417                 lyxerr << "ERROR (LyXParagraph::TeXFootnote): "
3418                         "No footnote!" << endl;
3419
3420         LyXParagraph * par = this;
3421         LyXLayout const & style =
3422                 textclasslist.Style(bparams.textclass, 
3423                                     previous->GetLayout());
3424         
3425         if (style.needprotect && footnotekind != LyXParagraph::FOOTNOTE){
3426                 lyxerr << "ERROR (LyXParagraph::TeXFootnote): "
3427                         "Float other than footnote in command"
3428                         " with moving argument is illegal" << endl;
3429         }
3430
3431         if (footnotekind != LyXParagraph::FOOTNOTE
3432             && footnotekind != LyXParagraph::MARGIN
3433             && os.tellp()
3434             // Thinko
3435             // How to solve this?
3436             //&& !suffixIs(file, '\n')
3437                 ) {
3438                 // we need to ensure that real floats like tables and figures
3439                 // have their \begin{} on a new line otherwise we can get
3440                 // incorrect results when using the endfloat.sty package
3441                 // especially if two floats follow one another.  ARRae 981022
3442                 // NOTE: if the file is length 0 it must have just been
3443                 //       written out so we assume it ended with a '\n'
3444                 // Thinkee:
3445                 // As far as I can see there is never any harm in writing
3446                 // a '\n' too much. Please tell me if I am wrong. (Lgb)
3447                 os << '\n';
3448                 texrow.newline();
3449         }
3450
3451         bool moving_arg = false;
3452         bool need_closing = false;
3453         bool is_rtl = isRightToLeftPar(bparams);
3454
3455         if (is_rtl != parent_is_rtl) {
3456                 if (is_rtl)
3457                         os << "\\R{";
3458                 else
3459                         os << "\\L{";
3460                 need_closing = true;
3461         }
3462         
3463         bool footer_in_body = true;
3464         switch (footnotekind) {
3465         case LyXParagraph::FOOTNOTE:
3466                 if (style.intitle) {
3467                         os << "\\thanks{\n";
3468                         footer_in_body = false;
3469                         moving_arg = true;
3470                 } else {
3471                         if (foot_count == -1) {
3472                                 // we're at depth 0 so we can use:
3473                                 os << "\\footnote{%\n";
3474                                 footer_in_body = false;
3475                         } else {
3476                                 os << "\\footnotemark{}%\n";
3477                                 if (foot_count) {
3478                                         // we only need this when there are
3479                                         // multiple footnotes
3480                                         os << "\\stepcounter{footnote}";
3481                                 }
3482                                 os << "\\footnotetext{%\n";
3483                                 foot_texrow.start(this, 0);
3484                                 foot_texrow.newline();
3485                                 ++foot_count;
3486                         }
3487                 }
3488                 break;
3489         case LyXParagraph::MARGIN:
3490                 os << "\\marginpar{\n";
3491                 break;
3492         case LyXParagraph::FIG:
3493                 if (pextra_type == PEXTRA_FLOATFLT
3494                     && (!pextra_width.empty()
3495                         || !pextra_widthp.empty())) {
3496                         if (!pextra_width.empty())
3497                                 os << "\\begin{floatingfigure}{"
3498                                    << pextra_width << "}\n";
3499                         else
3500                                 os << "\\begin{floatingfigure}{"
3501                                    << lyx::atoi(pextra_widthp) / 100.0
3502                                    << "\\textwidth}\n";
3503                 } else {
3504                         os << "\\begin{figure}";
3505                         if (!bparams.float_placement.empty()) { 
3506                                 os << '[' << bparams.float_placement << "]\n";
3507                         } else {
3508                                 os << '\n';
3509                         }
3510                 }
3511                 break;
3512         case LyXParagraph::TAB:
3513                 os << "\\begin{table}";
3514                 if (!bparams.float_placement.empty()) { 
3515                         os << '[' << bparams.float_placement << "]\n";
3516                 } else {
3517                         os << '\n';
3518                 }
3519                 break;
3520         case LyXParagraph::WIDE_FIG:
3521                 os << "\\begin{figure*}";
3522                 if (!bparams.float_placement.empty()) { 
3523                         os << '[' << bparams.float_placement << "]\n";
3524                 } else {
3525                         os << '\n';
3526                 }
3527                 break;
3528         case LyXParagraph::WIDE_TAB:
3529                 os << "\\begin{table*}";
3530                 if (!bparams.float_placement.empty()) { 
3531                         os << '[' << bparams.float_placement << "]\n";
3532                 } else {
3533                         os << '\n';
3534                 }
3535                 break;
3536         case LyXParagraph::ALGORITHM:
3537                 os << "\\begin{algorithm}\n";
3538                 break;
3539         }
3540         texrow.newline();
3541    
3542         if (footnotekind != LyXParagraph::FOOTNOTE
3543             || !footer_in_body) {
3544                 // Process text for all floats except footnotes in body
3545                 do {
3546                         LyXLayout const & style =
3547                                 textclasslist
3548                                 .Style(bparams.textclass, par->layout);
3549                         if (par->IsDummy())
3550                                 lyxerr << "ERROR (LyXParagraph::TeXFootnote)"
3551                                        << endl;
3552                         if (style.isEnvironment()
3553                             || par->pextra_type == PEXTRA_MINIPAGE) { /* && !minipage_open ?? */
3554                                 // Allows the use of minipages within float
3555                                 // environments. Shouldn't be circular because
3556                                 // we don't support footnotes inside
3557                                 // floats (yet). ARRae
3558                                 par = par->TeXEnvironment(buf, bparams, os,
3559                                                           texrow,
3560                                                           foot, foot_texrow,
3561                                                           foot_count);
3562                         } else {
3563                                 par = par->TeXOnePar(buf, bparams,
3564                                                      os, texrow, moving_arg,
3565                                                      foot, foot_texrow,
3566                                                      foot_count);
3567                         }
3568                         
3569                         if (par && !par->IsDummy() && par->depth > depth) {
3570                                 par = par->TeXDeeper(buf, bparams, os, texrow,
3571                                                      foot, foot_texrow,
3572                                                      foot_count);
3573                         }
3574                 } while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE);
3575         } else {
3576                 // process footnotes > depth 0 or in environments separately
3577                 // NOTE: Currently don't support footnotes within footnotes
3578                 //       even though that is possible using the \footnotemark
3579                 std::ostringstream dummy;
3580                 TexRow dummy_texrow;
3581                 int dummy_count = 0;
3582                 do {
3583                         LyXLayout const & style =
3584                                 textclasslist
3585                                 .Style(bparams.textclass, par->layout);
3586                         if (par->IsDummy())
3587                                 lyxerr << "ERROR (LyXParagraph::TeXFootnote)"
3588                                        << endl;
3589                         if (style.isEnvironment()
3590                             || par->pextra_type == PEXTRA_MINIPAGE) { /* && !minipage_open ?? */
3591                                 // Allows the use of minipages within float
3592                                 // environments. Shouldn't be circular because
3593                                 // we don't support footnotes inside
3594                                 // floats (yet). ARRae
3595                                 par = par->TeXEnvironment(buf, bparams,
3596                                                           foot, foot_texrow,
3597                                                           dummy, dummy_texrow,
3598                                                           dummy_count);
3599                         } else {
3600                                 par = par->TeXOnePar(buf, bparams,
3601                                                      foot, foot_texrow,
3602                                                      moving_arg,
3603                                                      dummy, dummy_texrow,
3604                                                      dummy_count);
3605                         }
3606
3607                         if (par && !par->IsDummy() && par->depth > depth) {
3608                                 par = par->TeXDeeper(buf, bparams,
3609                                                      foot, foot_texrow,
3610                                                      dummy, dummy_texrow,
3611                                                      dummy_count);
3612                         }
3613                 } while (par
3614                          && par->footnoteflag != LyXParagraph::NO_FOOTNOTE);
3615                 if (dummy_count) {
3616                         lyxerr << "ERROR (LyXParagraph::TeXFootnote): "
3617                                 "Footnote in a Footnote -- not supported"
3618                                << endl;
3619                 }
3620 //#ifndef HAVE_OSTREAM
3621 //              delete [] dummy.str();
3622 //#endif
3623         }
3624
3625         switch (footnotekind) {
3626         case LyXParagraph::FOOTNOTE:
3627                 if (footer_in_body) {
3628                         // This helps tell which of the multiple
3629                         // footnotetexts an error was in.
3630                         foot << "}%\n";
3631                         foot_texrow.newline();
3632                 } else {
3633                         os << '}';
3634                 }
3635                 break;
3636         case LyXParagraph::MARGIN:
3637                 os << '}';
3638                 break;
3639         case LyXParagraph::FIG:
3640                 if (pextra_type == PEXTRA_FLOATFLT
3641                     && (!pextra_width.empty()
3642                         || !pextra_widthp.empty()))
3643                         os << "\\end{floatingfigure}";
3644                 else
3645                         os << "\\end{figure}";
3646                 break;
3647         case LyXParagraph::TAB:
3648                 os << "\\end{table}";
3649                 break;
3650         case LyXParagraph::WIDE_FIG:
3651                 os << "\\end{figure*}";
3652                 break;
3653         case LyXParagraph::WIDE_TAB:
3654                 os << "\\end{table*}";
3655                 break;
3656         case LyXParagraph::ALGORITHM:
3657                 os << "\\end{algorithm}";
3658                 break;
3659         }
3660
3661         if (need_closing)
3662                 os << "}";
3663
3664         if (footnotekind != LyXParagraph::FOOTNOTE
3665             && footnotekind != LyXParagraph::MARGIN) {
3666                 // we need to ensure that real floats like tables and figures
3667                 // have their \end{} on a line of their own otherwise we can
3668                 // get incorrect results when using the endfloat.sty package.
3669                 os << "\n";
3670                 texrow.newline();
3671         }
3672
3673         lyxerr[Debug::LATEX] << "TeXFootnote...done " << par->next << endl;
3674         return par;
3675 }
3676
3677
3678 bool LyXParagraph::IsDummy() const
3679 {
3680         return (footnoteflag == LyXParagraph::NO_FOOTNOTE && previous
3681                 && previous->footnoteflag != LyXParagraph::NO_FOOTNOTE);
3682 }
3683 #endif
3684
3685 void LyXParagraph::SetPExtraType(BufferParams const & bparams,
3686                                  int type, string const & width,
3687                                  string const & widthp)
3688 {
3689         pextra_type = type;
3690         pextra_width = width;
3691         pextra_widthp = widthp;
3692
3693         if (textclasslist.Style(bparams.textclass, 
3694                                 layout).isEnvironment()) {
3695                 LyXParagraph * par = this;
3696                 LyXParagraph * ppar = par;
3697
3698                 while (par && (par->layout == layout)
3699                        && (par->depth == depth)) {
3700                         ppar = par;
3701                         par = par->Previous();
3702 #ifndef NEW_INSETS
3703                         if (par)
3704                                 par = par->FirstPhysicalPar();
3705 #endif
3706                         while (par && par->depth > depth) {
3707                                 par = par->Previous();
3708 #ifndef NEW_INSETS
3709                                 if (par)
3710                                         par = par->FirstPhysicalPar();
3711 #endif
3712                         }
3713                 }
3714                 par = ppar;
3715                 while (par && (par->layout == layout)
3716                        && (par->depth == depth)) {
3717                         par->pextra_type = type;
3718                         par->pextra_width = width;
3719                         par->pextra_widthp = widthp;
3720 #ifndef NEW_INSETS
3721                         par = par->NextAfterFootnote();
3722 #else
3723                         par = par->Next();
3724 #endif
3725                         if (par && (par->depth > depth))
3726                                 par->SetPExtraType(bparams,
3727                                                    type, width, widthp);
3728 #ifndef NEW_INSETS
3729                         while (par && ((par->depth > depth) || par->IsDummy()))
3730                                 par = par->NextAfterFootnote();
3731 #else
3732                         while (par && ((par->depth > depth)))
3733                                 par = par->Next();
3734 #endif
3735                 }
3736         }
3737 }
3738
3739
3740 void LyXParagraph::UnsetPExtraType(BufferParams const & bparams)
3741 {
3742         if (pextra_type == PEXTRA_NONE)
3743                 return;
3744     
3745         pextra_type = PEXTRA_NONE;
3746         pextra_width.erase();
3747         pextra_widthp.erase();
3748
3749         if (textclasslist.Style(bparams.textclass, 
3750                                 layout).isEnvironment()) {
3751                 LyXParagraph * par = this;
3752                 LyXParagraph * ppar = par;
3753
3754                 while (par && (par->layout == layout)
3755                        && (par->depth == depth)) {
3756                         ppar = par;
3757                         par = par->Previous();
3758 #ifndef NEW_INSETS
3759                         if (par)
3760                                 par = par->FirstPhysicalPar();
3761 #endif
3762                         while (par && par->depth > depth) {
3763                                 par = par->Previous();
3764 #ifndef NEW_INSETS
3765                                 if (par)
3766                                         par = par->FirstPhysicalPar();
3767 #endif
3768                         }
3769                 }
3770                 par = ppar;
3771                 while (par && (par->layout == layout)
3772                        && (par->depth == depth)) {
3773                         par->pextra_type = PEXTRA_NONE;
3774                         par->pextra_width.erase();
3775                         par->pextra_widthp.erase();
3776 #ifndef NEW_INSETS
3777                         par = par->NextAfterFootnote();
3778 #else
3779                         par = par->Next();
3780 #endif
3781                         if (par && (par->depth > depth))
3782                                 par->UnsetPExtraType(bparams);
3783 #ifndef NEW_INSETS
3784                         while (par && ((par->depth > depth) || par->IsDummy()))
3785                                 par = par->NextAfterFootnote();
3786 #else
3787                         while (par && ((par->depth > depth)))
3788                                 par = par->Next();
3789 #endif
3790                 }
3791         }
3792 }
3793
3794
3795 bool LyXParagraph::IsHfill(size_type pos) const
3796 {
3797         return IsHfillChar(GetChar(pos));
3798 }
3799
3800
3801 bool LyXParagraph::IsInset(size_type pos) const
3802 {
3803         return IsInsetChar(GetChar(pos));
3804 }
3805
3806
3807 #ifndef NEW_INSETS
3808 bool LyXParagraph::IsFloat(size_type pos) const
3809 {
3810         return IsFloatChar(GetChar(pos));
3811 }
3812 #endif
3813
3814
3815 bool LyXParagraph::IsNewline(size_type pos) const
3816 {
3817         return pos >= 0 && IsNewlineChar(GetChar(pos));
3818 }
3819
3820
3821 bool LyXParagraph::IsSeparator(size_type pos) const
3822 {
3823         return IsSeparatorChar(GetChar(pos));
3824 }
3825
3826
3827 bool LyXParagraph::IsLineSeparator(size_type pos) const
3828 {
3829         return IsLineSeparatorChar(GetChar(pos));
3830 }
3831
3832
3833 bool LyXParagraph::IsKomma(size_type pos) const
3834 {
3835         return IsKommaChar(GetChar(pos));
3836 }
3837
3838
3839 /// Used by the spellchecker
3840 bool LyXParagraph::IsLetter(LyXParagraph::size_type pos) const
3841 {
3842         value_type c = GetChar(pos);
3843         if (IsLetterChar(c))
3844                 return true;
3845         // '\0' is not a letter, allthough every string contains "" (below)
3846         if( c == '\0')
3847                 return false;
3848         // We want to pass the ' and escape chars to ispell
3849         string extra = lyxrc.isp_esc_chars + '\'';
3850         char ch[2] = { c, 0 };
3851         return contains(extra, ch);
3852 }
3853  
3854  
3855 bool LyXParagraph::IsWord(size_type pos ) const
3856 {
3857         return IsWordChar(GetChar(pos)) ;
3858 }
3859
3860
3861 Language const *
3862 LyXParagraph::getParLanguage(BufferParams const & bparams) const 
3863 {
3864 #ifndef NEW_INSETS
3865         if (IsDummy())
3866                 return FirstPhysicalPar()->getParLanguage(bparams);
3867         else
3868 #endif
3869         if (size() > 0) {
3870 #ifdef DO_USE_DEFAULT_LANGUAGE
3871                 Language const * lang = GetFirstFontSettings().language();
3872
3873                 if (lang->lang() == "default")
3874                         return bparams.language;
3875                 return lang;
3876 #else
3877                 return GetFirstFontSettings().language();
3878 #endif
3879         } else if (previous)
3880                 return previous->getParLanguage(bparams);
3881         else
3882                 return bparams.language;
3883 }
3884
3885
3886 bool LyXParagraph::isRightToLeftPar(BufferParams const & bparams) const
3887 {
3888         return lyxrc.rtl_support
3889                 && getParLanguage(bparams)->RightToLeft();
3890 }
3891
3892
3893 void LyXParagraph::ChangeLanguage(BufferParams const & bparams,
3894                                   Language const * from, Language const * to)
3895 {
3896         for(size_type i = 0; i < size(); ++i) {
3897                 LyXFont font = GetFontSettings(bparams, i);
3898                 if (font.language() == from) {
3899                         font.setLanguage(to);
3900                         SetFont(i, font);
3901                 }
3902         }
3903 }
3904
3905
3906 bool LyXParagraph::isMultiLingual(BufferParams const & bparams)
3907 {
3908         Language const * doc_language = bparams.language;
3909         for (FontList::const_iterator cit = fontlist.begin();
3910              cit != fontlist.end(); ++cit)
3911                 if ((*cit).font.language() != doc_language)
3912                         return true;
3913         return false;
3914 }
3915
3916
3917 // Convert the paragraph to a string.
3918 // Used for building the table of contents
3919 string const LyXParagraph::String(Buffer const * buffer, bool label)
3920 {
3921         BufferParams const & bparams = buffer->params;
3922         string s;
3923 #ifndef NEW_INSETS
3924         if (label && !IsDummy() && !labelstring.empty())
3925 #else
3926         if (label && !labelstring.empty())
3927 #endif
3928                 s += labelstring + ' ';
3929         string::size_type len = s.size();
3930
3931         for (LyXParagraph::size_type i = 0; i < size(); ++i) {
3932                 value_type c = GetChar(i);
3933                 if (IsPrintable(c))
3934                         s += c;
3935                 else if (c == META_INSET &&
3936                          GetInset(i)->LyxCode() == Inset::MATH_CODE) {
3937                         std::ostringstream ost;
3938                         GetInset(i)->Ascii(buffer, ost);
3939                         s += subst(ost.str(),'\n',' ');
3940                 }
3941         }
3942
3943 #ifndef NEW_INSETS
3944         if (next && next->footnoteflag != LyXParagraph::NO_FOOTNOTE 
3945             && footnoteflag == LyXParagraph::NO_FOOTNOTE)
3946                 s += NextAfterFootnote()->String(buffer, false);
3947
3948         if (!IsDummy()) {
3949 #endif
3950                 if (isRightToLeftPar(bparams))
3951                         reverse(s.begin() + len,s.end());
3952 #ifndef NEW_INSETS
3953         }
3954 #endif
3955         return s;
3956 }
3957
3958
3959 string const LyXParagraph::String(Buffer const * buffer, 
3960                             LyXParagraph::size_type beg,
3961                             LyXParagraph::size_type end)
3962 {
3963         string s;
3964
3965 #ifndef NEW_INSETS
3966         if (beg == 0 && !IsDummy() && !labelstring.empty())
3967 #else
3968         if (beg == 0 && !labelstring.empty())
3969 #endif
3970                 s += labelstring + ' ';
3971
3972         for (LyXParagraph::size_type i = beg; i < end; ++i) {
3973                 value_type c = GetChar(i);
3974                 if (IsPrintable(c))
3975                         s += c;
3976                 else if (c == META_INSET) {
3977                         std::ostringstream ost;
3978                         GetInset(i)->Ascii(buffer, ost);
3979                         s += ost.str();
3980                 }
3981         }
3982
3983         return s;
3984 }
3985
3986
3987 void LyXParagraph::SetInsetOwner(Inset * i)
3988 {
3989         inset_owner = i;
3990         for (InsetList::const_iterator cit = insetlist.begin();
3991              cit != insetlist.end(); ++cit) {
3992                 if ((*cit).inset)
3993                         (*cit).inset->setOwner(i);
3994         }
3995 }
3996
3997
3998 void LyXParagraph::deleteInsetsLyXText(BufferView * bv)
3999 {
4000         // then the insets
4001         for (InsetList::const_iterator cit = insetlist.begin();
4002              cit != insetlist.end(); ++cit) {
4003                 if ((*cit).inset) {
4004                         if ((*cit).inset->IsTextInset()) {
4005                                 static_cast<UpdatableInset *>
4006                                         ((*cit).inset)->deleteLyXText(bv);
4007                         }
4008                 }
4009         }
4010 }
4011
4012
4013 void LyXParagraph::resizeInsetsLyXText(BufferView * bv)
4014 {
4015         // then the insets
4016         for (InsetList::const_iterator cit = insetlist.begin();
4017              cit != insetlist.end(); ++cit) {
4018                 if ((*cit).inset) {
4019                         if ((*cit).inset->IsTextInset()) {
4020                                 static_cast<UpdatableInset *>
4021                                         ((*cit).inset)->resizeLyXText(bv);
4022                         }
4023                 }
4024         }
4025 }