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