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