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