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