]> git.lyx.org Git - lyx.git/blob - src/buffer.C
682298f00be437511c567113237b4620ba1a111c
[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") // This seems necessary
1713                         features.UsedLanguages.insert(default_language);
1714 #ifdef DO_USE_DEFAULT_LANGUAGE
1715                 if (params.language->lang() != "default" ||
1716                     !features.UsedLanguages.empty()) {
1717 #endif
1718                         use_babel = true;
1719                         for (LaTeXFeatures::LanguageList::const_iterator cit =
1720                                      features.UsedLanguages.begin();
1721                              cit != features.UsedLanguages.end(); ++cit)
1722                                 options += (*cit)->babel() + ",";
1723                         options += params.language->babel() + ',';
1724 #ifdef DO_USE_DEFAULT_LANGUAGE
1725                 }
1726 #endif
1727
1728                 // the user-defined options
1729                 if (!params.options.empty()) {
1730                         options += params.options + ',';
1731                 }
1732                 
1733                 if (!options.empty()){
1734                         options = strip(options, ',');
1735                         ofs << '[' << options << ']';
1736                 }
1737                 
1738                 ofs << '{'
1739                     << textclasslist.LatexnameOfClass(params.textclass)
1740                     << "}\n";
1741                 texrow.newline();
1742                 // end of \documentclass defs
1743                 
1744                 // font selection must be done before loading fontenc.sty
1745                 if (params.fonts != "default") {
1746                         ofs << "\\usepackage{" << params.fonts << "}\n";
1747                         texrow.newline();
1748                 }
1749                 // this one is not per buffer
1750                 if (lyxrc.fontenc != "default") {
1751                         ofs << "\\usepackage[" << lyxrc.fontenc
1752                             << "]{fontenc}\n";
1753                         texrow.newline();
1754                 }
1755
1756                 if (params.inputenc == "auto") {
1757                         string const doc_encoding =
1758                                 params.language->encoding()->LatexName();
1759
1760                         // Create a list with all the input encodings used 
1761                         // in the document
1762                         set<string> encodings;
1763                         for (LaTeXFeatures::LanguageList::const_iterator it =
1764                                      features.UsedLanguages.begin();
1765                              it != features.UsedLanguages.end(); ++it)
1766                                 if ((*it)->encoding()->LatexName() != doc_encoding)
1767                                         encodings.insert((*it)->encoding()->LatexName());
1768
1769                         ofs << "\\usepackage[";
1770                         std::copy(encodings.begin(), encodings.end(),
1771                                   std::ostream_iterator<string>(ofs, ","));
1772                         ofs << doc_encoding << "]{inputenc}\n";
1773                         texrow.newline();
1774                 } else if (params.inputenc != "default") {
1775                         ofs << "\\usepackage[" << params.inputenc
1776                             << "]{inputenc}\n";
1777                         texrow.newline();
1778                 }
1779
1780                 // At the very beginning the text parameters.
1781                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1782                         switch (params.paperpackage) {
1783                         case BufferParams::PACKAGE_A4:
1784                                 ofs << "\\usepackage{a4}\n";
1785                                 texrow.newline();
1786                                 break;
1787                         case BufferParams::PACKAGE_A4WIDE:
1788                                 ofs << "\\usepackage{a4wide}\n";
1789                                 texrow.newline();
1790                                 break;
1791                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1792                                 ofs << "\\usepackage[widemargins]{a4}\n";
1793                                 texrow.newline();
1794                                 break;
1795                         }
1796                 }
1797                 if (params.use_geometry) {
1798                         ofs << "\\usepackage{geometry}\n";
1799                         texrow.newline();
1800                         ofs << "\\geometry{verbose";
1801                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1802                                 ofs << ",landscape";
1803                         switch (params.papersize2) {
1804                         case BufferParams::VM_PAPER_CUSTOM:
1805                                 if (!params.paperwidth.empty())
1806                                         ofs << ",paperwidth="
1807                                             << params.paperwidth;
1808                                 if (!params.paperheight.empty())
1809                                         ofs << ",paperheight="
1810                                             << params.paperheight;
1811                                 break;
1812                         case BufferParams::VM_PAPER_USLETTER:
1813                                 ofs << ",letterpaper";
1814                                 break;
1815                         case BufferParams::VM_PAPER_USLEGAL:
1816                                 ofs << ",legalpaper";
1817                                 break;
1818                         case BufferParams::VM_PAPER_USEXECUTIVE:
1819                                 ofs << ",executivepaper";
1820                                 break;
1821                         case BufferParams::VM_PAPER_A3:
1822                                 ofs << ",a3paper";
1823                                 break;
1824                         case BufferParams::VM_PAPER_A4:
1825                                 ofs << ",a4paper";
1826                                 break;
1827                         case BufferParams::VM_PAPER_A5:
1828                                 ofs << ",a5paper";
1829                                 break;
1830                         case BufferParams::VM_PAPER_B3:
1831                                 ofs << ",b3paper";
1832                                 break;
1833                         case BufferParams::VM_PAPER_B4:
1834                                 ofs << ",b4paper";
1835                                 break;
1836                         case BufferParams::VM_PAPER_B5:
1837                                 ofs << ",b5paper";
1838                                 break;
1839                         default:
1840                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1841                                 switch (lyxrc.default_papersize) {
1842                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1843                                 case BufferParams::PAPER_USLETTER:
1844                                         ofs << ",letterpaper";
1845                                         break;
1846                                 case BufferParams::PAPER_LEGALPAPER:
1847                                         ofs << ",legalpaper";
1848                                         break;
1849                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1850                                         ofs << ",executivepaper";
1851                                         break;
1852                                 case BufferParams::PAPER_A3PAPER:
1853                                         ofs << ",a3paper";
1854                                         break;
1855                                 case BufferParams::PAPER_A4PAPER:
1856                                         ofs << ",a4paper";
1857                                         break;
1858                                 case BufferParams::PAPER_A5PAPER:
1859                                         ofs << ",a5paper";
1860                                         break;
1861                                 case BufferParams::PAPER_B5PAPER:
1862                                         ofs << ",b5paper";
1863                                         break;
1864                                 }
1865                         }
1866                         if (!params.topmargin.empty())
1867                                 ofs << ",tmargin=" << params.topmargin;
1868                         if (!params.bottommargin.empty())
1869                                 ofs << ",bmargin=" << params.bottommargin;
1870                         if (!params.leftmargin.empty())
1871                                 ofs << ",lmargin=" << params.leftmargin;
1872                         if (!params.rightmargin.empty())
1873                                 ofs << ",rmargin=" << params.rightmargin;
1874                         if (!params.headheight.empty())
1875                                 ofs << ",headheight=" << params.headheight;
1876                         if (!params.headsep.empty())
1877                                 ofs << ",headsep=" << params.headsep;
1878                         if (!params.footskip.empty())
1879                                 ofs << ",footskip=" << params.footskip;
1880                         ofs << "}\n";
1881                         texrow.newline();
1882                 }
1883                 if (params.use_amsmath
1884                     && !tclass.provides(LyXTextClass::amsmath)) {
1885                         ofs << "\\usepackage{amsmath}\n";
1886                         texrow.newline();
1887                 }
1888
1889                 if (tokenPos(tclass.opt_pagestyle(),
1890                              '|', params.pagestyle) >= 0) {
1891                         if (params.pagestyle == "fancy") {
1892                                 ofs << "\\usepackage{fancyhdr}\n";
1893                                 texrow.newline();
1894                         }
1895                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1896                         texrow.newline();
1897                 }
1898
1899                 // We try to load babel late, in case it interferes
1900                 // with other packages.
1901                 if (use_babel) {
1902                         ofs << lyxrc.language_package << endl;
1903                         texrow.newline();
1904                 }
1905
1906                 if (params.secnumdepth != tclass.secnumdepth()) {
1907                         ofs << "\\setcounter{secnumdepth}{"
1908                             << params.secnumdepth
1909                             << "}\n";
1910                         texrow.newline();
1911                 }
1912                 if (params.tocdepth != tclass.tocdepth()) {
1913                         ofs << "\\setcounter{tocdepth}{"
1914                             << params.tocdepth
1915                             << "}\n";
1916                         texrow.newline();
1917                 }
1918                 
1919                 if (params.paragraph_separation) {
1920                         switch (params.defskip.kind()) {
1921                         case VSpace::SMALLSKIP: 
1922                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1923                                 break;
1924                         case VSpace::MEDSKIP:
1925                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1926                                 break;
1927                         case VSpace::BIGSKIP:
1928                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1929                                 break;
1930                         case VSpace::LENGTH:
1931                                 ofs << "\\setlength\\parskip{"
1932                                     << params.defskip.length().asLatexString()
1933                                     << "}\n";
1934                                 break;
1935                         default: // should never happen // Then delete it.
1936                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1937                                 break;
1938                         }
1939                         texrow.newline();
1940                         
1941                         ofs << "\\setlength\\parindent{0pt}\n";
1942                         texrow.newline();
1943                 }
1944
1945                 // Now insert the LyX specific LaTeX commands...
1946
1947                 // The optional packages;
1948                 string preamble(features.getPackages());
1949
1950                 // this might be useful...
1951                 preamble += "\n\\makeatletter\n";
1952
1953                 // Some macros LyX will need
1954                 string tmppreamble(features.getMacros());
1955
1956                 if (!tmppreamble.empty()) {
1957                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1958                                 "LyX specific LaTeX commands.\n"
1959                                 + tmppreamble + '\n';
1960                 }
1961
1962                 // the text class specific preamble 
1963                 tmppreamble = features.getTClassPreamble();
1964                 if (!tmppreamble.empty()) {
1965                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1966                                 "Textclass specific LaTeX commands.\n"
1967                                 + tmppreamble + '\n';
1968                 }
1969
1970                 /* the user-defined preamble */
1971                 if (!params.preamble.empty()) {
1972                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1973                                 "User specified LaTeX commands.\n"
1974                                 + params.preamble + '\n';
1975                 }
1976
1977                 preamble += "\\makeatother\n";
1978
1979                 // Itemize bullet settings need to be last in case the user
1980                 // defines their own bullets that use a package included
1981                 // in the user-defined preamble -- ARRae
1982                 // Actually it has to be done much later than that
1983                 // since some packages like frenchb make modifications
1984                 // at \begin{document} time -- JMarc 
1985                 string bullets_def;
1986                 for (int i = 0; i < 4; ++i) {
1987                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1988                                 if (bullets_def.empty())
1989                                         bullets_def="\\AtBeginDocument{\n";
1990                                 bullets_def += "  \\renewcommand{\\labelitemi";
1991                                 switch (i) {
1992                                 // `i' is one less than the item to modify
1993                                 case 0:
1994                                         break;
1995                                 case 1:
1996                                         bullets_def += 'i';
1997                                         break;
1998                                 case 2:
1999                                         bullets_def += "ii";
2000                                         break;
2001                                 case 3:
2002                                         bullets_def += 'v';
2003                                         break;
2004                                 }
2005                                 bullets_def += "}{" + 
2006                                   params.user_defined_bullets[i].getText() 
2007                                   + "}\n";
2008                         }
2009                 }
2010
2011                 if (!bullets_def.empty())
2012                   preamble += bullets_def + "}\n\n";
2013
2014                 for (int j = countChar(preamble, '\n'); j-- ;) {
2015                         texrow.newline();
2016                 }
2017
2018                 ofs << preamble;
2019
2020                 // make the body.
2021                 ofs << "\\begin{document}\n";
2022                 texrow.newline();
2023         } // only_body
2024         lyxerr.debug() << "preamble finished, now the body." << endl;
2025 #ifdef DO_USE_DEFAULT_LANGUAGE
2026         if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
2027 #else
2028         if (!lyxrc.language_auto_begin) {
2029 #endif
2030                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2031                              params.language->babel())
2032                     << endl;
2033                 texrow.newline();
2034         }
2035         
2036         latexParagraphs(ofs, paragraph, 0, texrow);
2037
2038         // add this just in case after all the paragraphs
2039         ofs << endl;
2040         texrow.newline();
2041
2042 #ifdef DO_USE_DEFAULT_LANGUAGE
2043         if (!lyxrc.language_auto_end && params.language->lang() != "default") {
2044 #else
2045                 if (!lyxrc.language_auto_end) {
2046 #endif
2047                 ofs << subst(lyxrc.language_command_end, "$$lang",
2048                              params.language->babel())
2049                     << endl;
2050                 texrow.newline();
2051         }
2052
2053         if (!only_body) {
2054                 ofs << "\\end{document}\n";
2055                 texrow.newline();
2056         
2057                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2058         } else {
2059                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2060                                      << endl;
2061         }
2062
2063         // Just to be sure. (Asger)
2064         texrow.newline();
2065
2066         // tex_code_break_column's value is used to decide
2067         // if we are in batchmode or not (within mathed_write()
2068         // in math_write.C) so we must set it to a non-zero
2069         // value when we leave otherwise we save incorrect .lyx files.
2070         tex_code_break_column = lyxrc.ascii_linelen;
2071
2072         ofs.close();
2073         if (ofs.fail()) {
2074                 lyxerr << "File was not closed properly." << endl;
2075         }
2076         
2077         lyxerr.debug() << "Finished making latex file." << endl;
2078 }
2079
2080
2081 //
2082 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2083 //
2084 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2085                              LyXParagraph * endpar, TexRow & texrow) const
2086 {
2087         bool was_title = false;
2088         bool already_title = false;
2089         std::ostringstream ftnote;
2090         TexRow ft_texrow;
2091         int ftcount = 0;
2092
2093         // if only_body
2094         while (par != endpar) {
2095 #ifndef NEW_INSETS
2096                 if (par->IsDummy())
2097                         lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2098                                              << endl;
2099 #endif
2100                 LyXLayout const & layout =
2101                         textclasslist.Style(params.textclass,
2102                                             par->layout);
2103             
2104                 if (layout.intitle) {
2105                         if (already_title) {
2106                                 lyxerr <<"Error in latexParagraphs: You"
2107                                         " should not mix title layouts"
2108                                         " with normal ones." << endl;
2109                         } else
2110                                 was_title = true;
2111                 } else if (was_title && !already_title) {
2112                         ofs << "\\maketitle\n";
2113                         texrow.newline();
2114                         already_title = true;
2115                         was_title = false;                  
2116                 }
2117                 // We are at depth 0 so we can just use
2118                 // ordinary \footnote{} generation
2119                 // flag this with ftcount
2120                 ftcount = -1;
2121                 if (layout.isEnvironment()
2122                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2123                         par = par->TeXEnvironment(this, params, ofs, texrow
2124 #ifndef NEW_INSETS
2125                                                   ,ftnote, ft_texrow, ftcount
2126 #endif
2127                                 );
2128                 } else {
2129                         par = par->TeXOnePar(this, params, ofs, texrow, false
2130 #ifndef NEW_INSETS
2131                                              ,
2132                                              ftnote, ft_texrow, ftcount
2133 #endif
2134                                 );
2135                 }
2136
2137                 // Write out what we've generated...
2138                 if (ftcount >= 1) {
2139                         if (ftcount > 1) {
2140                                 ofs << "\\addtocounter{footnote}{-"
2141                                     << ftcount - 1
2142                                     << '}';
2143                         }
2144                         ofs << ftnote.str();
2145                         texrow += ft_texrow;
2146
2147                         // The extra .c_str() is needed when we use
2148                         // lyxstring instead of the STL string class. 
2149                         ftnote.str(string().c_str());
2150                         ft_texrow.reset();
2151                         ftcount = 0;
2152                 }
2153         }
2154         // It might be that we only have a title in this document
2155         if (was_title && !already_title) {
2156                 ofs << "\\maketitle\n";
2157                 texrow.newline();
2158         }
2159 }
2160
2161
2162 bool Buffer::isLatex() const
2163 {
2164         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2165 }
2166
2167
2168 bool Buffer::isLinuxDoc() const
2169 {
2170         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2171 }
2172
2173
2174 bool Buffer::isLiterate() const
2175 {
2176         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2177 }
2178
2179
2180 bool Buffer::isDocBook() const
2181 {
2182         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2183 }
2184
2185
2186 bool Buffer::isSGML() const
2187 {
2188         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2189                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2190 }
2191
2192
2193 void Buffer::sgmlOpenTag(ostream & os, int depth,
2194                          string const & latexname) const
2195 {
2196         if (latexname != "!-- --")
2197                 os << string(depth, ' ') << "<" << latexname << ">\n";
2198 }
2199
2200
2201 void Buffer::sgmlCloseTag(ostream & os, int depth,
2202                           string const & latexname) const
2203 {
2204         if (latexname != "!-- --")
2205                 os << string(depth, ' ') << "</" << latexname << ">\n";
2206 }
2207
2208
2209 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2210 {
2211         LyXParagraph * par = paragraph;
2212
2213         niceFile = nice; // this will be used by Insetincludes.
2214
2215         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2216         string environment_stack[10];
2217         string item_name;
2218
2219         int depth = 0; // paragraph depth
2220
2221         ofstream ofs(fname.c_str());
2222
2223         if (!ofs) {
2224                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2225                 return;
2226         }
2227
2228         LyXTextClass const & tclass =
2229                 textclasslist.TextClass(params.textclass);
2230
2231         LaTeXFeatures features(params, tclass.numLayouts());
2232         validate(features);
2233
2234         //if (nice)
2235         tex_code_break_column = lyxrc.ascii_linelen;
2236         //else
2237         //tex_code_break_column = 0;
2238
2239         texrow.reset();
2240
2241         if (!body_only) {
2242                 string sgml_includedfiles=features.getIncludedFiles(fname);
2243
2244                 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2245                         ofs << "<!doctype linuxdoc system>\n\n";
2246                 } else {
2247                         ofs << "<!doctype linuxdoc system [ "
2248                             << params.preamble << sgml_includedfiles << " \n]>\n\n";
2249                 }
2250
2251                 if (params.options.empty())
2252                         sgmlOpenTag(ofs, 0, top_element);
2253                 else {
2254                         string top = top_element;
2255                         top += " ";
2256                         top += params.options;
2257                         sgmlOpenTag(ofs, 0, top);
2258                 }
2259         }
2260
2261         ofs << "<!-- "  << LYX_DOCVERSION 
2262             << " created this file. For more info see http://www.lyx.org/"
2263             << " -->\n";
2264
2265         while (par) {
2266                 int desc_on = 0; // description mode
2267                 LyXLayout const & style =
2268                         textclasslist.Style(params.textclass,
2269                                             par->layout);
2270
2271                 // treat <toc> as a special case for compatibility with old code
2272                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2273                         Inset * inset = par->GetInset(0);
2274                         Inset::Code lyx_code = inset->LyxCode();
2275                         if (lyx_code == Inset::TOC_CODE){
2276                                 string const temp = "toc";
2277                                 sgmlOpenTag(ofs, depth, temp);
2278
2279                                 par = par->next;
2280 #ifndef NEW_INSETS
2281                                 linuxDocHandleFootnote(ofs, par, depth);
2282 #endif
2283                                 continue;
2284                         }
2285                 }
2286
2287                 // environment tag closing
2288                 for (; depth > par->depth; --depth) {
2289                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2290                         environment_stack[depth].erase();
2291                 }
2292
2293                 // write opening SGML tags
2294                 switch (style.latextype) {
2295                 case LATEX_PARAGRAPH:
2296                         if (depth == par->depth 
2297                            && !environment_stack[depth].empty()) {
2298                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2299                                 environment_stack[depth].erase();
2300                                 if (depth) 
2301                                         --depth;
2302                                 else
2303                                         ofs << "</p>";
2304                         }
2305                         sgmlOpenTag(ofs, depth, style.latexname());
2306                         break;
2307
2308                 case LATEX_COMMAND:
2309                         if (depth!= 0)
2310                                 LinuxDocError(par, 0,
2311                                               _("Error : Wrong depth for"
2312                                                 " LatexType Command.\n"));
2313
2314                         if (!environment_stack[depth].empty()){
2315                                 sgmlCloseTag(ofs, depth,
2316                                              environment_stack[depth]);
2317                                 ofs << "</p>";
2318                         }
2319
2320                         environment_stack[depth].erase();
2321                         sgmlOpenTag(ofs, depth, style.latexname());
2322                         break;
2323
2324                 case LATEX_ENVIRONMENT:
2325                 case LATEX_ITEM_ENVIRONMENT:
2326                         if (depth == par->depth 
2327                            && environment_stack[depth] != style.latexname()
2328                            && !environment_stack[depth].empty()) {
2329
2330                                 sgmlCloseTag(ofs, depth,
2331                                              environment_stack[depth]);
2332                                 environment_stack[depth].erase();
2333                         }
2334                         if (depth < par->depth) {
2335                                depth = par->depth;
2336                                environment_stack[depth].erase();
2337                         }
2338                         if (environment_stack[depth] != style.latexname()) {
2339                                 if (depth == 0) {
2340                                         string const temp = "p";
2341                                         sgmlOpenTag(ofs, depth, temp);
2342                                 }
2343                                 environment_stack[depth] = style.latexname();
2344                                 sgmlOpenTag(ofs, depth,
2345                                             environment_stack[depth]);
2346                         }
2347                         if (style.latextype == LATEX_ENVIRONMENT) break;
2348
2349                         desc_on = (style.labeltype == LABEL_MANUAL);
2350
2351                         if (desc_on)
2352                                 item_name = "tag";
2353                         else
2354                                 item_name = "item";
2355
2356                         sgmlOpenTag(ofs, depth + 1, item_name);
2357                         break;
2358                 default:
2359                         sgmlOpenTag(ofs, depth, style.latexname());
2360                         break;
2361                 }
2362
2363 #ifndef NEW_INSETS
2364                 do {
2365 #endif
2366                         SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2367
2368                         par = par->next;
2369 #ifndef NEW_INSETS
2370                         linuxDocHandleFootnote(ofs, par, depth);
2371                 }
2372                 while(par && par->IsDummy());
2373 #endif
2374
2375                 ofs << "\n";
2376                 // write closing SGML tags
2377                 switch (style.latextype) {
2378                 case LATEX_COMMAND:
2379                 case LATEX_ENVIRONMENT:
2380                 case LATEX_ITEM_ENVIRONMENT:
2381                         break;
2382                 default:
2383                         sgmlCloseTag(ofs, depth, style.latexname());
2384                         break;
2385                 }
2386         }
2387    
2388         // Close open tags
2389         for (; depth > 0; --depth)
2390                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2391
2392         if (!environment_stack[depth].empty())
2393                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2394
2395         if (!body_only) {
2396                 ofs << "\n\n";
2397                 sgmlCloseTag(ofs, 0, top_element);
2398         }
2399
2400         ofs.close();
2401         // How to check for successful close
2402 }
2403
2404
2405 #ifndef NEW_INSETS
2406 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2407                                     int depth)
2408 {
2409         string const tag = "footnote";
2410
2411         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2412                 sgmlOpenTag(os, depth + 1, tag);
2413                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2414                 sgmlCloseTag(os, depth + 1, tag);
2415                 par = par->next;
2416         }
2417 }
2418 #endif
2419
2420
2421 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2422                                   int depth, int desc_on,
2423                                   LyXParagraph * & par)
2424 {
2425         LyXParagraph * tpar = par;
2426         while (tpar
2427 #ifndef NEW_INSETS
2428                && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2429 #endif
2430                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2431                                                              "Caption").second))
2432                 tpar = tpar->next;
2433         if (tpar &&
2434             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2435                                                          "Caption").second) {
2436                 sgmlOpenTag(os, depth + 1, inner_tag);
2437                 string extra_par;
2438                 SimpleDocBookOnePar(os, extra_par, tpar,
2439                                     desc_on, depth + 2);
2440                 sgmlCloseTag(os, depth+1, inner_tag);
2441                 if (!extra_par.empty())
2442                         os << extra_par;
2443         }
2444 }
2445
2446
2447 #ifndef NEW_INSETS
2448 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2449                                    int depth)
2450 {
2451         string tag, inner_tag;
2452         string tmp_par, extra_par;
2453         bool inner_span = false;
2454         int desc_on = 4;
2455
2456         // Someone should give this enum a proper name (Lgb)
2457         enum SOME_ENUM {
2458                 NO_ONE,
2459                 FOOTNOTE_LIKE,
2460                 MARGIN_LIKE,
2461                 FIG_LIKE,
2462                 TAB_LIKE
2463         };
2464         SOME_ENUM last = NO_ONE;
2465         SOME_ENUM present = FOOTNOTE_LIKE;
2466
2467         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2468                 if (last == present) {
2469                         if (inner_span) {
2470                                 if (!tmp_par.empty()) {
2471                                         os << tmp_par;
2472                                         tmp_par.erase();
2473                                         sgmlCloseTag(os, depth + 1, inner_tag);
2474                                         sgmlOpenTag(os, depth + 1, inner_tag);
2475                                 }
2476                         } else {
2477                                 os << "\n";
2478                         }
2479                 } else {
2480                         os << tmp_par;
2481                         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2482                                                             inner_tag);
2483                         if (!extra_par.empty()) os << extra_par;
2484                         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2485                         extra_par.erase();
2486
2487                         switch (par->footnotekind) {
2488                         case LyXParagraph::FOOTNOTE:
2489                         case LyXParagraph::ALGORITHM:
2490                                 tag = "footnote";
2491                                 inner_tag = "para";
2492                                 present = FOOTNOTE_LIKE;
2493                                 inner_span = true;
2494                                 break;
2495                         case LyXParagraph::MARGIN:
2496                                 tag = "sidebar";
2497                                 inner_tag = "para";
2498                                 present = MARGIN_LIKE;
2499                                 inner_span = true;
2500                                 break;
2501                         case LyXParagraph::FIG:
2502                         case LyXParagraph::WIDE_FIG:
2503                                 tag = "figure";
2504                                 inner_tag = "title";
2505                                 present = FIG_LIKE;
2506                                 inner_span = false;
2507                                 break;
2508                         case LyXParagraph::TAB:
2509                         case LyXParagraph::WIDE_TAB:
2510                                 tag = "table";
2511                                 inner_tag = "title";
2512                                 present = TAB_LIKE;
2513                                 inner_span = false;
2514                                 break;
2515                         }
2516                         sgmlOpenTag(os, depth, tag);
2517                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2518                                 DocBookHandleCaption(os, inner_tag, depth,
2519                                                      desc_on, par);
2520                                 inner_tag.erase();
2521                         } else {
2522                                 sgmlOpenTag(os, depth + 1, inner_tag);
2523                         }
2524                 }
2525                 // ignore all caption here, we processed them above!!!
2526                 if (par->layout != textclasslist
2527                     .NumberOfLayout(params.textclass,
2528                                     "Caption").second) {
2529                         std::ostringstream ost;
2530                         SimpleDocBookOnePar(ost, extra_par, par,
2531                                             desc_on, depth + 2);
2532                         tmp_par += ost.str().c_str();
2533                 }
2534                 tmp_par = frontStrip(strip(tmp_par));
2535
2536                 last = present;
2537                 par = par->next;
2538         }
2539         os << tmp_par;
2540         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2541         if (!extra_par.empty()) os << extra_par;
2542         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2543 }
2544 #endif
2545
2546
2547 // push a tag in a style stack
2548 void Buffer::push_tag(ostream & os, string const & tag,
2549                       int & pos, char stack[5][3])
2550 {
2551 #ifdef WITH_WARNINGS
2552 #warning Use a real stack! (Lgb)
2553 #endif
2554         // pop all previous tags
2555         for (int j = pos; j >= 0; --j)
2556                 os << "</" << stack[j] << ">";
2557
2558         // add new tag
2559         sprintf(stack[++pos], "%s", tag.c_str());
2560
2561         // push all tags
2562         for (int i = 0; i <= pos; ++i)
2563                 os << "<" << stack[i] << ">";
2564 }
2565
2566
2567 void Buffer::pop_tag(ostream & os, string const & tag,
2568                      int & pos, char stack[5][3])
2569 {
2570 #ifdef WITH_WARNINGS
2571 #warning Use a real stack! (Lgb)
2572 #endif
2573         // Please, Lars, do not remove the global variable. I already
2574         // had to reintroduce it twice! (JMarc)
2575         // but...but... I'll remove it anyway. (well not quite) (Lgb)
2576 #if 0
2577         int j;
2578         
2579         // pop all tags till specified one
2580         for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2581                 os << "</" << stack[j] << ">";
2582
2583         // closes the tag
2584         os << "</" << tag << ">";
2585         
2586         // push all tags, but the specified one
2587         for (j = j + 1; j <= pos; ++j) {
2588                 os << "<" << stack[j] << ">";
2589                 strcpy(stack[j - 1], stack[j]);
2590         }
2591         --pos;
2592 #else
2593         // pop all tags till specified one
2594         int j = pos;
2595         for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2596                 os << "</" << stack[j] << ">";
2597
2598         // closes the tag
2599         os << "</" << tag << ">";
2600         
2601         // push all tags, but the specified one
2602         for (int i = j + 1; i <= pos; ++i) {
2603                 os << "<" << stack[i] << ">";
2604                 strcpy(stack[i - 1], stack[i]);
2605         }
2606         --pos;
2607 #endif
2608 }
2609
2610
2611 // Handle internal paragraph parsing -- layout already processed.
2612
2613 // checks, if newcol chars should be put into this line
2614 // writes newline, if necessary.
2615 static
2616 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2617                           string::size_type newcol)
2618 {
2619         colcount += newcol;
2620         if (colcount > lyxrc.ascii_linelen) {
2621                 os << "\n";
2622                 colcount = newcol; // assume write after this call
2623         }
2624 }
2625
2626
2627 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2628                                   int desc_on, int /*depth*/)
2629 {
2630         LyXFont font1;
2631         char c;
2632         Inset * inset;
2633         LyXParagraph::size_type main_body;
2634         int j;
2635         LyXLayout const & style = textclasslist.Style(params.textclass,
2636                                                       par->GetLayout());
2637
2638         char family_type = 0;               // family font flag 
2639         bool is_bold     = false;           // series font flag 
2640         char shape_type  = 0;               // shape font flag 
2641         bool is_em = false;                 // emphasis (italic) font flag 
2642
2643         int stack_num = -1;          // style stack position
2644         // Can this be rewritten to use a std::stack, please. (Lgb)
2645         char stack[5][3];            // style stack 
2646         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2647
2648         if (style.labeltype != LABEL_MANUAL)
2649                 main_body = 0;
2650         else
2651                 main_body = par->BeginningOfMainBody();
2652
2653         // gets paragraph main font
2654         if (main_body > 0)
2655                 font1 = style.labelfont;
2656         else
2657                 font1 = style.font;
2658
2659   
2660         // parsing main loop
2661         for (LyXParagraph::size_type i = 0;
2662              i < par->size(); ++i) {
2663
2664                 // handle quote tag
2665                 if (i == main_body
2666 #ifndef NEW_INSETS
2667                     && !par->IsDummy()
2668 #endif
2669                         ) {
2670                         if (main_body > 0)
2671                                 font1 = style.font;
2672                 }
2673
2674                 LyXFont const font2 = par->getFont(params, i);
2675
2676                 if (font1.family() != font2.family()) {
2677                         switch (family_type) {
2678                         case 0:
2679                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2680                                         push_tag(os, "tt", stack_num, stack);
2681                                         family_type = 1;
2682                                 }
2683                                 else if (font2.family() == LyXFont::SANS_FAMILY) {
2684                                         push_tag(os, "sf", stack_num, stack);
2685                                         family_type = 2;
2686                                 }
2687                                 break;
2688                         case 1:
2689                                 pop_tag(os, "tt", stack_num, stack);
2690                                 if (font2.family() == LyXFont::SANS_FAMILY) {
2691                                         push_tag(os, "sf", stack_num, stack);
2692                                         family_type = 2;
2693                                 } else {
2694                                         family_type = 0;
2695                                 }
2696                                 break;
2697                         case 2:
2698                                 pop_tag(os, "sf", stack_num, stack);
2699                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2700                                         push_tag(os, "tt", stack_num, stack);
2701                                         family_type = 1;
2702                                 } else {
2703                                         family_type = 0;
2704                                 }
2705                         }
2706                 }
2707
2708                 // handle bold face
2709                 if (font1.series() != font2.series()) {
2710                         if (font2.series() == LyXFont::BOLD_SERIES) {
2711                                 push_tag(os, "bf", stack_num, stack);
2712                                 is_bold = true;
2713                         } else if (is_bold) {
2714                                 pop_tag(os, "bf", stack_num, stack);
2715                                 is_bold = false;
2716                         }
2717                 }
2718
2719                 // handle italic and slanted fonts
2720                 if (font1.shape() != font2.shape()) {
2721                         switch (shape_type) {
2722                         case 0:
2723                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2724                                         push_tag(os, "it", stack_num, stack);
2725                                         shape_type = 1;
2726                                 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2727                                         push_tag(os, "sl", stack_num, stack);
2728                                         shape_type = 2;
2729                                 }
2730                                 break;
2731                         case 1:
2732                                 pop_tag(os, "it", stack_num, stack);
2733                                 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2734                                         push_tag(os, "sl", stack_num, stack);
2735                                         shape_type = 2;
2736                                 } else {
2737                                         shape_type = 0;
2738                                 }
2739                                 break;
2740                         case 2:
2741                                 pop_tag(os, "sl", stack_num, stack);
2742                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2743                                         push_tag(os, "it", stack_num, stack);
2744                                         shape_type = 1;
2745                                 } else {
2746                                         shape_type = 0;
2747                                 }
2748                         }
2749                 }
2750                 // handle <em> tag
2751                 if (font1.emph() != font2.emph()) {
2752                         if (font2.emph() == LyXFont::ON) {
2753                                 push_tag(os, "em", stack_num, stack);
2754                                 is_em = true;
2755                         } else if (is_em) {
2756                                 pop_tag(os, "em", stack_num, stack);
2757                                 is_em = false;
2758                         }
2759                 }
2760
2761                 c = par->GetChar(i);
2762
2763                 if (c == LyXParagraph::META_INSET) {
2764                         inset = par->GetInset(i);
2765                         inset->Linuxdoc(this, os);
2766                 }
2767
2768                 if (font2.latex() == LyXFont::ON) {
2769                         // "TeX"-Mode on == > SGML-Mode on.
2770                         if (c != '\0')
2771                                 os << c; // see LaTeX-Generation...
2772                         ++char_line_count;
2773                 } else {
2774                         string sgml_string;
2775                         if (par->linuxDocConvertChar(c, sgml_string)
2776                             && !style.free_spacing) { // in freespacing
2777                                                      // mode, spaces are
2778                                                      // non-breaking characters
2779                                 // char is ' '
2780                                 if (desc_on == 1) {
2781                                         ++char_line_count;
2782                                         linux_doc_line_break(os, char_line_count, 6);
2783                                         os << "</tag>";
2784                                         desc_on = 2;
2785                                 } else  {
2786                                         linux_doc_line_break(os, char_line_count, 1);
2787                                         os << c;
2788                                 }
2789                         } else {
2790                                 os << sgml_string;
2791                                 char_line_count += sgml_string.length();
2792                         }
2793                 }
2794                 font1 = font2;
2795         }
2796
2797         // needed if there is an optional argument but no contents
2798         if (main_body > 0 && main_body == par->size()) {
2799                 font1 = style.font;
2800         }
2801
2802         // pop all defined Styles
2803         for (j = stack_num; j >= 0; --j) {
2804                 linux_doc_line_break(os, 
2805                                      char_line_count, 
2806                                      3 + strlen(stack[j]));
2807                 os << "</" << stack[j] << ">";
2808         }
2809
2810         // resets description flag correctly
2811         switch (desc_on){
2812         case 1:
2813                 // <tag> not closed...
2814                 linux_doc_line_break(os, char_line_count, 6);
2815                 os << "</tag>";
2816                 break;
2817         case 2:
2818                 // fprintf(file, "</p>");
2819                 break;
2820         }
2821 }
2822
2823
2824 // Print an error message.
2825 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2826                            string const & message) 
2827 {
2828         // insert an error marker in text
2829         InsetError * new_inset = new InsetError(message);
2830         par->InsertInset(pos, new_inset);
2831 }
2832
2833 // This constant defines the maximum number of 
2834 // environment layouts that can be nesteded.
2835 // The same applies for command layouts.
2836 // These values should be more than enough.
2837 //           José Matos (1999/07/22)
2838
2839 enum { MAX_NEST_LEVEL = 25};
2840
2841 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2842 {
2843         LyXParagraph * par = paragraph;
2844
2845         niceFile = nice; // this will be used by Insetincludes.
2846
2847         string top_element= textclasslist.LatexnameOfClass(params.textclass);
2848         // Please use a real stack.
2849         string environment_stack[MAX_NEST_LEVEL];
2850         string environment_inner[MAX_NEST_LEVEL];
2851         // Please use a real stack.
2852         string command_stack[MAX_NEST_LEVEL];
2853         bool command_flag= false;
2854         int command_depth= 0, command_base= 0, cmd_depth= 0;
2855
2856         string item_name, command_name;
2857         string c_depth, c_params, tmps;
2858
2859         int depth = 0; // paragraph depth
2860         LyXTextClass const & tclass =
2861                 textclasslist.TextClass(params.textclass);
2862
2863         LaTeXFeatures features(params, tclass.numLayouts());
2864         validate(features);
2865
2866         //if (nice)
2867         tex_code_break_column = lyxrc.ascii_linelen;
2868         //else
2869         //tex_code_break_column = 0;
2870
2871         ofstream ofs(fname.c_str());
2872         if (!ofs) {
2873                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2874                 return;
2875         }
2876    
2877         texrow.reset();
2878
2879         if (!only_body) {
2880                 string sgml_includedfiles=features.getIncludedFiles(fname);
2881
2882                 ofs << "<!doctype " << top_element
2883                     << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2884
2885                 if (params.preamble.empty() && sgml_includedfiles.empty())
2886                         ofs << ">\n\n";
2887                 else
2888                         ofs << "\n [ " << params.preamble 
2889                             << sgml_includedfiles << " \n]>\n\n";
2890         }
2891
2892         if (params.options.empty())
2893                 sgmlOpenTag(ofs, 0, top_element);
2894         else {
2895                 string top = top_element;
2896                 top += " ";
2897                 top += params.options;
2898                 sgmlOpenTag(ofs, 0, top);
2899         }
2900
2901         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
2902             << "\n  See http://www.lyx.org/ for more information -->\n";
2903
2904         while (par) {
2905                 int desc_on = 0; // description mode
2906                 LyXLayout const & style =
2907                         textclasslist.Style(params.textclass,
2908                                             par->layout);
2909
2910                 // environment tag closing
2911                 for (; depth > par->depth; --depth) {
2912                         if (environment_inner[depth] != "!-- --") {
2913                                 item_name= "listitem";
2914                                 sgmlCloseTag(ofs, command_depth + depth,
2915                                              item_name);
2916                                 if (environment_inner[depth] == "varlistentry")
2917                                         sgmlCloseTag(ofs, depth+command_depth,
2918                                                      environment_inner[depth]);
2919                         }
2920                         sgmlCloseTag(ofs, depth + command_depth,
2921                                      environment_stack[depth]);
2922                         environment_stack[depth].erase();
2923                         environment_inner[depth].erase();
2924                 }
2925
2926                 if (depth == par->depth
2927                    && environment_stack[depth] != style.latexname()
2928                    && !environment_stack[depth].empty()) {
2929                         if (environment_inner[depth] != "!-- --") {
2930                                 item_name= "listitem";
2931                                 sgmlCloseTag(ofs, command_depth+depth,
2932                                              item_name);
2933                                 if (environment_inner[depth] == "varlistentry")
2934                                         sgmlCloseTag(ofs,
2935                                                      depth + command_depth,
2936                                                      environment_inner[depth]);
2937                         }
2938                         
2939                         sgmlCloseTag(ofs, depth + command_depth,
2940                                      environment_stack[depth]);
2941                         
2942                         environment_stack[depth].erase();
2943                         environment_inner[depth].erase();
2944                 }
2945
2946                 // Write opening SGML tags.
2947                 switch (style.latextype) {
2948                 case LATEX_PARAGRAPH:
2949                         sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2950                         break;
2951
2952                 case LATEX_COMMAND:
2953                         if (depth!= 0)
2954                                 LinuxDocError(par, 0,
2955                                               _("Error : Wrong depth for "
2956                                                 "LatexType Command.\n"));
2957                         
2958                         command_name = style.latexname();
2959                         
2960                         tmps = style.latexparam();
2961                         c_params = split(tmps, c_depth,'|');
2962                         
2963                         cmd_depth= lyx::atoi(c_depth);
2964                         
2965                         if (command_flag) {
2966                                 if (cmd_depth<command_base) {
2967                                         for (int j = command_depth;
2968                                             j >= command_base; --j)
2969                                                 if (!command_stack[j].empty())
2970                                                         sgmlCloseTag(ofs, j, command_stack[j]);
2971                                         command_depth= command_base= cmd_depth;
2972                                 } else if (cmd_depth <= command_depth) {
2973                                         for (int j = command_depth;
2974                                             j >= cmd_depth; --j)
2975
2976                                                 if (!command_stack[j].empty())
2977                                                         sgmlCloseTag(ofs, j, command_stack[j]);
2978                                         command_depth= cmd_depth;
2979                                 } else
2980                                         command_depth= cmd_depth;
2981                         } else {
2982                                 command_depth = command_base = cmd_depth;
2983                                 command_flag = true;
2984                         }
2985                         command_stack[command_depth]= command_name;
2986
2987                         // treat label as a special case for
2988                         // more WYSIWYM handling.
2989                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
2990                                 Inset * inset = par->GetInset(0);
2991                                 Inset::Code lyx_code = inset->LyxCode();
2992                                 if (lyx_code == Inset::LABEL_CODE){
2993                                         command_name += " id=\"";
2994                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
2995                                         command_name += "\"";
2996                                         desc_on = 3;
2997                                 }
2998                         }
2999
3000                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3001                         item_name = "title";
3002                         if (command_name != "!-- --")
3003                                 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3004                         break;
3005
3006                 case LATEX_ENVIRONMENT:
3007                 case LATEX_ITEM_ENVIRONMENT:
3008                         if (depth < par->depth) {
3009                                 depth = par->depth;
3010                                 environment_stack[depth].erase();
3011                         }
3012
3013                         if (environment_stack[depth] != style.latexname()) {
3014                                 environment_stack[depth] = style.latexname();
3015                                 environment_inner[depth] = "!-- --";
3016                                 sgmlOpenTag(ofs, depth + command_depth,
3017                                             environment_stack[depth]);
3018                         } else {
3019                                 if (environment_inner[depth] != "!-- --") {
3020                                         item_name= "listitem";
3021                                         sgmlCloseTag(ofs,
3022                                                      command_depth + depth,
3023                                                      item_name);
3024                                         if (environment_inner[depth] == "varlistentry")
3025                                                 sgmlCloseTag(ofs,
3026                                                              depth + command_depth,
3027                                                              environment_inner[depth]);
3028                                 }
3029                         }
3030                         
3031                         if (style.latextype == LATEX_ENVIRONMENT) {
3032                                 if (!style.latexparam().empty())
3033                                         sgmlOpenTag(ofs, depth + command_depth,
3034                                                     style.latexparam());
3035                                 break;
3036                         }
3037
3038                         desc_on = (style.labeltype == LABEL_MANUAL);
3039
3040                         if (desc_on)
3041                                 environment_inner[depth]= "varlistentry";
3042                         else
3043                                 environment_inner[depth]= "listitem";
3044
3045                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3046                                     environment_inner[depth]);
3047
3048                         if (desc_on) {
3049                                 item_name= "term";
3050                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3051                                             item_name);
3052                         } else {
3053                                 item_name= "para";
3054                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3055                                             item_name);
3056                         }
3057                         break;
3058                 default:
3059                         sgmlOpenTag(ofs, depth + command_depth,
3060                                     style.latexname());
3061                         break;
3062                 }
3063
3064 #ifndef NEW_INSETS
3065                 do {
3066 #endif
3067                         string extra_par;
3068                         SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3069                                             depth + 1 + command_depth);
3070                         par = par->next;
3071 #ifndef NEW_INSETS
3072                         DocBookHandleFootnote(ofs, par,
3073                                               depth + 1 + command_depth);
3074                 }
3075                 while(par && par->IsDummy());
3076 #endif
3077                 string end_tag;
3078                 // write closing SGML tags
3079                 switch (style.latextype) {
3080                 case LATEX_COMMAND:
3081                         end_tag = "title";
3082                         if (command_name != "!-- --")
3083                                 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3084                         break;
3085                 case LATEX_ENVIRONMENT:
3086                         if (!style.latexparam().empty())
3087                                 sgmlCloseTag(ofs, depth + command_depth,
3088                                              style.latexparam());
3089                         break;
3090                 case LATEX_ITEM_ENVIRONMENT:
3091                         if (desc_on == 1) break;
3092                         end_tag= "para";
3093                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3094                         break;
3095                 case LATEX_PARAGRAPH:
3096                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3097                         break;
3098                 default:
3099                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3100                         break;
3101                 }
3102         }
3103
3104         // Close open tags
3105         for (; depth >= 0; --depth) {
3106                 if (!environment_stack[depth].empty()) {
3107                         if (environment_inner[depth] != "!-- --") {
3108                                 item_name= "listitem";
3109                                 sgmlCloseTag(ofs, command_depth + depth,
3110                                              item_name);
3111                                if (environment_inner[depth] == "varlistentry")
3112                                        sgmlCloseTag(ofs, depth + command_depth,
3113                                                     environment_inner[depth]);
3114                         }
3115                         
3116                         sgmlCloseTag(ofs, depth + command_depth,
3117                                      environment_stack[depth]);
3118                 }
3119         }
3120         
3121         for (int j = command_depth; j >= command_base; --j)
3122                 if (!command_stack[j].empty())
3123                         sgmlCloseTag(ofs, j, command_stack[j]);
3124
3125         ofs << "\n\n";
3126         sgmlCloseTag(ofs, 0, top_element);
3127
3128         ofs.close();
3129         // How to check for successful close
3130 }
3131
3132
3133 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3134                                  LyXParagraph * par, int & desc_on,
3135                                  int depth) const
3136 {
3137         bool emph_flag = false;
3138
3139         LyXLayout const & style = textclasslist.Style(params.textclass,
3140                                                       par->GetLayout());
3141
3142         LyXParagraph::size_type main_body;
3143         if (style.labeltype != LABEL_MANUAL)
3144                 main_body = 0;
3145         else
3146                 main_body = par->BeginningOfMainBody();
3147
3148         // gets paragraph main font
3149         LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3150         
3151         int char_line_count = depth;
3152         if (!style.free_spacing)
3153                 for (int j = 0; j < depth; ++j)
3154                         os << ' ';
3155
3156         // parsing main loop
3157         for (LyXParagraph::size_type i = 0;
3158              i < par->size(); ++i) {
3159                 LyXFont font2 = par->getFont(params, i);
3160
3161                 // handle <emphasis> tag
3162                 if (font1.emph() != font2.emph() && i) {
3163                         if (font2.emph() == LyXFont::ON) {
3164                                 os << "<emphasis>";
3165                                 emph_flag = true;
3166                         }else {
3167                                 os << "</emphasis>";
3168                                 emph_flag = false;
3169                         }
3170                 }
3171       
3172                 char c = par->GetChar(i);
3173
3174                 if (c == LyXParagraph::META_INSET) {
3175                         Inset * inset = par->GetInset(i);
3176                         std::ostringstream ost;
3177                         inset->DocBook(this, ost);
3178                         string tmp_out = ost.str().c_str();
3179
3180                         //
3181                         // This code needs some explanation:
3182                         // Two insets are treated specially
3183                         //   label if it is the first element in a command paragraph
3184                         //         desc_on == 3
3185                         //   graphics inside tables or figure floats can't go on
3186                         //   title (the equivalente in latex for this case is caption
3187                         //   and title should come first
3188                         //         desc_on == 4
3189                         //
3190                         if (desc_on!= 3 || i!= 0) {
3191                                 if (!tmp_out.empty() && tmp_out[0] == '@') {
3192                                         if (desc_on == 4)
3193                                                 extra += frontStrip(tmp_out, '@');
3194                                         else
3195                                                 os << frontStrip(tmp_out, '@');
3196                                 }
3197                                 else
3198                                         os << tmp_out;
3199                         }
3200                 } else if (font2.latex() == LyXFont::ON) {
3201                         // "TeX"-Mode on ==> SGML-Mode on.
3202                         if (c != '\0')
3203                                 os << c;
3204                         ++char_line_count;
3205                 } else {
3206                         string sgml_string;
3207                         if (par->linuxDocConvertChar(c, sgml_string)
3208                             && !style.free_spacing) { // in freespacing
3209                                                      // mode, spaces are
3210                                                      // non-breaking characters
3211                                 // char is ' '
3212                                 if (desc_on == 1) {
3213                                         ++char_line_count;
3214                                         os << "\n</term><listitem><para>";
3215                                         desc_on = 2;
3216                                 } else {
3217                                         os << c;
3218                                 }
3219                         } else {
3220                                 os << sgml_string;
3221                         }
3222                 }
3223                 font1 = font2;
3224         }
3225
3226         // needed if there is an optional argument but no contents
3227         if (main_body > 0 && main_body == par->size()) {
3228                 font1 = style.font;
3229         }
3230         if (emph_flag) {
3231                 os << "</emphasis>";
3232         }
3233         
3234         // resets description flag correctly
3235         switch (desc_on){
3236         case 1:
3237                 // <term> not closed...
3238                 os << "</term>";
3239                 break;
3240         }
3241         os << '\n';
3242 }
3243
3244
3245 // This should be enabled when the Chktex class is implemented. (Asger)
3246 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3247 // Other flags: -wall -v0 -x
3248 int Buffer::runChktex()
3249 {
3250         if (!users->text) return 0;
3251
3252         ProhibitInput(users);
3253
3254         // get LaTeX-Filename
3255         string const name = getLatexName();
3256         string path = OnlyPath(filename);
3257
3258         string const org_path = path;
3259         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3260                 path = tmppath;  
3261         }
3262
3263         Path p(path); // path to LaTeX file
3264         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3265
3266         // Remove all error insets
3267         bool const removedErrorInsets = users->removeAutoInsets();
3268
3269         // Generate the LaTeX file if neccessary
3270         makeLaTeXFile(name, org_path, false);
3271
3272         TeXErrors terr;
3273         Chktex chktex(lyxrc.chktex_command, name, filepath);
3274         int res = chktex.run(terr); // run chktex
3275
3276         if (res == -1) {
3277                 WriteAlert(_("chktex did not work!"),
3278                            _("Could not run with file:"), name);
3279         } else if (res > 0) {
3280                 // Insert all errors as errors boxes
3281                 users->insertErrors(terr);
3282         }
3283
3284         // if we removed error insets before we ran chktex or if we inserted
3285         // error insets after we ran chktex, this must be run:
3286         if (removedErrorInsets || res){
3287                 users->redraw();
3288                 users->fitCursor(users->text);
3289         }
3290         AllowInput(users);
3291
3292         return res;
3293 }
3294
3295
3296 void Buffer::validate(LaTeXFeatures & features) const
3297 {
3298         LyXParagraph * par = paragraph;
3299         LyXTextClass const & tclass = 
3300                 textclasslist.TextClass(params.textclass);
3301     
3302         // AMS Style is at document level
3303     
3304         features.amsstyle = (params.use_amsmath ||
3305                              tclass.provides(LyXTextClass::amsmath));
3306     
3307         while (par) {
3308                 // We don't use "lyxerr.debug" because of speed. (Asger)
3309                 if (lyxerr.debugging(Debug::LATEX))
3310                         lyxerr << "Paragraph: " <<  par << endl;
3311
3312                 // Now just follow the list of paragraphs and run
3313                 // validate on each of them.
3314                 par->validate(features);
3315
3316                 // and then the next paragraph
3317                 par = par->next;
3318         }
3319
3320         // the bullet shapes are buffer level not paragraph level
3321         // so they are tested here
3322         for (int i = 0; i < 4; ++i) {
3323                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3324                         int const font = params.user_defined_bullets[i].getFont();
3325                         if (font == 0) {
3326                                 int const c = params
3327                                         .user_defined_bullets[i]
3328                                         .getCharacter();
3329                                 if (c == 16
3330                                    || c == 17
3331                                    || c == 25
3332                                    || c == 26
3333                                    || c == 31) {
3334                                         features.latexsym = true;
3335                                 }
3336                         } else if (font == 1) {
3337                                 features.amssymb = true;
3338                         } else if ((font >= 2 && font <= 5)) {
3339                                 features.pifont = true;
3340                         }
3341                 }
3342         }
3343         
3344         if (lyxerr.debugging(Debug::LATEX)) {
3345                 features.showStruct();
3346         }
3347 }
3348
3349
3350 void Buffer::setPaperStuff()
3351 {
3352         params.papersize = BufferParams::PAPER_DEFAULT;
3353         char const c1 = params.paperpackage;
3354         if (c1 == BufferParams::PACKAGE_NONE) {
3355                 char const c2 = params.papersize2;
3356                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3357                         params.papersize = BufferParams::PAPER_USLETTER;
3358                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3359                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3360                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3361                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3362                 else if (c2 == BufferParams::VM_PAPER_A3)
3363                         params.papersize = BufferParams::PAPER_A3PAPER;
3364                 else if (c2 == BufferParams::VM_PAPER_A4)
3365                         params.papersize = BufferParams::PAPER_A4PAPER;
3366                 else if (c2 == BufferParams::VM_PAPER_A5)
3367                         params.papersize = BufferParams::PAPER_A5PAPER;
3368                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3369                          (c2 == BufferParams::VM_PAPER_B5))
3370                         params.papersize = BufferParams::PAPER_B5PAPER;
3371         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3372                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3373                 params.papersize = BufferParams::PAPER_A4PAPER;
3374 }
3375
3376
3377 // This function should be in Buffer because it's a buffer's property (ale)
3378 string const Buffer::getIncludeonlyList(char delim)
3379 {
3380         string lst;
3381         for (inset_iterator it = inset_iterator_begin();
3382             it != inset_iterator_end(); ++it) {
3383                 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3384                         InsetInclude * insetinc = 
3385                                 static_cast<InsetInclude *>(*it);
3386                         if (insetinc->isInclude() 
3387                             && insetinc->isNoLoad()) {
3388                                 if (!lst.empty())
3389                                         lst += delim;
3390                                 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3391                         }
3392                 }
3393         }
3394         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3395         return lst;
3396 }
3397
3398
3399 vector<string> const Buffer::getLabelList()
3400 {
3401         /// if this is a child document and the parent is already loaded
3402         /// Use the parent's list instead  [ale990407]
3403         if (!params.parentname.empty()
3404             && bufferlist.exists(params.parentname)) {
3405                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3406                 if (tmp)
3407                         return tmp->getLabelList();
3408         }
3409
3410         vector<string> label_list;
3411         for (inset_iterator it = inset_iterator_begin();
3412              it != inset_iterator_end(); ++it) {
3413                 vector<string> const l = (*it)->getLabelList();
3414                 label_list.insert(label_list.end(), l.begin(), l.end());
3415         }
3416         return label_list;
3417 }
3418
3419
3420 vector<vector<Buffer::TocItem> > const Buffer::getTocList() const
3421 {
3422         int figs = 0;
3423         int tables = 0;
3424         int algs = 0;
3425         vector<vector<TocItem> > l(4);
3426         LyXParagraph * par = paragraph;
3427         while (par) {
3428 #ifndef NEW_INSETS
3429                 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3430                         if (textclasslist.Style(params.textclass, 
3431                                                 par->GetLayout()).labeltype
3432                             == LABEL_SENSITIVE) {
3433                                 TocItem tmp;
3434                                 tmp.par = par;
3435                                 tmp.depth = 0;
3436                                 tmp.str =  par->String(this, false);
3437                                 switch (par->footnotekind) {
3438                                 case LyXParagraph::FIG:
3439                                 case LyXParagraph::WIDE_FIG:
3440                                         tmp.str = tostr(++figs) + ". "
3441                                                 + tmp.str;
3442                                         l[TOC_LOF].push_back(tmp);
3443                                         break;
3444                                 case LyXParagraph::TAB:
3445                                 case LyXParagraph::WIDE_TAB:
3446                                         tmp.str = tostr(++tables) + ". "
3447                                                 + tmp.str;
3448                                         l[TOC_LOT].push_back(tmp);
3449                                         break;
3450                                 case LyXParagraph::ALGORITHM:
3451                                         tmp.str = tostr(++algs) + ". "
3452                                                 + tmp.str;
3453                                         l[TOC_LOA].push_back(tmp);
3454                                         break;
3455                                 case LyXParagraph::FOOTNOTE:
3456                                 case LyXParagraph::MARGIN:
3457                                         break;
3458                                 }
3459                         }
3460                 } else if (!par->IsDummy()) {
3461 #endif
3462                         char const labeltype =
3463                                 textclasslist.Style(params.textclass, 
3464                                                     par->GetLayout()).labeltype;
3465       
3466                         if (labeltype >= LABEL_COUNTER_CHAPTER
3467                             && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3468                                 // insert this into the table of contents
3469                                 TocItem tmp;
3470                                 tmp.par = par;
3471                                 tmp.depth = max(0,
3472                                                 labeltype - 
3473                                                 textclasslist.TextClass(params.textclass).maxcounter());
3474                                 tmp.str =  par->String(this, true);
3475                                 l[TOC_TOC].push_back(tmp);
3476                         }
3477 #ifndef NEW_INSETS
3478                 }
3479 #endif
3480                 par = par->next;
3481         }
3482         return l;
3483 }
3484
3485
3486 // This is also a buffer property (ale)
3487 vector<pair<string,string> > const Buffer::getBibkeyList()
3488 {
3489         /// if this is a child document and the parent is already loaded
3490         /// Use the parent's list instead  [ale990412]
3491         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3492                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3493                 if (tmp)
3494                         return tmp->getBibkeyList();
3495         }
3496
3497         vector<pair<string, string> > keys;
3498         LyXParagraph * par = paragraph;
3499         while (par) {
3500                 if (par->bibkey)
3501                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3502                                                            par->String(this, false)));
3503                 par = par->next;
3504         }
3505
3506         // Might be either using bibtex or a child has bibliography
3507         if (keys.empty()) {
3508                 for (inset_iterator it = inset_iterator_begin();
3509                         it != inset_iterator_end(); ++it) {
3510                         // Search for Bibtex or Include inset
3511                         if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3512                                 vector<pair<string,string> > tmp =
3513                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3514                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3515                         } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3516                                 vector<pair<string,string> > const tmp =
3517                                         static_cast<InsetInclude*>(*it)->getKeys();
3518                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3519                         }
3520                 }
3521         }
3522  
3523         return keys;
3524 }
3525
3526
3527 bool Buffer::isDepClean(string const & name) const
3528 {
3529         DEPCLEAN * item = dep_clean;
3530         while (item && item->master != name)
3531                 item = item->next;
3532         if (!item) return true;
3533         return item->clean;
3534 }
3535
3536
3537 void Buffer::markDepClean(string const & name)
3538 {
3539         if (!dep_clean) {
3540                 dep_clean = new DEPCLEAN;
3541                 dep_clean->clean = true;
3542                 dep_clean->master = name;
3543                 dep_clean->next = 0;
3544         } else {
3545                 DEPCLEAN * item = dep_clean;
3546                 while (item && item->master != name)
3547                         item = item->next;
3548                 if (item) {
3549                         item->clean = true;
3550                 } else {
3551                         item = new DEPCLEAN;
3552                         item->clean = true;
3553                         item->master = name;
3554                         item->next = 0;
3555                 }
3556         }
3557 }
3558
3559
3560 bool Buffer::Dispatch(string const & command)
3561 {
3562         // Split command string into command and argument
3563         string cmd;
3564         string line = frontStrip(command);
3565         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3566
3567         return Dispatch(lyxaction.LookupFunc(cmd), arg);
3568 }
3569
3570
3571 bool Buffer::Dispatch(int action, string const & argument)
3572 {
3573         bool dispatched = true;
3574         switch (action) {
3575                 case LFUN_EXPORT: 
3576                         Exporter::Export(this, argument, false);
3577                         break;
3578
3579                 default:
3580                         dispatched = false;
3581         }
3582         return dispatched;
3583 }
3584
3585
3586 void Buffer::resize()
3587 {
3588         /// resize the BufferViews!
3589         if (users)
3590                 users->resize();
3591 }
3592
3593
3594 void Buffer::resizeInsets(BufferView * bv)
3595 {
3596         /// then remove all LyXText in text-insets
3597         LyXParagraph * par = paragraph;
3598         for (; par; par = par->next) {
3599             par->resizeInsetsLyXText(bv);
3600         }
3601 }
3602
3603 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3604 {
3605
3606         LyXParagraph * par = paragraph;
3607         while (par) {
3608                 par->ChangeLanguage(params, from, to);
3609                 par = par->next;
3610         }
3611 }
3612
3613
3614 bool Buffer::isMultiLingual()
3615 {
3616         LyXParagraph * par = paragraph;
3617         while (par) {
3618                 if (par->isMultiLingual(params))
3619                         return true;
3620                 par = par->next;
3621         }
3622         return false;
3623 }
3624
3625
3626 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3627                                        LyXParagraph::size_type pos)
3628         : par(paragraph)
3629 {
3630         it = par->InsetIterator(pos);
3631         if (it == par->inset_iterator_end()) {
3632                 par = par->next;
3633                 SetParagraph();
3634         }
3635 }
3636
3637
3638 void Buffer::inset_iterator::SetParagraph()
3639 {
3640         while (par) {
3641                 it = par->inset_iterator_begin();
3642                 if (it != par->inset_iterator_end())
3643                         return;
3644                 par = par->next;
3645         }
3646         //it = 0;
3647         // We maintain an invariant that whenever par = 0 then it = 0
3648 }