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