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