]> git.lyx.org Git - lyx.git/blob - src/buffer.C
include sys/time.h
[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::max;
134 using std::stack;
135 using std::list;
136 using std::for_each;
137
138 using lyx::pos_type;
139 using lyx::textclass_type;
140
141 // all these externs should eventually be removed.
142 extern BufferList bufferlist;
143
144 namespace {
145
146 const int LYX_FORMAT = 222;
147
148 } // namespace anon
149
150 Buffer::Buffer(string const & file, bool ronly)
151         : niceFile(true), lyx_clean(true), bak_clean(true),
152           unnamed(false), read_only(ronly),
153           filename_(file), users(0)
154 {
155         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
156         filepath_ = OnlyPath(file);
157         lyxvc.buffer(this);
158         if (read_only || lyxrc.use_tempdir) {
159                 tmppath = CreateBufferTmpDir();
160         } else {
161                 tmppath.erase();
162         }
163
164         // set initial author
165         authorlist.record(Author(lyxrc.user_name, lyxrc.user_email)); 
166 }
167
168
169 Buffer::~Buffer()
170 {
171         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
172         // here the buffer should take care that it is
173         // saved properly, before it goes into the void.
174
175         // make sure that views using this buffer
176         // forgets it.
177         if (users)
178                 users->buffer(0);
179
180         if (!tmppath.empty()) {
181                 DestroyBufferTmpDir(tmppath);
182         }
183
184         paragraphs.clear();
185
186         // Remove any previewed LaTeX snippets assocoated with this buffer.
187         grfx::Previews::get().removeLoader(this);
188 }
189
190
191 string const Buffer::getLatexName(bool no_path) const
192 {
193         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
194         if (no_path)
195                 return OnlyFilename(name);
196         else
197                 return name;
198 }
199
200
201 pair<Buffer::LogType, string> const Buffer::getLogName() const
202 {
203         string const filename = getLatexName(false);
204
205         if (filename.empty())
206                 return make_pair(Buffer::latexlog, string());
207
208         string path = OnlyPath(filename);
209
210         if (lyxrc.use_tempdir || !IsDirWriteable(path))
211                 path = tmppath;
212
213         string const fname = AddName(path,
214                                      OnlyFilename(ChangeExtension(filename,
215                                                                   ".log")));
216         string const bname =
217                 AddName(path, OnlyFilename(
218                         ChangeExtension(filename,
219                                         formats.extension("literate") + ".out")));
220
221         // If no Latex log or Build log is newer, show Build log
222
223         FileInfo const f_fi(fname);
224         FileInfo const b_fi(bname);
225
226         if (b_fi.exist() &&
227             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
228                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
229                 return make_pair(Buffer::buildlog, bname);
230         }
231         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
232         return make_pair(Buffer::latexlog, fname);
233 }
234
235
236 void Buffer::setReadonly(bool flag)
237 {
238         if (read_only != flag) {
239                 read_only = flag;
240                 updateTitles();
241                 users->owner()->getDialogs().updateBufferDependent(false);
242         }
243 }
244
245
246 AuthorList & Buffer::authors()
247 {
248         return authorlist;
249 }
250
251
252 /// Update window titles of all users
253 // Should work on a list
254 void Buffer::updateTitles() const
255 {
256         if (users)
257                 users->owner()->updateWindowTitle();
258 }
259
260
261 /// Reset autosave timer of all users
262 // Should work on a list
263 void Buffer::resetAutosaveTimers() const
264 {
265         if (users)
266                 users->owner()->resetAutosaveTimer();
267 }
268
269
270 void Buffer::setFileName(string const & newfile)
271 {
272         filename_ = MakeAbsPath(newfile);
273         filepath_ = OnlyPath(filename_);
274         setReadonly(IsFileWriteable(filename_) == 0);
275         updateTitles();
276 }
277
278
279 // We'll remove this later. (Lgb)
280 namespace {
281
282 string last_inset_read;
283
284 #ifdef WITH_WARNINGS
285 #warning And _why_ is this here? (Lgb)
286 #endif
287 int unknown_layouts;
288 int unknown_tokens;
289 vector<int> author_ids;
290
291 } // anon
292
293
294 // candidate for move to BufferView
295 // (at least some parts in the beginning of the func)
296 //
297 // Uwe C. Schroeder
298 // changed to be public and have one parameter
299 // if par = 0 normal behavior
300 // else insert behavior
301 // Returns false if "\the_end" is not read (Asger)
302 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
303 {
304         unknown_layouts = 0;
305         unknown_tokens = 0;
306         author_ids.clear();
307
308         int pos = 0;
309         Paragraph::depth_type depth = 0;
310         bool the_end_read = false;
311
312         Paragraph * first_par = 0;
313         LyXFont font(LyXFont::ALL_INHERIT, params.language);
314
315         if (!par) {
316                 par = new Paragraph;
317                 par->layout(params.getLyXTextClass().defaultLayout());
318         } else {
319                 // We are inserting into an existing document
320                 users->text->breakParagraph(users);
321                 first_par = users->text->ownerParagraph();
322                 pos = 0;
323                 markDirty();
324                 // We don't want to adopt the parameters from the
325                 // document we insert, so we skip until the text begins:
326                 while (lex.isOK()) {
327                         lex.nextToken();
328                         string const pretoken = lex.getString();
329                         if (pretoken == "\\layout") {
330                                 lex.pushToken(pretoken);
331                                 break;
332                         }
333                 }
334         }
335
336         while (lex.isOK()) {
337                 lex.nextToken();
338                 string const token = lex.getString();
339
340                 if (token.empty()) continue;
341
342                 lyxerr[Debug::PARSER] << "Handling token: `"
343                                       << token << '\'' << endl;
344
345                 the_end_read =
346                         parseSingleLyXformat2Token(lex, par, first_par,
347                                                    token, pos, depth,
348                                                    font);
349         }
350
351         if (!first_par)
352                 first_par = par;
353
354         paragraphs.set(first_par);
355
356         if (unknown_layouts > 0) {
357                 string s = _("Couldn't set the layout for ");
358                 if (unknown_layouts == 1) {
359                         s += _("one paragraph");
360                 } else {
361                         s += tostr(unknown_layouts);
362                         s += _(" paragraphs");
363                 }
364 #if USE_BOOST_FORMAT
365                 Alert::alert(_("Textclass Loading Error!"), s,
366                            boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
367 #else
368                 Alert::alert(_("Textclass Loading Error!"), s,
369                              _("When reading ") + fileName());
370 #endif
371         }
372
373         if (unknown_tokens > 0) {
374                 string s = _("Encountered ");
375                 if (unknown_tokens == 1) {
376                         s += _("one unknown token");
377                 } else {
378                         s += tostr(unknown_tokens);
379                         s += _(" unknown tokens");
380                 }
381 #if USE_BOOST_FORMAT
382                 Alert::alert(_("Textclass Loading Error!"), s,
383                            boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
384 #else
385                 Alert::alert(_("Textclass Loading Error!"), s,
386                              _("When reading ") +  fileName());
387 #endif
388         }
389
390         return the_end_read;
391 }
392
393
394 namespace {
395         // This stuff is, in the traditional LyX terminology, Super UGLY
396         // but this code is too b0rken to admit of a better solution yet
397         Change current_change;
398 };
399  
400
401 bool
402 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
403                                    Paragraph *& first_par,
404                                    string const & token, int & pos,
405                                    Paragraph::depth_type & depth,
406                                    LyXFont & font
407         )
408 {
409         bool the_end_read = false;
410
411         // The order of the tags tested may seem unnatural, but this
412         // has been done in order to reduce the number of string
413         // comparisons needed to recognize a given token. This leads
414         // on large documents like UserGuide to a reduction of a
415         // factor 5! (JMarc)
416         if (token[0] != '\\') {
417                 for (string::const_iterator cit = token.begin();
418                      cit != token.end(); ++cit) {
419                         par->insertChar(pos, (*cit), font, current_change);
420                         ++pos;
421                 }
422         } else if (token == "\\layout") {
423                 // reset the font as we start a new layout and if the font is
424                 // not ALL_INHERIT,document_language then it will be set to the
425                 // right values after this tag (Jug 20020420)
426                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
427
428                 lex.eatLine();
429                 string layoutname = lex.getString();
430
431                 LyXTextClass const & tclass = params.getLyXTextClass();
432
433                 if (layoutname.empty()) {
434                         layoutname = tclass.defaultLayoutName();
435                 }
436                 bool hasLayout = tclass.hasLayout(layoutname);
437                 if (!hasLayout) {
438                         lyxerr << "Layout '" << layoutname << "' does not"
439                                << " exist in textclass '" << tclass.name()
440                                << "'." << endl;
441                         lyxerr << "Trying to use default layout instead."
442                                << endl;
443                         layoutname = tclass.defaultLayoutName();
444                 }
445
446 #ifdef USE_CAPTION
447                 // The is the compability reading of layout caption.
448                 // It can be removed in LyX version 1.3.0. (Lgb)
449                 if (compare_ascii_no_case(layoutname, "caption") == 0) {
450                         // We expect that the par we are now working on is
451                         // really inside a InsetText inside a InsetFloat.
452                         // We also know that captions can only be
453                         // one paragraph. (Lgb)
454
455                         // We should now read until the next "\layout"
456                         // is reached.
457                         // This is probably not good enough, what if the
458                         // caption is the last par in the document (Lgb)
459                         istream & ist = lex.getStream();
460                         stringstream ss;
461                         string line;
462                         int begin = 0;
463                         while (true) {
464                                 getline(ist, line);
465                                 if (prefixIs(line, "\\layout")) {
466                                         lex.pushToken(line);
467                                         break;
468                                 }
469                                 if (prefixIs(line, "\\begin_inset"))
470                                         ++begin;
471                                 if (prefixIs(line, "\\end_inset")) {
472                                         if (begin)
473                                                 --begin;
474                                         else {
475                                                 lex.pushToken(line);
476                                                 break;
477                                         }
478                                 }
479
480                                 ss << line << '\n';
481                         }
482                         // Now we should have the whole layout in ss
483                         // we should now be able to give this to the
484                         // caption inset.
485                         ss << "\\end_inset\n";
486
487                         // This seems like a bug in stringstream.
488                         // We really should be able to use ss
489                         // directly. (Lgb)
490                         istringstream is(ss.str());
491                         LyXLex tmplex(0, 0);
492                         tmplex.setStream(is);
493                         Inset * inset = new InsetCaption;
494                         inset->Read(this, tmplex);
495                         par->InsertInset(pos, inset, font);
496                         ++pos;
497                 } else {
498 #endif
499                         if (!first_par)
500                                 first_par = par;
501                         else {
502                                 par = new Paragraph(par);
503                                 par->layout(params.getLyXTextClass().defaultLayout());
504                                 if (params.tracking_changes)
505                                         par->trackChanges();
506                         }
507                         pos = 0;
508                         par->layout(params.getLyXTextClass()[layoutname]);
509                         // Test whether the layout is obsolete.
510                         LyXLayout_ptr const & layout = par->layout();
511                         if (!layout->obsoleted_by().empty())
512                                 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
513                         par->params().depth(depth);
514 #if USE_CAPTION
515                 }
516 #endif
517
518         } else if (token == "\\end_inset") {
519                 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
520                        << "Last inset read was: " << last_inset_read
521                        << endl;
522                 // Simply ignore this. The insets do not have
523                 // to read this.
524                 // But insets should read it, it is a part of
525                 // the inset isn't it? Lgb.
526         } else if (token == "\\begin_inset") {
527                 readInset(lex, par, pos, font);
528         } else if (token == "\\family") {
529                 lex.next();
530                 font.setLyXFamily(lex.getString());
531         } else if (token == "\\series") {
532                 lex.next();
533                 font.setLyXSeries(lex.getString());
534         } else if (token == "\\shape") {
535                 lex.next();
536                 font.setLyXShape(lex.getString());
537         } else if (token == "\\size") {
538                 lex.next();
539                 font.setLyXSize(lex.getString());
540         } else if (token == "\\lang") {
541                 lex.next();
542                 string const tok = lex.getString();
543                 Language const * lang = languages.getLanguage(tok);
544                 if (lang) {
545                         font.setLanguage(lang);
546                 } else {
547                         font.setLanguage(params.language);
548                         lex.printError("Unknown language `$$Token'");
549                 }
550         } else if (token == "\\numeric") {
551                 lex.next();
552                 font.setNumber(font.setLyXMisc(lex.getString()));
553         } else if (token == "\\emph") {
554                 lex.next();
555                 font.setEmph(font.setLyXMisc(lex.getString()));
556         } else if (token == "\\bar") {
557                 lex.next();
558                 string const tok = lex.getString();
559                 // This is dirty, but gone with LyX3. (Asger)
560                 if (tok == "under")
561                         font.setUnderbar(LyXFont::ON);
562                 else if (tok == "no")
563                         font.setUnderbar(LyXFont::OFF);
564                 else if (tok == "default")
565                         font.setUnderbar(LyXFont::INHERIT);
566                 else
567                         lex.printError("Unknown bar font flag "
568                                        "`$$Token'");
569         } else if (token == "\\noun") {
570                 lex.next();
571                 font.setNoun(font.setLyXMisc(lex.getString()));
572         } else if (token == "\\color") {
573                 lex.next();
574                 font.setLyXColor(lex.getString());
575         } else if (token == "\\SpecialChar") {
576                 LyXLayout_ptr const & layout = par->layout();
577
578                 // Insets don't make sense in a free-spacing context! ---Kayvan
579                 if (layout->free_spacing || par->isFreeSpacing()) {
580                         if (lex.isOK()) {
581                                 lex.next();
582                                 string const next_token = lex.getString();
583                                 if (next_token == "\\-") {
584                                         par->insertChar(pos, '-', font, current_change);
585                                 } else if (next_token == "~") {
586                                         par->insertChar(pos, ' ', font, current_change);
587                                 } else {
588                                         lex.printError("Token `$$Token' "
589                                                        "is in free space "
590                                                        "paragraph layout!");
591                                         --pos;
592                                 }
593                         }
594                 } else {
595                         Inset * inset = new InsetSpecialChar;
596                         inset->read(this, lex);
597                         par->insertInset(pos, inset, font, current_change);
598                 }
599                 ++pos;
600         } else if (token == "\\i") {
601                 Inset * inset = new InsetLatexAccent;
602                 inset->read(this, lex);
603                 par->insertInset(pos, inset, font, current_change);
604                 ++pos;
605         } else if (token == "\\backslash") {
606                 par->insertChar(pos, '\\', font, current_change);
607                 ++pos;
608         } else if (token == "\\begin_deeper") {
609                 ++depth;
610         } else if (token == "\\end_deeper") {
611                 if (!depth) {
612                         lex.printError("\\end_deeper: "
613                                        "depth is already null");
614                 }
615                 else
616                         --depth;
617         } else if (token == "\\begin_preamble") {
618                 params.readPreamble(lex);
619         } else if (token == "\\textclass") {
620                 lex.eatLine();
621                 pair<bool, textclass_type> pp =
622                         textclasslist.NumberOfClass(lex.getString());
623                 if (pp.first) {
624                         params.textclass = pp.second;
625                 } else {
626 #if USE_BOOST_FORMAT
627                         Alert::alert(_("Textclass error"),
628                                 boost::io::str(boost::format(_("The document uses an unknown textclass \"%1$s\".")) % lex.getString()),
629                                 _("-- substituting default."));
630 #else
631                         Alert::alert(
632                                 _("Textclass error"),
633                                 _("The document uses an unknown textclass ")
634                                 + lex.getString(),
635                                 _("-- substituting default."));
636 #endif
637                         params.textclass = 0;
638                 }
639                 if (!params.getLyXTextClass().load()) {
640                         // if the textclass wasn't loaded properly
641                         // we need to either substitute another
642                         // or stop loading the file.
643                         // I can substitute but I don't see how I can
644                         // stop loading... ideas??  ARRae980418
645 #if USE_BOOST_FORMAT
646                         Alert::alert(_("Textclass Loading Error!"),
647                                    boost::io::str(boost::format(_("Can't load textclass %1$s")) %
648                                    params.getLyXTextClass().name()),
649                                    _("-- substituting default."));
650 #else
651                         Alert::alert(_("Textclass Loading Error!"),
652                                      _("Can't load textclass ")
653                                      + params.getLyXTextClass().name(),
654                                      _("-- substituting default."));
655 #endif
656                         params.textclass = 0;
657                 }
658         } else if (token == "\\options") {
659                 lex.eatLine();
660                 params.options = lex.getString();
661         } else if (token == "\\language") {
662                 params.readLanguage(lex);
663         } else if (token == "\\fontencoding") {
664                 lex.eatLine();
665         } else if (token == "\\inputencoding") {
666                 lex.eatLine();
667                 params.inputenc = lex.getString();
668         } else if (token == "\\graphics") {
669                 params.readGraphicsDriver(lex);
670         } else if (token == "\\fontscheme") {
671                 lex.eatLine();
672                 params.fonts = lex.getString();
673         } else if (token == "\\noindent") {
674                 par->params().noindent(true);
675         } else if (token == "\\leftindent") {
676                 lex.nextToken();
677                 LyXLength value(lex.getString());
678                 par->params().leftIndent(value);
679         } else if (token == "\\fill_top") {
680                 par->params().spaceTop(VSpace(VSpace::VFILL));
681         } else if (token == "\\fill_bottom") {
682                 par->params().spaceBottom(VSpace(VSpace::VFILL));
683         } else if (token == "\\line_top") {
684                 par->params().lineTop(true);
685         } else if (token == "\\line_bottom") {
686                 par->params().lineBottom(true);
687         } else if (token == "\\pagebreak_top") {
688                 par->params().pagebreakTop(true);
689         } else if (token == "\\pagebreak_bottom") {
690                 par->params().pagebreakBottom(true);
691         } else if (token == "\\start_of_appendix") {
692                 par->params().startOfAppendix(true);
693         } else if (token == "\\paragraph_separation") {
694                 int tmpret = lex.findToken(string_paragraph_separation);
695                 if (tmpret == -1)
696                         ++tmpret;
697                 params.paragraph_separation =
698                         static_cast<BufferParams::PARSEP>(tmpret);
699         } else if (token == "\\defskip") {
700                 lex.nextToken();
701                 params.defskip = VSpace(lex.getString());
702         } else if (token == "\\quotes_language") {
703                 int tmpret = lex.findToken(string_quotes_language);
704                 if (tmpret == -1)
705                         ++tmpret;
706                 InsetQuotes::quote_language tmpl =
707                         InsetQuotes::EnglishQ;
708                 switch (tmpret) {
709                 case 0:
710                         tmpl = InsetQuotes::EnglishQ;
711                         break;
712                 case 1:
713                         tmpl = InsetQuotes::SwedishQ;
714                         break;
715                 case 2:
716                         tmpl = InsetQuotes::GermanQ;
717                         break;
718                 case 3:
719                         tmpl = InsetQuotes::PolishQ;
720                         break;
721                 case 4:
722                         tmpl = InsetQuotes::FrenchQ;
723                         break;
724                 case 5:
725                         tmpl = InsetQuotes::DanishQ;
726                         break;
727                 }
728                 params.quotes_language = tmpl;
729         } else if (token == "\\quotes_times") {
730                 lex.nextToken();
731                 switch (lex.getInteger()) {
732                 case 1:
733                         params.quotes_times = InsetQuotes::SingleQ;
734                         break;
735                 case 2:
736                         params.quotes_times = InsetQuotes::DoubleQ;
737                         break;
738                 }
739         } else if (token == "\\papersize") {
740                 int tmpret = lex.findToken(string_papersize);
741                 if (tmpret == -1)
742                         ++tmpret;
743                 else
744                         params.papersize2 = tmpret;
745         } else if (token == "\\paperpackage") {
746                 int tmpret = lex.findToken(string_paperpackages);
747                 if (tmpret == -1) {
748                         ++tmpret;
749                         params.paperpackage = BufferParams::PACKAGE_NONE;
750                 } else
751                         params.paperpackage = tmpret;
752         } else if (token == "\\use_geometry") {
753                 lex.nextToken();
754                 params.use_geometry = lex.getInteger();
755         } else if (token == "\\use_amsmath") {
756                 lex.nextToken();
757                 params.use_amsmath = lex.getInteger();
758         } else if (token == "\\use_natbib") {
759                 lex.nextToken();
760                 params.use_natbib = lex.getInteger();
761         } else if (token == "\\use_numerical_citations") {
762                 lex.nextToken();
763                 params.use_numerical_citations = lex.getInteger();
764         } else if (token == "\\tracking_changes") {
765                 lex.nextToken();
766                 params.tracking_changes = lex.getInteger();
767                 // mark the first paragraph
768                 if (params.tracking_changes)
769                         par->trackChanges();
770         } else if (token == "\\author") {
771                 lex.nextToken();
772                 istringstream ss(lex.getString());
773                 Author a;
774                 ss >> a;
775                 int aid(authorlist.record(a)); 
776                 lyxerr << "aid is " << aid << endl;
777                 lyxerr << "listed aid is " << author_ids.size() << endl;
778                 author_ids.push_back(authorlist.record(a));
779         } else if (token == "\\paperorientation") {
780                 int tmpret = lex.findToken(string_orientation);
781                 if (tmpret == -1)
782                         ++tmpret;
783                 params.orientation =
784                         static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
785         } else if (token == "\\paperwidth") {
786                 lex.next();
787                 params.paperwidth = lex.getString();
788         } else if (token == "\\paperheight") {
789                 lex.next();
790                 params.paperheight = lex.getString();
791         } else if (token == "\\leftmargin") {
792                 lex.next();
793                 params.leftmargin = lex.getString();
794         } else if (token == "\\topmargin") {
795                 lex.next();
796                 params.topmargin = lex.getString();
797         } else if (token == "\\rightmargin") {
798                 lex.next();
799                 params.rightmargin = lex.getString();
800         } else if (token == "\\bottommargin") {
801                 lex.next();
802                 params.bottommargin = lex.getString();
803         } else if (token == "\\headheight") {
804                 lex.next();
805                 params.headheight = lex.getString();
806         } else if (token == "\\headsep") {
807                 lex.next();
808                 params.headsep = lex.getString();
809         } else if (token == "\\footskip") {
810                 lex.next();
811                 params.footskip = lex.getString();
812         } else if (token == "\\paperfontsize") {
813                 lex.nextToken();
814                 params.fontsize = rtrim(lex.getString());
815         } else if (token == "\\papercolumns") {
816                 lex.nextToken();
817                 params.columns = lex.getInteger();
818         } else if (token == "\\papersides") {
819                 lex.nextToken();
820                 switch (lex.getInteger()) {
821                 default:
822                 case 1: params.sides = LyXTextClass::OneSide; break;
823                 case 2: params.sides = LyXTextClass::TwoSides; break;
824                 }
825         } else if (token == "\\paperpagestyle") {
826                 lex.nextToken();
827                 params.pagestyle = rtrim(lex.getString());
828         } else if (token == "\\bullet") {
829                 lex.nextToken();
830                 int const index = lex.getInteger();
831                 lex.nextToken();
832                 int temp_int = lex.getInteger();
833                 params.user_defined_bullets[index].setFont(temp_int);
834                 params.temp_bullets[index].setFont(temp_int);
835                 lex.nextToken();
836                 temp_int = lex.getInteger();
837                 params.user_defined_bullets[index].setCharacter(temp_int);
838                 params.temp_bullets[index].setCharacter(temp_int);
839                 lex.nextToken();
840                 temp_int = lex.getInteger();
841                 params.user_defined_bullets[index].setSize(temp_int);
842                 params.temp_bullets[index].setSize(temp_int);
843                 lex.nextToken();
844                 string const temp_str = lex.getString();
845                 if (temp_str != "\\end_bullet") {
846                                 // this element isn't really necessary for
847                                 // parsing but is easier for humans
848                                 // to understand bullets. Put it back and
849                                 // set a debug message?
850                         lex.printError("\\end_bullet expected, got" + temp_str);
851                                 //how can I put it back?
852                 }
853         } else if (token == "\\bulletLaTeX") {
854                 // The bullet class should be able to read this.
855                 lex.nextToken();
856                 int const index = lex.getInteger();
857                 lex.next();
858                 string temp_str = lex.getString();
859                 string sum_str;
860                 while (temp_str != "\\end_bullet") {
861                                 // this loop structure is needed when user
862                                 // enters an empty string since the first
863                                 // thing returned will be the \\end_bullet
864                                 // OR
865                                 // if the LaTeX entry has spaces. Each element
866                                 // therefore needs to be read in turn
867                         sum_str += temp_str;
868                         lex.next();
869                         temp_str = lex.getString();
870                 }
871
872                 params.user_defined_bullets[index].setText(sum_str);
873                 params.temp_bullets[index].setText(sum_str);
874         } else if (token == "\\secnumdepth") {
875                 lex.nextToken();
876                 params.secnumdepth = lex.getInteger();
877         } else if (token == "\\tocdepth") {
878                 lex.nextToken();
879                 params.tocdepth = lex.getInteger();
880         } else if (token == "\\spacing") {
881                 lex.next();
882                 string const tmp = rtrim(lex.getString());
883                 Spacing::Space tmp_space = Spacing::Default;
884                 float tmp_val = 0.0;
885                 if (tmp == "single") {
886                         tmp_space = Spacing::Single;
887                 } else if (tmp == "onehalf") {
888                         tmp_space = Spacing::Onehalf;
889                 } else if (tmp == "double") {
890                         tmp_space = Spacing::Double;
891                 } else if (tmp == "other") {
892                         lex.next();
893                         tmp_space = Spacing::Other;
894                         tmp_val = lex.getFloat();
895                 } else {
896                         lex.printError("Unknown spacing token: '$$Token'");
897                 }
898                 // Small hack so that files written with klyx will be
899                 // parsed correctly.
900                 if (first_par) {
901                         par->params().spacing(Spacing(tmp_space, tmp_val));
902                 } else {
903                         params.spacing.set(tmp_space, tmp_val);
904                 }
905         } else if (token == "\\paragraph_spacing") {
906                 lex.next();
907                 string const tmp = rtrim(lex.getString());
908                 if (tmp == "single") {
909                         par->params().spacing(Spacing(Spacing::Single));
910                 } else if (tmp == "onehalf") {
911                         par->params().spacing(Spacing(Spacing::Onehalf));
912                 } else if (tmp == "double") {
913                         par->params().spacing(Spacing(Spacing::Double));
914                 } else if (tmp == "other") {
915                         lex.next();
916                         par->params().spacing(Spacing(Spacing::Other,
917                                          lex.getFloat()));
918                 } else {
919                         lex.printError("Unknown spacing token: '$$Token'");
920                 }
921         } else if (token == "\\float_placement") {
922                 lex.nextToken();
923                 params.float_placement = lex.getString();
924         } else if (token == "\\align") {
925                 int tmpret = lex.findToken(string_align);
926                 if (tmpret == -1) ++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 linelenght!) (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 vector<pair<string, string> > const Buffer::getBibkeyList() const
2876 {
2877         typedef pair<string, string> StringPair;
2878         /// if this is a child document and the parent is already loaded
2879         /// Use the parent's list instead  [ale990412]
2880         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2881                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2882                 if (tmp)
2883                         return tmp->getBibkeyList();
2884         }
2885
2886         vector<StringPair> keys;
2887         ParagraphList::iterator pit = paragraphs.begin();
2888         ParagraphList::iterator pend = paragraphs.end();
2889         for (; pit != pend; ++pit) {
2890                 InsetBibKey * bib = pit->bibkey();
2891                 if (bib) {
2892                         string const key = bib->getContents();
2893                         string const opt = bib->getOptions();
2894                         string const ref = pit->asString(this, false);
2895                         string const info = opt + "TheBibliographyRef" + ref;
2896
2897                         keys.push_back(StringPair(key, info));
2898                 }
2899         }
2900
2901         if (!keys.empty())
2902                 return keys;
2903
2904         // Might be either using bibtex or a child has bibliography
2905         for (inset_iterator it = inset_const_iterator_begin();
2906                 it != inset_const_iterator_end(); ++it) {
2907                 // Search for Bibtex or Include inset
2908                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
2909                         vector<StringPair> tmp =
2910                                 static_cast<InsetBibtex &>(*it).getKeys(this);
2911                         keys.insert(keys.end(), tmp.begin(), tmp.end());
2912                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
2913                         vector<StringPair> const tmp =
2914                                 static_cast<InsetInclude &>(*it).getKeys();
2915                         keys.insert(keys.end(), tmp.begin(), tmp.end());
2916                 }
2917         }
2918
2919         return keys;
2920 }
2921
2922
2923 bool Buffer::isDepClean(string const & name) const
2924 {
2925         DepClean::const_iterator it = dep_clean_.find(name);
2926         if (it == dep_clean_.end())
2927                 return true;
2928         return it->second;
2929 }
2930
2931
2932 void Buffer::markDepClean(string const & name)
2933 {
2934         dep_clean_[name] = true;
2935 }
2936
2937
2938 bool Buffer::dispatch(string const & command, bool * result)
2939 {
2940         // Split command string into command and argument
2941         string cmd;
2942         string line = ltrim(command);
2943         string const arg = trim(split(line, cmd, ' '));
2944
2945         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2946 }
2947
2948
2949 bool Buffer::dispatch(int action, string const & argument, bool * result)
2950 {
2951         bool dispatched = true;
2952
2953         switch (action) {
2954                 case LFUN_EXPORT: {
2955                         bool const tmp = Exporter::Export(this, argument, false);
2956                         if (result)
2957                                 *result = tmp;
2958                         break;
2959                 }
2960
2961                 default:
2962                         dispatched = false;
2963         }
2964         return dispatched;
2965 }
2966
2967
2968 void Buffer::resizeInsets(BufferView * bv)
2969 {
2970         /// then remove all LyXText in text-insets
2971         for_each(paragraphs.begin(), paragraphs.end(),
2972                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2973 }
2974
2975
2976 void Buffer::redraw()
2977 {
2978 #warning repaint needed here, or do you mean update() ?
2979         users->repaint();
2980         users->fitCursor();
2981 }
2982
2983
2984 void Buffer::changeLanguage(Language const * from, Language const * to)
2985 {
2986
2987         ParIterator end = par_iterator_end();
2988         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2989                 (*it)->changeLanguage(params, from, to);
2990 }
2991
2992
2993 bool Buffer::isMultiLingual()
2994 {
2995         ParIterator end = par_iterator_end();
2996         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2997                 if ((*it)->isMultiLingual(params))
2998                         return true;
2999
3000         return false;
3001 }
3002
3003
3004 void Buffer::inset_iterator::setParagraph()
3005 {
3006         while (pit != pend) {
3007                 it = pit->insetlist.begin();
3008                 if (it != pit->insetlist.end())
3009                         return;
3010                 ++pit;
3011         }
3012 }
3013
3014
3015 Inset * Buffer::getInsetFromID(int id_arg) const
3016 {
3017         for (inset_iterator it = inset_const_iterator_begin();
3018                  it != inset_const_iterator_end(); ++it)
3019         {
3020                 if (it->id() == id_arg)
3021                         return &(*it);
3022                 Inset * in = it->getInsetFromID(id_arg);
3023                 if (in)
3024                         return in;
3025         }
3026         return 0;
3027 }
3028
3029
3030 Paragraph * Buffer::getParFromID(int id) const
3031 {
3032         if (id < 0)
3033                 return 0;
3034  
3035         // why should we allow < 0 ??
3036         //lyx::Assert(id >= 0);
3037
3038         ParConstIterator it(par_iterator_begin());
3039         ParConstIterator end(par_iterator_end());
3040
3041         for (; it != end; ++it) {
3042                 // go on then, show me how to remove
3043                 // the cast
3044                 if ((*it)->id() == id) {
3045                         return const_cast<Paragraph*>(*it);
3046                 }
3047         }
3048
3049         return 0;
3050 }
3051
3052
3053 ParIterator Buffer::par_iterator_begin()
3054 {
3055         return ParIterator(&*(paragraphs.begin()));
3056 }
3057
3058
3059 ParIterator Buffer::par_iterator_end()
3060 {
3061         return ParIterator();
3062 }
3063
3064 ParConstIterator Buffer::par_iterator_begin() const
3065 {
3066         return ParConstIterator(&*(paragraphs.begin()));
3067 }
3068
3069
3070 ParConstIterator Buffer::par_iterator_end() const
3071 {
3072         return ParConstIterator();
3073 }
3074
3075
3076
3077 void Buffer::addUser(BufferView * u)
3078 {
3079         users = u;
3080 }
3081
3082
3083 void Buffer::delUser(BufferView *)
3084 {
3085         users = 0;
3086 }
3087
3088
3089 Language const * Buffer::getLanguage() const
3090 {
3091         return params.language;
3092 }
3093
3094
3095 bool Buffer::isClean() const
3096 {
3097         return lyx_clean;
3098 }
3099
3100
3101 bool Buffer::isBakClean() const
3102 {
3103         return bak_clean;
3104 }
3105
3106
3107 void Buffer::markClean() const
3108 {
3109         if (!lyx_clean) {
3110                 lyx_clean = true;
3111                 updateTitles();
3112         }
3113         // if the .lyx file has been saved, we don't need an
3114         // autosave
3115         bak_clean = true;
3116 }
3117
3118
3119 void Buffer::markBakClean()
3120 {
3121         bak_clean = true;
3122 }
3123
3124
3125 void Buffer::setUnnamed(bool flag)
3126 {
3127         unnamed = flag;
3128 }
3129
3130
3131 bool Buffer::isUnnamed()
3132 {
3133         return unnamed;
3134 }
3135
3136
3137 void Buffer::markDirty()
3138 {
3139         if (lyx_clean) {
3140                 lyx_clean = false;
3141                 updateTitles();
3142         }
3143         bak_clean = false;
3144
3145         DepClean::iterator it = dep_clean_.begin();
3146         DepClean::const_iterator const end = dep_clean_.end();
3147
3148         for (; it != end; ++it) {
3149                 it->second = false;
3150         }
3151 }
3152
3153
3154 string const & Buffer::fileName() const
3155 {
3156         return filename_;
3157 }
3158
3159
3160 string const & Buffer::filePath() const
3161 {
3162         return filepath_;
3163 }
3164
3165
3166 bool Buffer::isReadonly() const
3167 {
3168         return read_only;
3169 }
3170
3171
3172 BufferView * Buffer::getUser() const
3173 {
3174         return users;
3175 }
3176
3177
3178 void Buffer::setParentName(string const & name)
3179 {
3180         params.parentname = name;
3181 }
3182
3183
3184 Buffer::inset_iterator::inset_iterator()
3185         : pit(0), pend(0)
3186 {}
3187
3188
3189 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3190         : pit(p), pend(e)
3191 {
3192         setParagraph();
3193 }
3194
3195
3196 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3197 {
3198         if (pit != pend) {
3199                 ++it;
3200                 if (it == pit->insetlist.end()) {
3201                         ++pit;
3202                         setParagraph();
3203                 }
3204         }
3205         return *this;
3206 }
3207
3208
3209 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3210 {
3211         inset_iterator tmp = *this;
3212         ++*this;
3213         return tmp;
3214 }
3215
3216
3217 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3218 {
3219         return *it.getInset();
3220 }
3221
3222
3223 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3224 {
3225         return it.getInset();
3226 }
3227
3228
3229 Paragraph * Buffer::inset_iterator::getPar()
3230 {
3231         return &(*pit);
3232 }
3233
3234
3235 lyx::pos_type Buffer::inset_iterator::getPos() const
3236 {
3237         return it.getPos();
3238 }
3239
3240
3241 bool operator==(Buffer::inset_iterator const & iter1,
3242                 Buffer::inset_iterator const & iter2)
3243 {
3244         return iter1.pit == iter2.pit
3245                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3246 }
3247
3248
3249 bool operator!=(Buffer::inset_iterator const & iter1,
3250                 Buffer::inset_iterator const & iter2)
3251 {
3252         return !(iter1 == iter2);
3253 }