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