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