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