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