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