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