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