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