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