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