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