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