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