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