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