]> git.lyx.org Git - features.git/blob - src/Buffer.cpp
Rationalize the handling of makeTextClass().
[features.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "BiblioInfo.h"
18 #include "BranchList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "Bullet.h"
23 #include "Chktex.h"
24 #include "Converter.h"
25 #include "Counters.h"
26 #include "DocIterator.h"
27 #include "EmbeddedFiles.h"
28 #include "Encoding.h"
29 #include "ErrorList.h"
30 #include "Exporter.h"
31 #include "Format.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LaTeX.h"
38 #include "Layout.h"
39 #include "Lexer.h"
40 #include "LyXAction.h"
41 #include "LyX.h"
42 #include "LyXRC.h"
43 #include "LyXVC.h"
44 #include "output_docbook.h"
45 #include "output.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
53 #include "Session.h"
54 #include "sgml.h"
55 #include "TexRow.h"
56 #include "TexStream.h"
57 #include "TextClassList.h"
58 #include "Text.h"
59 #include "TocBackend.h"
60 #include "Undo.h"
61 #include "VCBackend.h"
62 #include "version.h"
63
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
68
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
72
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
76
77 #include "graphics/Previews.h"
78
79 #include "support/convert.h"
80 #include "support/debug.h"
81 #include "support/ExceptionMessage.h"
82 #include "support/FileFilterList.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
96 #include "support/FileZipListDir.h"
97
98 #if !defined (HAVE_FORK)
99 # define fork() -1
100 #endif
101
102 #include <boost/bind.hpp>
103 #include <boost/shared_ptr.hpp>
104
105 #include <algorithm>
106 #include <iomanip>
107 #include <stack>
108 #include <sstream>
109 #include <fstream>
110
111 using namespace std;
112 using namespace lyx::support;
113
114 namespace lyx {
115
116 namespace Alert = frontend::Alert;
117 namespace os = support::os;
118
119 namespace {
120
121 int const LYX_FORMAT = 310; // Bernhard Reiter: support for \nocite{*}
122
123 } // namespace anon
124
125
126 typedef map<string, bool> DepClean;
127
128 class Buffer::Impl
129 {
130 public:
131         Impl(Buffer & parent, FileName const & file, bool readonly);
132
133         ~Impl()
134         {
135                 if (wa_) {
136                         wa_->closeAll();
137                         delete wa_;
138                 }
139         }
140         
141         BufferParams params;
142         LyXVC lyxvc;
143         FileName temppath;
144         mutable TexRow texrow;
145         Buffer const * parent_buffer;
146
147         /// need to regenerate .tex?
148         DepClean dep_clean;
149
150         /// is save needed?
151         mutable bool lyx_clean;
152
153         /// is autosave needed?
154         mutable bool bak_clean;
155
156         /// is this a unnamed file (New...)?
157         bool unnamed;
158
159         /// buffer is r/o
160         bool read_only;
161
162         /// name of the file the buffer is associated with.
163         FileName filename;
164
165         /** Set to true only when the file is fully loaded.
166          *  Used to prevent the premature generation of previews
167          *  and by the citation inset.
168          */
169         bool file_fully_loaded;
170
171         /// our Text that should be wrapped in an InsetText
172         InsetText inset;
173
174         ///
175         mutable TocBackend toc_backend;
176
177         /// macro tables
178         typedef pair<DocIterator, MacroData> ScopeMacro;
179         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
180         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
181         NamePositionScopeMacroMap macros;
182         bool macro_lock;
183         
184         /// positions of child buffers in the buffer
185         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
186         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
187         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
188         BufferPositionMap children_positions;
189         PositionScopeBufferMap position_to_children;
190
191         /// Container for all sort of Buffer dependant errors.
192         map<string, ErrorList> errorLists;
193
194         /// all embedded files of this buffer
195         EmbeddedFiles embedded_files;
196
197         /// timestamp and checksum used to test if the file has been externally
198         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199         time_t timestamp_;
200         unsigned long checksum_;
201
202         ///
203         frontend::WorkAreaManager * wa_;
204
205         ///
206         Undo undo_;
207
208         /// A cache for the bibfiles (including bibfiles of loaded child
209         /// documents), needed for appropriate update of natbib labels.
210         mutable FileNameList bibfilesCache_;
211 };
212
213 /// Creates the per buffer temporary directory
214 static FileName createBufferTmpDir()
215 {
216         static int count;
217         // We are in our own directory.  Why bother to mangle name?
218         // In fact I wrote this code to circumvent a problematic behaviour
219         // (bug?) of EMX mkstemp().
220         FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
221                 convert<string>(count++));
222
223         if (!tmpfl.createDirectory(0777)) {
224                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
225                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
226                         from_utf8(tmpfl.absFilename())));
227         }
228         return tmpfl;
229 }
230
231
232 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
233         : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
234           read_only(readonly_), filename(file), file_fully_loaded(false),
235           inset(params), toc_backend(&parent), macro_lock(false),
236           embedded_files(&parent), timestamp_(0), checksum_(0), wa_(0), 
237           undo_(parent)
238 {
239         temppath = createBufferTmpDir();
240         inset.setAutoBreakRows(true);
241         lyxvc.setBuffer(&parent);
242         if (use_gui)
243                 wa_ = new frontend::WorkAreaManager;
244 }
245
246
247 Buffer::Buffer(string const & file, bool readonly)
248         : d(new Impl(*this, FileName(file), readonly)), gui_(0)
249 {
250         LYXERR(Debug::INFO, "Buffer::Buffer()");
251
252         d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
253 }
254
255
256 Buffer::~Buffer()
257 {
258         LYXERR(Debug::INFO, "Buffer::~Buffer()");
259         // here the buffer should take care that it is
260         // saved properly, before it goes into the void.
261
262         // GuiView already destroyed
263         gui_ = 0;
264
265         Buffer const * master = masterBuffer();
266         if (master != this && use_gui) {
267                 // We are closing buf which was a child document so we
268                 // must update the labels and section numbering of its master
269                 // Buffer.
270                 updateLabels(*master);
271                 master->updateMacros();
272         }
273
274         resetChildDocuments(false);
275
276         if (!d->temppath.destroyDirectory()) {
277                 Alert::warning(_("Could not remove temporary directory"),
278                         bformat(_("Could not remove the temporary directory %1$s"),
279                         from_utf8(d->temppath.absFilename())));
280         }
281
282         // Remove any previewed LaTeX snippets associated with this buffer.
283         graphics::Previews::get().removeLoader(*this);
284
285         delete d;
286 }
287
288
289 void Buffer::changed() const
290 {
291         if (d->wa_)
292                 d->wa_->redrawAll();
293 }
294
295
296 frontend::WorkAreaManager & Buffer::workAreaManager() const
297 {
298         BOOST_ASSERT(d->wa_);
299         return *d->wa_;
300 }
301
302
303 Text & Buffer::text() const
304 {
305         return const_cast<Text &>(d->inset.text_);
306 }
307
308
309 Inset & Buffer::inset() const
310 {
311         return const_cast<InsetText &>(d->inset);
312 }
313
314
315 BufferParams & Buffer::params()
316 {
317         return d->params;
318 }
319
320
321 BufferParams const & Buffer::params() const
322 {
323         return d->params;
324 }
325
326
327 ParagraphList & Buffer::paragraphs()
328 {
329         return text().paragraphs();
330 }
331
332
333 ParagraphList const & Buffer::paragraphs() const
334 {
335         return text().paragraphs();
336 }
337
338
339 LyXVC & Buffer::lyxvc()
340 {
341         return d->lyxvc;
342 }
343
344
345 LyXVC const & Buffer::lyxvc() const
346 {
347         return d->lyxvc;
348 }
349
350
351 string const Buffer::temppath() const
352 {
353         return d->temppath.absFilename();
354 }
355
356
357 TexRow const & Buffer::texrow() const
358 {
359         return d->texrow;
360 }
361
362
363 TocBackend & Buffer::tocBackend() const
364 {
365         return d->toc_backend;
366 }
367
368
369 EmbeddedFiles & Buffer::embeddedFiles()
370 {
371         return d->embedded_files;
372 }
373
374
375 EmbeddedFiles const & Buffer::embeddedFiles() const
376 {
377         return d->embedded_files;
378 }
379
380
381 Undo & Buffer::undo()
382 {
383         return d->undo_;
384 }
385
386
387 string Buffer::latexName(bool const no_path) const
388 {
389         FileName latex_name = makeLatexName(d->filename);
390         return no_path ? latex_name.onlyFileName()
391                 : latex_name.absFilename();
392 }
393
394
395 string Buffer::logName(LogType * type) const
396 {
397         string const filename = latexName(false);
398
399         if (filename.empty()) {
400                 if (type)
401                         *type = latexlog;
402                 return string();
403         }
404
405         string const path = temppath();
406
407         FileName const fname(addName(temppath(),
408                                      onlyFilename(changeExtension(filename,
409                                                                   ".log"))));
410         FileName const bname(
411                 addName(path, onlyFilename(
412                         changeExtension(filename,
413                                         formats.extension("literate") + ".out"))));
414
415         // If no Latex log or Build log is newer, show Build log
416
417         if (bname.exists() &&
418             (!fname.exists() || fname.lastModified() < bname.lastModified())) {
419                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
420                 if (type)
421                         *type = buildlog;
422                 return bname.absFilename();
423         }
424         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
425         if (type)
426                         *type = latexlog;
427         return fname.absFilename();
428 }
429
430
431 void Buffer::setReadonly(bool const flag)
432 {
433         if (d->read_only != flag) {
434                 d->read_only = flag;
435                 setReadOnly(flag);
436         }
437 }
438
439
440 void Buffer::setFileName(string const & newfile)
441 {
442         d->filename = makeAbsPath(newfile);
443         setReadonly(d->filename.isReadOnly());
444         updateTitles();
445 }
446
447
448 int Buffer::readHeader(Lexer & lex)
449 {
450         int unknown_tokens = 0;
451         int line = -1;
452         int begin_header_line = -1;
453
454         // Initialize parameters that may be/go lacking in header:
455         params().branchlist().clear();
456         params().preamble.erase();
457         params().options.erase();
458         params().float_placement.erase();
459         params().paperwidth.erase();
460         params().paperheight.erase();
461         params().leftmargin.erase();
462         params().rightmargin.erase();
463         params().topmargin.erase();
464         params().bottommargin.erase();
465         params().headheight.erase();
466         params().headsep.erase();
467         params().footskip.erase();
468         params().listings_params.clear();
469         params().clearLayoutModules();
470         params().pdfoptions().clear();
471         
472         for (int i = 0; i < 4; ++i) {
473                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
474                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
475         }
476
477         ErrorList & errorList = d->errorLists["Parse"];
478
479         while (lex.isOK()) {
480                 lex.next();
481                 string const token = lex.getString();
482
483                 if (token.empty())
484                         continue;
485
486                 if (token == "\\end_header")
487                         break;
488
489                 ++line;
490                 if (token == "\\begin_header") {
491                         begin_header_line = line;
492                         continue;
493                 }
494
495                 LYXERR(Debug::PARSER, "Handling document header token: `"
496                                       << token << '\'');
497
498                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
499                 if (!unknown.empty()) {
500                         if (unknown[0] != '\\' && token == "\\textclass") {
501                                 Alert::warning(_("Unknown document class"),
502                        bformat(_("Using the default document class, because the "
503                                               "class %1$s is unknown."), from_utf8(unknown)));
504                         } else {
505                                 ++unknown_tokens;
506                                 docstring const s = bformat(_("Unknown token: "
507                                                                         "%1$s %2$s\n"),
508                                                          from_utf8(token),
509                                                          lex.getDocString());
510                                 errorList.push_back(ErrorItem(_("Document header error"),
511                                         s, -1, 0, 0));
512                         }
513                 }
514         }
515         if (begin_header_line) {
516                 docstring const s = _("\\begin_header is missing");
517                 errorList.push_back(ErrorItem(_("Document header error"),
518                         s, -1, 0, 0));
519         }
520         
521         params().makeTextClass();
522
523         return unknown_tokens;
524 }
525
526
527 // Uwe C. Schroeder
528 // changed to be public and have one parameter
529 // Returns false if "\end_document" is not read (Asger)
530 bool Buffer::readDocument(Lexer & lex)
531 {
532         ErrorList & errorList = d->errorLists["Parse"];
533         errorList.clear();
534
535         lex.next();
536         string const token = lex.getString();
537         if (token != "\\begin_document") {
538                 docstring const s = _("\\begin_document is missing");
539                 errorList.push_back(ErrorItem(_("Document header error"),
540                         s, -1, 0, 0));
541         }
542
543         // we are reading in a brand new document
544         BOOST_ASSERT(paragraphs().empty());
545
546         readHeader(lex);
547
548         if (params().outputChanges) {
549                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
550                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
551                                   LaTeXFeatures::isAvailable("xcolor");
552
553                 if (!dvipost && !xcolorsoul) {
554                         Alert::warning(_("Changes not shown in LaTeX output"),
555                                        _("Changes will not be highlighted in LaTeX output, "
556                                          "because neither dvipost nor xcolor/soul are installed.\n"
557                                          "Please install these packages or redefine "
558                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
559                 } else if (!xcolorsoul) {
560                         Alert::warning(_("Changes not shown in LaTeX output"),
561                                        _("Changes will not be highlighted in LaTeX output "
562                                          "when using pdflatex, because xcolor and soul are not installed.\n"
563                                          "Please install both packages or redefine "
564                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
565                 }
566         }
567
568         // read main text
569         bool const res = text().read(*this, lex, errorList);
570         for_each(text().paragraphs().begin(),
571                  text().paragraphs().end(),
572                  bind(&Paragraph::setInsetOwner, _1, &inset()));
573
574         updateMacros();
575         updateMacroInstances();
576         return res;
577 }
578
579
580 // needed to insert the selection
581 void Buffer::insertStringAsLines(ParagraphList & pars,
582         pit_type & pit, pos_type & pos,
583         Font const & fn, docstring const & str, bool autobreakrows)
584 {
585         Font font = fn;
586
587         // insert the string, don't insert doublespace
588         bool space_inserted = true;
589         for (docstring::const_iterator cit = str.begin();
590             cit != str.end(); ++cit) {
591                 Paragraph & par = pars[pit];
592                 if (*cit == '\n') {
593                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
594                                 breakParagraph(params(), pars, pit, pos,
595                                                par.layout()->isEnvironment());
596                                 ++pit;
597                                 pos = 0;
598                                 space_inserted = true;
599                         } else {
600                                 continue;
601                         }
602                         // do not insert consecutive spaces if !free_spacing
603                 } else if ((*cit == ' ' || *cit == '\t') &&
604                            space_inserted && !par.isFreeSpacing()) {
605                         continue;
606                 } else if (*cit == '\t') {
607                         if (!par.isFreeSpacing()) {
608                                 // tabs are like spaces here
609                                 par.insertChar(pos, ' ', font, params().trackChanges);
610                                 ++pos;
611                                 space_inserted = true;
612                         } else {
613                                 const pos_type n = 8 - pos % 8;
614                                 for (pos_type i = 0; i < n; ++i) {
615                                         par.insertChar(pos, ' ', font, params().trackChanges);
616                                         ++pos;
617                                 }
618                                 space_inserted = true;
619                         }
620                 } else if (!isPrintable(*cit)) {
621                         // Ignore unprintables
622                         continue;
623                 } else {
624                         // just insert the character
625                         par.insertChar(pos, *cit, font, params().trackChanges);
626                         ++pos;
627                         space_inserted = (*cit == ' ');
628                 }
629
630         }
631 }
632
633
634 bool Buffer::readString(string const & s)
635 {
636         params().compressed = false;
637
638         // remove dummy empty par
639         paragraphs().clear();
640         Lexer lex(0, 0);
641         istringstream is(s);
642         lex.setStream(is);
643         FileName const name = FileName::tempName();
644         switch (readFile(lex, name, true)) {
645         case failure:
646                 return false;
647         case wrongversion: {
648                 // We need to call lyx2lyx, so write the input to a file
649                 ofstream os(name.toFilesystemEncoding().c_str());
650                 os << s;
651                 os.close();
652                 return readFile(name);
653         }
654         case success:
655                 break;
656         }
657
658         return true;
659 }
660
661
662 bool Buffer::readFile(FileName const & filename)
663 {
664         FileName fname(filename);
665         // Check if the file is compressed.
666         string format = filename.guessFormatFromContents();
667         if (format == "zip") {
668                 // decompress to a temp directory
669                 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
670                 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
671                 //
672                 FileName lyxfile(addName(temppath(), "content.lyx"));
673                 // if both manifest.txt and file.lyx exist, this is am embedded file
674                 if (lyxfile.exists()) {
675                         params().embedded = true;
676                         fname = lyxfile;
677                 }
678         }
679         // The embedded lyx file can also be compressed, for backward compatibility
680         format = fname.guessFormatFromContents();
681         if (format == "gzip" || format == "zip" || format == "compress")
682                 params().compressed = true;
683
684         // remove dummy empty par
685         paragraphs().clear();
686         Lexer lex(0, 0);
687         lex.setFile(fname);
688         if (readFile(lex, fname) != success)
689                 return false;
690
691         return true;
692 }
693
694
695 bool Buffer::isFullyLoaded() const
696 {
697         return d->file_fully_loaded;
698 }
699
700
701 void Buffer::setFullyLoaded(bool value)
702 {
703         d->file_fully_loaded = value;
704 }
705
706
707 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
708                 bool fromstring)
709 {
710         BOOST_ASSERT(!filename.empty());
711
712         if (!lex.isOK()) {
713                 Alert::error(_("Document could not be read"),
714                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
715                 return failure;
716         }
717
718         lex.next();
719         string const token = lex.getString();
720
721         if (!lex) {
722                 Alert::error(_("Document could not be read"),
723                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
724                 return failure;
725         }
726
727         // the first token _must_ be...
728         if (token != "\\lyxformat") {
729                 lyxerr << "Token: " << token << endl;
730
731                 Alert::error(_("Document format failure"),
732                              bformat(_("%1$s is not a LyX document."),
733                                        from_utf8(filename.absFilename())));
734                 return failure;
735         }
736
737         lex.next();
738         string tmp_format = lex.getString();
739         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
740         // if present remove ".," from string.
741         string::size_type dot = tmp_format.find_first_of(".,");
742         //lyxerr << "           dot found at " << dot << endl;
743         if (dot != string::npos)
744                         tmp_format.erase(dot, 1);
745         int const file_format = convert<int>(tmp_format);
746         //lyxerr << "format: " << file_format << endl;
747
748         // save timestamp and checksum of the original disk file, making sure
749         // to not overwrite them with those of the file created in the tempdir
750         // when it has to be converted to the current format.
751         if (!d->checksum_) {
752                 // Save the timestamp and checksum of disk file. If filename is an
753                 // emergency file, save the timestamp and checksum of the original lyx file
754                 // because isExternallyModified will check for this file. (BUG4193)
755                 string diskfile = filename.absFilename();
756                 if (suffixIs(diskfile, ".emergency"))
757                         diskfile = diskfile.substr(0, diskfile.size() - 10);
758                 saveCheckSum(FileName(diskfile));
759         }
760
761         if (file_format != LYX_FORMAT) {
762
763                 if (fromstring)
764                         // lyx2lyx would fail
765                         return wrongversion;
766
767                 FileName const tmpfile = FileName::tempName();
768                 if (tmpfile.empty()) {
769                         Alert::error(_("Conversion failed"),
770                                      bformat(_("%1$s is from a different"
771                                               " version of LyX, but a temporary"
772                                               " file for converting it could"
773                                                             " not be created."),
774                                               from_utf8(filename.absFilename())));
775                         return failure;
776                 }
777                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
778                 if (lyx2lyx.empty()) {
779                         Alert::error(_("Conversion script not found"),
780                                      bformat(_("%1$s is from a different"
781                                                " version of LyX, but the"
782                                                " conversion script lyx2lyx"
783                                                             " could not be found."),
784                                                from_utf8(filename.absFilename())));
785                         return failure;
786                 }
787                 ostringstream command;
788                 command << os::python()
789                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
790                         << " -t " << convert<string>(LYX_FORMAT)
791                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
792                         << ' ' << quoteName(filename.toFilesystemEncoding());
793                 string const command_str = command.str();
794
795                 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
796
797                 cmd_ret const ret = runCommand(command_str);
798                 if (ret.first != 0) {
799                         Alert::error(_("Conversion script failed"),
800                                      bformat(_("%1$s is from a different version"
801                                               " of LyX, but the lyx2lyx script"
802                                                             " failed to convert it."),
803                                               from_utf8(filename.absFilename())));
804                         return failure;
805                 } else {
806                         bool const ret = readFile(tmpfile);
807                         // Do stuff with tmpfile name and buffer name here.
808                         return ret ? success : failure;
809                 }
810
811         }
812
813         if (readDocument(lex)) {
814                 Alert::error(_("Document format failure"),
815                              bformat(_("%1$s ended unexpectedly, which means"
816                                                     " that it is probably corrupted."),
817                                        from_utf8(filename.absFilename())));
818         }
819
820         d->file_fully_loaded = true;
821         return success;
822 }
823
824
825 // Should probably be moved to somewhere else: BufferView? LyXView?
826 bool Buffer::save() const
827 {
828         // We don't need autosaves in the immediate future. (Asger)
829         resetAutosaveTimers();
830
831         string const encodedFilename = d->filename.toFilesystemEncoding();
832
833         FileName backupName;
834         bool madeBackup = false;
835
836         // make a backup if the file already exists
837         if (lyxrc.make_backup && fileName().exists()) {
838                 backupName = FileName(absFileName() + '~');
839                 if (!lyxrc.backupdir_path.empty()) {
840                         string const mangledName =
841                                 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
842                         backupName = FileName(addName(lyxrc.backupdir_path,
843                                                       mangledName));
844                 }
845                 if (fileName().copyTo(backupName)) {
846                         madeBackup = true;
847                 } else {
848                         Alert::error(_("Backup failure"),
849                                      bformat(_("Cannot create backup file %1$s.\n"
850                                                "Please check whether the directory exists and is writeable."),
851                                              from_utf8(backupName.absFilename())));
852                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
853                 }
854         }
855
856         // ask if the disk file has been externally modified (use checksum method)
857         if (fileName().exists() && isExternallyModified(checksum_method)) {
858                 docstring const file = makeDisplayPath(absFileName(), 20);
859                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
860                                                              "you want to overwrite this file?"), file);
861                 int const ret = Alert::prompt(_("Overwrite modified file?"),
862                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
863                 if (ret == 1)
864                         return false;
865         }
866
867         if (writeFile(d->filename)) {
868                 markClean();
869                 return true;
870         } else {
871                 // Saving failed, so backup is not backup
872                 if (madeBackup)
873                         backupName.moveTo(d->filename);
874                 return false;
875         }
876 }
877
878
879 bool Buffer::writeFile(FileName const & fname) const
880 {
881         if (d->read_only && fname == d->filename)
882                 return false;
883
884         bool retval = false;
885
886         FileName content;
887         if (params().embedded)
888                 // first write the .lyx file to the temporary directory
889                 content = FileName(addName(temppath(), "content.lyx"));
890         else
891                 content = fname;
892
893         docstring const str = bformat(_("Saving document %1$s..."),
894                 makeDisplayPath(content.absFilename()));
895         message(str);
896
897         if (params().compressed) {
898                 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
899                 retval = ofs && write(ofs);
900         } else {
901                 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
902                 retval = ofs && write(ofs);
903         }
904
905         if (!retval) {
906                 message(str + _(" could not write file!."));
907                 return false;
908         }
909
910         removeAutosaveFile(d->filename.absFilename());
911         saveCheckSum(d->filename);
912         message(str + _(" done."));
913
914         if (!params().embedded)
915                 return true;
916
917         message(str + _(" writing embedded files!."));
918         // if embedding is enabled, write file.lyx and all the embedded files
919         // to the zip file fname.
920         if (!d->embedded_files.writeFile(fname)) {
921                 message(str + _(" could not write embedded files!."));
922                 return false;
923         }
924         message(str + _(" error while writing embedded files."));
925         return true;
926 }
927
928
929 bool Buffer::write(ostream & ofs) const
930 {
931 #ifdef HAVE_LOCALE
932         // Use the standard "C" locale for file output.
933         ofs.imbue(locale::classic());
934 #endif
935
936         // The top of the file should not be written by params().
937
938         // write out a comment in the top of the file
939         ofs << "#LyX " << lyx_version
940             << " created this file. For more info see http://www.lyx.org/\n"
941             << "\\lyxformat " << LYX_FORMAT << "\n"
942             << "\\begin_document\n";
943
944
945         /// For each author, set 'used' to true if there is a change
946         /// by this author in the document; otherwise set it to 'false'.
947         AuthorList::Authors::const_iterator a_it = params().authors().begin();
948         AuthorList::Authors::const_iterator a_end = params().authors().end();
949         for (; a_it != a_end; ++a_it)
950                 a_it->second.setUsed(false);
951
952         ParIterator const end = par_iterator_end();
953         ParIterator it = par_iterator_begin();
954         for ( ; it != end; ++it)
955                 it->checkAuthors(params().authors());
956
957         // now write out the buffer parameters.
958         ofs << "\\begin_header\n";
959         params().writeFile(ofs);
960         ofs << "\\end_header\n";
961
962         // write the text
963         ofs << "\n\\begin_body\n";
964         text().write(*this, ofs);
965         ofs << "\n\\end_body\n";
966
967         // Write marker that shows file is complete
968         ofs << "\\end_document" << endl;
969
970         // Shouldn't really be needed....
971         //ofs.close();
972
973         // how to check if close went ok?
974         // Following is an attempt... (BE 20001011)
975
976         // good() returns false if any error occured, including some
977         //        formatting error.
978         // bad()  returns true if something bad happened in the buffer,
979         //        which should include file system full errors.
980
981         bool status = true;
982         if (!ofs) {
983                 status = false;
984                 lyxerr << "File was not closed properly." << endl;
985         }
986
987         return status;
988 }
989
990
991 bool Buffer::makeLaTeXFile(FileName const & fname,
992                            string const & original_path,
993                            OutputParams const & runparams,
994                            bool output_preamble, bool output_body) const
995 {
996         string const encoding = runparams.encoding->iconvName();
997         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
998
999         odocfstream ofs;
1000         try { ofs.reset(encoding); }
1001         catch (iconv_codecvt_facet_exception & e) {
1002                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1003                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1004                         "verify that the support software for your encoding (%1$s) is "
1005                         "properly installed"), from_ascii(encoding)));
1006                 return false;
1007         }
1008         if (!openFileWrite(ofs, fname))
1009                 return false;
1010
1011         //TexStream ts(ofs.rdbuf(), &texrow());
1012         ErrorList & errorList = d->errorLists["Export"];
1013         errorList.clear();
1014         bool failed_export = false;
1015         try {
1016                 d->texrow.reset();
1017                 writeLaTeXSource(ofs, original_path,
1018                       runparams, output_preamble, output_body);
1019         }
1020         catch (EncodingException & e) {
1021                 odocstringstream ods;
1022                 ods.put(e.failed_char);
1023                 ostringstream oss;
1024                 oss << "0x" << hex << e.failed_char << dec;
1025                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1026                                           " (code point %2$s)"),
1027                                           ods.str(), from_utf8(oss.str()));
1028                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1029                                 "representable in the chosen encoding.\n"
1030                                 "Changing the document encoding to utf8 could help."),
1031                                 e.par_id, e.pos, e.pos + 1));
1032                 failed_export = true;                   
1033         }
1034         catch (iconv_codecvt_facet_exception & e) {
1035                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1036                         _(e.what()), -1, 0, 0));
1037                 failed_export = true;
1038         }
1039         catch (exception const & e) {
1040                 errorList.push_back(ErrorItem(_("conversion failed"),
1041                         _(e.what()), -1, 0, 0));
1042                 failed_export = true;
1043         }
1044         catch (...) {
1045                 lyxerr << "Caught some really weird exception..." << endl;
1046                 LyX::cref().exit(1);
1047         }
1048
1049         ofs.close();
1050         if (ofs.fail()) {
1051                 failed_export = true;
1052                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1053         }
1054
1055         errors("Export");
1056         return !failed_export;
1057 }
1058
1059
1060 void Buffer::writeLaTeXSource(odocstream & os,
1061                            string const & original_path,
1062                            OutputParams const & runparams_in,
1063                            bool const output_preamble, bool const output_body) const
1064 {
1065         OutputParams runparams = runparams_in;
1066
1067         // validate the buffer.
1068         LYXERR(Debug::LATEX, "  Validating buffer...");
1069         LaTeXFeatures features(*this, params(), runparams);
1070         validate(features);
1071         LYXERR(Debug::LATEX, "  Buffer validation done.");
1072
1073         // The starting paragraph of the coming rows is the
1074         // first paragraph of the document. (Asger)
1075         if (output_preamble && runparams.nice) {
1076                 os << "%% LyX " << lyx_version << " created this file.  "
1077                         "For more info, see http://www.lyx.org/.\n"
1078                         "%% Do not edit unless you really know what "
1079                         "you are doing.\n";
1080                 d->texrow.newline();
1081                 d->texrow.newline();
1082         }
1083         LYXERR(Debug::INFO, "lyx document header finished");
1084         // There are a few differences between nice LaTeX and usual files:
1085         // usual is \batchmode and has a
1086         // special input@path to allow the including of figures
1087         // with either \input or \includegraphics (what figinsets do).
1088         // input@path is set when the actual parameter
1089         // original_path is set. This is done for usual tex-file, but not
1090         // for nice-latex-file. (Matthias 250696)
1091         // Note that input@path is only needed for something the user does
1092         // in the preamble, included .tex files or ERT, files included by
1093         // LyX work without it.
1094         if (output_preamble) {
1095                 if (!runparams.nice) {
1096                         // code for usual, NOT nice-latex-file
1097                         os << "\\batchmode\n"; // changed
1098                         // from \nonstopmode
1099                         d->texrow.newline();
1100                 }
1101                 if (!original_path.empty()) {
1102                         // FIXME UNICODE
1103                         // We don't know the encoding of inputpath
1104                         docstring const inputpath = from_utf8(latex_path(original_path));
1105                         os << "\\makeatletter\n"
1106                            << "\\def\\input@path{{"
1107                            << inputpath << "/}}\n"
1108                            << "\\makeatother\n";
1109                         d->texrow.newline();
1110                         d->texrow.newline();
1111                         d->texrow.newline();
1112                 }
1113
1114                 // Write the preamble
1115                 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1116
1117                 if (!output_body)
1118                         return;
1119
1120                 // make the body.
1121                 os << "\\begin{document}\n";
1122                 d->texrow.newline();
1123         } // output_preamble
1124
1125         d->texrow.start(paragraphs().begin()->id(), 0);
1126         
1127         LYXERR(Debug::INFO, "preamble finished, now the body.");
1128
1129         // fold macros if possible, still with parent buffer as the
1130         // macros will be put in the prefix anyway.
1131         updateMacros();
1132         updateMacroInstances();
1133
1134         // if we are doing a real file with body, even if this is the
1135         // child of some other buffer, let's cut the link here.
1136         // This happens for example if only a child document is printed.
1137         Buffer const * save_parent = 0;
1138         if (output_preamble) {
1139                 // output the macros visible for this buffer
1140                 writeParentMacros(os);
1141
1142                 save_parent = d->parent_buffer;
1143                 d->parent_buffer = 0;
1144         }
1145
1146         loadChildDocuments();
1147
1148         // the real stuff
1149         latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1150
1151         // Restore the parenthood if needed
1152         if (output_preamble) {
1153                 d->parent_buffer = save_parent;
1154
1155                 // restore macros with correct parent buffer (especially
1156                 // important for the redefinition flag which depends on the 
1157                 // parent)
1158                 updateMacros();
1159         }
1160
1161         // add this just in case after all the paragraphs
1162         os << endl;
1163         d->texrow.newline();
1164
1165         if (output_preamble) {
1166                 os << "\\end{document}\n";
1167                 d->texrow.newline();
1168                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1169         } else {
1170                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1171         }
1172         runparams_in.encoding = runparams.encoding;
1173
1174         // Just to be sure. (Asger)
1175         d->texrow.newline();
1176
1177         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1178         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1179 }
1180
1181
1182 bool Buffer::isLatex() const
1183 {
1184         return params().getTextClass().outputType() == LATEX;
1185 }
1186
1187
1188 bool Buffer::isLiterate() const
1189 {
1190         return params().getTextClass().outputType() == LITERATE;
1191 }
1192
1193
1194 bool Buffer::isDocBook() const
1195 {
1196         return params().getTextClass().outputType() == DOCBOOK;
1197 }
1198
1199
1200 void Buffer::makeDocBookFile(FileName const & fname,
1201                               OutputParams const & runparams,
1202                               bool const body_only) const
1203 {
1204         LYXERR(Debug::LATEX, "makeDocBookFile...");
1205
1206         odocfstream ofs;
1207         if (!openFileWrite(ofs, fname))
1208                 return;
1209
1210         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1211
1212         ofs.close();
1213         if (ofs.fail())
1214                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1215 }
1216
1217
1218 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1219                              OutputParams const & runparams,
1220                              bool const only_body) const
1221 {
1222         LaTeXFeatures features(*this, params(), runparams);
1223         validate(features);
1224
1225         d->texrow.reset();
1226
1227         TextClass const & tclass = params().getTextClass();
1228         string const top_element = tclass.latexname();
1229
1230         if (!only_body) {
1231                 if (runparams.flavor == OutputParams::XML)
1232                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1233
1234                 // FIXME UNICODE
1235                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1236
1237                 // FIXME UNICODE
1238                 if (! tclass.class_header().empty())
1239                         os << from_ascii(tclass.class_header());
1240                 else if (runparams.flavor == OutputParams::XML)
1241                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1242                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1243                 else
1244                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1245
1246                 docstring preamble = from_utf8(params().preamble);
1247                 if (runparams.flavor != OutputParams::XML ) {
1248                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1249                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1250                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1251                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1252                 }
1253
1254                 string const name = runparams.nice
1255                         ? changeExtension(absFileName(), ".sgml") : fname;
1256                 preamble += features.getIncludedFiles(name);
1257                 preamble += features.getLyXSGMLEntities();
1258
1259                 if (!preamble.empty()) {
1260                         os << "\n [ " << preamble << " ]";
1261                 }
1262                 os << ">\n\n";
1263         }
1264
1265         string top = top_element;
1266         top += " lang=\"";
1267         if (runparams.flavor == OutputParams::XML)
1268                 top += params().language->code();
1269         else
1270                 top += params().language->code().substr(0,2);
1271         top += '"';
1272
1273         if (!params().options.empty()) {
1274                 top += ' ';
1275                 top += params().options;
1276         }
1277
1278         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1279             << " file was created by LyX " << lyx_version
1280             << "\n  See http://www.lyx.org/ for more information -->\n";
1281
1282         params().getTextClass().counters().reset();
1283
1284         loadChildDocuments();
1285
1286         sgml::openTag(os, top);
1287         os << '\n';
1288         docbookParagraphs(paragraphs(), *this, os, runparams);
1289         sgml::closeTag(os, top_element);
1290 }
1291
1292
1293 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1294 // Other flags: -wall -v0 -x
1295 int Buffer::runChktex()
1296 {
1297         setBusy(true);
1298
1299         // get LaTeX-Filename
1300         FileName const path(temppath());
1301         string const name = addName(path.absFilename(), latexName());
1302         string const org_path = filePath();
1303
1304         PathChanger p(path); // path to LaTeX file
1305         message(_("Running chktex..."));
1306
1307         // Generate the LaTeX file if neccessary
1308         OutputParams runparams(&params().encoding());
1309         runparams.flavor = OutputParams::LATEX;
1310         runparams.nice = false;
1311         makeLaTeXFile(FileName(name), org_path, runparams);
1312
1313         TeXErrors terr;
1314         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1315         int const res = chktex.run(terr); // run chktex
1316
1317         if (res == -1) {
1318                 Alert::error(_("chktex failure"),
1319                              _("Could not run chktex successfully."));
1320         } else if (res > 0) {
1321                 ErrorList & errlist = d->errorLists["ChkTeX"];
1322                 errlist.clear();
1323                 bufferErrors(terr, errlist);
1324         }
1325
1326         setBusy(false);
1327
1328         errors("ChkTeX");
1329
1330         return res;
1331 }
1332
1333
1334 void Buffer::validate(LaTeXFeatures & features) const
1335 {
1336         params().validate(features);
1337
1338         loadChildDocuments();
1339
1340         for_each(paragraphs().begin(), paragraphs().end(),
1341                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1342
1343         if (lyxerr.debugging(Debug::LATEX)) {
1344                 features.showStruct();
1345         }
1346 }
1347
1348
1349 void Buffer::getLabelList(vector<docstring> & list) const
1350 {
1351         /// if this is a child document and the parent is already loaded
1352         /// Use the parent's list instead  [ale990407]
1353         Buffer const * tmp = masterBuffer();
1354         if (!tmp) {
1355                 lyxerr << "masterBuffer() failed!" << endl;
1356                 BOOST_ASSERT(tmp);
1357         }
1358         if (tmp != this) {
1359                 tmp->getLabelList(list);
1360                 return;
1361         }
1362
1363         loadChildDocuments();
1364
1365         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1366                 it.nextInset()->getLabelList(*this, list);
1367 }
1368
1369
1370 void Buffer::updateBibfilesCache() const
1371 {
1372         // if this is a child document and the parent is already loaded
1373         // update the parent's cache instead
1374         Buffer const * tmp = masterBuffer();
1375         BOOST_ASSERT(tmp);
1376         if (tmp != this) {
1377                 tmp->updateBibfilesCache();
1378                 return;
1379         }
1380
1381         d->bibfilesCache_.clear();
1382         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1383                 if (it->lyxCode() == BIBTEX_CODE) {
1384                         InsetBibtex const & inset =
1385                                 static_cast<InsetBibtex const &>(*it);
1386                         FileNameList const bibfiles = inset.getFiles(*this);
1387                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1388                                 bibfiles.begin(),
1389                                 bibfiles.end());
1390                 } else if (it->lyxCode() == INCLUDE_CODE) {
1391                         InsetInclude & inset =
1392                                 static_cast<InsetInclude &>(*it);
1393                         inset.updateBibfilesCache(*this);
1394                         FileNameList const & bibfiles =
1395                                         inset.getBibfilesCache(*this);
1396                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1397                                 bibfiles.begin(),
1398                                 bibfiles.end());
1399                 }
1400         }
1401 }
1402
1403
1404 FileNameList const & Buffer::getBibfilesCache() const
1405 {
1406         // if this is a child document and the parent is already loaded
1407         // use the parent's cache instead
1408         Buffer const * tmp = masterBuffer();
1409         BOOST_ASSERT(tmp);
1410         if (tmp != this)
1411                 return tmp->getBibfilesCache();
1412
1413         // We update the cache when first used instead of at loading time.
1414         if (d->bibfilesCache_.empty())
1415                 const_cast<Buffer *>(this)->updateBibfilesCache();
1416
1417         return d->bibfilesCache_;
1418 }
1419
1420
1421 bool Buffer::isDepClean(string const & name) const
1422 {
1423         DepClean::const_iterator const it = d->dep_clean.find(name);
1424         if (it == d->dep_clean.end())
1425                 return true;
1426         return it->second;
1427 }
1428
1429
1430 void Buffer::markDepClean(string const & name)
1431 {
1432         d->dep_clean[name] = true;
1433 }
1434
1435
1436 bool Buffer::dispatch(string const & command, bool * result)
1437 {
1438         return dispatch(lyxaction.lookupFunc(command), result);
1439 }
1440
1441
1442 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1443 {
1444         bool dispatched = true;
1445
1446         switch (func.action) {
1447                 case LFUN_BUFFER_EXPORT: {
1448                         bool const tmp = doExport(to_utf8(func.argument()), false);
1449                         if (result)
1450                                 *result = tmp;
1451                         break;
1452                 }
1453
1454                 default:
1455                         dispatched = false;
1456         }
1457         return dispatched;
1458 }
1459
1460
1461 void Buffer::changeLanguage(Language const * from, Language const * to)
1462 {
1463         BOOST_ASSERT(from);
1464         BOOST_ASSERT(to);
1465
1466         for_each(par_iterator_begin(),
1467                  par_iterator_end(),
1468                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1469 }
1470
1471
1472 bool Buffer::isMultiLingual() const
1473 {
1474         ParConstIterator end = par_iterator_end();
1475         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1476                 if (it->isMultiLingual(params()))
1477                         return true;
1478
1479         return false;
1480 }
1481
1482
1483 ParIterator Buffer::getParFromID(int const id) const
1484 {
1485         ParConstIterator it = par_iterator_begin();
1486         ParConstIterator const end = par_iterator_end();
1487
1488         if (id < 0) {
1489                 // John says this is called with id == -1 from undo
1490                 lyxerr << "getParFromID(), id: " << id << endl;
1491                 return end;
1492         }
1493
1494         for (; it != end; ++it)
1495                 if (it->id() == id)
1496                         return it;
1497
1498         return end;
1499 }
1500
1501
1502 bool Buffer::hasParWithID(int const id) const
1503 {
1504         ParConstIterator const it = getParFromID(id);
1505         return it != par_iterator_end();
1506 }
1507
1508
1509 ParIterator Buffer::par_iterator_begin()
1510 {
1511         return lyx::par_iterator_begin(inset());
1512 }
1513
1514
1515 ParIterator Buffer::par_iterator_end()
1516 {
1517         return lyx::par_iterator_end(inset());
1518 }
1519
1520
1521 ParConstIterator Buffer::par_iterator_begin() const
1522 {
1523         return lyx::par_const_iterator_begin(inset());
1524 }
1525
1526
1527 ParConstIterator Buffer::par_iterator_end() const
1528 {
1529         return lyx::par_const_iterator_end(inset());
1530 }
1531
1532
1533 Language const * Buffer::language() const
1534 {
1535         return params().language;
1536 }
1537
1538
1539 docstring const Buffer::B_(string const & l10n) const
1540 {
1541         return params().B_(l10n);
1542 }
1543
1544
1545 bool Buffer::isClean() const
1546 {
1547         return d->lyx_clean;
1548 }
1549
1550
1551 bool Buffer::isBakClean() const
1552 {
1553         return d->bak_clean;
1554 }
1555
1556
1557 bool Buffer::isExternallyModified(CheckMethod method) const
1558 {
1559         BOOST_ASSERT(d->filename.exists());
1560         // if method == timestamp, check timestamp before checksum
1561         return (method == checksum_method 
1562                 || d->timestamp_ != d->filename.lastModified())
1563                 && d->checksum_ != d->filename.checksum();
1564 }
1565
1566
1567 void Buffer::saveCheckSum(FileName const & file) const
1568 {
1569         if (file.exists()) {
1570                 d->timestamp_ = file.lastModified();
1571                 d->checksum_ = file.checksum();
1572         } else {
1573                 // in the case of save to a new file.
1574                 d->timestamp_ = 0;
1575                 d->checksum_ = 0;
1576         }
1577 }
1578
1579
1580 void Buffer::markClean() const
1581 {
1582         if (!d->lyx_clean) {
1583                 d->lyx_clean = true;
1584                 updateTitles();
1585         }
1586         // if the .lyx file has been saved, we don't need an
1587         // autosave
1588         d->bak_clean = true;
1589 }
1590
1591
1592 void Buffer::markBakClean() const
1593 {
1594         d->bak_clean = true;
1595 }
1596
1597
1598 void Buffer::setUnnamed(bool flag)
1599 {
1600         d->unnamed = flag;
1601 }
1602
1603
1604 bool Buffer::isUnnamed() const
1605 {
1606         return d->unnamed;
1607 }
1608
1609
1610 // FIXME: this function should be moved to buffer_pimpl.C
1611 void Buffer::markDirty()
1612 {
1613         if (d->lyx_clean) {
1614                 d->lyx_clean = false;
1615                 updateTitles();
1616         }
1617         d->bak_clean = false;
1618
1619         DepClean::iterator it = d->dep_clean.begin();
1620         DepClean::const_iterator const end = d->dep_clean.end();
1621
1622         for (; it != end; ++it)
1623                 it->second = false;
1624 }
1625
1626
1627 FileName Buffer::fileName() const
1628 {
1629         return d->filename;
1630 }
1631
1632
1633 string Buffer::absFileName() const
1634 {
1635         return d->filename.absFilename();
1636 }
1637
1638
1639 string Buffer::filePath() const
1640 {
1641         return d->filename.onlyPath().absFilename() + "/";
1642 }
1643
1644
1645 bool Buffer::isReadonly() const
1646 {
1647         return d->read_only;
1648 }
1649
1650
1651 void Buffer::setParent(Buffer const * buffer)
1652 {
1653         // Avoids recursive include.
1654         d->parent_buffer = buffer == this ? 0 : buffer;
1655         updateMacros();
1656 }
1657
1658
1659 Buffer const * Buffer::parent()
1660 {
1661         return d->parent_buffer;
1662 }
1663
1664
1665 Buffer const * Buffer::masterBuffer() const
1666 {
1667         if (!d->parent_buffer)
1668                 return this;
1669         
1670         return d->parent_buffer->masterBuffer();
1671 }
1672
1673
1674 template<typename M>
1675 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1676 {
1677         if (m.empty())
1678                 return m.end();
1679
1680         typename M::iterator it = m.lower_bound(x);
1681         if (it == m.begin())
1682                 return m.end();
1683
1684         it--;
1685         return it;      
1686 }
1687
1688
1689 MacroData const * Buffer::getBufferMacro(docstring const & name, 
1690                                          DocIterator const & pos) const
1691 {
1692         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1693
1694         // if paragraphs have no macro context set, pos will be empty
1695         if (pos.empty())
1696                 return 0;
1697
1698         // we haven't found anything yet
1699         DocIterator bestPos = par_iterator_begin();
1700         MacroData const * bestData = 0;
1701         
1702         // find macro definitions for name
1703         Impl::NamePositionScopeMacroMap::iterator nameIt
1704         = d->macros.find(name);
1705         if (nameIt != d->macros.end()) {
1706                 // find last definition in front of pos or at pos itself
1707                 Impl::PositionScopeMacroMap::const_iterator it
1708                 = greatest_below(nameIt->second, pos);
1709                 if (it != nameIt->second.end()) {
1710                         while (true) {
1711                                 // scope ends behind pos?
1712                                 if (pos < it->second.first) {
1713                                         // Looks good, remember this. If there
1714                                         // is no external macro behind this,
1715                                         // we found the right one already.
1716                                         bestPos = it->first;
1717                                         bestData = &it->second.second;
1718                                         break;
1719                                 }
1720                                 
1721                                 // try previous macro if there is one
1722                                 if (it == nameIt->second.begin())
1723                                         break;
1724                                 it--;
1725                         }
1726                 }
1727         }
1728
1729         // find macros in included files
1730         Impl::PositionScopeBufferMap::const_iterator it
1731         = greatest_below(d->position_to_children, pos);
1732         if (it != d->position_to_children.end()) {
1733                 while (true) {
1734                         // do we know something better (i.e. later) already?
1735                         if (it->first < bestPos )               
1736                                 break;
1737
1738                         // scope ends behind pos?
1739                         if (pos < it->second.first) {
1740                                 // look for macro in external file
1741                                 d->macro_lock = true;
1742                                 MacroData const * data
1743                                 = it->second.second->getMacro(name, false);
1744                                 d->macro_lock = false;
1745                                 if (data) {
1746                                         bestPos = it->first;
1747                                         bestData = data;                               
1748                                         break;
1749                                 }
1750                         }
1751                         
1752                         // try previous file if there is one
1753                         if (it == d->position_to_children.begin())
1754                                 break;
1755                         --it;
1756                 }
1757         }
1758                 
1759         // return the best macro we have found
1760         return bestData;
1761 }
1762
1763
1764 MacroData const * Buffer::getMacro(docstring const & name,
1765         DocIterator const & pos, bool global) const
1766 {
1767         if (d->macro_lock)
1768                 return 0;       
1769
1770         // query buffer macros
1771         MacroData const * data = getBufferMacro(name, pos);
1772         if (data != 0)
1773                 return data;
1774
1775         // If there is a master buffer, query that
1776         if (d->parent_buffer) {
1777                 d->macro_lock = true;
1778                 MacroData const * macro
1779                 = d->parent_buffer->getMacro(name, *this, false);
1780                 d->macro_lock = false;
1781                 if (macro)
1782                         return macro;
1783         }
1784
1785         if (global) {
1786                 data = MacroTable::globalMacros().get(name);
1787                 if (data != 0)
1788                         return data;
1789         }
1790
1791         return 0;
1792 }
1793
1794
1795 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1796 {
1797         // set scope end behind the last paragraph
1798         DocIterator scope = par_iterator_begin();
1799         scope.pit() = scope.lastpit() + 1;
1800
1801         return getMacro(name, scope, global);
1802 }
1803
1804
1805 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1806 {
1807         // look where the child buffer is included first
1808         Impl::BufferPositionMap::iterator it
1809         = d->children_positions.find(&child);
1810         if (it == d->children_positions.end())
1811                 return 0;
1812
1813         // check for macros at the inclusion position
1814         return getMacro(name, it->second, global);
1815 }
1816
1817
1818 void Buffer::updateEnvironmentMacros(DocIterator & it, 
1819                                      pit_type lastpit, 
1820                                      DocIterator & scope) const
1821 {
1822         Paragraph & par = it.paragraph();
1823         depth_type depth 
1824         = par.params().depth();
1825         Length const & leftIndent
1826         = par.params().leftIndent();
1827
1828         // look for macros in each paragraph
1829         while (it.pit() <= lastpit) {
1830                 Paragraph & par = it.paragraph();
1831
1832                 // increased depth?
1833                 if ((par.params().depth() > depth
1834                      || par.params().leftIndent() != leftIndent)
1835                     && par.layout()->isEnvironment()) {
1836                         updateBlockMacros(it, scope);
1837                         continue;
1838                 }
1839
1840                 // iterate over the insets of the current paragraph
1841                 InsetList const & insets = par.insetList();
1842                 InsetList::const_iterator iit = insets.begin();
1843                 InsetList::const_iterator end = insets.end();
1844                 for (; iit != end; ++iit) {
1845                         it.pos() = iit->pos;
1846                         
1847                         // is it a nested text inset?
1848                         if (iit->inset->asInsetText()) {
1849                                 // Inset needs its own scope?
1850                                 InsetText const * itext 
1851                                 = iit->inset->asInsetText();
1852                                 bool newScope = itext->isMacroScope(*this);
1853
1854                                 // scope which ends just behind die inset       
1855                                 DocIterator insetScope = it;
1856                                 insetScope.pos()++;
1857
1858                                 // collect macros in inset
1859                                 it.push_back(CursorSlice(*iit->inset));
1860                                 updateInsetMacros(it, newScope ? insetScope : scope);
1861                                 it.pop_back();
1862                                 continue;
1863                         }
1864                                               
1865                         // is it an external file?
1866                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
1867                                 // get buffer of external file
1868                                 InsetCommand const & inset 
1869                                 = static_cast<InsetCommand const &>(*iit->inset);
1870                                 InsetCommandParams const & ip = inset.params();
1871                                 d->macro_lock = true;
1872                                 Buffer * child = loadIfNeeded(*this, ip);
1873                                 d->macro_lock = false;
1874                                 if (!child)
1875                                         continue;                               
1876
1877                                 // register it, but only when it is
1878                                 // included first in the buffer
1879                                 if (d->children_positions.find(child)
1880                                     == d->children_positions.end())
1881                                         d->children_positions[child] = it;
1882                                                                                                 
1883                                 // register child with its scope
1884                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1885
1886                                 continue;
1887                         }
1888
1889                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
1890                                 continue;
1891                         
1892                         // get macro data
1893                         MathMacroTemplate & macroTemplate
1894                         = static_cast<MathMacroTemplate &>(*iit->inset);
1895                         MacroContext mc(*this, it);
1896                         macroTemplate.updateToContext(mc);
1897
1898                         // valid?
1899                         bool valid = macroTemplate.validMacro();
1900                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
1901                         // then the BufferView's cursor will be invalid in
1902                         // some cases which leads to crashes.
1903                         if (!valid)
1904                                 continue;
1905
1906                         // register macro
1907                         d->macros[macroTemplate.name()][it] 
1908                         = Impl::ScopeMacro(scope, MacroData(*this, it));
1909                 }
1910
1911                 // next paragraph
1912                 it.pit()++;
1913                 it.pos() = 0;
1914         }
1915 }
1916
1917
1918 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1919 {
1920         Paragraph & par = it.paragraph();
1921                 
1922         // set scope for macros in this paragraph:
1923         // * either the "old" outer scope
1924         // * or the scope ending after the environment
1925         if (par.layout()->isEnvironment()) {
1926                 // find end of environment block,
1927                 DocIterator envEnd = it;
1928                 pit_type n = it.lastpit() + 1;
1929                 depth_type depth = par.params().depth();
1930                 Length const & length = par.params().leftIndent();
1931                 // looping through the paragraph, basically until
1932                 // the layout changes or the depth gets smaller.
1933                 // (the logic of output_latex.cpp's TeXEnvironment)
1934                 do {
1935                         envEnd.pit()++;
1936                         if (envEnd.pit() == n)
1937                                 break;
1938                 } while (par.layout() == envEnd.paragraph().layout()
1939                          || depth < envEnd.paragraph().params().depth()
1940                          || length != envEnd.paragraph().params().leftIndent());               
1941                 
1942                 // collect macros from environment block
1943                 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1944         } else {
1945                 // collect macros from paragraph
1946                 updateEnvironmentMacros(it, it.pit(), scope);
1947         }
1948 }
1949
1950
1951 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1952 {
1953         // look for macros in each paragraph
1954         pit_type n = it.lastpit() + 1;
1955         while (it.pit() < n)
1956                 updateBlockMacros(it, scope);       
1957 }
1958
1959
1960 void Buffer::updateMacros() const
1961 {
1962         if (d->macro_lock)
1963                 return;
1964
1965         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1966
1967         // start with empty table
1968         d->macros.clear();
1969         d->children_positions.clear();
1970         d->position_to_children.clear();
1971
1972         // Iterate over buffer, starting with first paragraph
1973         // The scope must be bigger than any lookup DocIterator
1974         // later. For the global lookup, lastpit+1 is used, hence
1975         // we use lastpit+2 here.
1976         DocIterator it = par_iterator_begin();
1977         DocIterator outerScope = it;
1978         outerScope.pit() = outerScope.lastpit() + 2;
1979         updateInsetMacros(it, outerScope);
1980 }
1981
1982
1983 void Buffer::updateMacroInstances() const
1984 {
1985         LYXERR(Debug::MACROS, "updateMacroInstances for " << d->filename.onlyFileName());
1986         ParIterator it = par_iterator_begin();
1987         ParIterator end = par_iterator_end();
1988         for (; it != end; it.forwardPos()) {
1989                 // look for MathData cells in InsetMathNest insets
1990                 Inset * inset = it.nextInset();
1991                 if (!inset)
1992                         continue;
1993
1994                 InsetMath * minset = inset->asInsetMath();
1995                 if (!minset)
1996                         continue;
1997
1998                 // update macro in all cells of the InsetMathNest
1999                 DocIterator::idx_type n = minset->nargs();
2000                 MacroContext mc = MacroContext(*this, it);
2001                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2002                         MathData & data = minset->cell(i);
2003                         data.updateMacros(0, mc);
2004                 }
2005         }
2006 }
2007
2008
2009 void Buffer::listMacroNames(MacroNameSet & macros) const
2010 {
2011         if (d->macro_lock)
2012                 return;
2013
2014         d->macro_lock = true;
2015         
2016         // loop over macro names
2017         Impl::NamePositionScopeMacroMap::iterator nameIt
2018         = d->macros.begin();
2019         Impl::NamePositionScopeMacroMap::iterator nameEnd
2020         = d->macros.end();
2021         for (; nameIt != nameEnd; ++nameIt)
2022                 macros.insert(nameIt->first);
2023
2024         // loop over children
2025         Impl::BufferPositionMap::iterator it
2026         = d->children_positions.begin();        
2027         Impl::BufferPositionMap::iterator end
2028         = d->children_positions.end();
2029         for (; it != end; ++it)
2030                 it->first->listMacroNames(macros);
2031
2032         // call parent
2033         if (d->parent_buffer)
2034                 d->parent_buffer->listMacroNames(macros);
2035
2036         d->macro_lock = false;  
2037 }
2038
2039
2040 void Buffer::writeParentMacros(odocstream & os) const
2041 {
2042         if (!d->parent_buffer)
2043                 return;
2044
2045         // collect macro names
2046         MacroNameSet names;
2047         d->parent_buffer->listMacroNames(names);
2048
2049         // resolve and output them
2050         MacroNameSet::iterator it = names.begin();
2051         MacroNameSet::iterator end = names.end();
2052         for (; it != end; ++it) {
2053                 // defined?
2054                 MacroData const * data = 
2055                 d->parent_buffer->getMacro(*it, *this, false);
2056                 if (data)
2057                         data->write(os, true);          
2058         }
2059 }
2060
2061
2062 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2063         InsetCode code)
2064 {
2065         //FIXME: This does not work for child documents yet.
2066         BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2067         // Check if the label 'from' appears more than once
2068         vector<docstring> labels;
2069
2070         string paramName;
2071         if (code == CITE_CODE) {
2072                 BiblioInfo keys;
2073                 keys.fillWithBibKeys(this);
2074                 BiblioInfo::const_iterator bit  = keys.begin();
2075                 BiblioInfo::const_iterator bend = keys.end();
2076
2077                 for (; bit != bend; ++bit)
2078                         // FIXME UNICODE
2079                         labels.push_back(bit->first);
2080                 paramName = "key";
2081         } else {
2082                 getLabelList(labels);
2083                 paramName = "reference";
2084         }
2085
2086         if (count(labels.begin(), labels.end(), from) > 1)
2087                 return;
2088
2089         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2090                 if (it->lyxCode() == code) {
2091                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2092                         docstring const oldValue = inset.getParam(paramName);
2093                         if (oldValue == from)
2094                                 inset.setParam(paramName, to);
2095                 }
2096         }
2097 }
2098
2099
2100 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2101         pit_type par_end, bool full_source)
2102 {
2103         OutputParams runparams(&params().encoding());
2104         runparams.nice = true;
2105         runparams.flavor = OutputParams::LATEX;
2106         runparams.linelen = lyxrc.plaintext_linelen;
2107         // No side effect of file copying and image conversion
2108         runparams.dryrun = true;
2109
2110         d->texrow.reset();
2111         if (full_source) {
2112                 os << "% " << _("Preview source code") << "\n\n";
2113                 d->texrow.newline();
2114                 d->texrow.newline();
2115                 if (isLatex())
2116                         writeLaTeXSource(os, filePath(), runparams, true, true);
2117                 else {
2118                         writeDocBookSource(os, absFileName(), runparams, false);
2119                 }
2120         } else {
2121                 runparams.par_begin = par_begin;
2122                 runparams.par_end = par_end;
2123                 if (par_begin + 1 == par_end)
2124                         os << "% "
2125                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2126                            << "\n\n";
2127                 else
2128                         os << "% "
2129                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2130                                         convert<docstring>(par_begin),
2131                                         convert<docstring>(par_end - 1))
2132                            << "\n\n";
2133                 d->texrow.newline();
2134                 d->texrow.newline();
2135                 // output paragraphs
2136                 if (isLatex()) {
2137                         latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
2138                 } else {
2139                         // DocBook
2140                         docbookParagraphs(paragraphs(), *this, os, runparams);
2141                 }
2142         }
2143 }
2144
2145
2146 ErrorList & Buffer::errorList(string const & type) const
2147 {
2148         static ErrorList emptyErrorList;
2149         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2150         if (I == d->errorLists.end())
2151                 return emptyErrorList;
2152
2153         return I->second;
2154 }
2155
2156
2157 void Buffer::structureChanged() const
2158 {
2159         if (gui_)
2160                 gui_->structureChanged();
2161 }
2162
2163
2164 void Buffer::errors(string const & err) const
2165 {
2166         if (gui_)
2167                 gui_->errors(err);
2168 }
2169
2170
2171 void Buffer::message(docstring const & msg) const
2172 {
2173         if (gui_)
2174                 gui_->message(msg);
2175 }
2176
2177
2178 void Buffer::setBusy(bool on) const
2179 {
2180         if (gui_)
2181                 gui_->setBusy(on);
2182 }
2183
2184
2185 void Buffer::setReadOnly(bool on) const
2186 {
2187         if (d->wa_)
2188                 d->wa_->setReadOnly(on);
2189 }
2190
2191
2192 void Buffer::updateTitles() const
2193 {
2194         if (d->wa_)
2195                 d->wa_->updateTitles();
2196 }
2197
2198
2199 void Buffer::resetAutosaveTimers() const
2200 {
2201         if (gui_)
2202                 gui_->resetAutosaveTimers();
2203 }
2204
2205
2206 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2207 {
2208         gui_ = gui;
2209 }
2210
2211
2212
2213 namespace {
2214
2215 class AutoSaveBuffer : public ForkedProcess {
2216 public:
2217         ///
2218         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2219                 : buffer_(buffer), fname_(fname) {}
2220         ///
2221         virtual boost::shared_ptr<ForkedProcess> clone() const
2222         {
2223                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2224         }
2225         ///
2226         int start()
2227         {
2228                 command_ = to_utf8(bformat(_("Auto-saving %1$s"), 
2229                                                  from_utf8(fname_.absFilename())));
2230                 return run(DontWait);
2231         }
2232 private:
2233         ///
2234         virtual int generateChild();
2235         ///
2236         Buffer const & buffer_;
2237         FileName fname_;
2238 };
2239
2240
2241 #if !defined (HAVE_FORK)
2242 # define fork() -1
2243 #endif
2244
2245 int AutoSaveBuffer::generateChild()
2246 {
2247         // tmp_ret will be located (usually) in /tmp
2248         // will that be a problem?
2249         pid_t const pid = fork();
2250         // If you want to debug the autosave
2251         // you should set pid to -1, and comment out the fork.
2252         if (pid == 0 || pid == -1) {
2253                 // pid = -1 signifies that lyx was unable
2254                 // to fork. But we will do the save
2255                 // anyway.
2256                 bool failed = false;
2257
2258                 FileName const tmp_ret = FileName::tempName("lyxauto");
2259                 if (!tmp_ret.empty()) {
2260                         buffer_.writeFile(tmp_ret);
2261                         // assume successful write of tmp_ret
2262                         if (!tmp_ret.moveTo(fname_)) {
2263                                 failed = true;
2264                                 // most likely couldn't move between
2265                                 // filesystems unless write of tmp_ret
2266                                 // failed so remove tmp file (if it
2267                                 // exists)
2268                                 tmp_ret.removeFile();
2269                         }
2270                 } else {
2271                         failed = true;
2272                 }
2273
2274                 if (failed) {
2275                         // failed to write/rename tmp_ret so try writing direct
2276                         if (!buffer_.writeFile(fname_)) {
2277                                 // It is dangerous to do this in the child,
2278                                 // but safe in the parent, so...
2279                                 if (pid == -1) // emit message signal.
2280                                         buffer_.message(_("Autosave failed!"));
2281                         }
2282                 }
2283                 if (pid == 0) { // we are the child so...
2284                         _exit(0);
2285                 }
2286         }
2287         return pid;
2288 }
2289
2290 } // namespace anon
2291
2292
2293 // Perfect target for a thread...
2294 void Buffer::autoSave() const
2295 {
2296         if (isBakClean() || isReadonly()) {
2297                 // We don't save now, but we'll try again later
2298                 resetAutosaveTimers();
2299                 return;
2300         }
2301
2302         // emit message signal.
2303         message(_("Autosaving current document..."));
2304
2305         // create autosave filename
2306         string fname = filePath();
2307         fname += '#';
2308         fname += d->filename.onlyFileName();
2309         fname += '#';
2310
2311         AutoSaveBuffer autosave(*this, FileName(fname));
2312         autosave.start();
2313
2314         markBakClean();
2315         resetAutosaveTimers();
2316 }
2317
2318
2319 void Buffer::resetChildDocuments(bool close_them) const
2320 {
2321         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2322                 if (it->lyxCode() != INCLUDE_CODE)
2323                         continue;
2324                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2325                 InsetCommandParams const & ip = inset.params();
2326
2327                 resetParentBuffer(this, ip, close_them);
2328         }
2329
2330         if (use_gui && masterBuffer() == this)
2331                 updateLabels(*this);
2332
2333         // clear references to children in macro tables
2334         d->children_positions.clear();
2335         d->position_to_children.clear();
2336 }
2337
2338
2339 void Buffer::loadChildDocuments() const
2340 {
2341         bool parse_error = false;
2342                 
2343         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2344                 if (it->lyxCode() != INCLUDE_CODE)
2345                         continue;
2346                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2347                 InsetCommandParams const & ip = inset.params();
2348                 Buffer * child = loadIfNeeded(*this, ip);
2349                 if (!child)
2350                         continue;
2351                 parse_error |= !child->errorList("Parse").empty();
2352                 child->loadChildDocuments();
2353         }
2354
2355         if (use_gui && masterBuffer() == this)
2356                 updateLabels(*this);
2357
2358         updateMacros();
2359 }
2360
2361
2362 string Buffer::bufferFormat() const
2363 {
2364         if (isDocBook())
2365                 return "docbook";
2366         if (isLiterate())
2367                 return "literate";
2368         return "latex";
2369 }
2370
2371
2372 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2373         string & result_file) const
2374 {
2375         string backend_format;
2376         OutputParams runparams(&params().encoding());
2377         runparams.flavor = OutputParams::LATEX;
2378         runparams.linelen = lyxrc.plaintext_linelen;
2379         vector<string> backs = backends();
2380         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2381                 // Get shortest path to format
2382                 Graph::EdgePath path;
2383                 for (vector<string>::const_iterator it = backs.begin();
2384                      it != backs.end(); ++it) {
2385                         Graph::EdgePath p = theConverters().getPath(*it, format);
2386                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2387                                 backend_format = *it;
2388                                 path = p;
2389                         }
2390                 }
2391                 if (!path.empty())
2392                         runparams.flavor = theConverters().getFlavor(path);
2393                 else {
2394                         Alert::error(_("Couldn't export file"),
2395                                 bformat(_("No information for exporting the format %1$s."),
2396                                    formats.prettyName(format)));
2397                         return false;
2398                 }
2399         } else {
2400                 backend_format = format;
2401                 // FIXME: Don't hardcode format names here, but use a flag
2402                 if (backend_format == "pdflatex")
2403                         runparams.flavor = OutputParams::PDFLATEX;
2404         }
2405
2406         string filename = latexName(false);
2407         filename = addName(temppath(), filename);
2408         filename = changeExtension(filename,
2409                                    formats.extension(backend_format));
2410
2411         // fix macros
2412         updateMacroInstances();
2413
2414         // Plain text backend
2415         if (backend_format == "text")
2416                 writePlaintextFile(*this, FileName(filename), runparams);
2417         // no backend
2418         else if (backend_format == "lyx")
2419                 writeFile(FileName(filename));
2420         // Docbook backend
2421         else if (isDocBook()) {
2422                 runparams.nice = !put_in_tempdir;
2423                 makeDocBookFile(FileName(filename), runparams);
2424         }
2425         // LaTeX backend
2426         else if (backend_format == format) {
2427                 runparams.nice = true;
2428                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2429                         return false;
2430         } else if (!lyxrc.tex_allows_spaces
2431                    && contains(filePath(), ' ')) {
2432                 Alert::error(_("File name error"),
2433                            _("The directory path to the document cannot contain spaces."));
2434                 return false;
2435         } else {
2436                 runparams.nice = false;
2437                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2438                         return false;
2439         }
2440
2441         string const error_type = (format == "program")
2442                 ? "Build" : bufferFormat();
2443         string const ext = formats.extension(format);
2444         FileName const tmp_result_file(changeExtension(filename, ext));
2445         bool const success = theConverters().convert(this, FileName(filename),
2446                 tmp_result_file, FileName(absFileName()), backend_format, format,
2447                 errorList(error_type));
2448         // Emit the signal to show the error list.
2449         if (format != backend_format)
2450                 errors(error_type);
2451         if (!success)
2452                 return false;
2453
2454         if (put_in_tempdir)
2455                 result_file = tmp_result_file.absFilename();
2456         else {
2457                 result_file = changeExtension(absFileName(), ext);
2458                 // We need to copy referenced files (e. g. included graphics
2459                 // if format == "dvi") to the result dir.
2460                 vector<ExportedFile> const files =
2461                         runparams.exportdata->externalFiles(format);
2462                 string const dest = onlyPath(result_file);
2463                 CopyStatus status = SUCCESS;
2464                 for (vector<ExportedFile>::const_iterator it = files.begin();
2465                                 it != files.end() && status != CANCEL; ++it) {
2466                         string const fmt =
2467                                 formats.getFormatFromFile(it->sourceName);
2468                         status = copyFile(fmt, it->sourceName,
2469                                           makeAbsPath(it->exportName, dest),
2470                                           it->exportName, status == FORCE);
2471                 }
2472                 if (status == CANCEL) {
2473                         message(_("Document export cancelled."));
2474                 } else if (tmp_result_file.exists()) {
2475                         // Finally copy the main file
2476                         status = copyFile(format, tmp_result_file,
2477                                           FileName(result_file), result_file,
2478                                           status == FORCE);
2479                         message(bformat(_("Document exported as %1$s "
2480                                                                "to file `%2$s'"),
2481                                                 formats.prettyName(format),
2482                                                 makeDisplayPath(result_file)));
2483                 } else {
2484                         // This must be a dummy converter like fax (bug 1888)
2485                         message(bformat(_("Document exported as %1$s"),
2486                                                 formats.prettyName(format)));
2487                 }
2488         }
2489
2490         return true;
2491 }
2492
2493
2494 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2495 {
2496         string result_file;
2497         return doExport(format, put_in_tempdir, result_file);
2498 }
2499
2500
2501 bool Buffer::preview(string const & format) const
2502 {
2503         string result_file;
2504         if (!doExport(format, true, result_file))
2505                 return false;
2506         return formats.view(*this, FileName(result_file), format);
2507 }
2508
2509
2510 bool Buffer::isExportable(string const & format) const
2511 {
2512         vector<string> backs = backends();
2513         for (vector<string>::const_iterator it = backs.begin();
2514              it != backs.end(); ++it)
2515                 if (theConverters().isReachable(*it, format))
2516                         return true;
2517         return false;
2518 }
2519
2520
2521 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2522 {
2523         vector<string> backs = backends();
2524         vector<Format const *> result =
2525                 theConverters().getReachable(backs[0], only_viewable, true);
2526         for (vector<string>::const_iterator it = backs.begin() + 1;
2527              it != backs.end(); ++it) {
2528                 vector<Format const *>  r =
2529                         theConverters().getReachable(*it, only_viewable, false);
2530                 result.insert(result.end(), r.begin(), r.end());
2531         }
2532         return result;
2533 }
2534
2535
2536 vector<string> Buffer::backends() const
2537 {
2538         vector<string> v;
2539         if (params().getTextClass().isTeXClassAvailable()) {
2540                 v.push_back(bufferFormat());
2541                 // FIXME: Don't hardcode format names here, but use a flag
2542                 if (v.back() == "latex")
2543                         v.push_back("pdflatex");
2544         }
2545         v.push_back("text");
2546         v.push_back("lyx");
2547         return v;
2548 }
2549
2550
2551 bool Buffer::readFileHelper(FileName const & s)
2552 {
2553         // File information about normal file
2554         if (!s.exists()) {
2555                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2556                 docstring text = bformat(_("The specified document\n%1$s"
2557                                                      "\ncould not be read."), file);
2558                 Alert::error(_("Could not read document"), text);
2559                 return false;
2560         }
2561
2562         // Check if emergency save file exists and is newer.
2563         FileName const e(s.absFilename() + ".emergency");
2564
2565         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2566                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2567                 docstring const text =
2568                         bformat(_("An emergency save of the document "
2569                                   "%1$s exists.\n\n"
2570                                                "Recover emergency save?"), file);
2571                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2572                                       _("&Recover"),  _("&Load Original"),
2573                                       _("&Cancel")))
2574                 {
2575                 case 0:
2576                         // the file is not saved if we load the emergency file.
2577                         markDirty();
2578                         return readFile(e);
2579                 case 1:
2580                         break;
2581                 default:
2582                         return false;
2583                 }
2584         }
2585
2586         // Now check if autosave file is newer.
2587         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2588
2589         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2590                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2591                 docstring const text =
2592                         bformat(_("The backup of the document "
2593                                   "%1$s is newer.\n\nLoad the "
2594                                                "backup instead?"), file);
2595                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2596                                       _("&Load backup"), _("Load &original"),
2597                                       _("&Cancel") ))
2598                 {
2599                 case 0:
2600                         // the file is not saved if we load the autosave file.
2601                         markDirty();
2602                         return readFile(a);
2603                 case 1:
2604                         // Here we delete the autosave
2605                         a.removeFile();
2606                         break;
2607                 default:
2608                         return false;
2609                 }
2610         }
2611         return readFile(s);
2612 }
2613
2614
2615 bool Buffer::loadLyXFile(FileName const & s)
2616 {
2617         if (s.isReadableFile()) {
2618                 if (readFileHelper(s)) {
2619                         lyxvc().file_found_hook(s);
2620                         if (!s.isWritable())
2621                                 setReadonly(true);
2622                         return true;
2623                 }
2624         } else {
2625                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2626                 // Here we probably should run
2627                 if (LyXVC::file_not_found_hook(s)) {
2628                         docstring const text =
2629                                 bformat(_("Do you want to retrieve the document"
2630                                                        " %1$s from version control?"), file);
2631                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2632                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2633
2634                         if (ret == 0) {
2635                                 // How can we know _how_ to do the checkout?
2636                                 // With the current VC support it has to be,
2637                                 // a RCS file since CVS do not have special ,v files.
2638                                 RCS::retrieve(s);
2639                                 return loadLyXFile(s);
2640                         }
2641                 }
2642         }
2643         return false;
2644 }
2645
2646
2647 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2648 {
2649         TeXErrors::Errors::const_iterator cit = terr.begin();
2650         TeXErrors::Errors::const_iterator end = terr.end();
2651
2652         for (; cit != end; ++cit) {
2653                 int id_start = -1;
2654                 int pos_start = -1;
2655                 int errorRow = cit->error_in_line;
2656                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2657                                                        pos_start);
2658                 int id_end = -1;
2659                 int pos_end = -1;
2660                 do {
2661                         ++errorRow;
2662                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2663                 } while (found && id_start == id_end && pos_start == pos_end);
2664
2665                 errorList.push_back(ErrorItem(cit->error_desc,
2666                         cit->error_text, id_start, pos_start, pos_end));
2667         }
2668 }
2669
2670 } // namespace lyx