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