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