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