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