]> git.lyx.org Git - lyx.git/blob - src/buffer.C
96eb02eb4ea6e40f3d138628d43731b9753998fa
[lyx.git] / src / buffer.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  *           This file is Copyright 1996-1999
10  *           Lars Gullik Bjønnes
11  *
12  * ====================================================== 
13  */
14
15 #include <config.h>
16
17 #include <fstream>
18 #include <iomanip>
19
20 #include <cstdlib>
21 #include <cmath>
22 #include <unistd.h>
23 #include <sys/types.h>
24 #include <utime.h>
25
26 #include <algorithm>
27
28 #ifdef HAVE_LOCALE
29 #include <locale>
30 #endif
31
32 #ifdef __GNUG__
33 #pragma implementation "buffer.h"
34 #endif
35
36 #include "buffer.h"
37 #include "bufferlist.h"
38 #include "lyx_main.h"
39 #include "lyx_gui_misc.h"
40 #include "LyXAction.h"
41 #include "lyxrc.h"
42 #include "lyxlex.h"
43 #include "tex-strings.h"
44 #include "layout.h"
45 #include "bufferview_funcs.h"
46 #include "minibuffer.h"
47 #include "lyxfont.h"
48 #include "version.h"
49 #include "mathed/formulamacro.h"
50 #include "insets/lyxinset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insetlabel.h"
53 #include "insets/insetref.h"
54 #include "insets/inseturl.h"
55 #include "insets/insetinfo.h"
56 #include "insets/insetquotes.h"
57 #include "insets/insetlatexaccent.h"
58 #include "insets/insetbib.h" 
59 #include "insets/insetcite.h" 
60 #include "insets/insetexternal.h"
61 #include "insets/insetindex.h" 
62 #include "insets/insetinclude.h"
63 #include "insets/insettoc.h"
64 #include "insets/insetparent.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/figinset.h"
67 #include "insets/insettext.h"
68 #include "insets/insetert.h"
69 #include "insets/insetgraphics.h"
70 #include "insets/insetfoot.h"
71 #include "insets/insetmarginal.h"
72 #include "insets/insetminipage.h"
73 #include "insets/insetfloat.h"
74 #include "insets/insetlist.h"
75 #include "insets/insettabular.h"
76 #include "insets/insettheorem.h"
77 #include "insets/insetcaption.h"
78 #include "support/filetools.h"
79 #include "support/path.h"
80 #include "LaTeX.h"
81 #include "Chktex.h"
82 #include "LyXView.h"
83 #include "debug.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
88 #include "support/lyxmanip.h"
89 #include "lyxtext.h"
90 #include "gettext.h"
91 #include "language.h"
92 #include "lyx_gui_misc.h"       // WarnReadonly()
93 #include "frontends/Dialogs.h"
94 #include "encoding.h"
95 #include "exporter.h"
96 #include "Lsstream.h"
97
98 using std::ostream;
99 using std::ofstream;
100 using std::ifstream;
101 using std::fstream;
102 using std::ios;
103 using std::setw;
104 using std::endl;
105 using std::pair;
106 using std::vector;
107 using std::max;
108 using std::set;
109
110 // all these externs should eventually be removed.
111 extern BufferList bufferlist;
112
113 extern LyXAction lyxaction;
114
115
116 static const float LYX_FORMAT = 2.17;
117
118 extern int tex_code_break_column;
119
120
121 Buffer::Buffer(string const & file, bool ronly)
122 {
123         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
124         filename = file;
125         filepath = OnlyPath(file);
126         paragraph = 0;
127         lyx_clean = true;
128         bak_clean = true;
129         dep_clean = 0;
130         read_only = ronly;
131         unnamed = false;
132         users = 0;
133         lyxvc.buffer(this);
134         if (read_only || (lyxrc.use_tempdir)) {
135                 tmppath = CreateBufferTmpDir();
136         } else tmppath.erase();
137 }
138
139
140 Buffer::~Buffer()
141 {
142         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
143         // here the buffer should take care that it is
144         // saved properly, before it goes into the void.
145
146         // make sure that views using this buffer
147         // forgets it.
148         if (users)
149                 users->buffer(0);
150         
151         if (!tmppath.empty()) {
152                 DestroyBufferTmpDir(tmppath);
153         }
154         
155         LyXParagraph * par = paragraph;
156         LyXParagraph * tmppar;
157         while (par) {
158                 tmppar = par->next;
159                 delete par;
160                 par = tmppar;
161         }
162         paragraph = 0;
163 }
164
165
166 string const Buffer::getLatexName(bool no_path) const
167 {
168         if (no_path)
169                 return OnlyFilename(ChangeExtension(MakeLatexName(filename), 
170                                                     ".tex"));
171         else
172                 return ChangeExtension(MakeLatexName(filename), 
173                                        ".tex"); 
174 }
175
176
177 void Buffer::setReadonly(bool flag)
178 {
179         if (read_only != flag) {
180                 read_only = flag; 
181                 updateTitles();
182                 users->owner()->getDialogs()->updateBufferDependent(false);
183         }
184         if (read_only) {
185                 WarnReadonly(filename);
186         }
187 }
188
189
190 bool Buffer::saveParamsAsDefaults() // const
191 {
192         string const fname = AddName(AddPath(user_lyxdir, "templates/"),
193                                "defaults.lyx");
194         Buffer defaults = Buffer(fname);
195         
196         // Use the current buffer's parameters as default
197         defaults.params = params;
198         
199         // add an empty paragraph. Is this enough?
200         defaults.paragraph = new LyXParagraph;
201
202         return defaults.writeFile(defaults.filename, false);
203 }
204
205
206 /// Update window titles of all users
207 // Should work on a list
208 void Buffer::updateTitles() const
209 {
210         if (users) users->owner()->updateWindowTitle();
211 }
212
213
214 /// Reset autosave timer of all users
215 // Should work on a list
216 void Buffer::resetAutosaveTimers() const
217 {
218         if (users) users->owner()->resetAutosaveTimer();
219 }
220
221
222 void Buffer::setFileName(string const & newfile)
223 {
224         filename = MakeAbsPath(newfile);
225         filepath = OnlyPath(filename);
226         setReadonly(IsFileWriteable(filename) == 0);
227         updateTitles();
228 }
229
230
231 // candidate for move to BufferView
232 // (at least some parts in the beginning of the func)
233 //
234 // Uwe C. Schroeder
235 // changed to be public and have one parameter
236 // if par = 0 normal behavior
237 // else insert behavior
238 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
239 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
240 {
241         int pos = 0;
242         char depth = 0; // signed or unsigned?
243 #ifndef NEW_INSETS
244         LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
245         LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
246 #endif
247         bool the_end_read = false;
248
249         LyXParagraph * return_par = 0;
250         LyXFont font(LyXFont::ALL_INHERIT, params.language);
251         if (format < 2.16 && params.language->lang() == "hebrew")
252                 font.setLanguage(default_language);
253
254         // If we are inserting, we cheat and get a token in advance
255         bool has_token = false;
256         string pretoken;
257
258         if (!par) {
259                 par = new LyXParagraph;
260         } else {
261                 users->text->BreakParagraph(users);
262                 return_par = users->text->FirstParagraph();
263                 pos = 0;
264                 markDirty();
265                 // We don't want to adopt the parameters from the
266                 // document we insert, so we skip until the text begins:
267                 while (lex.IsOK()) {
268                         lex.nextToken();
269                         pretoken = lex.GetString();
270                         if (pretoken == "\\layout") {
271                                 has_token = true;
272                                 break;
273                         }
274                 }
275         }
276
277         while (lex.IsOK()) {
278                 if (has_token) {
279                         has_token = false;
280                 } else {
281                         lex.nextToken();
282                         pretoken = lex.GetString();
283                 }
284
285                 if (pretoken.empty()) continue;
286                 
287                 the_end_read =
288                         parseSingleLyXformat2Token(lex, par, return_par,
289                                                    pretoken, pos, depth,
290                                                    font
291 #ifndef NEW_INSETS
292                                                    , footnoteflag,
293                                                    footnotekind
294 #endif
295                                 );
296         }
297    
298         if (!return_par)
299                 return_par = par;
300
301         paragraph = return_par;
302         
303         return the_end_read;
304 }
305
306
307 // We'll remove this later. (Lgb)
308 static string last_inset_read;
309
310
311 bool
312 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
313                                    LyXParagraph *& return_par,
314                                    string const & token, int & pos,
315                                    char & depth, LyXFont & font
316 #ifndef NEW_INSETS
317                                    , LyXParagraph::footnote_flag & footnoteflag,
318                                    LyXParagraph::footnote_kind & footnotekind
319 #endif
320         )
321 {
322         bool the_end_read = false;
323         
324         if (token[0] != '\\') {
325                 for (string::const_iterator cit = token.begin();
326                      cit != token.end(); ++cit) {
327                         par->InsertChar(pos, (*cit), font);
328                         ++pos;
329                 }
330         } else if (token == "\\i") {
331                 Inset * inset = new InsetLatexAccent;
332                 inset->Read(this, lex);
333                 par->InsertInset(pos, inset, font);
334                 ++pos;
335         } else if (token == "\\layout") {
336                 if (!return_par) 
337                         return_par = par;
338                 else {
339                         par->fitToSize();
340                         par = new LyXParagraph(par);
341                 }
342                 pos = 0;
343                 lex.EatLine();
344                 string const layoutname = lex.GetString();
345                 pair<bool, LyXTextClass::LayoutList::size_type> pp
346                         = textclasslist.NumberOfLayout(params.textclass,
347                                                        layoutname);
348                 if (pp.first) {
349                         par->layout = pp.second;
350                 } else { // layout not found
351                         // use default layout "Standard" (0)
352                         par->layout = 0;
353                 }
354                 // Test whether the layout is obsolete.
355                 LyXLayout const & layout =
356                         textclasslist.Style(params.textclass,
357                                             par->layout); 
358                 if (!layout.obsoleted_by().empty())
359                         par->layout = 
360                                 textclasslist.NumberOfLayout(params.textclass, 
361                                                              layout.obsoleted_by()).second;
362 #ifndef NEW_INSETS
363                 par->footnoteflag = footnoteflag;
364                 par->footnotekind = footnotekind;
365 #endif
366                 par->depth = depth;
367                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
368                 if (format < 2.16 && params.language->lang() == "hebrew")
369                         font.setLanguage(default_language);
370 #ifndef NEW_INSETS
371         } else if (token == "\\end_float") {
372                 if (!return_par) 
373                         return_par = par;
374                 else {
375                         par->fitToSize();
376                         par = new LyXParagraph(par);
377                 }
378                 footnotekind = LyXParagraph::FOOTNOTE;
379                 footnoteflag = LyXParagraph::NO_FOOTNOTE;
380                 pos = 0;
381                 lex.EatLine();
382                 par->layout = LYX_DUMMY_LAYOUT;
383                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
384                 if (format < 2.16 && params.language->lang() == "hebrew")
385                         font.setLanguage(default_language);
386         } else if (token == "\\begin_float") {
387                 int tmpret = lex.FindToken(string_footnotekinds);
388                 if (tmpret == -1) ++tmpret;
389                 if (tmpret != LYX_LAYOUT_DEFAULT) 
390                         footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
391                 if (footnotekind == LyXParagraph::FOOTNOTE
392                     || footnotekind == LyXParagraph::MARGIN)
393                         footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
394                 else 
395                         footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
396 #else
397         } else if (token == "\\begin_float") {
398                 // This is the compability reader, unfinished but tested.
399                 // (Lgb)
400                 lex.next();
401                 string const tmptok = lex.GetString();
402                 //lyxerr << "old float: " << tmptok << endl;
403                 
404                 Inset * inset = 0;
405                 string old_float;
406                 
407                 if (tmptok == "footnote") {
408                         inset = new InsetFoot;
409                 } else if (tmptok == "margin") {
410                         inset = new InsetMarginal;
411                 } else if (tmptok == "fig") {
412                         inset = new InsetFloat("figure");
413                         old_float += "placement htbp\n";
414                 } else if (tmptok == "tab") {
415                         inset = new InsetFloat("table");
416                         old_float += "placement htbp\n";
417                 } else if (tmptok == "alg") {
418                         inset = new InsetFloat("algorithm");
419                         old_float += "placement htbp\n";
420                 } else if (tmptok == "wide-fig") {
421                         InsetFloat * tmp = new InsetFloat("figure");
422                         tmp->wide(true);
423                         inset = tmp;
424                         old_float += "placement htbp\n";
425                 } else if (tmptok == "wide-tab") {
426                         InsetFloat * tmp = new InsetFloat("table");
427                         tmp->wide(true);
428                         inset = tmp;
429                         old_float += "placement htbp\n";
430                 }
431
432                 if (!inset) return false; // no end read yet
433                 
434                 old_float += "collapsed true\n";
435
436                 // Here we need to check for \end_deeper and handle that
437                 // before we do the footnote parsing.
438                 // This _is_ a hack! (Lgb)
439                 while(true) {
440                         lex.next();
441                         string const tmp = lex.GetString();
442                         if (tmp == "\\end_deeper") {
443                                 lyxerr << "\\end_deeper caught!" << endl;
444                                 if (!depth) {
445                                         lex.printError("\\end_deeper: "
446                                                        "depth is already null");
447                                 } else
448                                         --depth;
449                                 
450                         } else {
451                                 old_float += tmp;
452                                 old_float += ' ';
453                                 break;
454                         }
455                 }
456                 
457                 old_float += lex.getLongString("\\end_float");
458                 old_float += "\n\\end_inset\n";
459                 //lyxerr << "float body: " << old_float << endl;
460
461                 istringstream istr(old_float);
462                 
463                 LyXLex nylex(0, 0);
464                 nylex.setStream(istr);
465                 
466                 inset->Read(this, nylex);
467                 par->InsertInset(pos, inset, font);
468                 ++pos;
469 #endif
470         } else if (token == "\\begin_deeper") {
471                 ++depth;
472         } else if (token == "\\end_deeper") {
473                 if (!depth) {
474                         lex.printError("\\end_deeper: "
475                                        "depth is already null");
476                 }
477                 else
478                         --depth;
479         } else if (token == "\\begin_preamble") {
480                 params.readPreamble(lex);
481         } else if (token == "\\textclass") {
482                 lex.EatLine();
483                 pair<bool, LyXTextClassList::size_type> pp = 
484                         textclasslist.NumberOfClass(lex.GetString());
485                 if (pp.first) {
486                         params.textclass = pp.second;
487                 } else {
488                         WriteAlert(string(_("Textclass error")), 
489                                 string(_("The document uses an unknown textclass \"")) + 
490                                 lex.GetString() + string("\"."),
491                                 string(_("LyX will not be able to produce output correctly.")));
492                         params.textclass = 0;
493                 }
494                 if (!textclasslist.Load(params.textclass)) {
495                                 // if the textclass wasn't loaded properly
496                                 // we need to either substitute another
497                                 // or stop loading the file.
498                                 // I can substitute but I don't see how I can
499                                 // stop loading... ideas??  ARRae980418
500                         WriteAlert(_("Textclass Loading Error!"),
501                                    string(_("Can't load textclass ")) +
502                                    textclasslist.NameOfClass(params.textclass),
503                                    _("-- substituting default"));
504                         params.textclass = 0;
505                 }
506         } else if (token == "\\options") {
507                 lex.EatLine();
508                 params.options = lex.GetString();
509         } else if (token == "\\language") {
510                 params.readLanguage(lex);    
511         } else if (token == "\\fontencoding") {
512                 lex.EatLine();
513         } else if (token == "\\inputencoding") {
514                 lex.EatLine();
515                 params.inputenc = lex.GetString();
516         } else if (token == "\\graphics") {
517                 params.readGraphicsDriver(lex);
518         } else if (token == "\\fontscheme") {
519                 lex.EatLine();
520                 params.fonts = lex.GetString();
521         } else if (token == "\\noindent") {
522                 par->noindent = true;
523         } else if (token == "\\fill_top") {
524                 par->added_space_top = VSpace(VSpace::VFILL);
525         } else if (token == "\\fill_bottom") {
526                 par->added_space_bottom = VSpace(VSpace::VFILL);
527         } else if (token == "\\line_top") {
528                 par->line_top = true;
529         } else if (token == "\\line_bottom") {
530                 par->line_bottom = true;
531         } else if (token == "\\pagebreak_top") {
532                 par->pagebreak_top = true;
533         } else if (token == "\\pagebreak_bottom") {
534                 par->pagebreak_bottom = true;
535         } else if (token == "\\start_of_appendix") {
536                 par->start_of_appendix = true;
537         } else if (token == "\\paragraph_separation") {
538                 int tmpret = lex.FindToken(string_paragraph_separation);
539                 if (tmpret == -1) ++tmpret;
540                 if (tmpret != LYX_LAYOUT_DEFAULT) 
541                         params.paragraph_separation =
542                                 static_cast<BufferParams::PARSEP>(tmpret);
543         } else if (token == "\\defskip") {
544                 lex.nextToken();
545                 params.defskip = VSpace(lex.GetString());
546         } else if (token == "\\epsfig") { // obsolete
547                 // Indeed it is obsolete, but we HAVE to be backwards
548                 // compatible until 0.14, because otherwise all figures
549                 // in existing documents are irretrivably lost. (Asger)
550                 params.readGraphicsDriver(lex);
551         } else if (token == "\\quotes_language") {
552                 int tmpret = lex.FindToken(string_quotes_language);
553                 if (tmpret == -1) ++tmpret;
554                 if (tmpret != LYX_LAYOUT_DEFAULT) {
555                         InsetQuotes::quote_language tmpl = 
556                                 InsetQuotes::EnglishQ;
557                         switch (tmpret) {
558                         case 0:
559                                 tmpl = InsetQuotes::EnglishQ;
560                                 break;
561                         case 1:
562                                 tmpl = InsetQuotes::SwedishQ;
563                                 break;
564                         case 2:
565                                 tmpl = InsetQuotes::GermanQ;
566                                 break;
567                         case 3:
568                                 tmpl = InsetQuotes::PolishQ;
569                                 break;
570                         case 4:
571                                 tmpl = InsetQuotes::FrenchQ;
572                                 break;
573                         case 5:
574                                 tmpl = InsetQuotes::DanishQ;
575                                 break;  
576                         }
577                         params.quotes_language = tmpl;
578                 }
579         } else if (token == "\\quotes_times") {
580                 lex.nextToken();
581                 switch (lex.GetInteger()) {
582                 case 1: 
583                         params.quotes_times = InsetQuotes::SingleQ; 
584                         break;
585                 case 2: 
586                         params.quotes_times = InsetQuotes::DoubleQ; 
587                         break;
588                 }
589         } else if (token == "\\papersize") {
590                 int tmpret = lex.FindToken(string_papersize);
591                 if (tmpret == -1)
592                         ++tmpret;
593                 else
594                         params.papersize2 = tmpret;
595         } else if (token == "\\paperpackage") {
596                 int tmpret = lex.FindToken(string_paperpackages);
597                 if (tmpret == -1) {
598                         ++tmpret;
599                         params.paperpackage = BufferParams::PACKAGE_NONE;
600                 } else
601                         params.paperpackage = tmpret;
602         } else if (token == "\\use_geometry") {
603                 lex.nextToken();
604                 params.use_geometry = lex.GetInteger();
605         } else if (token == "\\use_amsmath") {
606                 lex.nextToken();
607                 params.use_amsmath = lex.GetInteger();
608         } else if (token == "\\paperorientation") {
609                 int tmpret = lex.FindToken(string_orientation);
610                 if (tmpret == -1) ++tmpret;
611                 if (tmpret != LYX_LAYOUT_DEFAULT) 
612                         params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
613         } else if (token == "\\paperwidth") {
614                 lex.next();
615                 params.paperwidth = lex.GetString();
616         } else if (token == "\\paperheight") {
617                 lex.next();
618                 params.paperheight = lex.GetString();
619         } else if (token == "\\leftmargin") {
620                 lex.next();
621                 params.leftmargin = lex.GetString();
622         } else if (token == "\\topmargin") {
623                 lex.next();
624                 params.topmargin = lex.GetString();
625         } else if (token == "\\rightmargin") {
626                 lex.next();
627                 params.rightmargin = lex.GetString();
628         } else if (token == "\\bottommargin") {
629                 lex.next();
630                 params.bottommargin = lex.GetString();
631         } else if (token == "\\headheight") {
632                 lex.next();
633                 params.headheight = lex.GetString();
634         } else if (token == "\\headsep") {
635                 lex.next();
636                 params.headsep = lex.GetString();
637         } else if (token == "\\footskip") {
638                 lex.next();
639                 params.footskip = lex.GetString();
640         } else if (token == "\\paperfontsize") {
641                 lex.nextToken();
642                 params.fontsize = strip(lex.GetString());
643         } else if (token == "\\papercolumns") {
644                 lex.nextToken();
645                 params.columns = lex.GetInteger();
646         } else if (token == "\\papersides") {
647                 lex.nextToken();
648                 switch (lex.GetInteger()) {
649                 default:
650                 case 1: params.sides = LyXTextClass::OneSide; break;
651                 case 2: params.sides = LyXTextClass::TwoSides; break;
652                 }
653         } else if (token == "\\paperpagestyle") {
654                 lex.nextToken();
655                 params.pagestyle = strip(lex.GetString());
656         } else if (token == "\\bullet") {
657                 lex.nextToken();
658                 int const index = lex.GetInteger();
659                 lex.nextToken();
660                 int temp_int = lex.GetInteger();
661                 params.user_defined_bullets[index].setFont(temp_int);
662                 params.temp_bullets[index].setFont(temp_int);
663                 lex.nextToken();
664                 temp_int = lex.GetInteger();
665                 params.user_defined_bullets[index].setCharacter(temp_int);
666                 params.temp_bullets[index].setCharacter(temp_int);
667                 lex.nextToken();
668                 temp_int = lex.GetInteger();
669                 params.user_defined_bullets[index].setSize(temp_int);
670                 params.temp_bullets[index].setSize(temp_int);
671                 lex.nextToken();
672                 string const temp_str = lex.GetString();
673                 if (temp_str != "\\end_bullet") {
674                                 // this element isn't really necessary for
675                                 // parsing but is easier for humans
676                                 // to understand bullets. Put it back and
677                                 // set a debug message?
678                         lex.printError("\\end_bullet expected, got" + temp_str);
679                                 //how can I put it back?
680                 }
681         } else if (token == "\\bulletLaTeX") {
682                 lex.nextToken();
683                 int const index = lex.GetInteger();
684                 lex.next();
685                 string temp_str = lex.GetString();
686                 string sum_str;
687                 while (temp_str != "\\end_bullet") {
688                                 // this loop structure is needed when user
689                                 // enters an empty string since the first
690                                 // thing returned will be the \\end_bullet
691                                 // OR
692                                 // if the LaTeX entry has spaces. Each element
693                                 // therefore needs to be read in turn
694                         sum_str += temp_str;
695                         lex.next();
696                         temp_str = lex.GetString();
697                 }
698                 params.user_defined_bullets[index].setText(sum_str);
699                 params.temp_bullets[index].setText(sum_str);
700         } else if (token == "\\secnumdepth") {
701                 lex.nextToken();
702                 params.secnumdepth = lex.GetInteger();
703         } else if (token == "\\tocdepth") {
704                 lex.nextToken();
705                 params.tocdepth = lex.GetInteger();
706         } else if (token == "\\spacing") {
707                 lex.next();
708                 string const tmp = strip(lex.GetString());
709                 Spacing::Space tmp_space = Spacing::Default;
710                 float tmp_val = 0.0;
711                 if (tmp == "single") {
712                         tmp_space = Spacing::Single;
713                 } else if (tmp == "onehalf") {
714                         tmp_space = Spacing::Onehalf;
715                 } else if (tmp == "double") {
716                         tmp_space = Spacing::Double;
717                 } else if (tmp == "other") {
718                         lex.next();
719                         tmp_space = Spacing::Other;
720                         tmp_val = lex.GetFloat();
721                 } else {
722                         lex.printError("Unknown spacing token: '$$Token'");
723                 }
724                 // Small hack so that files written with klyx will be
725                 // parsed correctly.
726                 if (return_par) {
727                         par->spacing.set(tmp_space, tmp_val);
728                 } else {
729                         params.spacing.set(tmp_space, tmp_val);
730                 }
731         } else if (token == "\\paragraph_spacing") {
732                 lex.next();
733                 string const tmp = strip(lex.GetString());
734                 if (tmp == "single") {
735                         par->spacing.set(Spacing::Single);
736                 } else if (tmp == "onehalf") {
737                         par->spacing.set(Spacing::Onehalf);
738                 } else if (tmp == "double") {
739                         par->spacing.set(Spacing::Double);
740                 } else if (tmp == "other") {
741                         lex.next();
742                         par->spacing.set(Spacing::Other,
743                                          lex.GetFloat());
744                 } else {
745                         lex.printError("Unknown spacing token: '$$Token'");
746                 }
747         } else if (token == "\\float_placement") {
748                 lex.nextToken();
749                 params.float_placement = lex.GetString();
750         } else if (token == "\\family") { 
751                 lex.next();
752                 font.setLyXFamily(lex.GetString());
753         } else if (token == "\\series") {
754                 lex.next();
755                 font.setLyXSeries(lex.GetString());
756         } else if (token == "\\shape") {
757                 lex.next();
758                 font.setLyXShape(lex.GetString());
759         } else if (token == "\\size") {
760                 lex.next();
761                 font.setLyXSize(lex.GetString());
762         } else if (token == "\\latex") {
763                 lex.next();
764                 string const tok = lex.GetString();
765                 // This is dirty, but gone with LyX3. (Asger)
766                 if (tok == "no_latex")
767                         font.setLatex(LyXFont::OFF);
768                 else if (tok == "latex")
769                         font.setLatex(LyXFont::ON);
770                 else if (tok == "default")
771                         font.setLatex(LyXFont::INHERIT);
772                 else
773                         lex.printError("Unknown LaTeX font flag "
774                                        "`$$Token'");
775         } else if (token == "\\lang") {
776                 lex.next();
777                 string const tok = lex.GetString();
778                 Language const * lang = languages.getLanguage(tok);
779                 if (lang) {
780                         font.setLanguage(lang);
781                 } else {
782                         font.setLanguage(params.language);
783                         lex.printError("Unknown language `$$Token'");
784                 }
785         } else if (token == "\\numeric") {
786                 lex.next();
787                 font.setNumber(font.setLyXMisc(lex.GetString()));
788         } else if (token == "\\emph") {
789                 lex.next();
790                 font.setEmph(font.setLyXMisc(lex.GetString()));
791         } else if (token == "\\bar") {
792                 lex.next();
793                 string const tok = lex.GetString();
794                 // This is dirty, but gone with LyX3. (Asger)
795                 if (tok == "under")
796                         font.setUnderbar(LyXFont::ON);
797                 else if (tok == "no")
798                         font.setUnderbar(LyXFont::OFF);
799                 else if (tok == "default")
800                         font.setUnderbar(LyXFont::INHERIT);
801                 else
802                         lex.printError("Unknown bar font flag "
803                                        "`$$Token'");
804         } else if (token == "\\noun") {
805                 lex.next();
806                 font.setNoun(font.setLyXMisc(lex.GetString()));
807         } else if (token == "\\color") {
808                 lex.next();
809                 font.setLyXColor(lex.GetString());
810         } else if (token == "\\align") {
811                 int tmpret = lex.FindToken(string_align);
812                 if (tmpret == -1) ++tmpret;
813                 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
814 #if 0
815                         int tmpret2 = 1;
816                         for (; tmpret > 0; --tmpret)
817                                 tmpret2 = tmpret2 * 2;
818 #else
819                         int const tmpret2 = int(pow(2.0, tmpret));
820 #endif
821                         //lyxerr << "Tmpret2 = " << tmpret2 << endl;
822                         par->align = LyXAlignment(tmpret2);
823                 }
824         } else if (token == "\\added_space_top") {
825                 lex.nextToken();
826                 par->added_space_top = VSpace(lex.GetString());
827         } else if (token == "\\added_space_bottom") {
828                 lex.nextToken();
829                 par->added_space_bottom = VSpace(lex.GetString());
830         } else if (token == "\\pextra_type") {
831                 lex.nextToken();
832                 par->pextra_type = lex.GetInteger();
833         } else if (token == "\\pextra_width") {
834                 lex.nextToken();
835                 par->pextra_width = lex.GetString();
836         } else if (token == "\\pextra_widthp") {
837                 lex.nextToken();
838                 par->pextra_widthp = lex.GetString();
839         } else if (token == "\\pextra_alignment") {
840                 lex.nextToken();
841                 par->pextra_alignment = lex.GetInteger();
842         } else if (token == "\\pextra_hfill") {
843                 lex.nextToken();
844                 par->pextra_hfill = lex.GetInteger();
845         } else if (token == "\\pextra_start_minipage") {
846                 lex.nextToken();
847                 par->pextra_start_minipage = lex.GetInteger();
848         } else if (token == "\\labelwidthstring") {
849                 lex.EatLine();
850                 par->labelwidthstring = lex.GetString();
851                 // do not delete this token, it is still needed!
852         } else if (token == "\\end_inset") {
853                 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
854                        << "Last inset read was: " << last_inset_read
855                        << endl;
856                 // Simply ignore this. The insets do not have
857                 // to read this.
858                 // But insets should read it, it is a part of
859                 // the inset isn't it? Lgb.
860         } else if (token == "\\begin_inset") {
861                 readInset(lex, par, pos, font);
862         } else if (token == "\\SpecialChar") {
863                 LyXLayout const & layout =
864                         textclasslist.Style(params.textclass, 
865                                             par->GetLayout());
866
867                 // Insets don't make sense in a free-spacing context! ---Kayvan
868                 if (layout.free_spacing) {
869                         if (lex.IsOK()) {
870                                 lex.next();
871                                 string next_token = lex.GetString();
872                                 if (next_token == "\\-") {
873                                         par->InsertChar(pos, '-', font);
874                                 } else if (next_token == "\\protected_separator"
875                                         || next_token == "~") {
876                                         par->InsertChar(pos, ' ', font);
877                                 } else {
878                                         lex.printError("Token `$$Token' "
879                                                        "is in free space "
880                                                        "paragraph layout!");
881                                         --pos;
882                                 }
883                         }
884                 } else {
885                         Inset * inset = new InsetSpecialChar;
886                         inset->Read(this, lex);
887                         par->InsertInset(pos, inset, font);
888                 }
889                 ++pos;
890         } else if (token == "\\newline") {
891                 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
892                 ++pos;
893         } else if (token == "\\LyXTable") {
894                 Inset * inset = new InsetTabular(*this);
895                 inset->Read(this, lex);
896                 par->InsertInset(pos, inset, font);
897                 ++pos;
898         } else if (token == "\\hfill") {
899                 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
900                 ++pos;
901         } else if (token == "\\protected_separator") { // obsolete
902                 // This is a backward compability thingie. (Lgb)
903                 // Remove it later some time...introduced with fileformat
904                 // 2.16. (Lgb)
905                 LyXLayout const & layout =
906                         textclasslist.Style(params.textclass, 
907                                             par->GetLayout());
908
909                 if (layout.free_spacing) {
910                         par->InsertChar(pos, ' ', font);
911                 } else {
912                         Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
913                         par->InsertInset(pos, inset, font);
914                 }
915                 ++pos;
916         } else if (token == "\\bibitem") {  // ale970302
917                 if (!par->bibkey) {
918                         InsetCommandParams p( "bibitem" );
919                         par->bibkey = new InsetBibKey(p);
920                 }
921                 par->bibkey->Read(this, lex);                   
922         } else if (token == "\\backslash") {
923                 par->InsertChar(pos, '\\', font);
924                 ++pos;
925         } else if (token == "\\the_end") {
926                 the_end_read = true;
927         } else {
928                 // This should be insurance for the future: (Asger)
929                 lex.printError("Unknown token `$$Token'. "
930                                "Inserting as text.");
931                 string::const_iterator cit = token.begin();
932                 string::const_iterator end = token.end();
933                 for (; cit != end; ++cit) {
934                         par->InsertChar(pos, (*cit), font);
935                         ++pos;
936                 }
937         }
938         return the_end_read;
939 }
940
941
942 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
943                        int & pos, LyXFont & font)
944 {
945         // consistency check
946         if (lex.GetString() != "\\begin_inset") {
947                 lyxerr << "Buffer::readInset: Consistency check failed."
948                        << endl;
949         }
950         
951         Inset * inset = 0;
952
953         lex.next();
954         string const tmptok = lex.GetString();
955         last_inset_read = tmptok;
956
957         // test the different insets
958         if (tmptok == "LatexCommand") {
959                 InsetCommandParams inscmd;
960                 inscmd.Read(lex);
961
962                 if (inscmd.getCmdName() == "cite") {
963                         inset = new InsetCitation(inscmd);
964                 } else if (inscmd.getCmdName() == "bibitem") {
965                         lex.printError("Wrong place for bibitem");
966                         inset = new InsetBibKey(inscmd);
967                 } else if (inscmd.getCmdName() == "BibTeX") {
968                         inset = new InsetBibtex(inscmd);
969                 } else if (inscmd.getCmdName() == "index") {
970                         inset = new InsetIndex(inscmd);
971                 } else if (inscmd.getCmdName() == "include") {
972                         inset = new InsetInclude(inscmd, *this);
973                 } else if (inscmd.getCmdName() == "label") {
974                         inset = new InsetLabel(inscmd);
975                 } else if (inscmd.getCmdName() == "url"
976                            || inscmd.getCmdName() == "htmlurl") {
977                         inset = new InsetUrl(inscmd);
978                 } else if (inscmd.getCmdName() == "ref"
979                            || inscmd.getCmdName() == "pageref"
980                            || inscmd.getCmdName() == "vref"
981                            || inscmd.getCmdName() == "vpageref"
982                            || inscmd.getCmdName() == "prettyref") {
983                         if (!inscmd.getOptions().empty()
984                             || !inscmd.getContents().empty()) {
985                                 inset = new InsetRef(inscmd, *this);
986                         }
987                 } else if (inscmd.getCmdName() == "tableofcontents"
988                            || inscmd.getCmdName() == "listofalgorithms"
989                            || inscmd.getCmdName() == "listoffigures"
990                            || inscmd.getCmdName() == "listoftables") {
991                         inset = new InsetTOC(inscmd);
992                 } else if (inscmd.getCmdName() == "printindex") {
993                         inset = new InsetPrintIndex(inscmd);
994                 } else if (inscmd.getCmdName() == "lyxparent") {
995                         inset = new InsetParent(inscmd, *this);
996                 }
997         } else {
998                 if (tmptok == "Quotes") {
999                         inset = new InsetQuotes;
1000                 } else if (tmptok == "External") {
1001                         inset = new InsetExternal;
1002                 } else if (tmptok == "FormulaMacro") {
1003                         inset = new InsetFormulaMacro;
1004                 } else if (tmptok == "Formula") {
1005                         inset = new InsetFormula;
1006                 } else if (tmptok == "Figure") {
1007                         inset = new InsetFig(100, 100, *this);
1008                 } else if (tmptok == "Info") {
1009                         inset = new InsetInfo;
1010                 } else if (tmptok == "Include") {
1011                         InsetCommandParams p( "Include" );
1012                         inset = new InsetInclude(p, *this);
1013                 } else if (tmptok == "ERT") {
1014                         inset = new InsetERT;
1015                 } else if (tmptok == "Tabular") {
1016                         inset = new InsetTabular(*this);
1017                 } else if (tmptok == "Text") {
1018                         inset = new InsetText;
1019                 } else if (tmptok == "Foot") {
1020                         inset = new InsetFoot;
1021                 } else if (tmptok == "Marginal") {
1022                         inset = new InsetMarginal;
1023                 } else if (tmptok == "Minipage") {
1024                         inset = new InsetMinipage;
1025                 } else if (tmptok == "Float") {
1026                         lex.next();
1027                         string tmptok = lex.GetString();
1028                         inset = new InsetFloat(tmptok);
1029                 } else if (tmptok == "List") {
1030                         inset = new InsetList;
1031                 } else if (tmptok == "Theorem") {
1032                         inset = new InsetList;
1033                 } else if (tmptok == "Caption") {
1034                         inset = new InsetCaption;
1035                 } else if (tmptok == "GRAPHICS") {
1036                         inset = new InsetGraphics;
1037                 }
1038                 
1039                 if (inset) inset->Read(this, lex);
1040         }
1041         
1042         if (inset) {
1043                 par->InsertInset(pos, inset, font);
1044                 ++pos;
1045         }
1046 }
1047
1048
1049 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1050 {
1051         if (lex.IsOK()) {
1052                 lex.next();
1053                 string const token(lex.GetString());
1054                 if (token == "\\lyxformat") { // the first token _must_ be...
1055                         lex.EatLine();
1056                         format = lex.GetFloat();
1057                         if (format > 1.0) {
1058                                 if (LYX_FORMAT - format > 0.05) {
1059                                         lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
1060                                                       LYX_FORMAT, format) << endl;
1061                                 }
1062                                 if (format - LYX_FORMAT > 0.05) {
1063                                         lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
1064                                                       LYX_FORMAT, format) << endl;
1065                                 }
1066                                 bool the_end = readLyXformat2(lex, par);
1067                                 // Formats >= 2.13 support "\the_end" marker
1068                                 if (format < 2.13)
1069                                         the_end = true;
1070
1071                                 setPaperStuff();
1072
1073                                 if (!the_end)
1074                                         WriteAlert(_("Warning!"),
1075                                                    _("Reading of document is not complete"),
1076                                                    _("Maybe the document is truncated"));
1077                                 // We simulate a safe reading anyways to allow
1078                                 // users to take the chance... (Asger)
1079                                 return true;
1080                         } // format < 1.0
1081                         else {
1082                                 WriteAlert(_("ERROR!"),
1083                                            _("Old LyX file format found. "
1084                                              "Use LyX 0.10.x to read this!"));
1085                                 return false;
1086                         }
1087
1088                 } else { // "\\lyxformat" not found
1089                         WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1090                 }
1091         } else
1092                 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1093         return false;
1094 }
1095                     
1096
1097
1098 // Should probably be moved to somewhere else: BufferView? LyXView?
1099 bool Buffer::save() const
1100 {
1101         // We don't need autosaves in the immediate future. (Asger)
1102         resetAutosaveTimers();
1103
1104         // make a backup
1105         string s;
1106         if (lyxrc.make_backup) {
1107                 s = fileName() + '~';
1108                 if (!lyxrc.backupdir_path.empty())
1109                         s = AddName(lyxrc.backupdir_path,
1110                                     subst(CleanupPath(s),'/','!'));
1111
1112                 // Rename is the wrong way of making a backup,
1113                 // this is the correct way.
1114                 /* truss cp fil fil2:
1115                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1116                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1117                    open("LyXVC.lyx", O_RDONLY)                     = 3
1118                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1119                    fstat(4, 0xEFFFF508)                            = 0
1120                    fstat(3, 0xEFFFF508)                            = 0
1121                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1122                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1123                    read(3, 0xEFFFD4A0, 8192)                       = 0
1124                    close(4)                                        = 0
1125                    close(3)                                        = 0
1126                    chmod("LyXVC3.lyx", 0100644)                    = 0
1127                    lseek(0, 0, SEEK_CUR)                           = 46440
1128                    _exit(0)
1129                 */
1130
1131                 // Should proabaly have some more error checking here.
1132                 // Should be cleaned up in 0.13, at least a bit.
1133                 // Doing it this way, also makes the inodes stay the same.
1134                 // This is still not a very good solution, in particular we
1135                 // might loose the owner of the backup.
1136                 FileInfo finfo(fileName());
1137                 if (finfo.exist()) {
1138                         mode_t fmode = finfo.getMode();
1139                         struct utimbuf times = {
1140                                 finfo.getAccessTime(),
1141                                 finfo.getModificationTime() };
1142
1143                         ifstream ifs(fileName().c_str());
1144                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1145                         if (ifs && ofs) {
1146                                 ofs << ifs.rdbuf();
1147                                 ifs.close();
1148                                 ofs.close();
1149                                 ::chmod(s.c_str(), fmode);
1150                                 
1151                                 if (::utime(s.c_str(), &times)) {
1152                                         lyxerr << "utime error." << endl;
1153                                 }
1154                         } else {
1155                                 lyxerr << "LyX was not able to make "
1156                                         "backupcopy. Beware." << endl;
1157                         }
1158                 }
1159         }
1160         
1161         if (writeFile(fileName(), false)) {
1162                 markLyxClean();
1163                 removeAutosaveFile(fileName());
1164         } else {
1165                 // Saving failed, so backup is not backup
1166                 if (lyxrc.make_backup) {
1167                         lyx::rename(s, fileName());
1168                 }
1169                 return false;
1170         }
1171         return true;
1172 }
1173
1174
1175 // Returns false if unsuccesful
1176 bool Buffer::writeFile(string const & fname, bool flag) const
1177 {
1178         // if flag is false writeFile will not create any GUI
1179         // warnings, only cerr.
1180         // Needed for autosave in background or panic save (Matthias 120496)
1181
1182         if (read_only && (fname == filename)) {
1183                 // Here we should come with a question if we should
1184                 // perform the write anyway.
1185                 if (flag)
1186                         lyxerr << _("Error! Document is read-only: ")
1187                                << fname << endl;
1188                 else
1189                         WriteAlert(_("Error! Document is read-only: "),
1190                                    fname);
1191                 return false;
1192         }
1193
1194         FileInfo finfo(fname);
1195         if (finfo.exist() && !finfo.writable()) {
1196                 // Here we should come with a question if we should
1197                 // try to do the save anyway. (i.e. do a chmod first)
1198                 if (flag)
1199                         lyxerr << _("Error! Cannot write file: ")
1200                                << fname << endl;
1201                 else
1202                         WriteFSAlert(_("Error! Cannot write file: "),
1203                                      fname);
1204                 return false;
1205         }
1206
1207         ofstream ofs(fname.c_str());
1208         if (!ofs) {
1209                 if (flag)
1210                         lyxerr << _("Error! Cannot open file: ")
1211                                << fname << endl;
1212                 else
1213                         WriteFSAlert(_("Error! Cannot open file: "),
1214                                      fname);
1215                 return false;
1216         }
1217
1218 #ifdef HAVE_LOCALE
1219         // Use the standard "C" locale for file output.
1220         ofs.imbue(std::locale::classic());
1221 #endif
1222
1223         // The top of the file should not be written by params.
1224
1225         // write out a comment in the top of the file
1226         ofs << '#' << LYX_DOCVERSION 
1227             << " created this file. For more info see http://www.lyx.org/\n";
1228         ofs.setf(ios::showpoint|ios::fixed);
1229         ofs.precision(2);
1230 #ifndef HAVE_LOCALE
1231         char dummy_format[512];
1232         sprintf(dummy_format, "%.2f", LYX_FORMAT);
1233         ofs << "\\lyxformat " <<  dummy_format << "\n";
1234 #else
1235         ofs << "\\lyxformat " << setw(4) <<  LYX_FORMAT << "\n";
1236 #endif
1237         // now write out the buffer paramters.
1238         params.writeFile(ofs);
1239
1240         char footnoteflag = 0;
1241         char depth = 0;
1242
1243         // this will write out all the paragraphs
1244         // using recursive descent.
1245         paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1246
1247         // Write marker that shows file is complete
1248         ofs << "\n\\the_end" << endl;
1249
1250         ofs.close();
1251
1252         // how to check if close went ok?
1253         // Following is an attempt... (BE 20001011)
1254         
1255         // good() returns false if any error occured, including some
1256         //        formatting error.
1257         // bad()  returns true if something bad happened in the buffer,
1258         //        which should include file system full errors.
1259
1260         bool status = true;
1261         if (!ofs.good()) {
1262                 status = false;
1263 #if 0
1264                 if (ofs.bad()) {
1265                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1266                 } else {
1267                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1268                                << endl;
1269                 }
1270 #endif
1271         }
1272         
1273         return status;
1274 }
1275
1276
1277 string const Buffer::asciiParagraph(LyXParagraph const * par,
1278                                     unsigned int linelen) const
1279 {
1280         ostringstream buffer;
1281         LyXFont font1;
1282         LyXFont font2;
1283         Inset const * inset;
1284         char c;
1285         LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1286         char depth = 0;
1287         int ltype = 0;
1288         int ltype_depth = 0;
1289         unsigned int currlinelen = 0;
1290         bool ref_printed = false;
1291
1292         int noparbreak = 0;
1293         int islatex = 0;
1294         if (
1295 #ifndef NEW_INSETS
1296                 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1297 #endif
1298                 !par->previous
1299 #ifndef NEW_INSETS
1300                 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1301 #endif
1302                 ){
1303 #ifndef NEW_INSETS
1304                 /* begins a footnote environment ? */ 
1305                 if (footnoteflag != par->footnoteflag) {
1306                         footnoteflag = par->footnoteflag;
1307                         if (footnoteflag) {
1308                                 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1309                                 if ((linelen > 0) &&
1310                                     ((currlinelen + j) > linelen)) {
1311                                         buffer << "\n";
1312                                         currlinelen = 0;
1313                                 }
1314                                 buffer << "(["
1315                                        << string_footnotekinds[par->footnotekind]
1316                                        << "] ";
1317                                 currlinelen += j;
1318                         }
1319                 }
1320 #endif
1321                 /* begins or ends a deeper area ?*/ 
1322                 if (depth != par->depth) {
1323                         if (par->depth > depth) {
1324                                 while (par->depth > depth) {
1325                                         ++depth;
1326                                 }
1327                         }
1328                         else {
1329                                 while (par->depth < depth) {
1330                                         --depth;
1331                                 }
1332                         }
1333                 }
1334                 
1335                 /* First write the layout */
1336                 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1337                 if (tmp == "Itemize") {
1338                         ltype = 1;
1339                         ltype_depth = depth+1;
1340                 } else if (tmp == "Enumerate") {
1341                         ltype = 2;
1342                         ltype_depth = depth+1;
1343                 } else if (strstr(tmp.c_str(), "ection")) {
1344                         ltype = 3;
1345                         ltype_depth = depth+1;
1346                 } else if (strstr(tmp.c_str(), "aragraph")) {
1347                         ltype = 4;
1348                         ltype_depth = depth+1;
1349                 } else if (tmp == "Description") {
1350                         ltype = 5;
1351                         ltype_depth = depth+1;
1352                 } else if (tmp == "Abstract") {
1353                         ltype = 6;
1354                         ltype_depth = 0;
1355                 } else if (tmp == "Bibliography") {
1356                         ltype = 7;
1357                         ltype_depth = 0;
1358                 } else {
1359                         ltype = 0;
1360                         ltype_depth = 0;
1361                 }
1362                 
1363                 /* maybe some vertical spaces */ 
1364                 
1365                 /* the labelwidthstring used in lists */ 
1366                 
1367                 /* some lines? */ 
1368                 
1369                 /* some pagebreaks? */ 
1370                 
1371                 /* noindent ? */ 
1372                 
1373                 /* what about the alignment */ 
1374         } else {
1375 #ifndef NEW_INSETS
1376                 /* dummy layout, that means a footnote ended */ 
1377                 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1378                 buffer << ") ";
1379                 noparbreak = 1;
1380 #else
1381                 lyxerr << "Should this ever happen?" << endl;
1382 #endif
1383         }
1384       
1385         font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1386         for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1387                 if (!i && !footnoteflag && !noparbreak){
1388                         if (linelen > 0)
1389                                 buffer << "\n\n";
1390                         for (char j = 0; j < depth; ++j)
1391                                 buffer << "  ";
1392                         currlinelen = depth * 2;
1393                         switch (ltype) {
1394                         case 0: /* Standard */
1395                         case 4: /* (Sub)Paragraph */
1396                         case 5: /* Description */
1397                                 break;
1398                         case 6: /* Abstract */
1399                                 if (linelen > 0)
1400                                         buffer << "Abstract\n\n";
1401                                 else
1402                                         buffer << "Abstract: ";
1403                                 break;
1404                         case 7: /* Bibliography */
1405                                 if (!ref_printed) {
1406                                         if (linelen > 0)
1407                                                 buffer << "References\n\n";
1408                                         else
1409                                                 buffer << "References: ";
1410                                         ref_printed = true;
1411                                 }
1412                                 break;
1413                         default:
1414                                 buffer << par->labelstring << " ";
1415                                 break;
1416                         }
1417                         if (ltype_depth > depth) {
1418                                 for (char j = ltype_depth - 1; j > depth; --j)
1419                                         buffer << "  ";
1420                                 currlinelen += (ltype_depth-depth)*2;
1421                         }
1422                 }
1423                 font2 = par->GetFontSettings(params, i);
1424                 if (font1.latex() != font2.latex()) {
1425                         if (font2.latex() == LyXFont::OFF)
1426                                 islatex = 0;
1427                         else
1428                                 islatex = 1;
1429                 } else {
1430                         islatex = 0;
1431                 }
1432                 c = par->GetChar(i);
1433                 if (islatex)
1434                         continue;
1435                 switch (c) {
1436                 case LyXParagraph::META_INSET:
1437                         if ((inset = par->GetInset(i))) {
1438                                 if (!inset->Ascii(this, buffer)) {
1439                                         string dummy;
1440                                         string s = rsplit(buffer.str().c_str(),
1441                                                           dummy, '\n');
1442                                         currlinelen += s.length();
1443                                 } else {
1444                                         // to be sure it breaks paragraph
1445                                         currlinelen += linelen;
1446                                 }
1447                         }
1448                         break;
1449                 case LyXParagraph::META_NEWLINE:
1450                         if (linelen > 0) {
1451                                 buffer << "\n";
1452                                 for (char j = 0; j < depth; ++j)
1453                                         buffer << "  ";
1454                         }
1455                         currlinelen = depth * 2;
1456                         if (ltype_depth > depth) {
1457                                 for (char j = ltype_depth;
1458                                     j > depth; --j)
1459                                         buffer << "  ";
1460                                 currlinelen += (ltype_depth - depth) * 2;
1461                         }
1462                         break;
1463                 case LyXParagraph::META_HFILL: 
1464                         buffer << "\t";
1465                         break;
1466                 case '\\':
1467                         buffer << "\\";
1468                         break;
1469                 default:
1470                         if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1471                             (c == ' ') && ((i + 2) < par->size()))
1472                         {
1473                                 buffer << "\n";
1474                                 for (char j = 0; j < depth; ++j)
1475                                         buffer << "  ";
1476                                 currlinelen = depth * 2;
1477                                 if (ltype_depth > depth) {
1478                                         for (char j = ltype_depth;
1479                                             j > depth; --j)
1480                                                 buffer << "  ";
1481                                         currlinelen += (ltype_depth-depth)*2;
1482                                 }
1483                         } else if (c != '\0')
1484                                 buffer << c;
1485                         else if (c == '\0')
1486                                 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1487                         ++currlinelen;
1488                         break;
1489                 }
1490         }
1491         return buffer.str().c_str();
1492 }
1493
1494
1495 void Buffer::writeFileAscii(string const & fname, int linelen) 
1496 {
1497         ofstream ofs(fname.c_str());
1498         if (!ofs) {
1499                 WriteFSAlert(_("Error: Cannot write file:"), fname);
1500                 return;
1501         }
1502         writeFileAscii(ofs, linelen);
1503 }
1504
1505
1506 void Buffer::writeFileAscii(ostream & ofs, int linelen) 
1507 {
1508         LyXParagraph * par = paragraph;
1509         while (par) {
1510                 ofs << asciiParagraph(par, linelen);
1511                 par = par->next;
1512         }
1513         ofs << "\n";
1514 }
1515
1516
1517 void Buffer::makeLaTeXFile(string const & fname, 
1518                            string const & original_path,
1519                            bool nice, bool only_body)
1520 {
1521         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1522         
1523         niceFile = nice; // this will be used by Insetincludes.
1524
1525         tex_code_break_column = lyxrc.ascii_linelen;
1526
1527         LyXTextClass const & tclass =
1528                 textclasslist.TextClass(params.textclass);
1529
1530         ofstream ofs(fname.c_str());
1531         if (!ofs) {
1532                 WriteFSAlert(_("Error: Cannot open file: "), fname);
1533                 return;
1534         }
1535         
1536         // validate the buffer.
1537         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1538         LaTeXFeatures features(params, tclass.numLayouts());
1539         validate(features);
1540         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1541         
1542         texrow.reset();
1543         // The starting paragraph of the coming rows is the 
1544         // first paragraph of the document. (Asger)
1545         texrow.start(paragraph, 0);
1546
1547         if (!only_body && nice) {
1548                 ofs << "%% " LYX_DOCVERSION " created this file.  "
1549                         "For more info, see http://www.lyx.org/.\n"
1550                         "%% Do not edit unless you really know what "
1551                         "you are doing.\n";
1552                 texrow.newline();
1553                 texrow.newline();
1554         }
1555         lyxerr.debug() << "lyx header finished" << endl;
1556         // There are a few differences between nice LaTeX and usual files:
1557         // usual is \batchmode and has a 
1558         // special input@path to allow the including of figures
1559         // with either \input or \includegraphics (what figinsets do).
1560         // batchmode is not set if there is a tex_code_break_column.
1561         // In this case somebody is interested in the generated LaTeX,
1562         // so this is OK. input@path is set when the actual parameter
1563         // original_path is set. This is done for usual tex-file, but not
1564         // for nice-latex-file. (Matthias 250696)
1565         if (!only_body) {
1566                 if (!nice){
1567                         // code for usual, NOT nice-latex-file
1568                         ofs << "\\batchmode\n"; // changed
1569                         // from \nonstopmode
1570                         texrow.newline();
1571                 }
1572                 if (!original_path.empty()) {
1573                         ofs << "\\makeatletter\n"
1574                             << "\\def\\input@path{{"
1575                             << original_path << "/}}\n"
1576                             << "\\makeatother\n";
1577                         texrow.newline();
1578                         texrow.newline();
1579                         texrow.newline();
1580                 }
1581                 
1582                 ofs << "\\documentclass";
1583                 
1584                 string options; // the document class options.
1585                 
1586                 if (tokenPos(tclass.opt_fontsize(),
1587                              '|', params.fontsize) >= 0) {
1588                         // only write if existing in list (and not default)
1589                         options += params.fontsize;
1590                         options += "pt,";
1591                 }
1592                 
1593                 
1594                 if (!params.use_geometry &&
1595                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1596                         switch (params.papersize) {
1597                         case BufferParams::PAPER_A4PAPER:
1598                                 options += "a4paper,";
1599                                 break;
1600                         case BufferParams::PAPER_USLETTER:
1601                                 options += "letterpaper,";
1602                                 break;
1603                         case BufferParams::PAPER_A5PAPER:
1604                                 options += "a5paper,";
1605                                 break;
1606                         case BufferParams::PAPER_B5PAPER:
1607                                 options += "b5paper,";
1608                                 break;
1609                         case BufferParams::PAPER_EXECUTIVEPAPER:
1610                                 options += "executivepaper,";
1611                                 break;
1612                         case BufferParams::PAPER_LEGALPAPER:
1613                                 options += "legalpaper,";
1614                                 break;
1615                         }
1616                 }
1617
1618                 // if needed
1619                 if (params.sides != tclass.sides()) {
1620                         switch (params.sides) {
1621                         case LyXTextClass::OneSide:
1622                                 options += "oneside,";
1623                                 break;
1624                         case LyXTextClass::TwoSides:
1625                                 options += "twoside,";
1626                                 break;
1627                         }
1628
1629                 }
1630
1631                 // if needed
1632                 if (params.columns != tclass.columns()) {
1633                         if (params.columns == 2)
1634                                 options += "twocolumn,";
1635                         else
1636                                 options += "onecolumn,";
1637                 }
1638
1639                 if (!params.use_geometry 
1640                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1641                         options += "landscape,";
1642                 
1643                 // language should be a parameter to \documentclass
1644                 bool use_babel = false;
1645                 if (params.language->babel() == "hebrew") // This seems necessary
1646                         features.UsedLanguages.insert(default_language);
1647 #ifdef DO_USE_DEFAULT_LANGUAGE
1648                 if (params.language->lang() != "default" ||
1649                     !features.UsedLanguages.empty()) {
1650 #endif
1651                         use_babel = true;
1652                         for (LaTeXFeatures::LanguageList::const_iterator cit =
1653                                      features.UsedLanguages.begin();
1654                              cit != features.UsedLanguages.end(); ++cit)
1655                                 options += (*cit)->babel() + ",";
1656                         options += params.language->babel() + ',';
1657 #ifdef DO_USE_DEFAULT_LANGUAGE
1658                 }
1659 #endif
1660
1661                 // the user-defined options
1662                 if (!params.options.empty()) {
1663                         options += params.options + ',';
1664                 }
1665                 
1666                 if (!options.empty()){
1667                         options = strip(options, ',');
1668                         ofs << '[' << options << ']';
1669                 }
1670                 
1671                 ofs << '{'
1672                     << textclasslist.LatexnameOfClass(params.textclass)
1673                     << "}\n";
1674                 texrow.newline();
1675                 // end of \documentclass defs
1676                 
1677                 // font selection must be done before loading fontenc.sty
1678                 if (params.fonts != "default") {
1679                         ofs << "\\usepackage{" << params.fonts << "}\n";
1680                         texrow.newline();
1681                 }
1682                 // this one is not per buffer
1683                 if (lyxrc.fontenc != "default") {
1684                         ofs << "\\usepackage[" << lyxrc.fontenc
1685                             << "]{fontenc}\n";
1686                         texrow.newline();
1687                 }
1688
1689                 if (params.inputenc == "auto") {
1690                         string const doc_encoding =
1691                                 params.language->encoding()->LatexName();
1692
1693                         // Create a list with all the input encodings used 
1694                         // in the document
1695                         set<string> encodings;
1696                         for (LaTeXFeatures::LanguageList::const_iterator it =
1697                                      features.UsedLanguages.begin();
1698                              it != features.UsedLanguages.end(); ++it)
1699                                 if ((*it)->encoding()->LatexName() != doc_encoding)
1700                                         encodings.insert((*it)->encoding()->LatexName());
1701
1702                         ofs << "\\usepackage[";
1703                         std::copy(encodings.begin(), encodings.end(),
1704                                   std::ostream_iterator<string>(ofs, ","));
1705                         ofs << doc_encoding << "]{inputenc}\n";
1706                         texrow.newline();
1707                 } else if (params.inputenc != "default") {
1708                         ofs << "\\usepackage[" << params.inputenc
1709                             << "]{inputenc}\n";
1710                         texrow.newline();
1711                 }
1712
1713                 // At the very beginning the text parameters.
1714                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1715                         switch (params.paperpackage) {
1716                         case BufferParams::PACKAGE_A4:
1717                                 ofs << "\\usepackage{a4}\n";
1718                                 texrow.newline();
1719                                 break;
1720                         case BufferParams::PACKAGE_A4WIDE:
1721                                 ofs << "\\usepackage{a4wide}\n";
1722                                 texrow.newline();
1723                                 break;
1724                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1725                                 ofs << "\\usepackage[widemargins]{a4}\n";
1726                                 texrow.newline();
1727                                 break;
1728                         }
1729                 }
1730                 if (params.use_geometry) {
1731                         ofs << "\\usepackage{geometry}\n";
1732                         texrow.newline();
1733                         ofs << "\\geometry{verbose";
1734                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1735                                 ofs << ",landscape";
1736                         switch (params.papersize2) {
1737                         case BufferParams::VM_PAPER_CUSTOM:
1738                                 if (!params.paperwidth.empty())
1739                                         ofs << ",paperwidth="
1740                                             << params.paperwidth;
1741                                 if (!params.paperheight.empty())
1742                                         ofs << ",paperheight="
1743                                             << params.paperheight;
1744                                 break;
1745                         case BufferParams::VM_PAPER_USLETTER:
1746                                 ofs << ",letterpaper";
1747                                 break;
1748                         case BufferParams::VM_PAPER_USLEGAL:
1749                                 ofs << ",legalpaper";
1750                                 break;
1751                         case BufferParams::VM_PAPER_USEXECUTIVE:
1752                                 ofs << ",executivepaper";
1753                                 break;
1754                         case BufferParams::VM_PAPER_A3:
1755                                 ofs << ",a3paper";
1756                                 break;
1757                         case BufferParams::VM_PAPER_A4:
1758                                 ofs << ",a4paper";
1759                                 break;
1760                         case BufferParams::VM_PAPER_A5:
1761                                 ofs << ",a5paper";
1762                                 break;
1763                         case BufferParams::VM_PAPER_B3:
1764                                 ofs << ",b3paper";
1765                                 break;
1766                         case BufferParams::VM_PAPER_B4:
1767                                 ofs << ",b4paper";
1768                                 break;
1769                         case BufferParams::VM_PAPER_B5:
1770                                 ofs << ",b5paper";
1771                                 break;
1772                         default:
1773                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1774                                 switch (lyxrc.default_papersize) {
1775                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1776                                 case BufferParams::PAPER_USLETTER:
1777                                         ofs << ",letterpaper";
1778                                         break;
1779                                 case BufferParams::PAPER_LEGALPAPER:
1780                                         ofs << ",legalpaper";
1781                                         break;
1782                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1783                                         ofs << ",executivepaper";
1784                                         break;
1785                                 case BufferParams::PAPER_A3PAPER:
1786                                         ofs << ",a3paper";
1787                                         break;
1788                                 case BufferParams::PAPER_A4PAPER:
1789                                         ofs << ",a4paper";
1790                                         break;
1791                                 case BufferParams::PAPER_A5PAPER:
1792                                         ofs << ",a5paper";
1793                                         break;
1794                                 case BufferParams::PAPER_B5PAPER:
1795                                         ofs << ",b5paper";
1796                                         break;
1797                                 }
1798                         }
1799                         if (!params.topmargin.empty())
1800                                 ofs << ",tmargin=" << params.topmargin;
1801                         if (!params.bottommargin.empty())
1802                                 ofs << ",bmargin=" << params.bottommargin;
1803                         if (!params.leftmargin.empty())
1804                                 ofs << ",lmargin=" << params.leftmargin;
1805                         if (!params.rightmargin.empty())
1806                                 ofs << ",rmargin=" << params.rightmargin;
1807                         if (!params.headheight.empty())
1808                                 ofs << ",headheight=" << params.headheight;
1809                         if (!params.headsep.empty())
1810                                 ofs << ",headsep=" << params.headsep;
1811                         if (!params.footskip.empty())
1812                                 ofs << ",footskip=" << params.footskip;
1813                         ofs << "}\n";
1814                         texrow.newline();
1815                 }
1816                 if (params.use_amsmath
1817                     && !tclass.provides(LyXTextClass::amsmath)) {
1818                         ofs << "\\usepackage{amsmath}\n";
1819                         texrow.newline();
1820                 }
1821
1822                 if (tokenPos(tclass.opt_pagestyle(),
1823                              '|', params.pagestyle) >= 0) {
1824                         if (params.pagestyle == "fancy") {
1825                                 ofs << "\\usepackage{fancyhdr}\n";
1826                                 texrow.newline();
1827                         }
1828                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1829                         texrow.newline();
1830                 }
1831
1832                 // We try to load babel late, in case it interferes
1833                 // with other packages.
1834                 if (use_babel) {
1835                         ofs << lyxrc.language_package << endl;
1836                         texrow.newline();
1837                 }
1838
1839                 if (params.secnumdepth != tclass.secnumdepth()) {
1840                         ofs << "\\setcounter{secnumdepth}{"
1841                             << params.secnumdepth
1842                             << "}\n";
1843                         texrow.newline();
1844                 }
1845                 if (params.tocdepth != tclass.tocdepth()) {
1846                         ofs << "\\setcounter{tocdepth}{"
1847                             << params.tocdepth
1848                             << "}\n";
1849                         texrow.newline();
1850                 }
1851                 
1852                 if (params.paragraph_separation) {
1853                         switch (params.defskip.kind()) {
1854                         case VSpace::SMALLSKIP: 
1855                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1856                                 break;
1857                         case VSpace::MEDSKIP:
1858                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1859                                 break;
1860                         case VSpace::BIGSKIP:
1861                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1862                                 break;
1863                         case VSpace::LENGTH:
1864                                 ofs << "\\setlength\\parskip{"
1865                                     << params.defskip.length().asLatexString()
1866                                     << "}\n";
1867                                 break;
1868                         default: // should never happen // Then delete it.
1869                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1870                                 break;
1871                         }
1872                         texrow.newline();
1873                         
1874                         ofs << "\\setlength\\parindent{0pt}\n";
1875                         texrow.newline();
1876                 }
1877
1878                 // Now insert the LyX specific LaTeX commands...
1879
1880                 // The optional packages;
1881                 string preamble(features.getPackages());
1882
1883                 // this might be useful...
1884                 preamble += "\n\\makeatletter\n";
1885
1886                 // Some macros LyX will need
1887                 string tmppreamble(features.getMacros());
1888
1889                 if (!tmppreamble.empty()) {
1890                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1891                                 "LyX specific LaTeX commands.\n"
1892                                 + tmppreamble + '\n';
1893                 }
1894
1895                 // the text class specific preamble 
1896                 tmppreamble = features.getTClassPreamble();
1897                 if (!tmppreamble.empty()) {
1898                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1899                                 "Textclass specific LaTeX commands.\n"
1900                                 + tmppreamble + '\n';
1901                 }
1902
1903                 /* the user-defined preamble */
1904                 if (!params.preamble.empty()) {
1905                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1906                                 "User specified LaTeX commands.\n"
1907                                 + params.preamble + '\n';
1908                 }
1909
1910                 preamble += "\\makeatother\n";
1911
1912                 // Itemize bullet settings need to be last in case the user
1913                 // defines their own bullets that use a package included
1914                 // in the user-defined preamble -- ARRae
1915                 // Actually it has to be done much later than that
1916                 // since some packages like frenchb make modifications
1917                 // at \begin{document} time -- JMarc 
1918                 string bullets_def;
1919                 for (int i = 0; i < 4; ++i) {
1920                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1921                                 if (bullets_def.empty())
1922                                         bullets_def="\\AtBeginDocument{\n";
1923                                 bullets_def += "  \\renewcommand{\\labelitemi";
1924                                 switch (i) {
1925                                 // `i' is one less than the item to modify
1926                                 case 0:
1927                                         break;
1928                                 case 1:
1929                                         bullets_def += 'i';
1930                                         break;
1931                                 case 2:
1932                                         bullets_def += "ii";
1933                                         break;
1934                                 case 3:
1935                                         bullets_def += 'v';
1936                                         break;
1937                                 }
1938                                 bullets_def += "}{" + 
1939                                   params.user_defined_bullets[i].getText() 
1940                                   + "}\n";
1941                         }
1942                 }
1943
1944                 if (!bullets_def.empty())
1945                   preamble += bullets_def + "}\n\n";
1946
1947                 for (int j = countChar(preamble, '\n'); j-- ;) {
1948                         texrow.newline();
1949                 }
1950
1951                 ofs << preamble;
1952
1953                 // make the body.
1954                 ofs << "\\begin{document}\n";
1955                 texrow.newline();
1956         } // only_body
1957         lyxerr.debug() << "preamble finished, now the body." << endl;
1958 #ifdef DO_USE_DEFAULT_LANGUAGE
1959         if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
1960 #else
1961         if (!lyxrc.language_auto_begin) {
1962 #endif
1963                 ofs << subst(lyxrc.language_command_begin, "$$lang",
1964                              params.language->babel())
1965                     << endl;
1966                 texrow.newline();
1967         }
1968         
1969         latexParagraphs(ofs, paragraph, 0, texrow);
1970
1971         // add this just in case after all the paragraphs
1972         ofs << endl;
1973         texrow.newline();
1974
1975 #ifdef DO_USE_DEFAULT_LANGUAGE
1976         if (!lyxrc.language_auto_end && params.language->lang() != "default") {
1977 #else
1978                 if (!lyxrc.language_auto_end) {
1979 #endif
1980                 ofs << subst(lyxrc.language_command_end, "$$lang",
1981                              params.language->babel())
1982                     << endl;
1983                 texrow.newline();
1984         }
1985
1986         if (!only_body) {
1987                 ofs << "\\end{document}\n";
1988                 texrow.newline();
1989         
1990                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1991         } else {
1992                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1993                                      << endl;
1994         }
1995
1996         // Just to be sure. (Asger)
1997         texrow.newline();
1998
1999         // tex_code_break_column's value is used to decide
2000         // if we are in batchmode or not (within mathed_write()
2001         // in math_write.C) so we must set it to a non-zero
2002         // value when we leave otherwise we save incorrect .lyx files.
2003         tex_code_break_column = lyxrc.ascii_linelen;
2004
2005         ofs.close();
2006         if (ofs.fail()) {
2007                 lyxerr << "File was not closed properly." << endl;
2008         }
2009         
2010         lyxerr.debug() << "Finished making latex file." << endl;
2011 }
2012
2013
2014 //
2015 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2016 //
2017 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2018                              LyXParagraph * endpar, TexRow & texrow) const
2019 {
2020         bool was_title = false;
2021         bool already_title = false;
2022         std::ostringstream ftnote;
2023         TexRow ft_texrow;
2024         int ftcount = 0;
2025
2026         // if only_body
2027         while (par != endpar) {
2028 #ifndef NEW_INSETS
2029                 if (par->IsDummy())
2030                         lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2031                                              << endl;
2032 #endif
2033                 LyXLayout const & layout =
2034                         textclasslist.Style(params.textclass,
2035                                             par->layout);
2036             
2037                 if (layout.intitle) {
2038                         if (already_title) {
2039                                 lyxerr <<"Error in latexParagraphs: You"
2040                                         " should not mix title layouts"
2041                                         " with normal ones." << endl;
2042                         } else
2043                                 was_title = true;
2044                 } else if (was_title && !already_title) {
2045                         ofs << "\\maketitle\n";
2046                         texrow.newline();
2047                         already_title = true;
2048                         was_title = false;                  
2049                 }
2050                 // We are at depth 0 so we can just use
2051                 // ordinary \footnote{} generation
2052                 // flag this with ftcount
2053                 ftcount = -1;
2054                 if (layout.isEnvironment()
2055                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2056                         par = par->TeXEnvironment(this, params, ofs, texrow
2057 #ifndef NEW_INSETS
2058                                                   ,ftnote, ft_texrow, ftcount
2059 #endif
2060                                 );
2061                 } else {
2062                         par = par->TeXOnePar(this, params, ofs, texrow, false
2063 #ifndef NEW_INSETS
2064                                              ,
2065                                              ftnote, ft_texrow, ftcount
2066 #endif
2067                                 );
2068                 }
2069
2070                 // Write out what we've generated...
2071                 if (ftcount >= 1) {
2072                         if (ftcount > 1) {
2073                                 ofs << "\\addtocounter{footnote}{-"
2074                                     << ftcount - 1
2075                                     << '}';
2076                         }
2077                         ofs << ftnote.str();
2078                         texrow += ft_texrow;
2079
2080                         // The extra .c_str() is needed when we use
2081                         // lyxstring instead of the STL string class. 
2082                         ftnote.str(string().c_str());
2083                         ft_texrow.reset();
2084                         ftcount = 0;
2085                 }
2086         }
2087         // It might be that we only have a title in this document
2088         if (was_title && !already_title) {
2089                 ofs << "\\maketitle\n";
2090                 texrow.newline();
2091         }
2092 }
2093
2094
2095 bool Buffer::isLatex() const
2096 {
2097         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2098 }
2099
2100
2101 bool Buffer::isLinuxDoc() const
2102 {
2103         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2104 }
2105
2106
2107 bool Buffer::isLiterate() const
2108 {
2109         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2110 }
2111
2112
2113 bool Buffer::isDocBook() const
2114 {
2115         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2116 }
2117
2118
2119 bool Buffer::isSGML() const
2120 {
2121         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2122                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2123 }
2124
2125
2126 void Buffer::sgmlOpenTag(ostream & os, int depth,
2127                          string const & latexname) const
2128 {
2129         if (latexname != "!-- --")
2130                 os << string(depth, ' ') << "<" << latexname << ">\n";
2131 }
2132
2133
2134 void Buffer::sgmlCloseTag(ostream & os, int depth,
2135                           string const & latexname) const
2136 {
2137         if (latexname != "!-- --")
2138                 os << string(depth, ' ') << "</" << latexname << ">\n";
2139 }
2140
2141
2142 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2143 {
2144         LyXParagraph * par = paragraph;
2145
2146         niceFile = nice; // this will be used by Insetincludes.
2147
2148         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2149         string environment_stack[10];
2150         string item_name;
2151
2152         int depth = 0; // paragraph depth
2153
2154         ofstream ofs(fname.c_str());
2155
2156         if (!ofs) {
2157                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2158                 return;
2159         }
2160
2161         LyXTextClass const & tclass =
2162                 textclasslist.TextClass(params.textclass);
2163
2164         LaTeXFeatures features(params, tclass.numLayouts());
2165         validate(features);
2166
2167         //if (nice)
2168         tex_code_break_column = lyxrc.ascii_linelen;
2169         //else
2170         //tex_code_break_column = 0;
2171
2172         texrow.reset();
2173
2174         if (!body_only) {
2175                 string sgml_includedfiles=features.getIncludedFiles(fname);
2176
2177                 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2178                         ofs << "<!doctype linuxdoc system>\n\n";
2179                 } else {
2180                         ofs << "<!doctype linuxdoc system [ "
2181                             << params.preamble << sgml_includedfiles << " \n]>\n\n";
2182                 }
2183
2184                 if (params.options.empty())
2185                         sgmlOpenTag(ofs, 0, top_element);
2186                 else {
2187                         string top = top_element;
2188                         top += " ";
2189                         top += params.options;
2190                         sgmlOpenTag(ofs, 0, top);
2191                 }
2192         }
2193
2194         ofs << "<!-- "  << LYX_DOCVERSION 
2195             << " created this file. For more info see http://www.lyx.org/"
2196             << " -->\n";
2197
2198         while (par) {
2199                 int desc_on = 0; // description mode
2200                 LyXLayout const & style =
2201                         textclasslist.Style(params.textclass,
2202                                             par->layout);
2203
2204                 // treat <toc> as a special case for compatibility with old code
2205                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2206                         Inset * inset = par->GetInset(0);
2207                         Inset::Code lyx_code = inset->LyxCode();
2208                         if (lyx_code == Inset::TOC_CODE){
2209                                 string const temp = "toc";
2210                                 sgmlOpenTag(ofs, depth, temp);
2211
2212                                 par = par->next;
2213 #ifndef NEW_INSETS
2214                                 linuxDocHandleFootnote(ofs, par, depth);
2215 #endif
2216                                 continue;
2217                         }
2218                 }
2219
2220                 // environment tag closing
2221                 for (; depth > par->depth; --depth) {
2222                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2223                         environment_stack[depth].erase();
2224                 }
2225
2226                 // write opening SGML tags
2227                 switch (style.latextype) {
2228                 case LATEX_PARAGRAPH:
2229                         if (depth == par->depth 
2230                            && !environment_stack[depth].empty()) {
2231                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2232                                 environment_stack[depth].erase();
2233                                 if (depth) 
2234                                         --depth;
2235                                 else
2236                                         ofs << "</p>";
2237                         }
2238                         sgmlOpenTag(ofs, depth, style.latexname());
2239                         break;
2240
2241                 case LATEX_COMMAND:
2242                         if (depth!= 0)
2243                                 LinuxDocError(par, 0,
2244                                               _("Error : Wrong depth for"
2245                                                 " LatexType Command.\n"));
2246
2247                         if (!environment_stack[depth].empty()){
2248                                 sgmlCloseTag(ofs, depth,
2249                                              environment_stack[depth]);
2250                                 ofs << "</p>";
2251                         }
2252
2253                         environment_stack[depth].erase();
2254                         sgmlOpenTag(ofs, depth, style.latexname());
2255                         break;
2256
2257                 case LATEX_ENVIRONMENT:
2258                 case LATEX_ITEM_ENVIRONMENT:
2259                         if (depth == par->depth 
2260                            && environment_stack[depth] != style.latexname()
2261                            && !environment_stack[depth].empty()) {
2262
2263                                 sgmlCloseTag(ofs, depth,
2264                                              environment_stack[depth]);
2265                                 environment_stack[depth].erase();
2266                         }
2267                         if (depth < par->depth) {
2268                                depth = par->depth;
2269                                environment_stack[depth].erase();
2270                         }
2271                         if (environment_stack[depth] != style.latexname()) {
2272                                 if (depth == 0) {
2273                                         string const temp = "p";
2274                                         sgmlOpenTag(ofs, depth, temp);
2275                                 }
2276                                 environment_stack[depth] = style.latexname();
2277                                 sgmlOpenTag(ofs, depth,
2278                                             environment_stack[depth]);
2279                         }
2280                         if (style.latextype == LATEX_ENVIRONMENT) break;
2281
2282                         desc_on = (style.labeltype == LABEL_MANUAL);
2283
2284                         if (desc_on)
2285                                 item_name = "tag";
2286                         else
2287                                 item_name = "item";
2288
2289                         sgmlOpenTag(ofs, depth + 1, item_name);
2290                         break;
2291                 default:
2292                         sgmlOpenTag(ofs, depth, style.latexname());
2293                         break;
2294                 }
2295
2296 #ifndef NEW_INSETS
2297                 do {
2298 #endif
2299                         SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2300
2301                         par = par->next;
2302 #ifndef NEW_INSETS
2303                         linuxDocHandleFootnote(ofs, par, depth);
2304                 }
2305                 while(par && par->IsDummy());
2306 #endif
2307
2308                 ofs << "\n";
2309                 // write closing SGML tags
2310                 switch (style.latextype) {
2311                 case LATEX_COMMAND:
2312                 case LATEX_ENVIRONMENT:
2313                 case LATEX_ITEM_ENVIRONMENT:
2314                         break;
2315                 default:
2316                         sgmlCloseTag(ofs, depth, style.latexname());
2317                         break;
2318                 }
2319         }
2320    
2321         // Close open tags
2322         for (; depth > 0; --depth)
2323                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2324
2325         if (!environment_stack[depth].empty())
2326                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2327
2328         if (!body_only) {
2329                 ofs << "\n\n";
2330                 sgmlCloseTag(ofs, 0, top_element);
2331         }
2332
2333         ofs.close();
2334         // How to check for successful close
2335 }
2336
2337
2338 #ifndef NEW_INSETS
2339 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2340                                     int depth)
2341 {
2342         string const tag = "footnote";
2343
2344         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2345                 sgmlOpenTag(os, depth + 1, tag);
2346                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2347                 sgmlCloseTag(os, depth + 1, tag);
2348                 par = par->next;
2349         }
2350 }
2351 #endif
2352
2353
2354 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2355                                   int depth, int desc_on,
2356                                   LyXParagraph * & par)
2357 {
2358         LyXParagraph * tpar = par;
2359         while (tpar
2360 #ifndef NEW_INSETS
2361                && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2362 #endif
2363                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2364                                                              "Caption").second))
2365                 tpar = tpar->next;
2366         if (tpar &&
2367             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2368                                                          "Caption").second) {
2369                 sgmlOpenTag(os, depth + 1, inner_tag);
2370                 string extra_par;
2371                 SimpleDocBookOnePar(os, extra_par, tpar,
2372                                     desc_on, depth + 2);
2373                 sgmlCloseTag(os, depth+1, inner_tag);
2374                 if (!extra_par.empty())
2375                         os << extra_par;
2376         }
2377 }
2378
2379
2380 #ifndef NEW_INSETS
2381 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2382                                    int depth)
2383 {
2384         string tag, inner_tag;
2385         string tmp_par, extra_par;
2386         bool inner_span = false;
2387         int desc_on = 4;
2388
2389         // Someone should give this enum a proper name (Lgb)
2390         enum SOME_ENUM {
2391                 NO_ONE,
2392                 FOOTNOTE_LIKE,
2393                 MARGIN_LIKE,
2394                 FIG_LIKE,
2395                 TAB_LIKE
2396         };
2397         SOME_ENUM last = NO_ONE;
2398         SOME_ENUM present = FOOTNOTE_LIKE;
2399
2400         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2401                 if (last == present) {
2402                         if (inner_span) {
2403                                 if (!tmp_par.empty()) {
2404                                         os << tmp_par;
2405                                         tmp_par.erase();
2406                                         sgmlCloseTag(os, depth + 1, inner_tag);
2407                                         sgmlOpenTag(os, depth + 1, inner_tag);
2408                                 }
2409                         } else {
2410                                 os << "\n";
2411                         }
2412                 } else {
2413                         os << tmp_par;
2414                         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2415                                                             inner_tag);
2416                         if (!extra_par.empty()) os << extra_par;
2417                         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2418                         extra_par.erase();
2419
2420                         switch (par->footnotekind) {
2421                         case LyXParagraph::FOOTNOTE:
2422                         case LyXParagraph::ALGORITHM:
2423                                 tag = "footnote";
2424                                 inner_tag = "para";
2425                                 present = FOOTNOTE_LIKE;
2426                                 inner_span = true;
2427                                 break;
2428                         case LyXParagraph::MARGIN:
2429                                 tag = "sidebar";
2430                                 inner_tag = "para";
2431                                 present = MARGIN_LIKE;
2432                                 inner_span = true;
2433                                 break;
2434                         case LyXParagraph::FIG:
2435                         case LyXParagraph::WIDE_FIG:
2436                                 tag = "figure";
2437                                 inner_tag = "title";
2438                                 present = FIG_LIKE;
2439                                 inner_span = false;
2440                                 break;
2441                         case LyXParagraph::TAB:
2442                         case LyXParagraph::WIDE_TAB:
2443                                 tag = "table";
2444                                 inner_tag = "title";
2445                                 present = TAB_LIKE;
2446                                 inner_span = false;
2447                                 break;
2448                         }
2449                         sgmlOpenTag(os, depth, tag);
2450                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2451                                 DocBookHandleCaption(os, inner_tag, depth,
2452                                                      desc_on, par);
2453                                 inner_tag.erase();
2454                         } else {
2455                                 sgmlOpenTag(os, depth + 1, inner_tag);
2456                         }
2457                 }
2458                 // ignore all caption here, we processed them above!!!
2459                 if (par->layout != textclasslist
2460                     .NumberOfLayout(params.textclass,
2461                                     "Caption").second) {
2462                         std::ostringstream ost;
2463                         SimpleDocBookOnePar(ost, extra_par, par,
2464                                             desc_on, depth + 2);
2465                         tmp_par += ost.str().c_str();
2466                 }
2467                 tmp_par = frontStrip(strip(tmp_par));
2468
2469                 last = present;
2470                 par = par->next;
2471         }
2472         os << tmp_par;
2473         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2474         if (!extra_par.empty()) os << extra_par;
2475         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2476 }
2477 #endif
2478
2479
2480 // push a tag in a style stack
2481 void Buffer::push_tag(ostream & os, string const & tag,
2482                       int & pos, char stack[5][3])
2483 {
2484 #ifdef WITH_WARNINGS
2485 #warning Use a real stack! (Lgb)
2486 #endif
2487         // pop all previous tags
2488         for (int j = pos; j >= 0; --j)
2489                 os << "</" << stack[j] << ">";
2490
2491         // add new tag
2492         sprintf(stack[++pos], "%s", tag.c_str());
2493
2494         // push all tags
2495         for (int i = 0; i <= pos; ++i)
2496                 os << "<" << stack[i] << ">";
2497 }
2498
2499
2500 void Buffer::pop_tag(ostream & os, string const & tag,
2501                      int & pos, char stack[5][3])
2502 {
2503 #ifdef WITH_WARNINGS
2504 #warning Use a real stack! (Lgb)
2505 #endif
2506         // Please, Lars, do not remove the global variable. I already
2507         // had to reintroduce it twice! (JMarc)
2508         // but...but... I'll remove it anyway. (well not quite) (Lgb)
2509 #if 0
2510         int j;
2511         
2512         // pop all tags till specified one
2513         for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2514                 os << "</" << stack[j] << ">";
2515
2516         // closes the tag
2517         os << "</" << tag << ">";
2518         
2519         // push all tags, but the specified one
2520         for (j = j + 1; j <= pos; ++j) {
2521                 os << "<" << stack[j] << ">";
2522                 strcpy(stack[j - 1], stack[j]);
2523         }
2524         --pos;
2525 #else
2526         // pop all tags till specified one
2527         int j = pos;
2528         for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2529                 os << "</" << stack[j] << ">";
2530
2531         // closes the tag
2532         os << "</" << tag << ">";
2533         
2534         // push all tags, but the specified one
2535         for (int i = j + 1; i <= pos; ++i) {
2536                 os << "<" << stack[i] << ">";
2537                 strcpy(stack[i - 1], stack[i]);
2538         }
2539         --pos;
2540 #endif
2541 }
2542
2543
2544 // Handle internal paragraph parsing -- layout already processed.
2545
2546 // checks, if newcol chars should be put into this line
2547 // writes newline, if necessary.
2548 static
2549 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2550                           string::size_type newcol)
2551 {
2552         colcount += newcol;
2553         if (colcount > lyxrc.ascii_linelen) {
2554                 os << "\n";
2555                 colcount = newcol; // assume write after this call
2556         }
2557 }
2558
2559
2560 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2561                                   int desc_on, int /*depth*/)
2562 {
2563         LyXFont font1;
2564         char c;
2565         Inset * inset;
2566         LyXParagraph::size_type main_body;
2567         int j;
2568         LyXLayout const & style = textclasslist.Style(params.textclass,
2569                                                       par->GetLayout());
2570
2571         char family_type = 0;               // family font flag 
2572         bool is_bold     = false;           // series font flag 
2573         char shape_type  = 0;               // shape font flag 
2574         bool is_em = false;                 // emphasis (italic) font flag 
2575
2576         int stack_num = -1;          // style stack position
2577         // Can this be rewritten to use a std::stack, please. (Lgb)
2578         char stack[5][3];            // style stack 
2579         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2580
2581         if (style.labeltype != LABEL_MANUAL)
2582                 main_body = 0;
2583         else
2584                 main_body = par->BeginningOfMainBody();
2585
2586         // gets paragraph main font
2587         if (main_body > 0)
2588                 font1 = style.labelfont;
2589         else
2590                 font1 = style.font;
2591
2592   
2593         // parsing main loop
2594         for (LyXParagraph::size_type i = 0;
2595              i < par->size(); ++i) {
2596
2597                 // handle quote tag
2598                 if (i == main_body
2599 #ifndef NEW_INSETS
2600                     && !par->IsDummy()
2601 #endif
2602                         ) {
2603                         if (main_body > 0)
2604                                 font1 = style.font;
2605                 }
2606
2607                 LyXFont const font2 = par->getFont(params, i);
2608
2609                 if (font1.family() != font2.family()) {
2610                         switch (family_type) {
2611                         case 0:
2612                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2613                                         push_tag(os, "tt", stack_num, stack);
2614                                         family_type = 1;
2615                                 }
2616                                 else if (font2.family() == LyXFont::SANS_FAMILY) {
2617                                         push_tag(os, "sf", stack_num, stack);
2618                                         family_type = 2;
2619                                 }
2620                                 break;
2621                         case 1:
2622                                 pop_tag(os, "tt", stack_num, stack);
2623                                 if (font2.family() == LyXFont::SANS_FAMILY) {
2624                                         push_tag(os, "sf", stack_num, stack);
2625                                         family_type = 2;
2626                                 } else {
2627                                         family_type = 0;
2628                                 }
2629                                 break;
2630                         case 2:
2631                                 pop_tag(os, "sf", stack_num, stack);
2632                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2633                                         push_tag(os, "tt", stack_num, stack);
2634                                         family_type = 1;
2635                                 } else {
2636                                         family_type = 0;
2637                                 }
2638                         }
2639                 }
2640
2641                 // handle bold face
2642                 if (font1.series() != font2.series()) {
2643                         if (font2.series() == LyXFont::BOLD_SERIES) {
2644                                 push_tag(os, "bf", stack_num, stack);
2645                                 is_bold = true;
2646                         } else if (is_bold) {
2647                                 pop_tag(os, "bf", stack_num, stack);
2648                                 is_bold = false;
2649                         }
2650                 }
2651
2652                 // handle italic and slanted fonts
2653                 if (font1.shape() != font2.shape()) {
2654                         switch (shape_type) {
2655                         case 0:
2656                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2657                                         push_tag(os, "it", stack_num, stack);
2658                                         shape_type = 1;
2659                                 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2660                                         push_tag(os, "sl", stack_num, stack);
2661                                         shape_type = 2;
2662                                 }
2663                                 break;
2664                         case 1:
2665                                 pop_tag(os, "it", stack_num, stack);
2666                                 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2667                                         push_tag(os, "sl", stack_num, stack);
2668                                         shape_type = 2;
2669                                 } else {
2670                                         shape_type = 0;
2671                                 }
2672                                 break;
2673                         case 2:
2674                                 pop_tag(os, "sl", stack_num, stack);
2675                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2676                                         push_tag(os, "it", stack_num, stack);
2677                                         shape_type = 1;
2678                                 } else {
2679                                         shape_type = 0;
2680                                 }
2681                         }
2682                 }
2683                 // handle <em> tag
2684                 if (font1.emph() != font2.emph()) {
2685                         if (font2.emph() == LyXFont::ON) {
2686                                 push_tag(os, "em", stack_num, stack);
2687                                 is_em = true;
2688                         } else if (is_em) {
2689                                 pop_tag(os, "em", stack_num, stack);
2690                                 is_em = false;
2691                         }
2692                 }
2693
2694                 c = par->GetChar(i);
2695
2696                 if (c == LyXParagraph::META_INSET) {
2697                         inset = par->GetInset(i);
2698                         inset->Linuxdoc(this, os);
2699                 }
2700
2701                 if (font2.latex() == LyXFont::ON) {
2702                         // "TeX"-Mode on == > SGML-Mode on.
2703                         if (c != '\0')
2704                                 os << c; // see LaTeX-Generation...
2705                         ++char_line_count;
2706                 } else {
2707                         string sgml_string;
2708                         if (par->linuxDocConvertChar(c, sgml_string)
2709                             && !style.free_spacing) { // in freespacing
2710                                                      // mode, spaces are
2711                                                      // non-breaking characters
2712                                 // char is ' '
2713                                 if (desc_on == 1) {
2714                                         ++char_line_count;
2715                                         linux_doc_line_break(os, char_line_count, 6);
2716                                         os << "</tag>";
2717                                         desc_on = 2;
2718                                 } else  {
2719                                         linux_doc_line_break(os, char_line_count, 1);
2720                                         os << c;
2721                                 }
2722                         } else {
2723                                 os << sgml_string;
2724                                 char_line_count += sgml_string.length();
2725                         }
2726                 }
2727                 font1 = font2;
2728         }
2729
2730         // needed if there is an optional argument but no contents
2731         if (main_body > 0 && main_body == par->size()) {
2732                 font1 = style.font;
2733         }
2734
2735         // pop all defined Styles
2736         for (j = stack_num; j >= 0; --j) {
2737                 linux_doc_line_break(os, 
2738                                      char_line_count, 
2739                                      3 + strlen(stack[j]));
2740                 os << "</" << stack[j] << ">";
2741         }
2742
2743         // resets description flag correctly
2744         switch (desc_on){
2745         case 1:
2746                 // <tag> not closed...
2747                 linux_doc_line_break(os, char_line_count, 6);
2748                 os << "</tag>";
2749                 break;
2750         case 2:
2751                 // fprintf(file, "</p>");
2752                 break;
2753         }
2754 }
2755
2756
2757 // Print an error message.
2758 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2759                            string const & message) 
2760 {
2761         // insert an error marker in text
2762         InsetError * new_inset = new InsetError(message);
2763         par->InsertInset(pos, new_inset);
2764 }
2765
2766 // This constant defines the maximum number of 
2767 // environment layouts that can be nesteded.
2768 // The same applies for command layouts.
2769 // These values should be more than enough.
2770 //           José Matos (1999/07/22)
2771
2772 enum { MAX_NEST_LEVEL = 25};
2773
2774 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2775 {
2776         LyXParagraph * par = paragraph;
2777
2778         niceFile = nice; // this will be used by Insetincludes.
2779
2780         string top_element= textclasslist.LatexnameOfClass(params.textclass);
2781         // Please use a real stack.
2782         string environment_stack[MAX_NEST_LEVEL];
2783         string environment_inner[MAX_NEST_LEVEL];
2784         // Please use a real stack.
2785         string command_stack[MAX_NEST_LEVEL];
2786         bool command_flag= false;
2787         int command_depth= 0, command_base= 0, cmd_depth= 0;
2788
2789         string item_name, command_name;
2790         string c_depth, c_params, tmps;
2791
2792         int depth = 0; // paragraph depth
2793         LyXTextClass const & tclass =
2794                 textclasslist.TextClass(params.textclass);
2795
2796         LaTeXFeatures features(params, tclass.numLayouts());
2797         validate(features);
2798
2799         //if (nice)
2800         tex_code_break_column = lyxrc.ascii_linelen;
2801         //else
2802         //tex_code_break_column = 0;
2803
2804         ofstream ofs(fname.c_str());
2805         if (!ofs) {
2806                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2807                 return;
2808         }
2809    
2810         texrow.reset();
2811
2812         if (!only_body) {
2813                 string sgml_includedfiles=features.getIncludedFiles(fname);
2814
2815                 ofs << "<!doctype " << top_element
2816                     << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2817
2818                 if (params.preamble.empty() && sgml_includedfiles.empty())
2819                         ofs << ">\n\n";
2820                 else
2821                         ofs << "\n [ " << params.preamble 
2822                             << sgml_includedfiles << " \n]>\n\n";
2823         }
2824
2825         if (params.options.empty())
2826                 sgmlOpenTag(ofs, 0, top_element);
2827         else {
2828                 string top = top_element;
2829                 top += " ";
2830                 top += params.options;
2831                 sgmlOpenTag(ofs, 0, top);
2832         }
2833
2834         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
2835             << "\n  See http://www.lyx.org/ for more information -->\n";
2836
2837         while (par) {
2838                 int desc_on = 0; // description mode
2839                 LyXLayout const & style =
2840                         textclasslist.Style(params.textclass,
2841                                             par->layout);
2842
2843                 // environment tag closing
2844                 for (; depth > par->depth; --depth) {
2845                         if (environment_inner[depth] != "!-- --") {
2846                                 item_name= "listitem";
2847                                 sgmlCloseTag(ofs, command_depth + depth,
2848                                              item_name);
2849                                 if (environment_inner[depth] == "varlistentry")
2850                                         sgmlCloseTag(ofs, depth+command_depth,
2851                                                      environment_inner[depth]);
2852                         }
2853                         sgmlCloseTag(ofs, depth + command_depth,
2854                                      environment_stack[depth]);
2855                         environment_stack[depth].erase();
2856                         environment_inner[depth].erase();
2857                 }
2858
2859                 if (depth == par->depth
2860                    && environment_stack[depth] != style.latexname()
2861                    && !environment_stack[depth].empty()) {
2862                         if (environment_inner[depth] != "!-- --") {
2863                                 item_name= "listitem";
2864                                 sgmlCloseTag(ofs, command_depth+depth,
2865                                              item_name);
2866                                 if (environment_inner[depth] == "varlistentry")
2867                                         sgmlCloseTag(ofs,
2868                                                      depth + command_depth,
2869                                                      environment_inner[depth]);
2870                         }
2871                         
2872                         sgmlCloseTag(ofs, depth + command_depth,
2873                                      environment_stack[depth]);
2874                         
2875                         environment_stack[depth].erase();
2876                         environment_inner[depth].erase();
2877                 }
2878
2879                 // Write opening SGML tags.
2880                 switch (style.latextype) {
2881                 case LATEX_PARAGRAPH:
2882                         sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2883                         break;
2884
2885                 case LATEX_COMMAND:
2886                         if (depth!= 0)
2887                                 LinuxDocError(par, 0,
2888                                               _("Error : Wrong depth for "
2889                                                 "LatexType Command.\n"));
2890                         
2891                         command_name = style.latexname();
2892                         
2893                         tmps = style.latexparam();
2894                         c_params = split(tmps, c_depth,'|');
2895                         
2896                         cmd_depth= lyx::atoi(c_depth);
2897                         
2898                         if (command_flag) {
2899                                 if (cmd_depth<command_base) {
2900                                         for (int j = command_depth;
2901                                             j >= command_base; --j)
2902                                                 if (!command_stack[j].empty())
2903                                                         sgmlCloseTag(ofs, j, command_stack[j]);
2904                                         command_depth= command_base= cmd_depth;
2905                                 } else if (cmd_depth <= command_depth) {
2906                                         for (int j = command_depth;
2907                                             j >= cmd_depth; --j)
2908
2909                                                 if (!command_stack[j].empty())
2910                                                         sgmlCloseTag(ofs, j, command_stack[j]);
2911                                         command_depth= cmd_depth;
2912                                 } else
2913                                         command_depth= cmd_depth;
2914                         } else {
2915                                 command_depth = command_base = cmd_depth;
2916                                 command_flag = true;
2917                         }
2918                         command_stack[command_depth]= command_name;
2919
2920                         // treat label as a special case for
2921                         // more WYSIWYM handling.
2922                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
2923                                 Inset * inset = par->GetInset(0);
2924                                 Inset::Code lyx_code = inset->LyxCode();
2925                                 if (lyx_code == Inset::LABEL_CODE){
2926                                         command_name += " id=\"";
2927                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
2928                                         command_name += "\"";
2929                                         desc_on = 3;
2930                                 }
2931                         }
2932
2933                         sgmlOpenTag(ofs, depth + command_depth, command_name);
2934                         item_name = "title";
2935                         if (command_name != "!-- --")
2936                                 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2937                         break;
2938
2939                 case LATEX_ENVIRONMENT:
2940                 case LATEX_ITEM_ENVIRONMENT:
2941                         if (depth < par->depth) {
2942                                 depth = par->depth;
2943                                 environment_stack[depth].erase();
2944                         }
2945
2946                         if (environment_stack[depth] != style.latexname()) {
2947                                 environment_stack[depth] = style.latexname();
2948                                 environment_inner[depth] = "!-- --";
2949                                 sgmlOpenTag(ofs, depth + command_depth,
2950                                             environment_stack[depth]);
2951                         } else {
2952                                 if (environment_inner[depth] != "!-- --") {
2953                                         item_name= "listitem";
2954                                         sgmlCloseTag(ofs,
2955                                                      command_depth + depth,
2956                                                      item_name);
2957                                         if (environment_inner[depth] == "varlistentry")
2958                                                 sgmlCloseTag(ofs,
2959                                                              depth + command_depth,
2960                                                              environment_inner[depth]);
2961                                 }
2962                         }
2963                         
2964                         if (style.latextype == LATEX_ENVIRONMENT) {
2965                                 if (!style.latexparam().empty())
2966                                         sgmlOpenTag(ofs, depth + command_depth,
2967                                                     style.latexparam());
2968                                 break;
2969                         }
2970
2971                         desc_on = (style.labeltype == LABEL_MANUAL);
2972
2973                         if (desc_on)
2974                                 environment_inner[depth]= "varlistentry";
2975                         else
2976                                 environment_inner[depth]= "listitem";
2977
2978                         sgmlOpenTag(ofs, depth + 1 + command_depth,
2979                                     environment_inner[depth]);
2980
2981                         if (desc_on) {
2982                                 item_name= "term";
2983                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
2984                                             item_name);
2985                         } else {
2986                                 item_name= "para";
2987                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
2988                                             item_name);
2989                         }
2990                         break;
2991                 default:
2992                         sgmlOpenTag(ofs, depth + command_depth,
2993                                     style.latexname());
2994                         break;
2995                 }
2996
2997 #ifndef NEW_INSETS
2998                 do {
2999 #endif
3000                         string extra_par;
3001                         SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3002                                             depth + 1 + command_depth);
3003                         par = par->next;
3004 #ifndef NEW_INSETS
3005                         DocBookHandleFootnote(ofs, par,
3006                                               depth + 1 + command_depth);
3007                 }
3008                 while(par && par->IsDummy());
3009 #endif
3010                 string end_tag;
3011                 // write closing SGML tags
3012                 switch (style.latextype) {
3013                 case LATEX_COMMAND:
3014                         end_tag = "title";
3015                         if (command_name != "!-- --")
3016                                 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3017                         break;
3018                 case LATEX_ENVIRONMENT:
3019                         if (!style.latexparam().empty())
3020                                 sgmlCloseTag(ofs, depth + command_depth,
3021                                              style.latexparam());
3022                         break;
3023                 case LATEX_ITEM_ENVIRONMENT:
3024                         if (desc_on == 1) break;
3025                         end_tag= "para";
3026                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3027                         break;
3028                 case LATEX_PARAGRAPH:
3029                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3030                         break;
3031                 default:
3032                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3033                         break;
3034                 }
3035         }
3036
3037         // Close open tags
3038         for (; depth >= 0; --depth) {
3039                 if (!environment_stack[depth].empty()) {
3040                         if (environment_inner[depth] != "!-- --") {
3041                                 item_name= "listitem";
3042                                 sgmlCloseTag(ofs, command_depth + depth,
3043                                              item_name);
3044                                if (environment_inner[depth] == "varlistentry")
3045                                        sgmlCloseTag(ofs, depth + command_depth,
3046                                                     environment_inner[depth]);
3047                         }
3048                         
3049                         sgmlCloseTag(ofs, depth + command_depth,
3050                                      environment_stack[depth]);
3051                 }
3052         }
3053         
3054         for (int j = command_depth; j >= command_base; --j)
3055                 if (!command_stack[j].empty())
3056                         sgmlCloseTag(ofs, j, command_stack[j]);
3057
3058         ofs << "\n\n";
3059         sgmlCloseTag(ofs, 0, top_element);
3060
3061         ofs.close();
3062         // How to check for successful close
3063 }
3064
3065
3066 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3067                                  LyXParagraph * par, int & desc_on,
3068                                  int depth) const
3069 {
3070         bool emph_flag = false;
3071
3072         LyXLayout const & style = textclasslist.Style(params.textclass,
3073                                                       par->GetLayout());
3074
3075         LyXParagraph::size_type main_body;
3076         if (style.labeltype != LABEL_MANUAL)
3077                 main_body = 0;
3078         else
3079                 main_body = par->BeginningOfMainBody();
3080
3081         // gets paragraph main font
3082         LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3083         
3084         int char_line_count = depth;
3085         if (!style.free_spacing)
3086                 for (int j = 0; j < depth; ++j)
3087                         os << ' ';
3088
3089         // parsing main loop
3090         for (LyXParagraph::size_type i = 0;
3091              i < par->size(); ++i) {
3092                 LyXFont font2 = par->getFont(params, i);
3093
3094                 // handle <emphasis> tag
3095                 if (font1.emph() != font2.emph() && i) {
3096                         if (font2.emph() == LyXFont::ON) {
3097                                 os << "<emphasis>";
3098                                 emph_flag = true;
3099                         }else {
3100                                 os << "</emphasis>";
3101                                 emph_flag = false;
3102                         }
3103                 }
3104       
3105                 char c = par->GetChar(i);
3106
3107                 if (c == LyXParagraph::META_INSET) {
3108                         Inset * inset = par->GetInset(i);
3109                         std::ostringstream ost;
3110                         inset->DocBook(this, ost);
3111                         string tmp_out = ost.str().c_str();
3112
3113                         //
3114                         // This code needs some explanation:
3115                         // Two insets are treated specially
3116                         //   label if it is the first element in a command paragraph
3117                         //         desc_on == 3
3118                         //   graphics inside tables or figure floats can't go on
3119                         //   title (the equivalente in latex for this case is caption
3120                         //   and title should come first
3121                         //         desc_on == 4
3122                         //
3123                         if (desc_on!= 3 || i!= 0) {
3124                                 if (!tmp_out.empty() && tmp_out[0] == '@') {
3125                                         if (desc_on == 4)
3126                                                 extra += frontStrip(tmp_out, '@');
3127                                         else
3128                                                 os << frontStrip(tmp_out, '@');
3129                                 }
3130                                 else
3131                                         os << tmp_out;
3132                         }
3133                 } else if (font2.latex() == LyXFont::ON) {
3134                         // "TeX"-Mode on ==> SGML-Mode on.
3135                         if (c != '\0')
3136                                 os << c;
3137                         ++char_line_count;
3138                 } else {
3139                         string sgml_string;
3140                         if (par->linuxDocConvertChar(c, sgml_string)
3141                             && !style.free_spacing) { // in freespacing
3142                                                      // mode, spaces are
3143                                                      // non-breaking characters
3144                                 // char is ' '
3145                                 if (desc_on == 1) {
3146                                         ++char_line_count;
3147                                         os << "\n</term><listitem><para>";
3148                                         desc_on = 2;
3149                                 } else {
3150                                         os << c;
3151                                 }
3152                         } else {
3153                                 os << sgml_string;
3154                         }
3155                 }
3156                 font1 = font2;
3157         }
3158
3159         // needed if there is an optional argument but no contents
3160         if (main_body > 0 && main_body == par->size()) {
3161                 font1 = style.font;
3162         }
3163         if (emph_flag) {
3164                 os << "</emphasis>";
3165         }
3166         
3167         // resets description flag correctly
3168         switch (desc_on){
3169         case 1:
3170                 // <term> not closed...
3171                 os << "</term>";
3172                 break;
3173         }
3174         os << '\n';
3175 }
3176
3177
3178 // This should be enabled when the Chktex class is implemented. (Asger)
3179 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3180 // Other flags: -wall -v0 -x
3181 int Buffer::runChktex()
3182 {
3183         if (!users->text) return 0;
3184
3185         ProhibitInput(users);
3186
3187         // get LaTeX-Filename
3188         string const name = getLatexName();
3189         string path = OnlyPath(filename);
3190
3191         string const org_path = path;
3192         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3193                 path = tmppath;  
3194         }
3195
3196         Path p(path); // path to LaTeX file
3197         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3198
3199         // Remove all error insets
3200         bool const removedErrorInsets = users->removeAutoInsets();
3201
3202         // Generate the LaTeX file if neccessary
3203         makeLaTeXFile(name, org_path, false);
3204
3205         TeXErrors terr;
3206         Chktex chktex(lyxrc.chktex_command, name, filepath);
3207         int res = chktex.run(terr); // run chktex
3208
3209         if (res == -1) {
3210                 WriteAlert(_("chktex did not work!"),
3211                            _("Could not run with file:"), name);
3212         } else if (res > 0) {
3213                 // Insert all errors as errors boxes
3214                 users->insertErrors(terr);
3215         }
3216
3217         // if we removed error insets before we ran chktex or if we inserted
3218         // error insets after we ran chktex, this must be run:
3219         if (removedErrorInsets || res){
3220                 users->redraw();
3221                 users->fitCursor(users->text);
3222         }
3223         AllowInput(users);
3224
3225         return res;
3226 }
3227
3228
3229 void Buffer::validate(LaTeXFeatures & features) const
3230 {
3231         LyXParagraph * par = paragraph;
3232         LyXTextClass const & tclass = 
3233                 textclasslist.TextClass(params.textclass);
3234     
3235         // AMS Style is at document level
3236     
3237         features.amsstyle = (params.use_amsmath ||
3238                              tclass.provides(LyXTextClass::amsmath));
3239     
3240         while (par) {
3241                 // We don't use "lyxerr.debug" because of speed. (Asger)
3242                 if (lyxerr.debugging(Debug::LATEX))
3243                         lyxerr << "Paragraph: " <<  par << endl;
3244
3245                 // Now just follow the list of paragraphs and run
3246                 // validate on each of them.
3247                 par->validate(features);
3248
3249                 // and then the next paragraph
3250                 par = par->next;
3251         }
3252
3253         // the bullet shapes are buffer level not paragraph level
3254         // so they are tested here
3255         for (int i = 0; i < 4; ++i) {
3256                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3257                         int const font = params.user_defined_bullets[i].getFont();
3258                         if (font == 0) {
3259                                 int const c = params
3260                                         .user_defined_bullets[i]
3261                                         .getCharacter();
3262                                 if (c == 16
3263                                    || c == 17
3264                                    || c == 25
3265                                    || c == 26
3266                                    || c == 31) {
3267                                         features.latexsym = true;
3268                                 }
3269                         } else if (font == 1) {
3270                                 features.amssymb = true;
3271                         } else if ((font >= 2 && font <= 5)) {
3272                                 features.pifont = true;
3273                         }
3274                 }
3275         }
3276         
3277         if (lyxerr.debugging(Debug::LATEX)) {
3278                 features.showStruct();
3279         }
3280 }
3281
3282
3283 void Buffer::setPaperStuff()
3284 {
3285         params.papersize = BufferParams::PAPER_DEFAULT;
3286         char const c1 = params.paperpackage;
3287         if (c1 == BufferParams::PACKAGE_NONE) {
3288                 char const c2 = params.papersize2;
3289                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3290                         params.papersize = BufferParams::PAPER_USLETTER;
3291                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3292                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3293                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3294                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3295                 else if (c2 == BufferParams::VM_PAPER_A3)
3296                         params.papersize = BufferParams::PAPER_A3PAPER;
3297                 else if (c2 == BufferParams::VM_PAPER_A4)
3298                         params.papersize = BufferParams::PAPER_A4PAPER;
3299                 else if (c2 == BufferParams::VM_PAPER_A5)
3300                         params.papersize = BufferParams::PAPER_A5PAPER;
3301                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3302                          (c2 == BufferParams::VM_PAPER_B5))
3303                         params.papersize = BufferParams::PAPER_B5PAPER;
3304         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3305                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3306                 params.papersize = BufferParams::PAPER_A4PAPER;
3307 }
3308
3309
3310 // This function should be in Buffer because it's a buffer's property (ale)
3311 string const Buffer::getIncludeonlyList(char delim)
3312 {
3313         string lst;
3314         for (inset_iterator it = inset_iterator_begin();
3315             it != inset_iterator_end(); ++it) {
3316                 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3317                         InsetInclude * insetinc = 
3318                                 static_cast<InsetInclude *>(*it);
3319                         if (insetinc->isInclude() 
3320                             && insetinc->isNoLoad()) {
3321                                 if (!lst.empty())
3322                                         lst += delim;
3323                                 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3324                         }
3325                 }
3326         }
3327         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3328         return lst;
3329 }
3330
3331
3332 vector<string> const Buffer::getLabelList()
3333 {
3334         /// if this is a child document and the parent is already loaded
3335         /// Use the parent's list instead  [ale990407]
3336         if (!params.parentname.empty()
3337             && bufferlist.exists(params.parentname)) {
3338                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3339                 if (tmp)
3340                         return tmp->getLabelList();
3341         }
3342
3343         vector<string> label_list;
3344         for (inset_iterator it = inset_iterator_begin();
3345              it != inset_iterator_end(); ++it) {
3346                 vector<string> const l = (*it)->getLabelList();
3347                 label_list.insert(label_list.end(), l.begin(), l.end());
3348         }
3349         return label_list;
3350 }
3351
3352
3353 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3354 {
3355         int figs = 0;
3356         int tables = 0;
3357         int algs = 0;
3358         vector<vector<TocItem> > l(4);
3359         LyXParagraph * par = paragraph;
3360         while (par) {
3361 #ifndef NEW_INSETS
3362                 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3363                         if (textclasslist.Style(params.textclass, 
3364                                                 par->GetLayout()).labeltype
3365                             == LABEL_SENSITIVE) {
3366                                 TocItem tmp;
3367                                 tmp.par = par;
3368                                 tmp.depth = 0;
3369                                 tmp.str =  par->String(this, false);
3370                                 switch (par->footnotekind) {
3371                                 case LyXParagraph::FIG:
3372                                 case LyXParagraph::WIDE_FIG:
3373                                         tmp.str = tostr(++figs) + ". "
3374                                                 + tmp.str;
3375                                         l[TOC_LOF].push_back(tmp);
3376                                         break;
3377                                 case LyXParagraph::TAB:
3378                                 case LyXParagraph::WIDE_TAB:
3379                                         tmp.str = tostr(++tables) + ". "
3380                                                 + tmp.str;
3381                                         l[TOC_LOT].push_back(tmp);
3382                                         break;
3383                                 case LyXParagraph::ALGORITHM:
3384                                         tmp.str = tostr(++algs) + ". "
3385                                                 + tmp.str;
3386                                         l[TOC_LOA].push_back(tmp);
3387                                         break;
3388                                 case LyXParagraph::FOOTNOTE:
3389                                 case LyXParagraph::MARGIN:
3390                                         break;
3391                                 }
3392                         }
3393                 } else if (!par->IsDummy()) {
3394 #endif
3395                         char const labeltype =
3396                                 textclasslist.Style(params.textclass, 
3397                                                     par->GetLayout()).labeltype;
3398       
3399                         if (labeltype >= LABEL_COUNTER_CHAPTER
3400                             && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3401                                 // insert this into the table of contents
3402                                 TocItem tmp;
3403                                 tmp.par = par;
3404                                 tmp.depth = max(0,
3405                                                 labeltype - 
3406                                                 textclasslist.TextClass(params.textclass).maxcounter());
3407                                 tmp.str =  par->String(this, true);
3408                                 l[TOC_TOC].push_back(tmp);
3409                         }
3410 #ifndef NEW_INSETS
3411                 }
3412 #endif
3413                 par = par->next;
3414         }
3415         return l;
3416 }
3417
3418
3419 // This is also a buffer property (ale)
3420 vector<pair<string,string> > const Buffer::getBibkeyList()
3421 {
3422         /// if this is a child document and the parent is already loaded
3423         /// Use the parent's list instead  [ale990412]
3424         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3425                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3426                 if (tmp)
3427                         return tmp->getBibkeyList();
3428         }
3429
3430         vector<pair<string, string> > keys;
3431         LyXParagraph * par = paragraph;
3432         while (par) {
3433                 if (par->bibkey)
3434                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3435                                                            par->String(this, false)));
3436                 par = par->next;
3437         }
3438
3439         // Might be either using bibtex or a child has bibliography
3440         if (keys.empty()) {
3441                 for (inset_iterator it = inset_iterator_begin();
3442                         it != inset_iterator_end(); ++it) {
3443                         // Search for Bibtex or Include inset
3444                         if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3445                                 vector<pair<string,string> > tmp =
3446                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3447                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3448                         } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3449                                 vector<pair<string,string> > const tmp =
3450                                         static_cast<InsetInclude*>(*it)->getKeys();
3451                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3452                         }
3453                 }
3454         }
3455  
3456         return keys;
3457 }
3458
3459
3460 bool Buffer::isDepClean(string const & name) const
3461 {
3462         DEPCLEAN * item = dep_clean;
3463         while (item && item->master != name)
3464                 item = item->next;
3465         if (!item) return true;
3466         return item->clean;
3467 }
3468
3469
3470 void Buffer::markDepClean(string const & name)
3471 {
3472         if (!dep_clean) {
3473                 dep_clean = new DEPCLEAN;
3474                 dep_clean->clean = true;
3475                 dep_clean->master = name;
3476                 dep_clean->next = 0;
3477         } else {
3478                 DEPCLEAN * item = dep_clean;
3479                 while (item && item->master != name)
3480                         item = item->next;
3481                 if (item) {
3482                         item->clean = true;
3483                 } else {
3484                         item = new DEPCLEAN;
3485                         item->clean = true;
3486                         item->master = name;
3487                         item->next = 0;
3488                 }
3489         }
3490 }
3491
3492
3493 bool Buffer::Dispatch(string const & command)
3494 {
3495         // Split command string into command and argument
3496         string cmd;
3497         string line = frontStrip(command);
3498         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3499
3500         return Dispatch(lyxaction.LookupFunc(cmd), arg);
3501 }
3502
3503
3504 bool Buffer::Dispatch(int action, string const & argument)
3505 {
3506         bool dispatched = true;
3507         switch (action) {
3508                 case LFUN_EXPORT: 
3509                         Exporter::Export(this, argument, false);
3510                         break;
3511
3512                 default:
3513                         dispatched = false;
3514         }
3515         return dispatched;
3516 }
3517
3518
3519 void Buffer::resize()
3520 {
3521         /// resize the BufferViews!
3522         if (users)
3523                 users->resize();
3524 }
3525
3526
3527 void Buffer::resizeInsets(BufferView * bv)
3528 {
3529         /// then remove all LyXText in text-insets
3530         LyXParagraph * par = paragraph;
3531         for (; par; par = par->next) {
3532             par->resizeInsetsLyXText(bv);
3533         }
3534 }
3535
3536 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3537 {
3538
3539         LyXParagraph * par = paragraph;
3540         while (par) {
3541                 par->ChangeLanguage(params, from, to);
3542                 par = par->next;
3543         }
3544 }
3545
3546
3547 bool Buffer::isMultiLingual()
3548 {
3549         LyXParagraph * par = paragraph;
3550         while (par) {
3551                 if (par->isMultiLingual(params))
3552                         return true;
3553                 par = par->next;
3554         }
3555         return false;
3556 }
3557
3558
3559 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3560                                        LyXParagraph::size_type pos)
3561         : par(paragraph)
3562 {
3563         it = par->InsetIterator(pos);
3564         if (it == par->inset_iterator_end()) {
3565                 par = par->next;
3566                 SetParagraph();
3567         }
3568 }
3569
3570
3571 void Buffer::inset_iterator::SetParagraph()
3572 {
3573         while (par) {
3574                 it = par->inset_iterator_begin();
3575                 if (it != par->inset_iterator_end())
3576                         return;
3577                 par = par->next;
3578         }
3579         //it = 0;
3580         // We maintain an invariant that whenever par = 0 then it = 0
3581 }