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