]> git.lyx.org Git - features.git/blob - src/Buffer.cpp
Rename a couple routines in preparation for more.
[features.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 = 361;  // jspitzm: bibliography custom width
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                 docstring styleinfo = features.getTClassHTMLStyles();
1381                 if (!styleinfo.empty()) {
1382                         os << "<style type='text/css'>\n";
1383                         os << styleinfo;
1384                         os << "</style>\n";
1385                 }
1386                 os << "</head>\n<body>\n";
1387         }
1388
1389         params().documentClass().counters().reset();
1390         xhtmlParagraphs(paragraphs(), *this, os, runparams);
1391         if (!only_body)
1392                 os << "</body>\n</html>\n";
1393 }
1394
1395
1396 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1397 // Other flags: -wall -v0 -x
1398 int Buffer::runChktex()
1399 {
1400         setBusy(true);
1401
1402         // get LaTeX-Filename
1403         FileName const path(temppath());
1404         string const name = addName(path.absFilename(), latexName());
1405         string const org_path = filePath();
1406
1407         PathChanger p(path); // path to LaTeX file
1408         message(_("Running chktex..."));
1409
1410         // Generate the LaTeX file if neccessary
1411         OutputParams runparams(&params().encoding());
1412         runparams.flavor = OutputParams::LATEX;
1413         runparams.nice = false;
1414         makeLaTeXFile(FileName(name), org_path, runparams);
1415
1416         TeXErrors terr;
1417         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1418         int const res = chktex.run(terr); // run chktex
1419
1420         if (res == -1) {
1421                 Alert::error(_("chktex failure"),
1422                              _("Could not run chktex successfully."));
1423         } else if (res > 0) {
1424                 ErrorList & errlist = d->errorLists["ChkTeX"];
1425                 errlist.clear();
1426                 bufferErrors(terr, errlist);
1427         }
1428
1429         setBusy(false);
1430
1431         errors("ChkTeX");
1432
1433         return res;
1434 }
1435
1436
1437 void Buffer::validate(LaTeXFeatures & features) const
1438 {
1439         params().validate(features);
1440
1441         updateMacros();
1442
1443         for_each(paragraphs().begin(), paragraphs().end(),
1444                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1445
1446         if (lyxerr.debugging(Debug::LATEX)) {
1447                 features.showStruct();
1448         }
1449 }
1450
1451
1452 void Buffer::getLabelList(vector<docstring> & list) const
1453 {
1454         // If this is a child document, use the parent's list instead.
1455         Buffer const * const pbuf = d->parent();
1456         if (pbuf) {
1457                 pbuf->getLabelList(list);
1458                 return;
1459         }
1460
1461         list.clear();
1462         Toc & toc = d->toc_backend.toc("label");
1463         TocIterator toc_it = toc.begin();
1464         TocIterator end = toc.end();
1465         for (; toc_it != end; ++toc_it) {
1466                 if (toc_it->depth() == 0)
1467                         list.push_back(toc_it->str());
1468         }
1469 }
1470
1471
1472 void Buffer::updateBibfilesCache(UpdateScope scope) const
1473 {
1474         // If this is a child document, use the parent's cache instead.
1475         Buffer const * const pbuf = d->parent();
1476         if (pbuf && scope != UpdateChildOnly) {
1477                 pbuf->updateBibfilesCache();
1478                 return;
1479         }
1480
1481         d->bibfilesCache_.clear();
1482         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1483                 if (it->lyxCode() == BIBTEX_CODE) {
1484                         InsetBibtex const & inset =
1485                                 static_cast<InsetBibtex const &>(*it);
1486                         support::FileNameList const bibfiles = inset.getBibFiles();
1487                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1488                                 bibfiles.begin(),
1489                                 bibfiles.end());
1490                 } else if (it->lyxCode() == INCLUDE_CODE) {
1491                         InsetInclude & inset =
1492                                 static_cast<InsetInclude &>(*it);
1493                         inset.updateBibfilesCache();
1494                         support::FileNameList const & bibfiles =
1495                                         inset.getBibfilesCache();
1496                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1497                                 bibfiles.begin(),
1498                                 bibfiles.end());
1499                 }
1500         }
1501         // the bibinfo cache is now invalid
1502         d->bibinfoCacheValid_ = false;
1503 }
1504
1505
1506 void Buffer::invalidateBibinfoCache()
1507 {
1508         d->bibinfoCacheValid_ = false;
1509 }
1510
1511
1512 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1513 {
1514         // If this is a child document, use the parent's cache instead.
1515         Buffer const * const pbuf = d->parent();
1516         if (pbuf && scope != UpdateChildOnly)
1517                 return pbuf->getBibfilesCache();
1518
1519         // We update the cache when first used instead of at loading time.
1520         if (d->bibfilesCache_.empty())
1521                 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1522
1523         return d->bibfilesCache_;
1524 }
1525
1526
1527 BiblioInfo const & Buffer::masterBibInfo() const
1528 {
1529         // if this is a child document and the parent is already loaded
1530         // use the parent's list instead  [ale990412]
1531         Buffer const * const tmp = masterBuffer();
1532         LASSERT(tmp, /**/);
1533         if (tmp != this)
1534                 return tmp->masterBibInfo();
1535         return localBibInfo();
1536 }
1537
1538
1539 BiblioInfo const & Buffer::localBibInfo() const
1540 {
1541         if (d->bibinfoCacheValid_) {
1542                 support::FileNameList const & bibfilesCache = getBibfilesCache();
1543                 // compare the cached timestamps with the actual ones.
1544                 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1545                 support::FileNameList::const_iterator en = bibfilesCache.end();
1546                 for (; ei != en; ++ ei) {
1547                         time_t lastw = ei->lastModified();
1548                         if (lastw != d->bibfileStatus_[*ei]) {
1549                                 d->bibinfoCacheValid_ = false;
1550                                 d->bibfileStatus_[*ei] = lastw;
1551                                 break;
1552                         }
1553                 }
1554         }
1555
1556         if (!d->bibinfoCacheValid_) {
1557                 d->bibinfo_.clear();
1558                 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1559                         it->fillWithBibKeys(d->bibinfo_, it);
1560                 d->bibinfoCacheValid_ = true;
1561         }
1562         return d->bibinfo_;
1563 }
1564
1565
1566 bool Buffer::isDepClean(string const & name) const
1567 {
1568         DepClean::const_iterator const it = d->dep_clean.find(name);
1569         if (it == d->dep_clean.end())
1570                 return true;
1571         return it->second;
1572 }
1573
1574
1575 void Buffer::markDepClean(string const & name)
1576 {
1577         d->dep_clean[name] = true;
1578 }
1579
1580
1581 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1582 {
1583         switch (cmd.action) {
1584                 case LFUN_BUFFER_EXPORT: {
1585                         docstring const arg = cmd.argument();
1586                         bool enable = arg == "custom" || isExportable(to_utf8(arg));
1587                         if (!enable)
1588                                 flag.message(bformat(
1589                                         _("Don't know how to export to format: %1$s"), arg));
1590                         flag.setEnabled(enable);
1591                         break;
1592                 }
1593
1594                 case LFUN_BRANCH_ACTIVATE: 
1595                 case LFUN_BRANCH_DEACTIVATE: {
1596                 BranchList const & branchList = params().branchlist();
1597                 docstring const branchName = cmd.argument();
1598                 flag.setEnabled(!branchName.empty()
1599                                 && branchList.find(branchName));
1600                         break;
1601                 }
1602
1603                 case LFUN_BUFFER_PRINT:
1604                         // if no Buffer is present, then of course we won't be called!
1605                         flag.setEnabled(true);
1606                         break;
1607
1608                 default:
1609                         return false;
1610         }
1611         return true;
1612 }
1613
1614
1615 void Buffer::dispatch(string const & command, DispatchResult & result)
1616 {
1617         return dispatch(lyxaction.lookupFunc(command), result);
1618 }
1619
1620
1621 // NOTE We can end up here even if we have no GUI, because we are called
1622 // by LyX::exec to handled command-line requests. So we may need to check 
1623 // whether we have a GUI or not. The boolean use_gui holds this information.
1624 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1625 {
1626         // We'll set this back to false if need be.
1627         bool dispatched = true;
1628
1629         switch (func.action) {
1630         case LFUN_BUFFER_EXPORT: {
1631                 bool success = doExport(to_utf8(func.argument()), false);
1632                 dr.setError(success);
1633                 if (!success)
1634                         dr.setMessage(bformat(_("Error exporting to format: %1$s."), 
1635                                               func.argument()));
1636                 break;
1637         }
1638
1639         case LFUN_BRANCH_ACTIVATE:
1640         case LFUN_BRANCH_DEACTIVATE: {
1641                 BranchList & branchList = params().branchlist();
1642                 docstring const branchName = func.argument();
1643                 // the case without a branch name is handled elsewhere
1644                 if (branchName.empty()) {
1645                         dispatched = false;
1646                         break;
1647                 }
1648                 Branch * branch = branchList.find(branchName);
1649                 if (!branch) {
1650                         LYXERR0("Branch " << branchName << " does not exist.");
1651                         dr.setError(true);
1652                         docstring const msg = 
1653                                 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1654                         dr.setMessage(msg);
1655                 } else {
1656                         branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1657                         dr.setError(false);
1658                         dr.update(Update::Force);
1659                 }
1660                 break;
1661         }
1662
1663         case LFUN_BUFFER_PRINT: {
1664                 // we'll assume there's a problem until we succeed
1665                 dr.setError(true); 
1666                 string target = func.getArg(0);
1667                 string target_name = func.getArg(1);
1668                 string command = func.getArg(2);
1669
1670                 if (target.empty()
1671                     || target_name.empty()
1672                     || command.empty()) {
1673                         LYXERR0("Unable to parse " << func.argument());
1674                         docstring const msg = 
1675                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
1676                         dr.setMessage(msg);
1677                         break;
1678                 }
1679                 if (target != "printer" && target != "file") {
1680                         LYXERR0("Unrecognized target \"" << target << '"');
1681                         docstring const msg = 
1682                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1683                         dr.setMessage(msg);
1684                         break;
1685                 }
1686
1687                 if (!doExport("dvi", true)) {
1688                         showPrintError(absFileName());
1689                         dr.setMessage(_("Error exporting to DVI."));
1690                         break;
1691                 }
1692
1693                 // Push directory path.
1694                 string const path = temppath();
1695                 // Prevent the compiler from optimizing away p
1696                 FileName pp(path);
1697                 PathChanger p(pp);
1698
1699                 // there are three cases here:
1700                 // 1. we print to a file
1701                 // 2. we print directly to a printer
1702                 // 3. we print using a spool command (print to file first)
1703                 Systemcall one;
1704                 int res = 0;
1705                 string const dviname = changeExtension(latexName(true), "dvi");
1706
1707                 if (target == "printer") {
1708                         if (!lyxrc.print_spool_command.empty()) {
1709                                 // case 3: print using a spool
1710                                 string const psname = changeExtension(dviname,".ps");
1711                                 command += ' ' + lyxrc.print_to_file
1712                                         + quoteName(psname)
1713                                         + ' '
1714                                         + quoteName(dviname);
1715
1716                                 string command2 = lyxrc.print_spool_command + ' ';
1717                                 if (target_name != "default") {
1718                                         command2 += lyxrc.print_spool_printerprefix
1719                                                 + target_name
1720                                                 + ' ';
1721                                 }
1722                                 command2 += quoteName(psname);
1723                                 // First run dvips.
1724                                 // If successful, then spool command
1725                                 res = one.startscript(Systemcall::Wait, command);
1726
1727                                 if (res == 0) {
1728                                         // If there's no GUI, we have to wait on this command. Otherwise,
1729                                         // LyX deletes the temporary directory, and with it the spooled
1730                                         // file, before it can be printed!!
1731                                         Systemcall::Starttype stype = use_gui ?
1732                                                 Systemcall::DontWait : Systemcall::Wait;
1733                                         res = one.startscript(stype, command2);
1734                                 }
1735                         } else {
1736                                 // case 2: print directly to a printer
1737                                 if (target_name != "default")
1738                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1739                                 // as above....
1740                                 Systemcall::Starttype stype = use_gui ?
1741                                         Systemcall::DontWait : Systemcall::Wait;
1742                                 res = one.startscript(stype, command + quoteName(dviname));
1743                         }
1744
1745                 } else {
1746                         // case 1: print to a file
1747                         FileName const filename(makeAbsPath(target_name, filePath()));
1748                         FileName const dvifile(makeAbsPath(dviname, path));
1749                         if (filename.exists()) {
1750                                 docstring text = bformat(
1751                                         _("The file %1$s already exists.\n\n"
1752                                           "Do you want to overwrite that file?"),
1753                                         makeDisplayPath(filename.absFilename()));
1754                                 if (Alert::prompt(_("Overwrite file?"),
1755                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1756                                         break;
1757                         }
1758                         command += ' ' + lyxrc.print_to_file
1759                                 + quoteName(filename.toFilesystemEncoding())
1760                                 + ' '
1761                                 + quoteName(dvifile.toFilesystemEncoding());
1762                         // as above....
1763                         Systemcall::Starttype stype = use_gui ?
1764                                 Systemcall::DontWait : Systemcall::Wait;
1765                         res = one.startscript(stype, command);
1766                 }
1767
1768                 if (res == 0) 
1769                         dr.setError(false);
1770                 else {
1771                         dr.setMessage(_("Error running external commands."));
1772                         showPrintError(absFileName());
1773                 }
1774                 break;
1775         }
1776
1777         default:
1778                 dispatched = false;
1779                 break;
1780         }
1781         dr.dispatched(dispatched);
1782 }
1783
1784
1785 void Buffer::changeLanguage(Language const * from, Language const * to)
1786 {
1787         LASSERT(from, /**/);
1788         LASSERT(to, /**/);
1789
1790         for_each(par_iterator_begin(),
1791                  par_iterator_end(),
1792                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1793 }
1794
1795
1796 bool Buffer::isMultiLingual() const
1797 {
1798         ParConstIterator end = par_iterator_end();
1799         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1800                 if (it->isMultiLingual(params()))
1801                         return true;
1802
1803         return false;
1804 }
1805
1806
1807 DocIterator Buffer::getParFromID(int const id) const
1808 {
1809         Buffer * buf = const_cast<Buffer *>(this);
1810         if (id < 0) {
1811                 // John says this is called with id == -1 from undo
1812                 lyxerr << "getParFromID(), id: " << id << endl;
1813                 return doc_iterator_end(buf);
1814         }
1815
1816         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1817                 if (it.paragraph().id() == id)
1818                         return it;
1819
1820         return doc_iterator_end(buf);
1821 }
1822
1823
1824 bool Buffer::hasParWithID(int const id) const
1825 {
1826         return !getParFromID(id).atEnd();
1827 }
1828
1829
1830 ParIterator Buffer::par_iterator_begin()
1831 {
1832         return ParIterator(doc_iterator_begin(this));
1833 }
1834
1835
1836 ParIterator Buffer::par_iterator_end()
1837 {
1838         return ParIterator(doc_iterator_end(this));
1839 }
1840
1841
1842 ParConstIterator Buffer::par_iterator_begin() const
1843 {
1844         return ParConstIterator(doc_iterator_begin(this));
1845 }
1846
1847
1848 ParConstIterator Buffer::par_iterator_end() const
1849 {
1850         return ParConstIterator(doc_iterator_end(this));
1851 }
1852
1853
1854 Language const * Buffer::language() const
1855 {
1856         return params().language;
1857 }
1858
1859
1860 docstring const Buffer::B_(string const & l10n) const
1861 {
1862         return params().B_(l10n);
1863 }
1864
1865
1866 bool Buffer::isClean() const
1867 {
1868         return d->lyx_clean;
1869 }
1870
1871
1872 bool Buffer::isBakClean() const
1873 {
1874         return d->bak_clean;
1875 }
1876
1877
1878 bool Buffer::isExternallyModified(CheckMethod method) const
1879 {
1880         LASSERT(d->filename.exists(), /**/);
1881         // if method == timestamp, check timestamp before checksum
1882         return (method == checksum_method
1883                 || d->timestamp_ != d->filename.lastModified())
1884                 && d->checksum_ != d->filename.checksum();
1885 }
1886
1887
1888 void Buffer::saveCheckSum(FileName const & file) const
1889 {
1890         if (file.exists()) {
1891                 d->timestamp_ = file.lastModified();
1892                 d->checksum_ = file.checksum();
1893         } else {
1894                 // in the case of save to a new file.
1895                 d->timestamp_ = 0;
1896                 d->checksum_ = 0;
1897         }
1898 }
1899
1900
1901 void Buffer::markClean() const
1902 {
1903         if (!d->lyx_clean) {
1904                 d->lyx_clean = true;
1905                 updateTitles();
1906         }
1907         // if the .lyx file has been saved, we don't need an
1908         // autosave
1909         d->bak_clean = true;
1910 }
1911
1912
1913 void Buffer::markBakClean() const
1914 {
1915         d->bak_clean = true;
1916 }
1917
1918
1919 void Buffer::setUnnamed(bool flag)
1920 {
1921         d->unnamed = flag;
1922 }
1923
1924
1925 bool Buffer::isUnnamed() const
1926 {
1927         return d->unnamed;
1928 }
1929
1930
1931 // FIXME: this function should be moved to buffer_pimpl.C
1932 void Buffer::markDirty()
1933 {
1934         if (d->lyx_clean) {
1935                 d->lyx_clean = false;
1936                 updateTitles();
1937         }
1938         d->bak_clean = false;
1939
1940         DepClean::iterator it = d->dep_clean.begin();
1941         DepClean::const_iterator const end = d->dep_clean.end();
1942
1943         for (; it != end; ++it)
1944                 it->second = false;
1945 }
1946
1947
1948 FileName Buffer::fileName() const
1949 {
1950         return d->filename;
1951 }
1952
1953
1954 string Buffer::absFileName() const
1955 {
1956         return d->filename.absFilename();
1957 }
1958
1959
1960 string Buffer::filePath() const
1961 {
1962         return d->filename.onlyPath().absFilename() + "/";
1963 }
1964
1965
1966 bool Buffer::isReadonly() const
1967 {
1968         return d->read_only;
1969 }
1970
1971
1972 void Buffer::setParent(Buffer const * buffer)
1973 {
1974         // Avoids recursive include.
1975         d->setParent(buffer == this ? 0 : buffer);
1976         updateMacros();
1977 }
1978
1979
1980 Buffer const * Buffer::parent() const
1981 {
1982         return d->parent();
1983 }
1984
1985
1986 void Buffer::collectRelatives(BufferSet & bufs) const
1987 {
1988         bufs.insert(this);
1989         if (parent())
1990                 parent()->collectRelatives(bufs);
1991
1992         // loop over children
1993         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1994         Impl::BufferPositionMap::iterator end = d->children_positions.end();
1995         for (; it != end; ++it)
1996                 bufs.insert(const_cast<Buffer *>(it->first));
1997 }
1998
1999
2000 std::vector<Buffer const *> Buffer::allRelatives() const
2001 {
2002         BufferSet bufs;
2003         collectRelatives(bufs);
2004         BufferSet::iterator it = bufs.begin();
2005         std::vector<Buffer const *> ret;
2006         for (; it != bufs.end(); ++it)
2007                 ret.push_back(*it);
2008         return ret;
2009 }
2010
2011
2012 Buffer const * Buffer::masterBuffer() const
2013 {
2014         Buffer const * const pbuf = d->parent();
2015         if (!pbuf)
2016                 return this;
2017
2018         return pbuf->masterBuffer();
2019 }
2020
2021
2022 bool Buffer::isChild(Buffer * child) const
2023 {
2024         return d->children_positions.find(child) != d->children_positions.end();
2025 }
2026
2027
2028 DocIterator Buffer::firstChildPosition(Buffer const * child)
2029 {
2030         Impl::BufferPositionMap::iterator it;
2031         it = d->children_positions.find(child);
2032         if (it == d->children_positions.end())
2033                 return DocIterator(this);
2034         return it->second;
2035 }
2036
2037
2038 std::vector<Buffer *> Buffer::getChildren() const
2039 {
2040         std::vector<Buffer *> clist;
2041         // loop over children
2042         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2043         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2044         for (; it != end; ++it) {
2045                 Buffer * child = const_cast<Buffer *>(it->first);
2046                 clist.push_back(child);
2047                 // there might be grandchildren
2048                 std::vector<Buffer *> glist = child->getChildren();
2049                 for (vector<Buffer *>::const_iterator git = glist.begin();
2050                      git != glist.end(); ++git)
2051                         clist.push_back(*git);
2052         }
2053         return clist;
2054 }
2055
2056
2057 template<typename M>
2058 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2059 {
2060         if (m.empty())
2061                 return m.end();
2062
2063         typename M::iterator it = m.lower_bound(x);
2064         if (it == m.begin())
2065                 return m.end();
2066
2067         it--;
2068         return it;
2069 }
2070
2071
2072 MacroData const * Buffer::getBufferMacro(docstring const & name,
2073                                          DocIterator const & pos) const
2074 {
2075         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2076
2077         // if paragraphs have no macro context set, pos will be empty
2078         if (pos.empty())
2079                 return 0;
2080
2081         // we haven't found anything yet
2082         DocIterator bestPos = par_iterator_begin();
2083         MacroData const * bestData = 0;
2084
2085         // find macro definitions for name
2086         Impl::NamePositionScopeMacroMap::iterator nameIt
2087                 = d->macros.find(name);
2088         if (nameIt != d->macros.end()) {
2089                 // find last definition in front of pos or at pos itself
2090                 Impl::PositionScopeMacroMap::const_iterator it
2091                         = greatest_below(nameIt->second, pos);
2092                 if (it != nameIt->second.end()) {
2093                         while (true) {
2094                                 // scope ends behind pos?
2095                                 if (pos < it->second.first) {
2096                                         // Looks good, remember this. If there
2097                                         // is no external macro behind this,
2098                                         // we found the right one already.
2099                                         bestPos = it->first;
2100                                         bestData = &it->second.second;
2101                                         break;
2102                                 }
2103
2104                                 // try previous macro if there is one
2105                                 if (it == nameIt->second.begin())
2106                                         break;
2107                                 it--;
2108                         }
2109                 }
2110         }
2111
2112         // find macros in included files
2113         Impl::PositionScopeBufferMap::const_iterator it
2114                 = greatest_below(d->position_to_children, pos);
2115         if (it == d->position_to_children.end())
2116                 // no children before
2117                 return bestData;
2118
2119         while (true) {
2120                 // do we know something better (i.e. later) already?
2121                 if (it->first < bestPos )
2122                         break;
2123
2124                 // scope ends behind pos?
2125                 if (pos < it->second.first) {
2126                         // look for macro in external file
2127                         d->macro_lock = true;
2128                         MacroData const * data
2129                         = it->second.second->getMacro(name, false);
2130                         d->macro_lock = false;
2131                         if (data) {
2132                                 bestPos = it->first;
2133                                 bestData = data;
2134                                 break;
2135                         }
2136                 }
2137
2138                 // try previous file if there is one
2139                 if (it == d->position_to_children.begin())
2140                         break;
2141                 --it;
2142         }
2143
2144         // return the best macro we have found
2145         return bestData;
2146 }
2147
2148
2149 MacroData const * Buffer::getMacro(docstring const & name,
2150         DocIterator const & pos, bool global) const
2151 {
2152         if (d->macro_lock)
2153                 return 0;
2154
2155         // query buffer macros
2156         MacroData const * data = getBufferMacro(name, pos);
2157         if (data != 0)
2158                 return data;
2159
2160         // If there is a master buffer, query that
2161         Buffer const * const pbuf = d->parent();
2162         if (pbuf) {
2163                 d->macro_lock = true;
2164                 MacroData const * macro = pbuf->getMacro(
2165                         name, *this, false);
2166                 d->macro_lock = false;
2167                 if (macro)
2168                         return macro;
2169         }
2170
2171         if (global) {
2172                 data = MacroTable::globalMacros().get(name);
2173                 if (data != 0)
2174                         return data;
2175         }
2176
2177         return 0;
2178 }
2179
2180
2181 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2182 {
2183         // set scope end behind the last paragraph
2184         DocIterator scope = par_iterator_begin();
2185         scope.pit() = scope.lastpit() + 1;
2186
2187         return getMacro(name, scope, global);
2188 }
2189
2190
2191 MacroData const * Buffer::getMacro(docstring const & name,
2192         Buffer const & child, bool global) const
2193 {
2194         // look where the child buffer is included first
2195         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2196         if (it == d->children_positions.end())
2197                 return 0;
2198
2199         // check for macros at the inclusion position
2200         return getMacro(name, it->second, global);
2201 }
2202
2203
2204 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2205 {
2206         pit_type lastpit = it.lastpit();
2207
2208         // look for macros in each paragraph
2209         while (it.pit() <= lastpit) {
2210                 Paragraph & par = it.paragraph();
2211
2212                 // iterate over the insets of the current paragraph
2213                 InsetList const & insets = par.insetList();
2214                 InsetList::const_iterator iit = insets.begin();
2215                 InsetList::const_iterator end = insets.end();
2216                 for (; iit != end; ++iit) {
2217                         it.pos() = iit->pos;
2218
2219                         // is it a nested text inset?
2220                         if (iit->inset->asInsetText()) {
2221                                 // Inset needs its own scope?
2222                                 InsetText const * itext = iit->inset->asInsetText();
2223                                 bool newScope = itext->isMacroScope();
2224
2225                                 // scope which ends just behind the inset
2226                                 DocIterator insetScope = it;
2227                                 ++insetScope.pos();
2228
2229                                 // collect macros in inset
2230                                 it.push_back(CursorSlice(*iit->inset));
2231                                 updateMacros(it, newScope ? insetScope : scope);
2232                                 it.pop_back();
2233                                 continue;
2234                         }
2235
2236                         // is it an external file?
2237                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2238                                 // get buffer of external file
2239                                 InsetInclude const & inset =
2240                                         static_cast<InsetInclude const &>(*iit->inset);
2241                                 d->macro_lock = true;
2242                                 Buffer * child = inset.getChildBuffer();
2243                                 d->macro_lock = false;
2244                                 if (!child)
2245                                         continue;
2246
2247                                 // register its position, but only when it is
2248                                 // included first in the buffer
2249                                 if (d->children_positions.find(child) ==
2250                                         d->children_positions.end())
2251                                                 d->children_positions[child] = it;
2252
2253                                 // register child with its scope
2254                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2255                                 continue;
2256                         }
2257
2258                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2259                                 continue;
2260
2261                         // get macro data
2262                         MathMacroTemplate & macroTemplate =
2263                                 static_cast<MathMacroTemplate &>(*iit->inset);
2264                         MacroContext mc(*this, it);
2265                         macroTemplate.updateToContext(mc);
2266
2267                         // valid?
2268                         bool valid = macroTemplate.validMacro();
2269                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2270                         // then the BufferView's cursor will be invalid in
2271                         // some cases which leads to crashes.
2272                         if (!valid)
2273                                 continue;
2274
2275                         // register macro
2276                         d->macros[macroTemplate.name()][it] =
2277                                 Impl::ScopeMacro(scope, MacroData(*this, it));
2278                 }
2279
2280                 // next paragraph
2281                 it.pit()++;
2282                 it.pos() = 0;
2283         }
2284 }
2285
2286
2287 void Buffer::updateMacros() const
2288 {
2289         if (d->macro_lock)
2290                 return;
2291
2292         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2293
2294         // start with empty table
2295         d->macros.clear();
2296         d->children_positions.clear();
2297         d->position_to_children.clear();
2298
2299         // Iterate over buffer, starting with first paragraph
2300         // The scope must be bigger than any lookup DocIterator
2301         // later. For the global lookup, lastpit+1 is used, hence
2302         // we use lastpit+2 here.
2303         DocIterator it = par_iterator_begin();
2304         DocIterator outerScope = it;
2305         outerScope.pit() = outerScope.lastpit() + 2;
2306         updateMacros(it, outerScope);
2307 }
2308
2309
2310 void Buffer::updateMacroInstances() const
2311 {
2312         LYXERR(Debug::MACROS, "updateMacroInstances for "
2313                 << d->filename.onlyFileName());
2314         DocIterator it = doc_iterator_begin(this);
2315         DocIterator end = doc_iterator_end(this);
2316         for (; it != end; it.forwardPos()) {
2317                 // look for MathData cells in InsetMathNest insets
2318                 Inset * inset = it.nextInset();
2319                 if (!inset)
2320                         continue;
2321
2322                 InsetMath * minset = inset->asInsetMath();
2323                 if (!minset)
2324                         continue;
2325
2326                 // update macro in all cells of the InsetMathNest
2327                 DocIterator::idx_type n = minset->nargs();
2328                 MacroContext mc = MacroContext(*this, it);
2329                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2330                         MathData & data = minset->cell(i);
2331                         data.updateMacros(0, mc);
2332                 }
2333         }
2334 }
2335
2336
2337 void Buffer::listMacroNames(MacroNameSet & macros) const
2338 {
2339         if (d->macro_lock)
2340                 return;
2341
2342         d->macro_lock = true;
2343
2344         // loop over macro names
2345         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2346         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2347         for (; nameIt != nameEnd; ++nameIt)
2348                 macros.insert(nameIt->first);
2349
2350         // loop over children
2351         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2352         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2353         for (; it != end; ++it)
2354                 it->first->listMacroNames(macros);
2355
2356         // call parent
2357         Buffer const * const pbuf = d->parent();
2358         if (pbuf)
2359                 pbuf->listMacroNames(macros);
2360
2361         d->macro_lock = false;
2362 }
2363
2364
2365 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2366 {
2367         Buffer const * const pbuf = d->parent();
2368         if (!pbuf)
2369                 return;
2370
2371         MacroNameSet names;
2372         pbuf->listMacroNames(names);
2373
2374         // resolve macros
2375         MacroNameSet::iterator it = names.begin();
2376         MacroNameSet::iterator end = names.end();
2377         for (; it != end; ++it) {
2378                 // defined?
2379                 MacroData const * data =
2380                 pbuf->getMacro(*it, *this, false);
2381                 if (data) {
2382                         macros.insert(data);
2383
2384                         // we cannot access the original MathMacroTemplate anymore
2385                         // here to calls validate method. So we do its work here manually.
2386                         // FIXME: somehow make the template accessible here.
2387                         if (data->optionals() > 0)
2388                                 features.require("xargs");
2389                 }
2390         }
2391 }
2392
2393
2394 Buffer::References & Buffer::references(docstring const & label)
2395 {
2396         if (d->parent())
2397                 return const_cast<Buffer *>(masterBuffer())->references(label);
2398
2399         RefCache::iterator it = d->ref_cache_.find(label);
2400         if (it != d->ref_cache_.end())
2401                 return it->second.second;
2402
2403         static InsetLabel const * dummy_il = 0;
2404         static References const dummy_refs;
2405         it = d->ref_cache_.insert(
2406                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2407         return it->second.second;
2408 }
2409
2410
2411 Buffer::References const & Buffer::references(docstring const & label) const
2412 {
2413         return const_cast<Buffer *>(this)->references(label);
2414 }
2415
2416
2417 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2418 {
2419         masterBuffer()->d->ref_cache_[label].first = il;
2420 }
2421
2422
2423 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2424 {
2425         return masterBuffer()->d->ref_cache_[label].first;
2426 }
2427
2428
2429 void Buffer::clearReferenceCache() const
2430 {
2431         if (!d->parent())
2432                 d->ref_cache_.clear();
2433 }
2434
2435
2436 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2437         InsetCode code)
2438 {
2439         //FIXME: This does not work for child documents yet.
2440         LASSERT(code == CITE_CODE, /**/);
2441         // Check if the label 'from' appears more than once
2442         vector<docstring> labels;
2443         string paramName;
2444         BiblioInfo const & keys = masterBibInfo();
2445         BiblioInfo::const_iterator bit  = keys.begin();
2446         BiblioInfo::const_iterator bend = keys.end();
2447
2448         for (; bit != bend; ++bit)
2449                 // FIXME UNICODE
2450                 labels.push_back(bit->first);
2451         paramName = "key";
2452
2453         if (count(labels.begin(), labels.end(), from) > 1)
2454                 return;
2455
2456         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2457                 if (it->lyxCode() == code) {
2458                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2459                         docstring const oldValue = inset.getParam(paramName);
2460                         if (oldValue == from)
2461                                 inset.setParam(paramName, to);
2462                 }
2463         }
2464 }
2465
2466
2467 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2468         pit_type par_end, bool full_source) const
2469 {
2470         OutputParams runparams(&params().encoding());
2471         runparams.nice = true;
2472         runparams.flavor = params().useXetex ? 
2473                 OutputParams::XETEX : OutputParams::LATEX;
2474         runparams.linelen = lyxrc.plaintext_linelen;
2475         // No side effect of file copying and image conversion
2476         runparams.dryrun = true;
2477
2478         if (full_source) {
2479                 os << "% " << _("Preview source code") << "\n\n";
2480                 d->texrow.reset();
2481                 d->texrow.newline();
2482                 d->texrow.newline();
2483                 if (isDocBook())
2484                         writeDocBookSource(os, absFileName(), runparams, false);
2485                 else
2486                         // latex or literate
2487                         writeLaTeXSource(os, string(), runparams, true, true);
2488         } else {
2489                 runparams.par_begin = par_begin;
2490                 runparams.par_end = par_end;
2491                 if (par_begin + 1 == par_end) {
2492                         os << "% "
2493                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2494                            << "\n\n";
2495                 } else {
2496                         os << "% "
2497                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2498                                         convert<docstring>(par_begin),
2499                                         convert<docstring>(par_end - 1))
2500                            << "\n\n";
2501                 }
2502                 TexRow texrow;
2503                 texrow.reset();
2504                 texrow.newline();
2505                 texrow.newline();
2506                 // output paragraphs
2507                 if (isDocBook())
2508                         docbookParagraphs(paragraphs(), *this, os, runparams);
2509                 else 
2510                         // latex or literate
2511                         latexParagraphs(*this, text(), os, texrow, runparams);
2512         }
2513 }
2514
2515
2516 ErrorList & Buffer::errorList(string const & type) const
2517 {
2518         static ErrorList emptyErrorList;
2519         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2520         if (I == d->errorLists.end())
2521                 return emptyErrorList;
2522
2523         return I->second;
2524 }
2525
2526
2527 void Buffer::updateTocItem(std::string const & type,
2528         DocIterator const & dit) const
2529 {
2530         if (gui_)
2531                 gui_->updateTocItem(type, dit);
2532 }
2533
2534
2535 void Buffer::structureChanged() const
2536 {
2537         if (gui_)
2538                 gui_->structureChanged();
2539 }
2540
2541
2542 void Buffer::errors(string const & err) const
2543 {
2544         if (gui_)
2545                 gui_->errors(err);
2546 }
2547
2548
2549 void Buffer::message(docstring const & msg) const
2550 {
2551         if (gui_)
2552                 gui_->message(msg);
2553 }
2554
2555
2556 void Buffer::setBusy(bool on) const
2557 {
2558         if (gui_)
2559                 gui_->setBusy(on);
2560 }
2561
2562
2563 void Buffer::setReadOnly(bool on) const
2564 {
2565         if (d->wa_)
2566                 d->wa_->setReadOnly(on);
2567 }
2568
2569
2570 void Buffer::updateTitles() const
2571 {
2572         if (d->wa_)
2573                 d->wa_->updateTitles();
2574 }
2575
2576
2577 void Buffer::resetAutosaveTimers() const
2578 {
2579         if (gui_)
2580                 gui_->resetAutosaveTimers();
2581 }
2582
2583
2584 bool Buffer::hasGuiDelegate() const
2585 {
2586         return gui_;
2587 }
2588
2589
2590 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2591 {
2592         gui_ = gui;
2593 }
2594
2595
2596
2597 namespace {
2598
2599 class AutoSaveBuffer : public ForkedProcess {
2600 public:
2601         ///
2602         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2603                 : buffer_(buffer), fname_(fname) {}
2604         ///
2605         virtual boost::shared_ptr<ForkedProcess> clone() const
2606         {
2607                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2608         }
2609         ///
2610         int start()
2611         {
2612                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2613                                                  from_utf8(fname_.absFilename())));
2614                 return run(DontWait);
2615         }
2616 private:
2617         ///
2618         virtual int generateChild();
2619         ///
2620         Buffer const & buffer_;
2621         FileName fname_;
2622 };
2623
2624
2625 int AutoSaveBuffer::generateChild()
2626 {
2627         // tmp_ret will be located (usually) in /tmp
2628         // will that be a problem?
2629         // Note that this calls ForkedCalls::fork(), so it's
2630         // ok cross-platform.
2631         pid_t const pid = fork();
2632         // If you want to debug the autosave
2633         // you should set pid to -1, and comment out the fork.
2634         if (pid != 0 && pid != -1)
2635                 return pid;
2636
2637         // pid = -1 signifies that lyx was unable
2638         // to fork. But we will do the save
2639         // anyway.
2640         bool failed = false;
2641         FileName const tmp_ret = FileName::tempName("lyxauto");
2642         if (!tmp_ret.empty()) {
2643                 buffer_.writeFile(tmp_ret);
2644                 // assume successful write of tmp_ret
2645                 if (!tmp_ret.moveTo(fname_))
2646                         failed = true;
2647         } else
2648                 failed = true;
2649
2650         if (failed) {
2651                 // failed to write/rename tmp_ret so try writing direct
2652                 if (!buffer_.writeFile(fname_)) {
2653                         // It is dangerous to do this in the child,
2654                         // but safe in the parent, so...
2655                         if (pid == -1) // emit message signal.
2656                                 buffer_.message(_("Autosave failed!"));
2657                 }
2658         }
2659
2660         if (pid == 0) // we are the child so...
2661                 _exit(0);
2662
2663         return pid;
2664 }
2665
2666 } // namespace anon
2667
2668
2669 FileName Buffer::getAutosaveFilename() const
2670 {
2671         // if the document is unnamed try to save in the backup dir, else
2672         // in the default document path, and as a last try in the filePath, 
2673         // which will most often be the temporary directory
2674         string fpath;
2675         if (isUnnamed())
2676                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
2677                         : lyxrc.backupdir_path;
2678         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
2679                 fpath = filePath();
2680
2681         string const fname = "#" + d->filename.onlyFileName() + "#";
2682         return makeAbsPath(fname, fpath);
2683 }
2684
2685
2686 void Buffer::removeAutosaveFile() const
2687 {
2688         FileName const f = getAutosaveFilename();
2689         if (f.exists())
2690                 f.removeFile();
2691 }
2692
2693
2694 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2695 {
2696         FileName const newauto = getAutosaveFilename();
2697         if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2698                 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2699 }
2700
2701
2702 // Perfect target for a thread...
2703 void Buffer::autoSave() const
2704 {
2705         if (isBakClean() || isReadonly()) {
2706                 // We don't save now, but we'll try again later
2707                 resetAutosaveTimers();
2708                 return;
2709         }
2710
2711         // emit message signal.
2712         message(_("Autosaving current document..."));
2713         AutoSaveBuffer autosave(*this, getAutosaveFilename());
2714         autosave.start();
2715
2716         markBakClean();
2717         resetAutosaveTimers();
2718 }
2719
2720
2721 string Buffer::bufferFormat() const
2722 {
2723         string format = params().documentClass().outputFormat();
2724         if (format == "latex") {
2725                 if (params().useXetex)
2726                         return "xetex";
2727                 if (params().encoding().package() == Encoding::japanese)
2728                         return "platex";
2729         }
2730         return format;
2731 }
2732
2733
2734 string Buffer::getDefaultOutputFormat() const
2735 {
2736         if (!params().defaultOutputFormat.empty()
2737             && params().defaultOutputFormat != "default")
2738                 return params().defaultOutputFormat;
2739         typedef vector<Format const *> Formats;
2740         Formats formats = exportableFormats(true);
2741         if (isDocBook()
2742             || isLiterate()
2743             || params().useXetex
2744             || params().encoding().package() == Encoding::japanese) {
2745                 if (formats.empty())
2746                         return string();
2747                 // return the first we find
2748                 return formats.front()->name();
2749         }
2750         return lyxrc.default_view_format;
2751 }
2752
2753
2754
2755 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2756         string & result_file) const
2757 {
2758         string backend_format;
2759         OutputParams runparams(&params().encoding());
2760         runparams.flavor = OutputParams::LATEX;
2761         runparams.linelen = lyxrc.plaintext_linelen;
2762         vector<string> backs = backends();
2763         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2764                 // Get shortest path to format
2765                 Graph::EdgePath path;
2766                 for (vector<string>::const_iterator it = backs.begin();
2767                      it != backs.end(); ++it) {
2768                         Graph::EdgePath p = theConverters().getPath(*it, format);
2769                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2770                                 backend_format = *it;
2771                                 path = p;
2772                         }
2773                 }
2774                 if (!path.empty())
2775                         runparams.flavor = theConverters().getFlavor(path);
2776                 else {
2777                         Alert::error(_("Couldn't export file"),
2778                                 bformat(_("No information for exporting the format %1$s."),
2779                                    formats.prettyName(format)));
2780                         return false;
2781                 }
2782         } else {
2783                 backend_format = format;
2784                 // FIXME: Don't hardcode format names here, but use a flag
2785                 if (backend_format == "pdflatex")
2786                         runparams.flavor = OutputParams::PDFLATEX;
2787         }
2788
2789         string filename = latexName(false);
2790         filename = addName(temppath(), filename);
2791         filename = changeExtension(filename,
2792                                    formats.extension(backend_format));
2793
2794         // fix macros
2795         updateMacroInstances();
2796
2797         // Plain text backend
2798         if (backend_format == "text")
2799                 writePlaintextFile(*this, FileName(filename), runparams);
2800         // no backend
2801         else if (backend_format == "xhtml")
2802                 makeLyXHTMLFile(FileName(filename), runparams);
2803         else if (backend_format == "lyx")
2804                 writeFile(FileName(filename));
2805         // Docbook backend
2806         else if (isDocBook()) {
2807                 runparams.nice = !put_in_tempdir;
2808                 makeDocBookFile(FileName(filename), runparams);
2809         }
2810         // LaTeX backend
2811         else if (backend_format == format) {
2812                 runparams.nice = true;
2813                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2814                         return false;
2815         } else if (!lyxrc.tex_allows_spaces
2816                    && contains(filePath(), ' ')) {
2817                 Alert::error(_("File name error"),
2818                            _("The directory path to the document cannot contain spaces."));
2819                 return false;
2820         } else {
2821                 runparams.nice = false;
2822                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2823                         return false;
2824         }
2825
2826         string const error_type = (format == "program")
2827                 ? "Build" : bufferFormat();
2828         ErrorList & error_list = d->errorLists[error_type];
2829         string const ext = formats.extension(format);
2830         FileName const tmp_result_file(changeExtension(filename, ext));
2831         bool const success = theConverters().convert(this, FileName(filename),
2832                 tmp_result_file, FileName(absFileName()), backend_format, format,
2833                 error_list);
2834         // Emit the signal to show the error list.
2835         if (format != backend_format)
2836                 errors(error_type);
2837         if (!success)
2838                 return false;
2839
2840         if (put_in_tempdir) {
2841                 result_file = tmp_result_file.absFilename();
2842                 return true;
2843         }
2844
2845         result_file = changeExtension(absFileName(), ext);
2846         // We need to copy referenced files (e. g. included graphics
2847         // if format == "dvi") to the result dir.
2848         vector<ExportedFile> const files =
2849                 runparams.exportdata->externalFiles(format);
2850         string const dest = onlyPath(result_file);
2851         CopyStatus status = SUCCESS;
2852         for (vector<ExportedFile>::const_iterator it = files.begin();
2853                 it != files.end() && status != CANCEL; ++it) {
2854                 string const fmt = formats.getFormatFromFile(it->sourceName);
2855                 status = copyFile(fmt, it->sourceName,
2856                         makeAbsPath(it->exportName, dest),
2857                         it->exportName, status == FORCE);
2858         }
2859         if (status == CANCEL) {
2860                 message(_("Document export cancelled."));
2861         } else if (tmp_result_file.exists()) {
2862                 // Finally copy the main file
2863                 status = copyFile(format, tmp_result_file,
2864                         FileName(result_file), result_file,
2865                         status == FORCE);
2866                 message(bformat(_("Document exported as %1$s "
2867                         "to file `%2$s'"),
2868                         formats.prettyName(format),
2869                         makeDisplayPath(result_file)));
2870         } else {
2871                 // This must be a dummy converter like fax (bug 1888)
2872                 message(bformat(_("Document exported as %1$s"),
2873                         formats.prettyName(format)));
2874         }
2875
2876         return true;
2877 }
2878
2879
2880 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2881 {
2882         string result_file;
2883         return doExport(format, put_in_tempdir, result_file);
2884 }
2885
2886
2887 bool Buffer::preview(string const & format) const
2888 {
2889         string result_file;
2890         if (!doExport(format, true, result_file))
2891                 return false;
2892         return formats.view(*this, FileName(result_file), format);
2893 }
2894
2895
2896 bool Buffer::isExportable(string const & format) const
2897 {
2898         vector<string> backs = backends();
2899         for (vector<string>::const_iterator it = backs.begin();
2900              it != backs.end(); ++it)
2901                 if (theConverters().isReachable(*it, format))
2902                         return true;
2903         return false;
2904 }
2905
2906
2907 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2908 {
2909         vector<string> backs = backends();
2910         vector<Format const *> result =
2911                 theConverters().getReachable(backs[0], only_viewable, true);
2912         for (vector<string>::const_iterator it = backs.begin() + 1;
2913              it != backs.end(); ++it) {
2914                 vector<Format const *>  r =
2915                         theConverters().getReachable(*it, only_viewable, false);
2916                 result.insert(result.end(), r.begin(), r.end());
2917         }
2918         return result;
2919 }
2920
2921
2922 vector<string> Buffer::backends() const
2923 {
2924         vector<string> v;
2925         if (params().baseClass()->isTeXClassAvailable()) {
2926                 v.push_back(bufferFormat());
2927                 // FIXME: Don't hardcode format names here, but use a flag
2928                 if (v.back() == "latex")
2929                         v.push_back("pdflatex");
2930         }
2931         v.push_back("text");
2932         v.push_back("xhtml");
2933         v.push_back("lyx");
2934         return v;
2935 }
2936
2937
2938 bool Buffer::readFileHelper(FileName const & s)
2939 {
2940         // File information about normal file
2941         if (!s.exists()) {
2942                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2943                 docstring text = bformat(_("The specified document\n%1$s"
2944                                                      "\ncould not be read."), file);
2945                 Alert::error(_("Could not read document"), text);
2946                 return false;
2947         }
2948
2949         // Check if emergency save file exists and is newer.
2950         FileName const e(s.absFilename() + ".emergency");
2951
2952         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2953                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2954                 docstring const text =
2955                         bformat(_("An emergency save of the document "
2956                                   "%1$s exists.\n\n"
2957                                                "Recover emergency save?"), file);
2958                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2959                                       _("&Recover"),  _("&Load Original"),
2960                                       _("&Cancel")))
2961                 {
2962                 case 0:
2963                         // the file is not saved if we load the emergency file.
2964                         markDirty();
2965                         return readFile(e);
2966                 case 1:
2967                         break;
2968                 default:
2969                         return false;
2970                 }
2971         }
2972
2973         // Now check if autosave file is newer.
2974         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2975
2976         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2977                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2978                 docstring const text =
2979                         bformat(_("The backup of the document "
2980                                   "%1$s is newer.\n\nLoad the "
2981                                                "backup instead?"), file);
2982                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2983                                       _("&Load backup"), _("Load &original"),
2984                                       _("&Cancel") ))
2985                 {
2986                 case 0:
2987                         // the file is not saved if we load the autosave file.
2988                         markDirty();
2989                         return readFile(a);
2990                 case 1:
2991                         // Here we delete the autosave
2992                         a.removeFile();
2993                         break;
2994                 default:
2995                         return false;
2996                 }
2997         }
2998         return readFile(s);
2999 }
3000
3001
3002 bool Buffer::loadLyXFile(FileName const & s)
3003 {
3004         if (s.isReadableFile()) {
3005                 if (readFileHelper(s)) {
3006                         lyxvc().file_found_hook(s);
3007                         if (!s.isWritable())
3008                                 setReadonly(true);
3009                         return true;
3010                 }
3011         } else {
3012                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3013                 // Here we probably should run
3014                 if (LyXVC::file_not_found_hook(s)) {
3015                         docstring const text =
3016                                 bformat(_("Do you want to retrieve the document"
3017                                                        " %1$s from version control?"), file);
3018                         int const ret = Alert::prompt(_("Retrieve from version control?"),
3019                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3020
3021                         if (ret == 0) {
3022                                 // How can we know _how_ to do the checkout?
3023                                 // With the current VC support it has to be,
3024                                 // a RCS file since CVS do not have special ,v files.
3025                                 RCS::retrieve(s);
3026                                 return loadLyXFile(s);
3027                         }
3028                 }
3029         }
3030         return false;
3031 }
3032
3033
3034 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3035 {
3036         TeXErrors::Errors::const_iterator cit = terr.begin();
3037         TeXErrors::Errors::const_iterator end = terr.end();
3038
3039         for (; cit != end; ++cit) {
3040                 int id_start = -1;
3041                 int pos_start = -1;
3042                 int errorRow = cit->error_in_line;
3043                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3044                                                        pos_start);
3045                 int id_end = -1;
3046                 int pos_end = -1;
3047                 do {
3048                         ++errorRow;
3049                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3050                 } while (found && id_start == id_end && pos_start == pos_end);
3051
3052                 errorList.push_back(ErrorItem(cit->error_desc,
3053                         cit->error_text, id_start, pos_start, pos_end));
3054         }
3055 }
3056
3057
3058 void Buffer::setBuffersForInsets() const
3059 {
3060         inset().setBuffer(const_cast<Buffer &>(*this)); 
3061 }
3062
3063
3064 void Buffer::updateLabels(UpdateScope scope) const
3065 {
3066         // Use the master text class also for child documents
3067         Buffer const * const master = masterBuffer();
3068         DocumentClass const & textclass = master->params().documentClass();
3069
3070         // keep the buffers to be children in this set. If the call from the
3071         // master comes back we can see which of them were actually seen (i.e.
3072         // via an InsetInclude). The remaining ones in the set need still be updated.
3073         static std::set<Buffer const *> bufToUpdate;
3074         if (scope == UpdateMaster) {
3075                 // If this is a child document start with the master
3076                 if (master != this) {
3077                         bufToUpdate.insert(this);
3078                         master->updateLabels();
3079                         // Do this here in case the master has no gui associated with it. Then, 
3080                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3081                         if (!master->gui_)
3082                                 structureChanged();     
3083
3084                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3085                         if (bufToUpdate.find(this) == bufToUpdate.end())
3086                                 return;
3087                 }
3088
3089                 // start over the counters in the master
3090                 textclass.counters().reset();
3091         }
3092
3093         // update will be done below for this buffer
3094         bufToUpdate.erase(this);
3095
3096         // update all caches
3097         clearReferenceCache();
3098         updateMacros();
3099
3100         Buffer & cbuf = const_cast<Buffer &>(*this);
3101
3102         LASSERT(!text().paragraphs().empty(), /**/);
3103
3104         // do the real work
3105         ParIterator parit = cbuf.par_iterator_begin();
3106         updateLabels(parit);
3107
3108         if (master != this)
3109                 // TocBackend update will be done later.
3110                 return;
3111
3112         cbuf.tocBackend().update();
3113         if (scope == UpdateMaster)
3114                 cbuf.structureChanged();
3115 }
3116
3117
3118 static depth_type getDepth(DocIterator const & it)
3119 {
3120         depth_type depth = 0;
3121         for (size_t i = 0 ; i < it.depth() ; ++i)
3122                 if (!it[i].inset().inMathed())
3123                         depth += it[i].paragraph().getDepth() + 1;
3124         // remove 1 since the outer inset does not count
3125         return depth - 1;
3126 }
3127
3128 static depth_type getItemDepth(ParIterator const & it)
3129 {
3130         Paragraph const & par = *it;
3131         LabelType const labeltype = par.layout().labeltype;
3132
3133         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3134                 return 0;
3135
3136         // this will hold the lowest depth encountered up to now.
3137         depth_type min_depth = getDepth(it);
3138         ParIterator prev_it = it;
3139         while (true) {
3140                 if (prev_it.pit())
3141                         --prev_it.top().pit();
3142                 else {
3143                         // start of nested inset: go to outer par
3144                         prev_it.pop_back();
3145                         if (prev_it.empty()) {
3146                                 // start of document: nothing to do
3147                                 return 0;
3148                         }
3149                 }
3150
3151                 // We search for the first paragraph with same label
3152                 // that is not more deeply nested.
3153                 Paragraph & prev_par = *prev_it;
3154                 depth_type const prev_depth = getDepth(prev_it);
3155                 if (labeltype == prev_par.layout().labeltype) {
3156                         if (prev_depth < min_depth)
3157                                 return prev_par.itemdepth + 1;
3158                         if (prev_depth == min_depth)
3159                                 return prev_par.itemdepth;
3160                 }
3161                 min_depth = min(min_depth, prev_depth);
3162                 // small optimization: if we are at depth 0, we won't
3163                 // find anything else
3164                 if (prev_depth == 0)
3165                         return 0;
3166         }
3167 }
3168
3169
3170 static bool needEnumCounterReset(ParIterator const & it)
3171 {
3172         Paragraph const & par = *it;
3173         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3174         depth_type const cur_depth = par.getDepth();
3175         ParIterator prev_it = it;
3176         while (prev_it.pit()) {
3177                 --prev_it.top().pit();
3178                 Paragraph const & prev_par = *prev_it;
3179                 if (prev_par.getDepth() <= cur_depth)
3180                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3181         }
3182         // start of nested inset: reset
3183         return true;
3184 }
3185
3186
3187 // set the label of a paragraph. This includes the counters.
3188 static void setLabel(Buffer const & buf, ParIterator & it)
3189 {
3190         BufferParams const & bp = buf.masterBuffer()->params();
3191         DocumentClass const & textclass = bp.documentClass();
3192         Paragraph & par = it.paragraph();
3193         Layout const & layout = par.layout();
3194         Counters & counters = textclass.counters();
3195
3196         if (par.params().startOfAppendix()) {
3197                 // FIXME: only the counter corresponding to toplevel
3198                 // sectionning should be reset
3199                 counters.reset();
3200                 counters.appendix(true);
3201         }
3202         par.params().appendix(counters.appendix());
3203
3204         // Compute the item depth of the paragraph
3205         par.itemdepth = getItemDepth(it);
3206
3207         if (layout.margintype == MARGIN_MANUAL
3208             || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3209                 if (par.params().labelWidthString().empty())
3210                         par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
3211         } else {
3212                 par.params().labelWidthString(docstring());
3213         }
3214
3215         switch(layout.labeltype) {
3216         case LABEL_COUNTER:
3217                 if (layout.toclevel <= bp.secnumdepth
3218                     && (layout.latextype != LATEX_ENVIRONMENT
3219                         || isFirstInSequence(it.pit(), it.plist()))) {
3220                         counters.step(layout.counter);
3221                         par.params().labelString(
3222                                 par.expandLabel(layout, bp));
3223                 } else
3224                         par.params().labelString(docstring());
3225                 break;
3226
3227         case LABEL_ITEMIZE: {
3228                 // At some point of time we should do something more
3229                 // clever here, like:
3230                 //   par.params().labelString(
3231                 //    bp.user_defined_bullet(par.itemdepth).getText());
3232                 // for now, use a simple hardcoded label
3233                 docstring itemlabel;
3234                 switch (par.itemdepth) {
3235                 case 0:
3236                         itemlabel = char_type(0x2022);
3237                         break;
3238                 case 1:
3239                         itemlabel = char_type(0x2013);
3240                         break;
3241                 case 2:
3242                         itemlabel = char_type(0x2217);
3243                         break;
3244                 case 3:
3245                         itemlabel = char_type(0x2219); // or 0x00b7
3246                         break;
3247                 }
3248                 par.params().labelString(itemlabel);
3249                 break;
3250         }
3251
3252         case LABEL_ENUMERATE: {
3253                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3254
3255                 switch (par.itemdepth) {
3256                 case 2:
3257                         enumcounter += 'i';
3258                 case 1:
3259                         enumcounter += 'i';
3260                 case 0:
3261                         enumcounter += 'i';
3262                         break;
3263                 case 3:
3264                         enumcounter += "iv";
3265                         break;
3266                 default:
3267                         // not a valid enumdepth...
3268                         break;
3269                 }
3270
3271                 // Maybe we have to reset the enumeration counter.
3272                 if (needEnumCounterReset(it))
3273                         counters.reset(enumcounter);
3274                 counters.step(enumcounter);
3275
3276                 par.params().labelString(counters.theCounter(enumcounter));
3277
3278                 break;
3279         }
3280
3281         case LABEL_SENSITIVE: {
3282                 string const & type = counters.current_float();
3283                 docstring full_label;
3284                 if (type.empty())
3285                         full_label = buf.B_("Senseless!!! ");
3286                 else {
3287                         docstring name = buf.B_(textclass.floats().getType(type).name());
3288                         if (counters.hasCounter(from_utf8(type))) {
3289                                 counters.step(from_utf8(type));
3290                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
3291                                                      name, 
3292                                                      counters.theCounter(from_utf8(type)));
3293                         } else
3294                                 full_label = bformat(from_ascii("%1$s #:"), name);      
3295                 }
3296                 par.params().labelString(full_label);   
3297                 break;
3298         }
3299
3300         case LABEL_NO_LABEL:
3301                 par.params().labelString(docstring());
3302                 break;
3303
3304         case LABEL_MANUAL:
3305         case LABEL_TOP_ENVIRONMENT:
3306         case LABEL_CENTERED_TOP_ENVIRONMENT:
3307         case LABEL_STATIC:      
3308         case LABEL_BIBLIO:
3309                 par.params().labelString(
3310                         par.translateIfPossible(layout.labelstring(), bp));
3311                 break;
3312         }
3313 }
3314
3315
3316 void Buffer::updateLabels(ParIterator & parit) const
3317 {
3318         LASSERT(parit.pit() == 0, /**/);
3319
3320         // set the position of the text in the buffer to be able
3321         // to resolve macros in it. This has nothing to do with
3322         // labels, but by putting it here we avoid implementing
3323         // a whole bunch of traversal routines just for this call.
3324         parit.text()->setMacrocontextPosition(parit);
3325
3326         depth_type maxdepth = 0;
3327         pit_type const lastpit = parit.lastpit();
3328         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3329                 // reduce depth if necessary
3330                 parit->params().depth(min(parit->params().depth(), maxdepth));
3331                 maxdepth = parit->getMaxDepthAfter();
3332
3333                 // set the counter for this paragraph
3334                 setLabel(*this, parit);
3335
3336                 // Now the insets
3337                 InsetList::const_iterator iit = parit->insetList().begin();
3338                 InsetList::const_iterator end = parit->insetList().end();
3339                 for (; iit != end; ++iit) {
3340                         parit.pos() = iit->pos;
3341                         iit->inset->updateLabels(parit);
3342                 }
3343         }
3344 }
3345
3346
3347 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3348         docstring & word) const
3349 {
3350         bool inword = false;
3351         bool ignoreword = false;
3352         string lang_code;
3353         // Go backward a bit if needed in order to return the word currently
3354         // pointed by 'from'.
3355         while (from && from.pos() && isLetter(from))
3356                 from.backwardPos();
3357         // OK, we start from here.
3358         to = from;
3359         while (to.depth()) {
3360                 if (isLetter(to)) {
3361                         if (!inword) {
3362                                 inword = true;
3363                                 ignoreword = false;
3364                                 from = to;
3365                                 word.clear();
3366                                 lang_code = to.paragraph().getFontSettings(params(),
3367                                         to.pos()).language()->code();
3368                         }
3369                         // Insets like optional hyphens and ligature
3370                         // break are part of a word.
3371                         if (!to.paragraph().isInset(to.pos())) {
3372                                 char_type const c = to.paragraph().getChar(to.pos());
3373                                 word += c;
3374                                 if (isDigit(c))
3375                                         ignoreword = true;
3376                         }
3377                 } else { // !isLetter(cur)
3378                         if (inword && !word.empty() && !ignoreword)
3379                                 return true;
3380                         inword = false;
3381                 }
3382                 to.forwardPos();
3383         }
3384         from = to;
3385         word.clear();
3386         return false;
3387 }
3388
3389
3390 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3391         WordLangTuple & word_lang, docstring_list & suggestions) const
3392 {
3393         int progress = 0;
3394         SpellChecker::Result res = SpellChecker::OK;
3395         SpellChecker * speller = theSpellChecker();
3396         suggestions.clear();
3397         docstring word;
3398         while (nextWord(from, to, word)) {
3399                 ++progress;
3400                 string lang_code = lyxrc.spellchecker_use_alt_lang
3401                       ? lyxrc.spellchecker_alt_lang
3402                       : from.paragraph().getFontSettings(params(), from.pos()).language()->code();
3403                 WordLangTuple wl(word, lang_code);
3404                 res = speller->check(wl);
3405                 // ... just bail out if the spellchecker reports an error.
3406                 if (!speller->error().empty()) {
3407                         throw ExceptionMessage(WarningException,
3408                                 _("The spellchecker has failed."), speller->error());
3409                 }
3410                 if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
3411                         word_lang = wl;
3412                         break;
3413                 }
3414                 from = to;
3415         }
3416         while (!(word = speller->nextMiss()).empty())
3417                 suggestions.push_back(word);
3418         return progress;
3419 }
3420
3421 } // namespace lyx