]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
ec30037200a20f47007c4c542b2b620f1ca3e31c
[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 "Cursor.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
33 #include "Exporter.h"
34 #include "Format.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
40 #include "Language.h"
41 #include "LaTeXFeatures.h"
42 #include "LaTeX.h"
43 #include "Layout.h"
44 #include "Lexer.h"
45 #include "LyXAction.h"
46 #include "LyX.h"
47 #include "LyXRC.h"
48 #include "LyXVC.h"
49 #include "output_docbook.h"
50 #include "output.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
59 #include "sgml.h"
60 #include "TexRow.h"
61 #include "Text.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
64 #include "Undo.h"
65 #include "VCBackend.h"
66 #include "version.h"
67 #include "WordLangTuple.h"
68 #include "WordList.h"
69
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
75
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
80
81 #include "graphics/PreviewLoader.h"
82
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
86
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/mutex.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
108
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
111
112 #include <algorithm>
113 #include <fstream>
114 #include <iomanip>
115 #include <map>
116 #include <set>
117 #include <sstream>
118 #include <vector>
119
120 using namespace std;
121 using namespace lyx::support;
122 using namespace lyx::graphics;
123
124 namespace lyx {
125
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
128
129 namespace {
130
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
132
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135
136 void showPrintError(string const & name)
137 {
138         docstring str = bformat(_("Could not print the document %1$s.\n"
139                                             "Check that your printer is set up correctly."),
140                              makeDisplayPath(name, 50));
141         Alert::error(_("Print document failed"), str);
142 }
143
144 } // namespace anon
145
146
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
149
150
151 class Buffer::Impl
152 {
153 public:
154         Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
155
156         ~Impl()
157         {
158                 delete preview_loader_;
159                 if (wa_) {
160                         wa_->closeAll();
161                         delete wa_;
162                 }
163                 delete inset;
164         }
165
166         /// search for macro in local (buffer) table or in children
167         MacroData const * getBufferMacro(docstring const & name,
168                 DocIterator const & pos) const;
169
170         /// Update macro table starting with position of it \param it in some
171         /// text inset.
172         void updateMacros(DocIterator & it, DocIterator & scope);
173         ///
174         void setLabel(ParIterator & it, UpdateType utype) const;
175
176         /** If we have branches that use the file suffix
177             feature, return the file name with suffix appended.
178         */
179         support::FileName exportFileName() const;
180
181         Buffer * owner_;
182
183         BufferParams params;
184         LyXVC lyxvc;
185         FileName temppath;
186         mutable TexRow texrow;
187
188         /// need to regenerate .tex?
189         DepClean dep_clean;
190
191         /// is save needed?
192         mutable bool lyx_clean;
193
194         /// is autosave needed?
195         mutable bool bak_clean;
196
197         /// is this an unnamed file (New...)?
198         bool unnamed;
199
200         /// is this an internal bufffer?
201         bool internal_buffer;
202
203         /// buffer is r/o
204         bool read_only;
205
206         /// name of the file the buffer is associated with.
207         FileName filename;
208
209         /** Set to true only when the file is fully loaded.
210          *  Used to prevent the premature generation of previews
211          *  and by the citation inset.
212          */
213         bool file_fully_loaded;
214
215         /// Ignore the parent (e.g. when exporting a child standalone)?
216         bool ignore_parent;
217
218         ///
219         mutable TocBackend toc_backend;
220
221         /// macro tables
222         typedef pair<DocIterator, MacroData> ScopeMacro;
223         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
224         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
225         /// map from the macro name to the position map,
226         /// which maps the macro definition position to the scope and the MacroData.
227         NamePositionScopeMacroMap macros;
228         /// This seem to change the way Buffer::getMacro() works
229         mutable bool macro_lock;
230
231         /// positions of child buffers in the buffer
232         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
233         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
234         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
235         /// position of children buffers in this buffer
236         BufferPositionMap children_positions;
237         /// map from children inclusion positions to their scope and their buffer
238         PositionScopeBufferMap position_to_children;
239
240         /// Container for all sort of Buffer dependant errors.
241         map<string, ErrorList> errorLists;
242
243         /// timestamp and checksum used to test if the file has been externally
244         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
245         time_t timestamp_;
246         unsigned long checksum_;
247
248         ///
249         frontend::WorkAreaManager * wa_;
250         ///
251         frontend::GuiBufferDelegate * gui_;
252
253         ///
254         Undo undo_;
255
256         /// A cache for the bibfiles (including bibfiles of loaded child
257         /// documents), needed for appropriate update of natbib labels.
258         mutable support::FileNameList bibfiles_cache_;
259
260         // FIXME The caching mechanism could be improved. At present, we have a
261         // cache for each Buffer, that caches all the bibliography info for that
262         // Buffer. A more efficient solution would be to have a global cache per
263         // file, and then to construct the Buffer's bibinfo from that.
264         /// A cache for bibliography info
265         mutable BiblioInfo bibinfo_;
266         /// whether the bibinfo cache is valid
267         mutable bool bibinfo_cache_valid_;
268         /// whether the bibfile cache is valid
269         mutable bool bibfile_cache_valid_;
270         /// Cache of timestamps of .bib files
271         map<FileName, time_t> bibfile_status_;
272         /// Indicates whether the bibinfo has changed since the last time
273         /// we ran updateBuffer(), i.e., whether citation labels may need
274         /// to be updated.
275         mutable bool cite_labels_valid_;
276
277         mutable RefCache ref_cache_;
278
279         /// our Text that should be wrapped in an InsetText
280         InsetText * inset;
281
282         ///
283         PreviewLoader * preview_loader_;
284
285         /// This is here to force the test to be done whenever parent_buffer
286         /// is accessed.
287         Buffer const * parent() const
288         {
289                 // ignore_parent temporarily "orphans" a buffer
290                 // (e.g. if a child is compiled standalone)
291                 if (ignore_parent)
292                         return 0;
293                 // if parent_buffer is not loaded, then it has been unloaded,
294                 // which means that parent_buffer is an invalid pointer. So we
295                 // set it to null in that case.
296                 // however, the BufferList doesn't know about cloned buffers, so
297                 // they will always be regarded as unloaded. in that case, we hope
298                 // for the best.
299                 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
300                         parent_buffer = 0;
301                 return parent_buffer;
302         }
303
304         ///
305         void setParent(Buffer const * pb)
306         {
307                 if (parent_buffer == pb)
308                         // nothing to do
309                         return;
310                 if (!cloned_buffer_ && parent_buffer && pb)
311                         LYXERR0("Warning: a buffer should not have two parents!");
312                 parent_buffer = pb;
313                 if (!cloned_buffer_ && parent_buffer) {
314                         parent_buffer->invalidateBibfileCache();
315                         parent_buffer->invalidateBibinfoCache();
316                 }
317         }
318
319         /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
320         /// This one is useful for preview detached in a thread.
321         Buffer const * cloned_buffer_;
322         ///
323         CloneList * clone_list_;
324         /// are we in the process of exporting this buffer?
325         mutable bool doing_export;
326
327         /// compute statistics
328         /// \p from initial position
329         /// \p to points to the end position
330         void updateStatistics(DocIterator & from, DocIterator & to,
331                               bool skipNoOutput = true);
332         /// statistics accessor functions
333         int wordCount() const
334         {
335                 return word_count_;
336         }
337         int charCount(bool with_blanks) const
338         {
339                 return char_count_
340                 + (with_blanks ? blank_count_ : 0);
341         }
342
343 private:
344         /// So we can force access via the accessors.
345         mutable Buffer const * parent_buffer;
346
347         int word_count_;
348         int char_count_;
349         int blank_count_;
350
351 };
352
353
354 /// Creates the per buffer temporary directory
355 static FileName createBufferTmpDir()
356 {
357         // FIXME This would be the ideal application for a TempDir class (like
358         //       TempFile but for directories) 
359         string counter;
360         {
361                 static int count;
362                 static Mutex mutex;
363                 Mutex::Locker locker(&mutex);
364                 counter = convert<string>(count++);
365         }
366         // We are in our own directory.  Why bother to mangle name?
367         // In fact I wrote this code to circumvent a problematic behaviour
368         // (bug?) of EMX mkstemp().
369         FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
370                 counter);
371
372         if (!tmpfl.createDirectory(0777)) {
373                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
374                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
375                         from_utf8(tmpfl.absFileName())));
376         }
377         return tmpfl;
378 }
379
380
381 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
382         Buffer const * cloned_buffer)
383         : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
384           internal_buffer(false), read_only(readonly_), filename(file),
385           file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
386           macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
387           undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
388           cite_labels_valid_(false), inset(0), preview_loader_(0),
389           cloned_buffer_(cloned_buffer), clone_list_(0),
390           doing_export(false), parent_buffer(0),
391           word_count_(0), char_count_(0), blank_count_(0)
392 {
393         if (!cloned_buffer_) {
394                 temppath = createBufferTmpDir();
395                 lyxvc.setBuffer(owner_);
396                 if (use_gui)
397                         wa_ = new frontend::WorkAreaManager;
398                 return;
399         }
400         temppath = cloned_buffer_->d->temppath;
401         file_fully_loaded = true;
402         params = cloned_buffer_->d->params;
403         bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
404         bibinfo_ = cloned_buffer_->d->bibinfo_;
405         bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
406         bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
407         bibfile_status_ = cloned_buffer_->d->bibfile_status_;
408         cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
409         unnamed = cloned_buffer_->d->unnamed;
410         internal_buffer = cloned_buffer_->d->internal_buffer;
411 }
412
413
414 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
415         : d(new Impl(this, FileName(file), readonly, cloned_buffer))
416 {
417         LYXERR(Debug::INFO, "Buffer::Buffer()");
418         if (cloned_buffer) {
419                 d->inset = new InsetText(*cloned_buffer->d->inset);
420                 d->inset->setBuffer(*this);
421                 // FIXME: optimize this loop somewhat, maybe by creating a new
422                 // general recursive Inset::setId().
423                 DocIterator it = doc_iterator_begin(this);
424                 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
425                 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
426                         it.paragraph().setId(cloned_it.paragraph().id());
427         } else
428                 d->inset = new InsetText(this);
429         d->inset->setAutoBreakRows(true);
430         d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
431 }
432
433
434 Buffer::~Buffer()
435 {
436         LYXERR(Debug::INFO, "Buffer::~Buffer()");
437         // here the buffer should take care that it is
438         // saved properly, before it goes into the void.
439
440         // GuiView already destroyed
441         d->gui_ = 0;
442
443         if (isInternal()) {
444                 // No need to do additional cleanups for internal buffer.
445                 delete d;
446                 return;
447         }
448
449         if (isClone()) {
450                 // this is in case of recursive includes: we won't try to delete
451                 // ourselves as a child.
452                 d->clone_list_->erase(this);
453                 // loop over children
454                 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
455                 Impl::BufferPositionMap::iterator end = d->children_positions.end();
456                 for (; it != end; ++it) {
457                         Buffer * child = const_cast<Buffer *>(it->first);
458                                 if (d->clone_list_->erase(child))
459                                         delete child;
460                 }
461                 // if we're the master buffer, then we should get rid of the list
462                 // of clones
463                 if (!parent()) {
464                         // If this is not empty, we have leaked something. Worse, one of the
465                         // children still has a reference to this list. But we will try to
466                         // continue, rather than shut down.
467                         LATTEST(d->clone_list_->empty());
468                         list<CloneList *>::iterator it =
469                                 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
470                         if (it == cloned_buffers.end()) {
471                                 // We will leak in this case, but it is safe to continue.
472                                 LATTEST(false);
473                         } else
474                                 cloned_buffers.erase(it);
475                         delete d->clone_list_;
476                 }
477                 // FIXME Do we really need to do this right before we delete d?
478                 // clear references to children in macro tables
479                 d->children_positions.clear();
480                 d->position_to_children.clear();
481         } else {
482                 // loop over children
483                 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
484                 Impl::BufferPositionMap::iterator end = d->children_positions.end();
485                 for (; it != end; ++it) {
486                         Buffer * child = const_cast<Buffer *>(it->first);
487                         if (theBufferList().isLoaded(child))
488                                 theBufferList().releaseChild(this, child);
489                 }
490
491                 if (!isClean()) {
492                         docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
493                         msg += emergencyWrite();
494                         Alert::warning(_("Attempting to close changed document!"), msg);
495                 }
496
497                 // FIXME Do we really need to do this right before we delete d?
498                 // clear references to children in macro tables
499                 d->children_positions.clear();
500                 d->position_to_children.clear();
501
502                 if (!d->temppath.destroyDirectory()) {
503                         Alert::warning(_("Could not remove temporary directory"),
504                                 bformat(_("Could not remove the temporary directory %1$s"),
505                                 from_utf8(d->temppath.absFileName())));
506                 }
507                 removePreviews();
508         }
509
510         delete d;
511 }
512
513
514 Buffer * Buffer::cloneFromMaster() const
515 {
516         BufferMap bufmap;
517         cloned_buffers.push_back(new CloneList);
518         CloneList * clones = cloned_buffers.back();
519
520         masterBuffer()->cloneWithChildren(bufmap, clones);
521
522         // make sure we got cloned
523         BufferMap::const_iterator bit = bufmap.find(this);
524         LASSERT(bit != bufmap.end(), return 0);
525         Buffer * cloned_buffer = bit->second;
526
527         return cloned_buffer;
528 }
529
530
531 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
532 {
533         // have we already been cloned?
534         if (bufmap.find(this) != bufmap.end())
535                 return;
536
537         Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
538
539         // The clone needs its own DocumentClass, since running updateBuffer() will
540         // modify it, and we would otherwise be sharing it with the original Buffer.
541         buffer_clone->params().makeDocumentClass(true);
542         ErrorList el;
543         cap::switchBetweenClasses(
544                         params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
545                         static_cast<InsetText &>(buffer_clone->inset()), el);
546
547         bufmap[this] = buffer_clone;
548         clones->insert(buffer_clone);
549         buffer_clone->d->clone_list_ = clones;
550         buffer_clone->d->macro_lock = true;
551         buffer_clone->d->children_positions.clear();
552
553         // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
554         // math macro caches need to be rethought and simplified.
555         // I am not sure wether we should handle Buffer cloning here or in BufferList.
556         // Right now BufferList knows nothing about buffer clones.
557         Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
558         Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
559         for (; it != end; ++it) {
560                 DocIterator dit = it->first.clone(buffer_clone);
561                 dit.setBuffer(buffer_clone);
562                 Buffer * child = const_cast<Buffer *>(it->second.second);
563
564                 child->cloneWithChildren(bufmap, clones);
565                 BufferMap::iterator const bit = bufmap.find(child);
566                 LASSERT(bit != bufmap.end(), continue);
567                 Buffer * child_clone = bit->second;
568
569                 Inset * inset = dit.nextInset();
570                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
571                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
572                 inset_inc->setChildBuffer(child_clone);
573                 child_clone->d->setParent(buffer_clone);
574                 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
575                 buffer_clone->setChild(dit, child_clone);
576         }
577         buffer_clone->d->macro_lock = false;
578         return;
579 }
580
581
582 Buffer * Buffer::cloneBufferOnly() const {
583         cloned_buffers.push_back(new CloneList);
584         CloneList * clones = cloned_buffers.back();
585         Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
586
587         // The clone needs its own DocumentClass, since running updateBuffer() will
588         // modify it, and we would otherwise be sharing it with the original Buffer.
589         buffer_clone->params().makeDocumentClass(true);
590         ErrorList el;
591         cap::switchBetweenClasses(
592                         params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
593                         static_cast<InsetText &>(buffer_clone->inset()), el);
594
595         clones->insert(buffer_clone);
596         buffer_clone->d->clone_list_ = clones;
597
598         // we won't be cloning the children
599         buffer_clone->d->children_positions.clear();
600         return buffer_clone;
601 }
602
603
604 bool Buffer::isClone() const
605 {
606         return d->cloned_buffer_;
607 }
608
609
610 void Buffer::changed(bool update_metrics) const
611 {
612         if (d->wa_)
613                 d->wa_->redrawAll(update_metrics);
614 }
615
616
617 frontend::WorkAreaManager & Buffer::workAreaManager() const
618 {
619         LBUFERR(d->wa_);
620         return *d->wa_;
621 }
622
623
624 Text & Buffer::text() const
625 {
626         return d->inset->text();
627 }
628
629
630 Inset & Buffer::inset() const
631 {
632         return *d->inset;
633 }
634
635
636 BufferParams & Buffer::params()
637 {
638         return d->params;
639 }
640
641
642 BufferParams const & Buffer::params() const
643 {
644         return d->params;
645 }
646
647
648 BufferParams const & Buffer::masterParams() const
649 {
650         if (masterBuffer() == this)
651                 return params();
652
653         BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
654         // Copy child authors to the params. We need those pointers.
655         AuthorList const & child_authors = params().authors();
656         AuthorList::Authors::const_iterator it = child_authors.begin();
657         for (; it != child_authors.end(); ++it)
658                 mparams.authors().record(*it);
659         return mparams;
660 }
661
662
663 double Buffer::fontScalingFactor() const
664 {
665         return isExporting() ? 75.0 * params().html_math_img_scale
666                 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
667 }
668
669
670 ParagraphList & Buffer::paragraphs()
671 {
672         return text().paragraphs();
673 }
674
675
676 ParagraphList const & Buffer::paragraphs() const
677 {
678         return text().paragraphs();
679 }
680
681
682 LyXVC & Buffer::lyxvc()
683 {
684         return d->lyxvc;
685 }
686
687
688 LyXVC const & Buffer::lyxvc() const
689 {
690         return d->lyxvc;
691 }
692
693
694 string const Buffer::temppath() const
695 {
696         return d->temppath.absFileName();
697 }
698
699
700 TexRow & Buffer::texrow()
701 {
702         return d->texrow;
703 }
704
705
706 TexRow const & Buffer::texrow() const
707 {
708         return d->texrow;
709 }
710
711
712 TocBackend & Buffer::tocBackend() const
713 {
714         return d->toc_backend;
715 }
716
717
718 Undo & Buffer::undo()
719 {
720         return d->undo_;
721 }
722
723
724 void Buffer::setChild(DocIterator const & dit, Buffer * child)
725 {
726         d->children_positions[child] = dit;
727 }
728
729
730 string Buffer::latexName(bool const no_path) const
731 {
732         FileName latex_name =
733                 makeLatexName(d->exportFileName());
734         return no_path ? latex_name.onlyFileName()
735                 : latex_name.absFileName();
736 }
737
738
739 FileName Buffer::Impl::exportFileName() const
740 {
741         docstring const branch_suffix =
742                 params.branchlist().getFileNameSuffix();
743         if (branch_suffix.empty())
744                 return filename;
745
746         string const name = filename.onlyFileNameWithoutExt()
747                 + to_utf8(branch_suffix);
748         FileName res(filename.onlyPath().absFileName() + "/" + name);
749         res.changeExtension(filename.extension());
750
751         return res;
752 }
753
754
755 string Buffer::logName(LogType * type) const
756 {
757         string const filename = latexName(false);
758
759         if (filename.empty()) {
760                 if (type)
761                         *type = latexlog;
762                 return string();
763         }
764
765         string const path = temppath();
766
767         FileName const fname(addName(temppath(),
768                                      onlyFileName(changeExtension(filename,
769                                                                   ".log"))));
770
771         // FIXME: how do we know this is the name of the build log?
772         FileName const bname(
773                 addName(path, onlyFileName(
774                         changeExtension(filename,
775                                         formats.extension(params().bufferFormat()) + ".out"))));
776
777         // Also consider the master buffer log file
778         FileName masterfname = fname;
779         LogType mtype = latexlog;
780         if (masterBuffer() != this) {
781                 string const mlogfile = masterBuffer()->logName(&mtype);
782                 masterfname = FileName(mlogfile);
783         }
784
785         // If no Latex log or Build log is newer, show Build log
786         if (bname.exists() &&
787             ((!fname.exists() && !masterfname.exists())
788              || (fname.lastModified() < bname.lastModified()
789                  && masterfname.lastModified() < bname.lastModified()))) {
790                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
791                 if (type)
792                         *type = buildlog;
793                 return bname.absFileName();
794         // If we have a newer master file log or only a master log, show this
795         } else if (fname != masterfname
796                    && (!fname.exists() && (masterfname.exists()
797                    || fname.lastModified() < masterfname.lastModified()))) {
798                 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
799                 if (type)
800                         *type = mtype;
801                 return masterfname.absFileName();
802         }
803         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
804         if (type)
805                         *type = latexlog;
806         return fname.absFileName();
807 }
808
809
810 void Buffer::setReadonly(bool const flag)
811 {
812         if (d->read_only != flag) {
813                 d->read_only = flag;
814                 changed(false);
815         }
816 }
817
818
819 void Buffer::setFileName(FileName const & fname)
820 {
821         bool const changed = fname != d->filename;
822         d->filename = fname;
823         if (changed)
824                 lyxvc().file_found_hook(fname);
825         setReadonly(d->filename.isReadOnly());
826         saveCheckSum();
827         updateTitles();
828 }
829
830
831 int Buffer::readHeader(Lexer & lex)
832 {
833         int unknown_tokens = 0;
834         int line = -1;
835         int begin_header_line = -1;
836
837         // Initialize parameters that may be/go lacking in header:
838         params().branchlist().clear();
839         params().preamble.erase();
840         params().options.erase();
841         params().master.erase();
842         params().float_placement.erase();
843         params().paperwidth.erase();
844         params().paperheight.erase();
845         params().leftmargin.erase();
846         params().rightmargin.erase();
847         params().topmargin.erase();
848         params().bottommargin.erase();
849         params().headheight.erase();
850         params().headsep.erase();
851         params().footskip.erase();
852         params().columnsep.erase();
853         params().fonts_cjk.erase();
854         params().listings_params.clear();
855         params().clearLayoutModules();
856         params().clearRemovedModules();
857         params().clearIncludedChildren();
858         params().pdfoptions().clear();
859         params().indiceslist().clear();
860         params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
861         params().isbackgroundcolor = false;
862         params().fontcolor = RGBColor(0, 0, 0);
863         params().isfontcolor = false;
864         params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
865         params().boxbgcolor = RGBColor(0xFF, 0, 0);
866         params().html_latex_start.clear();
867         params().html_latex_end.clear();
868         params().html_math_img_scale = 1.0;
869         params().output_sync_macro.erase();
870         params().setLocalLayout(string(), false);
871         params().setLocalLayout(string(), true);
872
873         for (int i = 0; i < 4; ++i) {
874                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
875                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
876         }
877
878         ErrorList & errorList = d->errorLists["Parse"];
879
880         while (lex.isOK()) {
881                 string token;
882                 lex >> token;
883
884                 if (token.empty())
885                         continue;
886
887                 if (token == "\\end_header")
888                         break;
889
890                 ++line;
891                 if (token == "\\begin_header") {
892                         begin_header_line = line;
893                         continue;
894                 }
895
896                 LYXERR(Debug::PARSER, "Handling document header token: `"
897                                       << token << '\'');
898
899                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
900                 if (!unknown.empty()) {
901                         if (unknown[0] != '\\' && token == "\\textclass") {
902                                 Alert::warning(_("Unknown document class"),
903                        bformat(_("Using the default document class, because the "
904                                               "class %1$s is unknown."), from_utf8(unknown)));
905                         } else {
906                                 ++unknown_tokens;
907                                 docstring const s = bformat(_("Unknown token: "
908                                                                         "%1$s %2$s\n"),
909                                                          from_utf8(token),
910                                                          lex.getDocString());
911                                 errorList.push_back(ErrorItem(_("Document header error"),
912                                         s, -1, 0, 0));
913                         }
914                 }
915         }
916         if (begin_header_line) {
917                 docstring const s = _("\\begin_header is missing");
918                 errorList.push_back(ErrorItem(_("Document header error"),
919                         s, -1, 0, 0));
920         }
921
922         params().makeDocumentClass();
923
924         return unknown_tokens;
925 }
926
927
928 // Uwe C. Schroeder
929 // changed to be public and have one parameter
930 // Returns true if "\end_document" is not read (Asger)
931 bool Buffer::readDocument(Lexer & lex)
932 {
933         ErrorList & errorList = d->errorLists["Parse"];
934         errorList.clear();
935
936         // remove dummy empty par
937         paragraphs().clear();
938
939         if (!lex.checkFor("\\begin_document")) {
940                 docstring const s = _("\\begin_document is missing");
941                 errorList.push_back(ErrorItem(_("Document header error"),
942                         s, -1, 0, 0));
943         }
944
945         readHeader(lex);
946
947         if (params().output_changes) {
948                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
949                 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
950                                   LaTeXFeatures::isAvailable("xcolor");
951
952                 if (!dvipost && !xcolorulem) {
953                         Alert::warning(_("Changes not shown in LaTeX output"),
954                                        _("Changes will not be highlighted in LaTeX output, "
955                                          "because neither dvipost nor xcolor/ulem are installed.\n"
956                                          "Please install these packages or redefine "
957                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
958                 } else if (!xcolorulem) {
959                         Alert::warning(_("Changes not shown in LaTeX output"),
960                                        _("Changes will not be highlighted in LaTeX output "
961                                          "when using pdflatex, because xcolor and ulem are not installed.\n"
962                                          "Please install both packages or redefine "
963                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
964                 }
965         }
966
967         if (!parent() && !params().master.empty()) {
968                 FileName const master_file = makeAbsPath(params().master,
969                            onlyPath(absFileName()));
970                 if (isLyXFileName(master_file.absFileName())) {
971                         Buffer * master =
972                                 checkAndLoadLyXFile(master_file, true);
973                         if (master) {
974                                 // necessary e.g. after a reload
975                                 // to re-register the child (bug 5873)
976                                 // FIXME: clean up updateMacros (here, only
977                                 // child registering is needed).
978                                 master->updateMacros();
979                                 // set master as master buffer, but only
980                                 // if we are a real child
981                                 if (master->isChild(this))
982                                         setParent(master);
983                                 // if the master is not fully loaded
984                                 // it is probably just loading this
985                                 // child. No warning needed then.
986                                 else if (master->isFullyLoaded())
987                                         LYXERR0("The master '"
988                                                 << params().master
989                                                 << "' assigned to this document ("
990                                                 << absFileName()
991                                                 << ") does not include "
992                                                 "this document. Ignoring the master assignment.");
993                         }
994                 }
995         }
996
997         // assure we have a default index
998         params().indiceslist().addDefault(B_("Index"));
999
1000         // read main text
1001         bool const res = text().read(lex, errorList, d->inset);
1002
1003         // inform parent buffer about local macros
1004         if (parent()) {
1005                 Buffer const * pbuf = parent();
1006                 UserMacroSet::const_iterator cit = usermacros.begin();
1007                 UserMacroSet::const_iterator end = usermacros.end();
1008                 for (; cit != end; ++cit)
1009                         pbuf->usermacros.insert(*cit);
1010         }
1011         usermacros.clear();
1012         updateMacros();
1013         updateMacroInstances(InternalUpdate);
1014         return res;
1015 }
1016
1017
1018 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1019 {
1020         Format const * fmt = formats.getFormat(format);
1021         if (!fmt)
1022                 return false;
1023         // It is important to use the correct extension here, since some
1024         // converters create a wrong output file otherwise (e.g. html2latex)
1025         TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1026         FileName const name(tempfile.name());
1027         ofdocstream os(name.toFilesystemEncoding().c_str());
1028         // Do not convert os implicitly to bool, since that is forbidden in C++11.
1029         bool const success = !(os << contents).fail();
1030         os.close();
1031
1032         bool converted = false;
1033         if (success) {
1034                 params().compressed = false;
1035
1036                 // remove dummy empty par
1037                 paragraphs().clear();
1038
1039                 converted = importFile(format, name, errorList);
1040         }
1041
1042         if (name.exists())
1043                 name.removeFile();
1044         return converted;
1045 }
1046
1047
1048 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1049 {
1050         if (!theConverters().isReachable(format, "lyx"))
1051                 return false;
1052
1053         TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1054         FileName const lyx(tempfile.name());
1055         if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1056                 return readFile(lyx) == ReadSuccess;
1057
1058         return false;
1059 }
1060
1061
1062 bool Buffer::readString(string const & s)
1063 {
1064         params().compressed = false;
1065
1066         Lexer lex;
1067         istringstream is(s);
1068         lex.setStream(is);
1069         TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1070         FileName const fn = tempfile.name();
1071
1072         int file_format;
1073         bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1074
1075         if (success && file_format != LYX_FORMAT) {
1076                 // We need to call lyx2lyx, so write the input to a file
1077                 ofstream os(fn.toFilesystemEncoding().c_str());
1078                 os << s;
1079                 os.close();
1080                 // lyxvc in readFile
1081                 if (readFile(fn) != ReadSuccess)
1082                         success = false;
1083         }
1084         else if (success)
1085                 if (readDocument(lex))
1086                         success = false;
1087         return success;
1088 }
1089
1090
1091 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1092 {
1093         FileName fname(fn);
1094         Lexer lex;
1095         if (!lex.setFile(fname)) {
1096                 Alert::error(_("File Not Found"),
1097                         bformat(_("Unable to open file `%1$s'."),
1098                                 from_utf8(fn.absFileName())));
1099                 return ReadFileNotFound;
1100         }
1101
1102         int file_format;
1103         ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1104         if (ret_plf != ReadSuccess)
1105                 return ret_plf;
1106
1107         if (file_format != LYX_FORMAT) {
1108                 FileName tmpFile;
1109                 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1110                 if (ret_clf != ReadSuccess)
1111                         return ret_clf;
1112                 return readFile(tmpFile);
1113         }
1114
1115         // FIXME: InsetInfo needs to know whether the file is under VCS
1116         // during the parse process, so this has to be done before.
1117         lyxvc().file_found_hook(d->filename);
1118
1119         if (readDocument(lex)) {
1120                 Alert::error(_("Document format failure"),
1121                         bformat(_("%1$s ended unexpectedly, which means"
1122                                 " that it is probably corrupted."),
1123                                         from_utf8(fn.absFileName())));
1124                 return ReadDocumentFailure;
1125         }
1126
1127         d->file_fully_loaded = true;
1128         d->read_only = !d->filename.isWritable();
1129         params().compressed = formats.isZippedFile(d->filename);
1130         saveCheckSum();
1131         return ReadSuccess;
1132 }
1133
1134
1135 bool Buffer::isFullyLoaded() const
1136 {
1137         return d->file_fully_loaded;
1138 }
1139
1140
1141 void Buffer::setFullyLoaded(bool value)
1142 {
1143         d->file_fully_loaded = value;
1144 }
1145
1146
1147 PreviewLoader * Buffer::loader() const
1148 {
1149         if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1150                 return 0;
1151         if (!d->preview_loader_)
1152                 d->preview_loader_ = new PreviewLoader(*this);
1153         return d->preview_loader_;
1154 }
1155
1156
1157 void Buffer::removePreviews() const
1158 {
1159         delete d->preview_loader_;
1160         d->preview_loader_ = 0;
1161 }
1162
1163
1164 void Buffer::updatePreviews() const
1165 {
1166         PreviewLoader * ploader = loader();
1167         if (!ploader)
1168                 return;
1169
1170         InsetIterator it = inset_iterator_begin(*d->inset);
1171         InsetIterator const end = inset_iterator_end(*d->inset);
1172         for (; it != end; ++it)
1173                 it->addPreview(it, *ploader);
1174
1175         ploader->startLoading();
1176 }
1177
1178
1179 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1180         FileName const & fn, int & file_format) const
1181 {
1182         if(!lex.checkFor("\\lyxformat")) {
1183                 Alert::error(_("Document format failure"),
1184                         bformat(_("%1$s is not a readable LyX document."),
1185                                 from_utf8(fn.absFileName())));
1186                 return ReadNoLyXFormat;
1187         }
1188
1189         string tmp_format;
1190         lex >> tmp_format;
1191
1192         // LyX formats 217 and earlier were written as 2.17. This corresponds
1193         // to files from LyX versions < 1.1.6.3. We just remove the dot in
1194         // these cases. See also: www.lyx.org/trac/changeset/1313.
1195         size_t dot = tmp_format.find_first_of(".,");
1196         if (dot != string::npos)
1197                 tmp_format.erase(dot, 1);
1198
1199         file_format = convert<int>(tmp_format);
1200         return ReadSuccess;
1201 }
1202
1203
1204 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1205         FileName & tmpfile, int from_format)
1206 {
1207         TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1208         tempfile.setAutoRemove(false);
1209         tmpfile = tempfile.name();
1210         if(tmpfile.empty()) {
1211                 Alert::error(_("Conversion failed"),
1212                         bformat(_("%1$s is from a different"
1213                                 " version of LyX, but a temporary"
1214                                 " file for converting it could"
1215                                 " not be created."),
1216                                 from_utf8(fn.absFileName())));
1217                 return LyX2LyXNoTempFile;
1218         }
1219
1220         FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1221         if (lyx2lyx.empty()) {
1222                 Alert::error(_("Conversion script not found"),
1223                      bformat(_("%1$s is from a different"
1224                                " version of LyX, but the"
1225                                " conversion script lyx2lyx"
1226                                " could not be found."),
1227                                from_utf8(fn.absFileName())));
1228                 return LyX2LyXNotFound;
1229         }
1230
1231         // Run lyx2lyx:
1232         //   $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1233         ostringstream command;
1234         command << os::python()
1235                 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1236                 << " -t " << convert<string>(LYX_FORMAT)
1237                 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1238                 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1239         string const command_str = command.str();
1240
1241         LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1242
1243         cmd_ret const ret = runCommand(command_str);
1244         if (ret.first != 0) {
1245                 if (from_format < LYX_FORMAT) {
1246                         Alert::error(_("Conversion script failed"),
1247                                 bformat(_("%1$s is from an older version"
1248                                         " of LyX and the lyx2lyx script"
1249                                         " failed to convert it."),
1250                                         from_utf8(fn.absFileName())));
1251                         return LyX2LyXOlderFormat;
1252                 } else {
1253                         Alert::error(_("Conversion script failed"),
1254                                 bformat(_("%1$s is from a newer version"
1255                                         " of LyX and the lyx2lyx script"
1256                                         " failed to convert it."),
1257                                         from_utf8(fn.absFileName())));
1258                         return LyX2LyXNewerFormat;
1259                 }
1260         }
1261         return ReadSuccess;
1262 }
1263
1264
1265 // Should probably be moved to somewhere else: BufferView? GuiView?
1266 bool Buffer::save() const
1267 {
1268         docstring const file = makeDisplayPath(absFileName(), 20);
1269         d->filename.refresh();
1270
1271         // check the read-only status before moving the file as a backup
1272         if (d->filename.exists()) {
1273                 bool const read_only = !d->filename.isWritable();
1274                 if (read_only) {
1275                         Alert::warning(_("File is read-only"),
1276                                 bformat(_("The file %1$s cannot be written because it "
1277                                 "is marked as read-only."), file));
1278                         return false;
1279                 }
1280         }
1281
1282         // ask if the disk file has been externally modified (use checksum method)
1283         if (fileName().exists() && isExternallyModified(checksum_method)) {
1284                 docstring text =
1285                         bformat(_("Document %1$s has been externally modified. "
1286                                 "Are you sure you want to overwrite this file?"), file);
1287                 int const ret = Alert::prompt(_("Overwrite modified file?"),
1288                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
1289                 if (ret == 1)
1290                         return false;
1291         }
1292
1293         // We don't need autosaves in the immediate future. (Asger)
1294         resetAutosaveTimers();
1295
1296         // if the file does not yet exist, none of the backup activity
1297         // that follows is necessary
1298         if (!fileName().exists())
1299                 return writeFile(fileName());
1300
1301         // we first write the file to a new name, then move it to its
1302         // proper location once that has been done successfully. that
1303         // way we preserve the original file if something goes wrong.
1304         string const justname = fileName().onlyFileNameWithoutExt();
1305         boost::scoped_ptr<TempFile>
1306                 tempfile(new TempFile(fileName().onlyPath(),
1307                    justname + "-XXXXXX.lyx"));
1308         bool const symlink = fileName().isSymLink();
1309         if (!symlink)
1310                 tempfile->setAutoRemove(false);
1311
1312         FileName savefile(tempfile->name());
1313         LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1314         if (!writeFile(savefile))
1315                 return false;
1316
1317         // we will set this to false if we fail
1318         bool made_backup = true;
1319
1320         FileName backupName(absFileName() + '~');
1321         if (lyxrc.make_backup) {
1322                 if (!lyxrc.backupdir_path.empty()) {
1323                         string const mangledName =
1324                                 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1325                         backupName = FileName(addName(lyxrc.backupdir_path,
1326                                                       mangledName));
1327                 }
1328
1329                 LYXERR(Debug::FILES, "Backing up original file to " <<
1330                                 backupName.absFileName());
1331                 // Except file is symlink do not copy because of #6587.
1332                 // Hard links have bad luck.
1333                 made_backup = symlink ?
1334                         fileName().copyTo(backupName):
1335                         fileName().moveTo(backupName);
1336
1337                 if (!made_backup) {
1338                         Alert::error(_("Backup failure"),
1339                                      bformat(_("Cannot create backup file %1$s.\n"
1340                                                "Please check whether the directory exists and is writable."),
1341                                              from_utf8(backupName.absFileName())));
1342                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1343                 }
1344         }
1345
1346         // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1347         // Only do this if tempfile is not in autoremove mode
1348         if (!symlink)
1349                 tempfile.reset();
1350         // If we have no symlink, we can simply rename the temp file.
1351         // Otherwise, we need to copy it so the symlink stays intact.
1352         if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1353                                            savefile.moveTo(fileName()))
1354         {
1355                 // saveCheckSum() was already called by writeFile(), but the
1356                 // time stamp is invalidated by copying/moving
1357                 saveCheckSum();
1358                 markClean();
1359                 return true;
1360         }
1361         // else we saved the file, but failed to move it to the right location.
1362
1363         if (lyxrc.make_backup && made_backup && !symlink) {
1364                 // the original file was moved to filename.lyx~, so it will look
1365                 // to the user as if it was deleted. (see bug #9234.) we could try
1366                 // to restore it, but that would basically mean trying to do again
1367                 // what we just failed to do. better to leave things as they are.
1368                 Alert::error(_("Write failure"),
1369                              bformat(_("The file has successfully been saved as:\n  %1$s.\n"
1370                            "But LyX could not move it to:\n  %2$s.\n"
1371                                                          "Your original file has been backed up to:\n  %3$s"),
1372                                      from_utf8(savefile.absFileName()),
1373              from_utf8(fileName().absFileName()),
1374                          from_utf8(backupName.absFileName())));
1375         } else {
1376                 // either we did not try to make a backup, or else we tried and failed,
1377                 // or else the original file was a symlink, in which case it was copied,
1378                 // not moved. so the original file is intact.
1379                 Alert::error(_("Write failure"),
1380                              bformat(_("Cannot move saved file to:\n  %1$s.\n"
1381                                        "But the file has successfully been saved as:\n  %2$s."),
1382                                      from_utf8(fileName().absFileName()),
1383                          from_utf8(savefile.absFileName())));
1384         }
1385         return false;
1386 }
1387
1388
1389 bool Buffer::writeFile(FileName const & fname) const
1390 {
1391         if (d->read_only && fname == d->filename)
1392                 return false;
1393
1394         bool retval = false;
1395
1396         docstring const str = bformat(_("Saving document %1$s..."),
1397                 makeDisplayPath(fname.absFileName()));
1398         message(str);
1399
1400         string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1401
1402         if (params().compressed) {
1403                 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1404                 retval = ofs && write(ofs);
1405         } else {
1406                 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1407                 retval = ofs && write(ofs);
1408         }
1409
1410         if (!retval) {
1411                 message(str + _(" could not write file!"));
1412                 return false;
1413         }
1414
1415         // see bug 6587
1416         // removeAutosaveFile();
1417
1418         saveCheckSum();
1419         message(str + _(" done."));
1420
1421         return true;
1422 }
1423
1424
1425 docstring Buffer::emergencyWrite()
1426 {
1427         // No need to save if the buffer has not changed.
1428         if (isClean())
1429                 return docstring();
1430
1431         string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1432
1433         docstring user_message = bformat(
1434                 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1435
1436         // We try to save three places:
1437         // 1) Same place as document. Unless it is an unnamed doc.
1438         if (!isUnnamed()) {
1439                 string s = absFileName();
1440                 s += ".emergency";
1441                 LYXERR0("  " << s);
1442                 if (writeFile(FileName(s))) {
1443                         markClean();
1444                         user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1445                         return user_message;
1446                 } else {
1447                         user_message += "  " + _("Save failed! Trying again...\n");
1448                 }
1449         }
1450
1451         // 2) In HOME directory.
1452         string s = addName(Package::get_home_dir().absFileName(), absFileName());
1453         s += ".emergency";
1454         lyxerr << ' ' << s << endl;
1455         if (writeFile(FileName(s))) {
1456                 markClean();
1457                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1458                 return user_message;
1459         }
1460
1461         user_message += "  " + _("Save failed! Trying yet again...\n");
1462
1463         // 3) In "/tmp" directory.
1464         // MakeAbsPath to prepend the current
1465         // drive letter on OS/2
1466         s = addName(package().temp_dir().absFileName(), absFileName());
1467         s += ".emergency";
1468         lyxerr << ' ' << s << endl;
1469         if (writeFile(FileName(s))) {
1470                 markClean();
1471                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1472                 return user_message;
1473         }
1474
1475         user_message += "  " + _("Save failed! Bummer. Document is lost.");
1476         // Don't try again.
1477         markClean();
1478         return user_message;
1479 }
1480
1481
1482 bool Buffer::write(ostream & ofs) const
1483 {
1484 #ifdef HAVE_LOCALE
1485         // Use the standard "C" locale for file output.
1486         ofs.imbue(locale::classic());
1487 #endif
1488
1489         // The top of the file should not be written by params().
1490
1491         // write out a comment in the top of the file
1492         // Important: Keep the version formatting in sync with lyx2lyx and
1493         //            tex2lyx (bug 7951)
1494         ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1495             << " created this file. For more info see http://www.lyx.org/\n"
1496             << "\\lyxformat " << LYX_FORMAT << "\n"
1497             << "\\begin_document\n";
1498
1499         /// For each author, set 'used' to true if there is a change
1500         /// by this author in the document; otherwise set it to 'false'.
1501         AuthorList::Authors::const_iterator a_it = params().authors().begin();
1502         AuthorList::Authors::const_iterator a_end = params().authors().end();
1503         for (; a_it != a_end; ++a_it)
1504                 a_it->setUsed(false);
1505
1506         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1507         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1508         for ( ; it != end; ++it)
1509                 it->checkAuthors(params().authors());
1510
1511         // now write out the buffer parameters.
1512         ofs << "\\begin_header\n";
1513         params().writeFile(ofs);
1514         ofs << "\\end_header\n";
1515
1516         // write the text
1517         ofs << "\n\\begin_body\n";
1518         text().write(ofs);
1519         ofs << "\n\\end_body\n";
1520
1521         // Write marker that shows file is complete
1522         ofs << "\\end_document" << endl;
1523
1524         // Shouldn't really be needed....
1525         //ofs.close();
1526
1527         // how to check if close went ok?
1528         // Following is an attempt... (BE 20001011)
1529
1530         // good() returns false if any error occurred, including some
1531         //        formatting error.
1532         // bad()  returns true if something bad happened in the buffer,
1533         //        which should include file system full errors.
1534
1535         bool status = true;
1536         if (!ofs) {
1537                 status = false;
1538                 lyxerr << "File was not closed properly." << endl;
1539         }
1540
1541         return status;
1542 }
1543
1544
1545 bool Buffer::makeLaTeXFile(FileName const & fname,
1546                            string const & original_path,
1547                            OutputParams const & runparams_in,
1548                            OutputWhat output) const
1549 {
1550         OutputParams runparams = runparams_in;
1551
1552         // This is necessary for LuaTeX/XeTeX with tex fonts.
1553         // See FIXME in BufferParams::encoding()
1554         if (runparams.isFullUnicode())
1555                 runparams.encoding = encodings.fromLyXName("utf8-plain");
1556
1557         string const encoding = runparams.encoding->iconvName();
1558         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1559
1560         ofdocstream ofs;
1561         try { ofs.reset(encoding); }
1562         catch (iconv_codecvt_facet_exception const & e) {
1563                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1564                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1565                         "verify that the support software for your encoding (%1$s) is "
1566                         "properly installed"), from_ascii(encoding)));
1567                 return false;
1568         }
1569         if (!openFileWrite(ofs, fname))
1570                 return false;
1571
1572         ErrorList & errorList = d->errorLists["Export"];
1573         errorList.clear();
1574         bool failed_export = false;
1575         otexstream os(ofs, d->texrow);
1576
1577         // make sure we are ready to export
1578         // this needs to be done before we validate
1579         // FIXME Do we need to do this all the time? I.e., in children
1580         // of a master we are exporting?
1581         updateBuffer();
1582         updateMacroInstances(OutputUpdate);
1583
1584         try {
1585                 os.texrow().reset();
1586                 writeLaTeXSource(os, original_path, runparams, output);
1587         }
1588         catch (EncodingException const & e) {
1589                 docstring const failed(1, e.failed_char);
1590                 ostringstream oss;
1591                 oss << "0x" << hex << e.failed_char << dec;
1592                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1593                                           " (code point %2$s)"),
1594                                           failed, from_utf8(oss.str()));
1595                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1596                                 "representable in the chosen encoding.\n"
1597                                 "Changing the document encoding to utf8 could help."),
1598                                 e.par_id, e.pos, e.pos + 1));
1599                 failed_export = true;
1600         }
1601         catch (iconv_codecvt_facet_exception const & e) {
1602                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1603                         _(e.what()), -1, 0, 0));
1604                 failed_export = true;
1605         }
1606         catch (exception const & e) {
1607                 errorList.push_back(ErrorItem(_("conversion failed"),
1608                         _(e.what()), -1, 0, 0));
1609                 failed_export = true;
1610         }
1611         catch (...) {
1612                 lyxerr << "Caught some really weird exception..." << endl;
1613                 lyx_exit(1);
1614         }
1615
1616         ofs.close();
1617         if (ofs.fail()) {
1618                 failed_export = true;
1619                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1620         }
1621
1622         if (runparams_in.silent)
1623                 errorList.clear();
1624         else
1625                 errors("Export");
1626         return !failed_export;
1627 }
1628
1629
1630 void Buffer::writeLaTeXSource(otexstream & os,
1631                            string const & original_path,
1632                            OutputParams const & runparams_in,
1633                            OutputWhat output) const
1634 {
1635         // The child documents, if any, shall be already loaded at this point.
1636
1637         OutputParams runparams = runparams_in;
1638
1639         // This is necessary for LuaTeX/XeTeX with tex fonts.
1640         // See FIXME in BufferParams::encoding()
1641         if (runparams.isFullUnicode())
1642                 runparams.encoding = encodings.fromLyXName("utf8-plain");
1643
1644         // If we are compiling a file standalone, even if this is the
1645         // child of some other buffer, let's cut the link here, so the
1646         // file is really independent and no concurring settings from
1647         // the master (e.g. branch state) interfere (see #8100).
1648         if (!runparams.is_child)
1649                 d->ignore_parent = true;
1650
1651         // Classify the unicode characters appearing in math insets
1652         BufferEncodings::initUnicodeMath(*this);
1653
1654         // validate the buffer.
1655         LYXERR(Debug::LATEX, "  Validating buffer...");
1656         LaTeXFeatures features(*this, params(), runparams);
1657         validate(features);
1658         // This is only set once per document (in master)
1659         if (!runparams.is_child)
1660                 runparams.use_polyglossia = features.usePolyglossia();
1661         LYXERR(Debug::LATEX, "  Buffer validation done.");
1662
1663         bool const output_preamble =
1664                 output == FullSource || output == OnlyPreamble;
1665         bool const output_body =
1666                 output == FullSource || output == OnlyBody;
1667
1668         // The starting paragraph of the coming rows is the
1669         // first paragraph of the document. (Asger)
1670         if (output_preamble && runparams.nice) {
1671                 os << "%% LyX " << lyx_version << " created this file.  "
1672                         "For more info, see http://www.lyx.org/.\n"
1673                         "%% Do not edit unless you really know what "
1674                         "you are doing.\n";
1675         }
1676         LYXERR(Debug::INFO, "lyx document header finished");
1677
1678         // There are a few differences between nice LaTeX and usual files:
1679         // usual files have \batchmode and special input@path to allow
1680         // inclusion of figures specified by an explicitly relative path
1681         // (i.e., a path starting with './' or '../') with either \input or
1682         // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1683         // input@path is set when the actual parameter original_path is set.
1684         // This is done for usual tex-file, but not for nice-latex-file.
1685         // (Matthias 250696)
1686         // Note that input@path is only needed for something the user does
1687         // in the preamble, included .tex files or ERT, files included by
1688         // LyX work without it.
1689         if (output_preamble) {
1690                 if (!runparams.nice) {
1691                         // code for usual, NOT nice-latex-file
1692                         os << "\\batchmode\n"; // changed from \nonstopmode
1693                 }
1694                 if (!original_path.empty()) {
1695                         // FIXME UNICODE
1696                         // We don't know the encoding of inputpath
1697                         docstring const inputpath = from_utf8(original_path);
1698                         docstring uncodable_glyphs;
1699                         Encoding const * const enc = runparams.encoding;
1700                         if (enc) {
1701                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1702                                         if (!enc->encodable(inputpath[n])) {
1703                                                 docstring const glyph(1, inputpath[n]);
1704                                                 LYXERR0("Uncodable character '"
1705                                                         << glyph
1706                                                         << "' in input path!");
1707                                                 uncodable_glyphs += glyph;
1708                                         }
1709                                 }
1710                         }
1711
1712                         // warn user if we found uncodable glyphs.
1713                         if (!uncodable_glyphs.empty()) {
1714                                 frontend::Alert::warning(
1715                                         _("Uncodable character in file path"),
1716                                         support::bformat(
1717                                           _("The path of your document\n"
1718                                             "(%1$s)\n"
1719                                             "contains glyphs that are unknown "
1720                                             "in the current document encoding "
1721                                             "(namely %2$s). This may result in "
1722                                             "incomplete output, unless "
1723                                             "TEXINPUTS contains the document "
1724                                             "directory and you don't use "
1725                                             "explicitly relative paths (i.e., "
1726                                             "paths starting with './' or "
1727                                             "'../') in the preamble or in ERT."
1728                                             "\n\nIn case of problems, choose "
1729                                             "an appropriate document encoding\n"
1730                                             "(such as utf8) or change the "
1731                                             "file path name."),
1732                                           inputpath, uncodable_glyphs));
1733                         } else {
1734                                 string docdir =
1735                                         support::latex_path(original_path);
1736                                 if (contains(docdir, '#')) {
1737                                         docdir = subst(docdir, "#", "\\#");
1738                                         os << "\\catcode`\\#=11"
1739                                               "\\def\\#{#}\\catcode`\\#=6\n";
1740                                 }
1741                                 if (contains(docdir, '%')) {
1742                                         docdir = subst(docdir, "%", "\\%");
1743                                         os << "\\catcode`\\%=11"
1744                                               "\\def\\%{%}\\catcode`\\%=14\n";
1745                                 }
1746                                 os << "\\makeatletter\n"
1747                                    << "\\def\\input@path{{"
1748                                    << docdir << "/}}\n"
1749                                    << "\\makeatother\n";
1750                         }
1751                 }
1752
1753                 // get parent macros (if this buffer has a parent) which will be
1754                 // written at the document begin further down.
1755                 MacroSet parentMacros;
1756                 listParentMacros(parentMacros, features);
1757
1758                 // Write the preamble
1759                 runparams.use_babel = params().writeLaTeX(os, features,
1760                                                           d->filename.onlyPath());
1761
1762                 // Japanese might be required only in some children of a document,
1763                 // but once required, we must keep use_japanese true.
1764                 runparams.use_japanese |= features.isRequired("japanese");
1765
1766                 if (!output_body) {
1767                         // Restore the parenthood if needed
1768                         if (!runparams.is_child)
1769                                 d->ignore_parent = false;
1770                         return;
1771                 }
1772
1773                 // make the body.
1774                 os << "\\begin{document}\n";
1775
1776                 // output the parent macros
1777                 MacroSet::iterator it = parentMacros.begin();
1778                 MacroSet::iterator end = parentMacros.end();
1779                 for (; it != end; ++it) {
1780                         int num_lines = (*it)->write(os.os(), true);
1781                         os.texrow().newlines(num_lines);
1782                 }
1783
1784         } // output_preamble
1785
1786         os.texrow().start(paragraphs().begin()->id(), 0);
1787
1788         LYXERR(Debug::INFO, "preamble finished, now the body.");
1789
1790         // the real stuff
1791         latexParagraphs(*this, text(), os, runparams);
1792
1793         // Restore the parenthood if needed
1794         if (!runparams.is_child)
1795                 d->ignore_parent = false;
1796
1797         // add this just in case after all the paragraphs
1798         os << endl;
1799
1800         if (output_preamble) {
1801                 os << "\\end{document}\n";
1802                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1803         } else {
1804                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1805         }
1806         runparams_in.encoding = runparams.encoding;
1807
1808         // Just to be sure. (Asger)
1809         os.texrow().newline();
1810
1811         //for (int i = 0; i<d->texrow.rows(); i++) {
1812         // int id,pos;
1813         // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1814         //      lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1815         //}
1816
1817         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1818         LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1819 }
1820
1821
1822 void Buffer::makeDocBookFile(FileName const & fname,
1823                               OutputParams const & runparams,
1824                               OutputWhat output) const
1825 {
1826         LYXERR(Debug::LATEX, "makeDocBookFile...");
1827
1828         ofdocstream ofs;
1829         if (!openFileWrite(ofs, fname))
1830                 return;
1831
1832         // make sure we are ready to export
1833         // this needs to be done before we validate
1834         updateBuffer();
1835         updateMacroInstances(OutputUpdate);
1836
1837         writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1838
1839         ofs.close();
1840         if (ofs.fail())
1841                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1842 }
1843
1844
1845 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1846                              OutputParams const & runparams,
1847                              OutputWhat output) const
1848 {
1849         LaTeXFeatures features(*this, params(), runparams);
1850         validate(features);
1851
1852         d->texrow.reset();
1853
1854         DocumentClass const & tclass = params().documentClass();
1855         string const & top_element = tclass.latexname();
1856
1857         bool const output_preamble =
1858                 output == FullSource || output == OnlyPreamble;
1859         bool const output_body =
1860           output == FullSource || output == OnlyBody;
1861
1862         if (output_preamble) {
1863                 if (runparams.flavor == OutputParams::XML)
1864                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1865
1866                 // FIXME UNICODE
1867                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1868
1869                 // FIXME UNICODE
1870                 if (! tclass.class_header().empty())
1871                         os << from_ascii(tclass.class_header());
1872                 else if (runparams.flavor == OutputParams::XML)
1873                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1874                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1875                 else
1876                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1877
1878                 docstring preamble = from_utf8(params().preamble);
1879                 if (runparams.flavor != OutputParams::XML ) {
1880                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1881                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1882                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1883                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1884                 }
1885
1886                 string const name = runparams.nice
1887                         ? changeExtension(absFileName(), ".sgml") : fname;
1888                 preamble += features.getIncludedFiles(name);
1889                 preamble += features.getLyXSGMLEntities();
1890
1891                 if (!preamble.empty()) {
1892                         os << "\n [ " << preamble << " ]";
1893                 }
1894                 os << ">\n\n";
1895         }
1896
1897         if (output_body) {
1898                 string top = top_element;
1899                 top += " lang=\"";
1900                 if (runparams.flavor == OutputParams::XML)
1901                         top += params().language->code();
1902                 else
1903                         top += params().language->code().substr(0, 2);
1904                 top += '"';
1905
1906                 if (!params().options.empty()) {
1907                         top += ' ';
1908                         top += params().options;
1909                 }
1910
1911                 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1912                                 << " file was created by LyX " << lyx_version
1913                                 << "\n  See http://www.lyx.org/ for more information -->\n";
1914
1915                 params().documentClass().counters().reset();
1916
1917                 sgml::openTag(os, top);
1918                 os << '\n';
1919                 docbookParagraphs(text(), *this, os, runparams);
1920                 sgml::closeTag(os, top_element);
1921         }
1922 }
1923
1924
1925 void Buffer::makeLyXHTMLFile(FileName const & fname,
1926                               OutputParams const & runparams) const
1927 {
1928         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1929
1930         ofdocstream ofs;
1931         if (!openFileWrite(ofs, fname))
1932                 return;
1933
1934         // make sure we are ready to export
1935         // this has to be done before we validate
1936         updateBuffer(UpdateMaster, OutputUpdate);
1937         updateMacroInstances(OutputUpdate);
1938
1939         writeLyXHTMLSource(ofs, runparams, FullSource);
1940
1941         ofs.close();
1942         if (ofs.fail())
1943                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1944 }
1945
1946
1947 void Buffer::writeLyXHTMLSource(odocstream & os,
1948                              OutputParams const & runparams,
1949                              OutputWhat output) const
1950 {
1951         LaTeXFeatures features(*this, params(), runparams);
1952         validate(features);
1953         d->bibinfo_.makeCitationLabels(*this);
1954
1955         bool const output_preamble =
1956                 output == FullSource || output == OnlyPreamble;
1957         bool const output_body =
1958           output == FullSource || output == OnlyBody || output == IncludedFile;
1959
1960         if (output_preamble) {
1961                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1962                    << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\">\n"
1963                    // FIXME Language should be set properly.
1964                    << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1965                    << "<head>\n"
1966                    << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1967                    // FIXME Presumably need to set this right
1968                    << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1969
1970                 docstring const & doctitle = features.htmlTitle();
1971                 os << "<title>"
1972                    << (doctitle.empty() ?
1973                          from_ascii("LyX Document") :
1974                          html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1975                    << "</title>\n";
1976
1977                 docstring styles = features.getTClassHTMLPreamble();
1978                 if (!styles.empty())
1979                         os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1980
1981                 styles = from_utf8(features.getPreambleSnippets());
1982                 if (!styles.empty())
1983                         os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1984
1985                 // we will collect CSS information in a stream, and then output it
1986                 // either here, as part of the header, or else in a separate file.
1987                 odocstringstream css;
1988                 styles = from_utf8(features.getCSSSnippets());
1989                 if (!styles.empty())
1990                         css << "/* LyX Provided Styles */\n" << styles << '\n';
1991
1992                 styles = features.getTClassHTMLStyles();
1993                 if (!styles.empty())
1994                         css << "/* Layout-provided Styles */\n" << styles << '\n';
1995
1996                 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1997                 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1998                 if (needfg || needbg) {
1999                                 css << "\nbody {\n";
2000                                 if (needfg)
2001                                    css << "  color: "
2002                                             << from_ascii(X11hexname(params().fontcolor))
2003                                             << ";\n";
2004                                 if (needbg)
2005                                    css << "  background-color: "
2006                                             << from_ascii(X11hexname(params().backgroundcolor))
2007                                             << ";\n";
2008                                 css << "}\n";
2009                 }
2010
2011                 docstring const dstyles = css.str();
2012                 if (!dstyles.empty()) {
2013                         bool written = false;
2014                         if (params().html_css_as_file) {
2015                                 // open a file for CSS info
2016                                 ofdocstream ocss;
2017                                 string const fcssname = addName(temppath(), "docstyle.css");
2018                                 FileName const fcssfile = FileName(fcssname);
2019                                 if (openFileWrite(ocss, fcssfile)) {
2020                                         ocss << dstyles;
2021                                         ocss.close();
2022                                         written = true;
2023                                         // write link to header
2024                                         os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2025                                         // register file
2026                                         runparams.exportdata->addExternalFile("xhtml", fcssfile);
2027                                 }
2028                         }
2029                         // we are here if the CSS is supposed to be written to the header
2030                         // or if we failed to write it to an external file.
2031                         if (!written) {
2032                                 os << "<style type='text/css'>\n"
2033                                          << dstyles
2034                                          << "\n</style>\n";
2035                         }
2036                 }
2037                 os << "</head>\n";
2038         }
2039
2040         if (output_body) {
2041                 bool const output_body_tag = (output != IncludedFile);
2042                 if (output_body_tag)
2043                         os << "<body>\n";
2044                 XHTMLStream xs(os);
2045                 if (output != IncludedFile)
2046                         // if we're an included file, the counters are in the master.
2047                         params().documentClass().counters().reset();
2048                 xhtmlParagraphs(text(), *this, xs, runparams);
2049                 if (output_body_tag)
2050                         os << "</body>\n";
2051         }
2052
2053         if (output_preamble)
2054                 os << "</html>\n";
2055 }
2056
2057
2058 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2059 // Other flags: -wall -v0 -x
2060 int Buffer::runChktex()
2061 {
2062         setBusy(true);
2063
2064         // get LaTeX-Filename
2065         FileName const path(temppath());
2066         string const name = addName(path.absFileName(), latexName());
2067         string const org_path = filePath();
2068
2069         PathChanger p(path); // path to LaTeX file
2070         message(_("Running chktex..."));
2071
2072         // Generate the LaTeX file if neccessary
2073         OutputParams runparams(&params().encoding());
2074         runparams.flavor = OutputParams::LATEX;
2075         runparams.nice = false;
2076         runparams.linelen = lyxrc.plaintext_linelen;
2077         makeLaTeXFile(FileName(name), org_path, runparams);
2078
2079         TeXErrors terr;
2080         Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2081         int const res = chktex.run(terr); // run chktex
2082
2083         if (res == -1) {
2084                 Alert::error(_("chktex failure"),
2085                              _("Could not run chktex successfully."));
2086         } else {
2087                 ErrorList & errlist = d->errorLists["ChkTeX"];
2088                 errlist.clear();
2089                 bufferErrors(terr, errlist);
2090         }
2091
2092         setBusy(false);
2093
2094         if (runparams.silent)
2095                 d->errorLists["ChkTeX"].clear();
2096         else
2097                 errors("ChkTeX");
2098
2099         return res;
2100 }
2101
2102
2103 void Buffer::validate(LaTeXFeatures & features) const
2104 {
2105         // Validate the buffer params, but not for included
2106         // files, since they also use the parent buffer's
2107         // params (# 5941)
2108         if (!features.runparams().is_child)
2109                 params().validate(features);
2110
2111         for_each(paragraphs().begin(), paragraphs().end(),
2112                  bind(&Paragraph::validate, _1, ref(features)));
2113
2114         if (lyxerr.debugging(Debug::LATEX)) {
2115                 features.showStruct();
2116         }
2117 }
2118
2119
2120 void Buffer::getLabelList(vector<docstring> & list) const
2121 {
2122         // If this is a child document, use the master's list instead.
2123         if (parent()) {
2124                 masterBuffer()->getLabelList(list);
2125                 return;
2126         }
2127
2128         list.clear();
2129         Toc & toc = d->toc_backend.toc("label");
2130         TocIterator toc_it = toc.begin();
2131         TocIterator end = toc.end();
2132         for (; toc_it != end; ++toc_it) {
2133                 if (toc_it->depth() == 0)
2134                         list.push_back(toc_it->str());
2135         }
2136 }
2137
2138
2139 void Buffer::updateBibfilesCache(UpdateScope scope) const
2140 {
2141         // FIXME This is probably unnecssary, given where we call this.
2142         // If this is a child document, use the parent's cache instead.
2143         if (parent() && scope != UpdateChildOnly) {
2144                 masterBuffer()->updateBibfilesCache();
2145                 return;
2146         }
2147
2148         d->bibfiles_cache_.clear();
2149         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2150                 if (it->lyxCode() == BIBTEX_CODE) {
2151                         InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2152                         support::FileNameList const bibfiles = inset.getBibFiles();
2153                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2154                                 bibfiles.begin(),
2155                                 bibfiles.end());
2156                 } else if (it->lyxCode() == INCLUDE_CODE) {
2157                         InsetInclude & inset = static_cast<InsetInclude &>(*it);
2158                         Buffer const * const incbuf = inset.getChildBuffer();
2159                         if (!incbuf)
2160                                 continue;
2161                         support::FileNameList const & bibfiles =
2162                                         incbuf->getBibfilesCache(UpdateChildOnly);
2163                         if (!bibfiles.empty()) {
2164                                 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2165                                         bibfiles.begin(),
2166                                         bibfiles.end());
2167                         }
2168                 }
2169         }
2170         d->bibfile_cache_valid_ = true;
2171         d->bibinfo_cache_valid_ = false;
2172         d->cite_labels_valid_ = false;
2173 }
2174
2175
2176 void Buffer::invalidateBibinfoCache() const
2177 {
2178         d->bibinfo_cache_valid_ = false;
2179         d->cite_labels_valid_ = false;
2180         // also invalidate the cache for the parent buffer
2181         Buffer const * const pbuf = d->parent();
2182         if (pbuf)
2183                 pbuf->invalidateBibinfoCache();
2184 }
2185
2186
2187 void Buffer::invalidateBibfileCache() const
2188 {
2189         d->bibfile_cache_valid_ = false;
2190         d->bibinfo_cache_valid_ = false;
2191         d->cite_labels_valid_ = false;
2192         // also invalidate the cache for the parent buffer
2193         Buffer const * const pbuf = d->parent();
2194         if (pbuf)
2195                 pbuf->invalidateBibfileCache();
2196 }
2197
2198
2199 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2200 {
2201         // FIXME This is probably unnecessary, given where we call this.
2202         // If this is a child document, use the master's cache instead.
2203         Buffer const * const pbuf = masterBuffer();
2204         if (pbuf != this && scope != UpdateChildOnly)
2205                 return pbuf->getBibfilesCache();
2206
2207         if (!d->bibfile_cache_valid_)
2208                 this->updateBibfilesCache(scope);
2209
2210         return d->bibfiles_cache_;
2211 }
2212
2213
2214 BiblioInfo const & Buffer::masterBibInfo() const
2215 {
2216         Buffer const * const tmp = masterBuffer();
2217         if (tmp != this)
2218                 return tmp->masterBibInfo();
2219         return d->bibinfo_;
2220 }
2221
2222
2223 void Buffer::checkIfBibInfoCacheIsValid() const
2224 {
2225         // use the master's cache
2226         Buffer const * const tmp = masterBuffer();
2227         if (tmp != this) {
2228                 tmp->checkIfBibInfoCacheIsValid();
2229                 return;
2230         }
2231
2232         // compare the cached timestamps with the actual ones.
2233         FileNameList const & bibfiles_cache = getBibfilesCache();
2234         FileNameList::const_iterator ei = bibfiles_cache.begin();
2235         FileNameList::const_iterator en = bibfiles_cache.end();
2236         for (; ei != en; ++ ei) {
2237                 time_t lastw = ei->lastModified();
2238                 time_t prevw = d->bibfile_status_[*ei];
2239                 if (lastw != prevw) {
2240                         d->bibinfo_cache_valid_ = false;
2241                         d->cite_labels_valid_ = false;
2242                         d->bibfile_status_[*ei] = lastw;
2243                 }
2244         }
2245 }
2246
2247
2248 void Buffer::reloadBibInfoCache() const
2249 {
2250         // use the master's cache
2251         Buffer const * const tmp = masterBuffer();
2252         if (tmp != this) {
2253                 tmp->reloadBibInfoCache();
2254                 return;
2255         }
2256
2257         checkIfBibInfoCacheIsValid();
2258         if (d->bibinfo_cache_valid_)
2259                 return;
2260
2261         d->bibinfo_.clear();
2262         collectBibKeys();
2263         d->bibinfo_cache_valid_ = true;
2264 }
2265
2266
2267 void Buffer::collectBibKeys() const
2268 {
2269         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2270                 it->collectBibKeys(it);
2271 }
2272
2273
2274 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2275 {
2276         Buffer const * tmp = masterBuffer();
2277         BiblioInfo & masterbi = (tmp == this) ?
2278                 d->bibinfo_ : tmp->d->bibinfo_;
2279         masterbi.mergeBiblioInfo(bi);
2280 }
2281
2282
2283 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2284 {
2285         Buffer const * tmp = masterBuffer();
2286         BiblioInfo & masterbi = (tmp == this) ?
2287                 d->bibinfo_ : tmp->d->bibinfo_;
2288         masterbi[key] = bi;
2289 }
2290
2291
2292 void Buffer::makeCitationLabels() const
2293 {
2294         Buffer const * const master = masterBuffer();
2295         return d->bibinfo_.makeCitationLabels(*master);
2296 }
2297
2298
2299 bool Buffer::citeLabelsValid() const
2300 {
2301         return masterBuffer()->d->cite_labels_valid_;
2302 }
2303
2304
2305 void Buffer::removeBiblioTempFiles() const
2306 {
2307         // We remove files that contain LaTeX commands specific to the
2308         // particular bibliographic style being used, in order to avoid
2309         // LaTeX errors when we switch style.
2310         FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2311         FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2312         LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2313         aux_file.removeFile();
2314         LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2315         bbl_file.removeFile();
2316         // Also for the parent buffer
2317         Buffer const * const pbuf = parent();
2318         if (pbuf)
2319                 pbuf->removeBiblioTempFiles();
2320 }
2321
2322
2323 bool Buffer::isDepClean(string const & name) const
2324 {
2325         DepClean::const_iterator const it = d->dep_clean.find(name);
2326         if (it == d->dep_clean.end())
2327                 return true;
2328         return it->second;
2329 }
2330
2331
2332 void Buffer::markDepClean(string const & name)
2333 {
2334         d->dep_clean[name] = true;
2335 }
2336
2337
2338 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2339 {
2340         if (isInternal()) {
2341                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2342                 // if internal, put a switch '(cmd.action)' here.
2343                 return false;
2344         }
2345
2346         bool enable = true;
2347
2348         switch (cmd.action()) {
2349
2350         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2351                 flag.setOnOff(isReadonly());
2352                 break;
2353
2354                 // FIXME: There is need for a command-line import.
2355                 //case LFUN_BUFFER_IMPORT:
2356
2357         case LFUN_BUFFER_AUTO_SAVE:
2358                 break;
2359
2360         case LFUN_BUFFER_EXPORT_CUSTOM:
2361                 // FIXME: Nothing to check here?
2362                 break;
2363
2364         case LFUN_BUFFER_EXPORT: {
2365                 docstring const arg = cmd.argument();
2366                 if (arg == "custom") {
2367                         enable = true;
2368                         break;
2369                 }
2370                 string format = to_utf8(arg);
2371                 size_t pos = format.find(' ');
2372                 if (pos != string::npos)
2373                         format = format.substr(0, pos);
2374                 enable = params().isExportable(format);
2375                 if (!enable)
2376                         flag.message(bformat(
2377                                              _("Don't know how to export to format: %1$s"), arg));
2378                 break;
2379         }
2380
2381         case LFUN_BUFFER_CHKTEX:
2382                 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2383                 break;
2384
2385         case LFUN_BUILD_PROGRAM:
2386                 enable = params().isExportable("program");
2387                 break;
2388
2389         case LFUN_BRANCH_ACTIVATE:
2390         case LFUN_BRANCH_DEACTIVATE:
2391         case LFUN_BRANCH_MASTER_ACTIVATE:
2392         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2393                 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2394                                      || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2395                 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2396                         : params().branchlist();
2397                 docstring const branchName = cmd.argument();
2398                 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2399                 break;
2400         }
2401
2402         case LFUN_BRANCH_ADD:
2403         case LFUN_BRANCHES_RENAME:
2404         case LFUN_BUFFER_PRINT:
2405                 // if no Buffer is present, then of course we won't be called!
2406                 break;
2407
2408         case LFUN_BUFFER_LANGUAGE:
2409                 enable = !isReadonly();
2410                 break;
2411
2412         default:
2413                 return false;
2414         }
2415         flag.setEnabled(enable);
2416         return true;
2417 }
2418
2419
2420 void Buffer::dispatch(string const & command, DispatchResult & result)
2421 {
2422         return dispatch(lyxaction.lookupFunc(command), result);
2423 }
2424
2425
2426 // NOTE We can end up here even if we have no GUI, because we are called
2427 // by LyX::exec to handled command-line requests. So we may need to check
2428 // whether we have a GUI or not. The boolean use_gui holds this information.
2429 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2430 {
2431         if (isInternal()) {
2432                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2433                 // if internal, put a switch '(cmd.action())' here.
2434                 dr.dispatched(false);
2435                 return;
2436         }
2437         string const argument = to_utf8(func.argument());
2438         // We'll set this back to false if need be.
2439         bool dispatched = true;
2440         undo().beginUndoGroup();
2441
2442         switch (func.action()) {
2443         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2444                 if (lyxvc().inUse()) {
2445                         string log = lyxvc().toggleReadOnly();
2446                         if (!log.empty())
2447                                 dr.setMessage(log);
2448                 }
2449                 else
2450                         setReadonly(!isReadonly());
2451                 break;
2452
2453         case LFUN_BUFFER_EXPORT: {
2454                 ExportStatus const status = doExport(argument, false);
2455                 dr.setError(status != ExportSuccess);
2456                 if (status != ExportSuccess)
2457                         dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2458                                               func.argument()));
2459                 break;
2460         }
2461
2462         case LFUN_BUILD_PROGRAM: {
2463                 ExportStatus const status = doExport("program", true);
2464                 dr.setError(status != ExportSuccess);
2465                 if (status != ExportSuccess)
2466                         dr.setMessage(_("Error generating literate programming code."));
2467                 break;
2468         }
2469
2470         case LFUN_BUFFER_CHKTEX:
2471                 runChktex();
2472                 break;
2473
2474         case LFUN_BUFFER_EXPORT_CUSTOM: {
2475                 string format_name;
2476                 string command = split(argument, format_name, ' ');
2477                 Format const * format = formats.getFormat(format_name);
2478                 if (!format) {
2479                         lyxerr << "Format \"" << format_name
2480                                 << "\" not recognized!"
2481                                 << endl;
2482                         break;
2483                 }
2484
2485                 // The name of the file created by the conversion process
2486                 string filename;
2487
2488                 // Output to filename
2489                 if (format->name() == "lyx") {
2490                         string const latexname = latexName(false);
2491                         filename = changeExtension(latexname,
2492                                 format->extension());
2493                         filename = addName(temppath(), filename);
2494
2495                         if (!writeFile(FileName(filename)))
2496                                 break;
2497
2498                 } else {
2499                         doExport(format_name, true, filename);
2500                 }
2501
2502                 // Substitute $$FName for filename
2503                 if (!contains(command, "$$FName"))
2504                         command = "( " + command + " ) < $$FName";
2505                 command = subst(command, "$$FName", filename);
2506
2507                 // Execute the command in the background
2508                 Systemcall call;
2509                 call.startscript(Systemcall::DontWait, command, filePath());
2510                 break;
2511         }
2512
2513         // FIXME: There is need for a command-line import.
2514         /*
2515         case LFUN_BUFFER_IMPORT:
2516                 doImport(argument);
2517                 break;
2518         */
2519
2520         case LFUN_BUFFER_AUTO_SAVE:
2521                 autoSave();
2522                 resetAutosaveTimers();
2523                 break;
2524
2525         case LFUN_BRANCH_ACTIVATE:
2526         case LFUN_BRANCH_DEACTIVATE:
2527         case LFUN_BRANCH_MASTER_ACTIVATE:
2528         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2529                 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2530                                      || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2531                 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2532                                       : this;
2533
2534                 docstring const branch_name = func.argument();
2535                 // the case without a branch name is handled elsewhere
2536                 if (branch_name.empty()) {
2537                         dispatched = false;
2538                         break;
2539                 }
2540                 Branch * branch = buf->params().branchlist().find(branch_name);
2541                 if (!branch) {
2542                         LYXERR0("Branch " << branch_name << " does not exist.");
2543                         dr.setError(true);
2544                         docstring const msg =
2545                                 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2546                         dr.setMessage(msg);
2547                         break;
2548                 }
2549                 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2550                                        || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2551                 if (branch->isSelected() != activate) {
2552                         buf->undo().recordUndoBufferParams(CursorData());
2553                         branch->setSelected(activate);
2554                         dr.setError(false);
2555                         dr.screenUpdate(Update::Force);
2556                         dr.forceBufferUpdate();
2557                 }
2558                 break;
2559         }
2560
2561         case LFUN_BRANCH_ADD: {
2562                 docstring branch_name = func.argument();
2563                 if (branch_name.empty()) {
2564                         dispatched = false;
2565                         break;
2566                 }
2567                 BranchList & branch_list = params().branchlist();
2568                 vector<docstring> const branches =
2569                         getVectorFromString(branch_name, branch_list.separator());
2570                 docstring msg;
2571                 for (vector<docstring>::const_iterator it = branches.begin();
2572                      it != branches.end(); ++it) {
2573                         branch_name = *it;
2574                         Branch * branch = branch_list.find(branch_name);
2575                         if (branch) {
2576                                 LYXERR0("Branch " << branch_name << " already exists.");
2577                                 dr.setError(true);
2578                                 if (!msg.empty())
2579                                         msg += ("\n");
2580                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2581                         } else {
2582                                 undo().recordUndoBufferParams(CursorData());
2583                                 branch_list.add(branch_name);
2584                                 branch = branch_list.find(branch_name);
2585                                 string const x11hexname = X11hexname(branch->color());
2586                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2587                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2588                                 dr.setError(false);
2589                                 dr.screenUpdate(Update::Force);
2590                         }
2591                 }
2592                 if (!msg.empty())
2593                         dr.setMessage(msg);
2594                 break;
2595         }
2596
2597         case LFUN_BRANCHES_RENAME: {
2598                 if (func.argument().empty())
2599                         break;
2600
2601                 docstring const oldname = from_utf8(func.getArg(0));
2602                 docstring const newname = from_utf8(func.getArg(1));
2603                 InsetIterator it  = inset_iterator_begin(inset());
2604                 InsetIterator const end = inset_iterator_end(inset());
2605                 bool success = false;
2606                 for (; it != end; ++it) {
2607                         if (it->lyxCode() == BRANCH_CODE) {
2608                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2609                                 if (ins.branch() == oldname) {
2610                                         undo().recordUndo(CursorData(it));
2611                                         ins.rename(newname);
2612                                         success = true;
2613                                         continue;
2614                                 }
2615                         }
2616                         if (it->lyxCode() == INCLUDE_CODE) {
2617                                 // get buffer of external file
2618                                 InsetInclude const & ins =
2619                                         static_cast<InsetInclude const &>(*it);
2620                                 Buffer * child = ins.getChildBuffer();
2621                                 if (!child)
2622                                         continue;
2623                                 child->dispatch(func, dr);
2624                         }
2625                 }
2626
2627                 if (success) {
2628                         dr.screenUpdate(Update::Force);
2629                         dr.forceBufferUpdate();
2630                 }
2631                 break;
2632         }
2633
2634         case LFUN_BUFFER_PRINT: {
2635                 // we'll assume there's a problem until we succeed
2636                 dr.setError(true);
2637                 string target = func.getArg(0);
2638                 string target_name = func.getArg(1);
2639                 string command = func.getArg(2);
2640
2641                 if (target.empty()
2642                     || target_name.empty()
2643                     || command.empty()) {
2644                         LYXERR0("Unable to parse " << func.argument());
2645                         docstring const msg =
2646                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2647                         dr.setMessage(msg);
2648                         break;
2649                 }
2650                 if (target != "printer" && target != "file") {
2651                         LYXERR0("Unrecognized target \"" << target << '"');
2652                         docstring const msg =
2653                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2654                         dr.setMessage(msg);
2655                         break;
2656                 }
2657
2658                 if (doExport("dvi", true) != ExportSuccess) {
2659                         showPrintError(absFileName());
2660                         dr.setMessage(_("Error exporting to DVI."));
2661                         break;
2662                 }
2663
2664                 // Push directory path.
2665                 string const path = temppath();
2666                 // Prevent the compiler from optimizing away p
2667                 FileName pp(path);
2668                 PathChanger p(pp);
2669
2670                 // there are three cases here:
2671                 // 1. we print to a file
2672                 // 2. we print directly to a printer
2673                 // 3. we print using a spool command (print to file first)
2674                 Systemcall one;
2675                 int res = 0;
2676                 string const dviname = changeExtension(latexName(true), "dvi");
2677
2678                 if (target == "printer") {
2679                         if (!lyxrc.print_spool_command.empty()) {
2680                                 // case 3: print using a spool
2681                                 string const psname = changeExtension(dviname,".ps");
2682                                 command += ' ' + lyxrc.print_to_file
2683                                         + quoteName(psname)
2684                                         + ' '
2685                                         + quoteName(dviname);
2686
2687                                 string command2 = lyxrc.print_spool_command + ' ';
2688                                 if (target_name != "default") {
2689                                         command2 += lyxrc.print_spool_printerprefix
2690                                                 + target_name
2691                                                 + ' ';
2692                                 }
2693                                 command2 += quoteName(psname);
2694                                 // First run dvips.
2695                                 // If successful, then spool command
2696                                 res = one.startscript(Systemcall::Wait, command,
2697                                                       filePath());
2698
2699                                 if (res == 0) {
2700                                         // If there's no GUI, we have to wait on this command. Otherwise,
2701                                         // LyX deletes the temporary directory, and with it the spooled
2702                                         // file, before it can be printed!!
2703                                         Systemcall::Starttype stype = use_gui ?
2704                                                 Systemcall::DontWait : Systemcall::Wait;
2705                                         res = one.startscript(stype, command2,
2706                                                               filePath());
2707                                 }
2708                         } else {
2709                                 // case 2: print directly to a printer
2710                                 if (target_name != "default")
2711                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2712                                 // as above....
2713                                 Systemcall::Starttype stype = use_gui ?
2714                                         Systemcall::DontWait : Systemcall::Wait;
2715                                 res = one.startscript(stype, command +
2716                                                 quoteName(dviname), filePath());
2717                         }
2718
2719                 } else {
2720                         // case 1: print to a file
2721                         FileName const filename(makeAbsPath(target_name, filePath()));
2722                         FileName const dvifile(makeAbsPath(dviname, path));
2723                         if (filename.exists()) {
2724                                 docstring text = bformat(
2725                                         _("The file %1$s already exists.\n\n"
2726                                           "Do you want to overwrite that file?"),
2727                                         makeDisplayPath(filename.absFileName()));
2728                                 if (Alert::prompt(_("Overwrite file?"),
2729                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2730                                         break;
2731                         }
2732                         command += ' ' + lyxrc.print_to_file
2733                                 + quoteName(filename.toFilesystemEncoding())
2734                                 + ' '
2735                                 + quoteName(dvifile.toFilesystemEncoding());
2736                         // as above....
2737                         Systemcall::Starttype stype = use_gui ?
2738                                 Systemcall::DontWait : Systemcall::Wait;
2739                         res = one.startscript(stype, command, filePath());
2740                 }
2741
2742                 if (res == 0)
2743                         dr.setError(false);
2744                 else {
2745                         dr.setMessage(_("Error running external commands."));
2746                         showPrintError(absFileName());
2747                 }
2748                 break;
2749         }
2750
2751         default:
2752                 dispatched = false;
2753                 break;
2754         }
2755         dr.dispatched(dispatched);
2756         undo().endUndoGroup();
2757 }
2758
2759
2760 void Buffer::changeLanguage(Language const * from, Language const * to)
2761 {
2762         LASSERT(from, return);
2763         LASSERT(to, return);
2764
2765         for_each(par_iterator_begin(),
2766                  par_iterator_end(),
2767                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2768 }
2769
2770
2771 bool Buffer::isMultiLingual() const
2772 {
2773         ParConstIterator end = par_iterator_end();
2774         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2775                 if (it->isMultiLingual(params()))
2776                         return true;
2777
2778         return false;
2779 }
2780
2781
2782 std::set<Language const *> Buffer::getLanguages() const
2783 {
2784         std::set<Language const *> languages;
2785         getLanguages(languages);
2786         return languages;
2787 }
2788
2789
2790 void Buffer::getLanguages(std::set<Language const *> & languages) const
2791 {
2792         ParConstIterator end = par_iterator_end();
2793         // add the buffer language, even if it's not actively used
2794         languages.insert(language());
2795         // iterate over the paragraphs
2796         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2797                 it->getLanguages(languages);
2798         // also children
2799         ListOfBuffers clist = getDescendents();
2800         ListOfBuffers::const_iterator cit = clist.begin();
2801         ListOfBuffers::const_iterator const cen = clist.end();
2802         for (; cit != cen; ++cit)
2803                 (*cit)->getLanguages(languages);
2804 }
2805
2806
2807 DocIterator Buffer::getParFromID(int const id) const
2808 {
2809         Buffer * buf = const_cast<Buffer *>(this);
2810         if (id < 0) {
2811                 // John says this is called with id == -1 from undo
2812                 lyxerr << "getParFromID(), id: " << id << endl;
2813                 return doc_iterator_end(buf);
2814         }
2815
2816         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2817                 if (it.paragraph().id() == id)
2818                         return it;
2819
2820         return doc_iterator_end(buf);
2821 }
2822
2823
2824 bool Buffer::hasParWithID(int const id) const
2825 {
2826         return !getParFromID(id).atEnd();
2827 }
2828
2829
2830 ParIterator Buffer::par_iterator_begin()
2831 {
2832         return ParIterator(doc_iterator_begin(this));
2833 }
2834
2835
2836 ParIterator Buffer::par_iterator_end()
2837 {
2838         return ParIterator(doc_iterator_end(this));
2839 }
2840
2841
2842 ParConstIterator Buffer::par_iterator_begin() const
2843 {
2844         return ParConstIterator(doc_iterator_begin(this));
2845 }
2846
2847
2848 ParConstIterator Buffer::par_iterator_end() const
2849 {
2850         return ParConstIterator(doc_iterator_end(this));
2851 }
2852
2853
2854 Language const * Buffer::language() const
2855 {
2856         return params().language;
2857 }
2858
2859
2860 docstring const Buffer::B_(string const & l10n) const
2861 {
2862         return params().B_(l10n);
2863 }
2864
2865
2866 bool Buffer::isClean() const
2867 {
2868         return d->lyx_clean;
2869 }
2870
2871
2872 bool Buffer::isExternallyModified(CheckMethod method) const
2873 {
2874         LASSERT(d->filename.exists(), return false);
2875         // if method == timestamp, check timestamp before checksum
2876         return (method == checksum_method
2877                 || d->timestamp_ != d->filename.lastModified())
2878                 && d->checksum_ != d->filename.checksum();
2879 }
2880
2881
2882 void Buffer::saveCheckSum() const
2883 {
2884         FileName const & file = d->filename;
2885
2886         file.refresh();
2887         if (file.exists()) {
2888                 d->timestamp_ = file.lastModified();
2889                 d->checksum_ = file.checksum();
2890         } else {
2891                 // in the case of save to a new file.
2892                 d->timestamp_ = 0;
2893                 d->checksum_ = 0;
2894         }
2895 }
2896
2897
2898 void Buffer::markClean() const
2899 {
2900         if (!d->lyx_clean) {
2901                 d->lyx_clean = true;
2902                 updateTitles();
2903         }
2904         // if the .lyx file has been saved, we don't need an
2905         // autosave
2906         d->bak_clean = true;
2907         d->undo_.markDirty();
2908 }
2909
2910
2911 void Buffer::setUnnamed(bool flag)
2912 {
2913         d->unnamed = flag;
2914 }
2915
2916
2917 bool Buffer::isUnnamed() const
2918 {
2919         return d->unnamed;
2920 }
2921
2922
2923 /// \note
2924 /// Don't check unnamed, here: isInternal() is used in
2925 /// newBuffer(), where the unnamed flag has not been set by anyone
2926 /// yet. Also, for an internal buffer, there should be no need for
2927 /// retrieving fileName() nor for checking if it is unnamed or not.
2928 bool Buffer::isInternal() const
2929 {
2930         return d->internal_buffer;
2931 }
2932
2933
2934 void Buffer::setInternal(bool flag)
2935 {
2936         d->internal_buffer = flag;
2937 }
2938
2939
2940 void Buffer::markDirty()
2941 {
2942         if (d->lyx_clean) {
2943                 d->lyx_clean = false;
2944                 updateTitles();
2945         }
2946         d->bak_clean = false;
2947
2948         DepClean::iterator it = d->dep_clean.begin();
2949         DepClean::const_iterator const end = d->dep_clean.end();
2950
2951         for (; it != end; ++it)
2952                 it->second = false;
2953 }
2954
2955
2956 FileName Buffer::fileName() const
2957 {
2958         return d->filename;
2959 }
2960
2961
2962 string Buffer::absFileName() const
2963 {
2964         return d->filename.absFileName();
2965 }
2966
2967
2968 string Buffer::filePath() const
2969 {
2970         string const abs = d->filename.onlyPath().absFileName();
2971         if (abs.empty())
2972                 return abs;
2973         int last = abs.length() - 1;
2974
2975         return abs[last] == '/' ? abs : abs + '/';
2976 }
2977
2978
2979 bool Buffer::isReadonly() const
2980 {
2981         return d->read_only;
2982 }
2983
2984
2985 void Buffer::setParent(Buffer const * buffer)
2986 {
2987         // Avoids recursive include.
2988         d->setParent(buffer == this ? 0 : buffer);
2989         updateMacros();
2990 }
2991
2992
2993 Buffer const * Buffer::parent() const
2994 {
2995         return d->parent();
2996 }
2997
2998
2999 ListOfBuffers Buffer::allRelatives() const
3000 {
3001         ListOfBuffers lb = masterBuffer()->getDescendents();
3002         lb.push_front(const_cast<Buffer *>(masterBuffer()));
3003         return lb;
3004 }
3005
3006
3007 Buffer const * Buffer::masterBuffer() const
3008 {
3009         // FIXME Should be make sure we are not in some kind
3010         // of recursive include? A -> B -> A will crash this.
3011         Buffer const * const pbuf = d->parent();
3012         if (!pbuf)
3013                 return this;
3014
3015         return pbuf->masterBuffer();
3016 }
3017
3018
3019 bool Buffer::isChild(Buffer * child) const
3020 {
3021         return d->children_positions.find(child) != d->children_positions.end();
3022 }
3023
3024
3025 DocIterator Buffer::firstChildPosition(Buffer const * child)
3026 {
3027         Impl::BufferPositionMap::iterator it;
3028         it = d->children_positions.find(child);
3029         if (it == d->children_positions.end())
3030                 return DocIterator(this);
3031         return it->second;
3032 }
3033
3034
3035 bool Buffer::hasChildren() const
3036 {
3037         return !d->children_positions.empty();
3038 }
3039
3040
3041 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3042 {
3043         // loop over children
3044         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3045         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3046         for (; it != end; ++it) {
3047                 Buffer * child = const_cast<Buffer *>(it->first);
3048                 // No duplicates
3049                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3050                 if (bit != clist.end())
3051                         continue;
3052                 clist.push_back(child);
3053                 if (grand_children)
3054                         // there might be grandchildren
3055                         child->collectChildren(clist, true);
3056         }
3057 }
3058
3059
3060 ListOfBuffers Buffer::getChildren() const
3061 {
3062         ListOfBuffers v;
3063         collectChildren(v, false);
3064         // Make sure we have not included ourselves.
3065         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3066         if (bit != v.end()) {
3067                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3068                 v.erase(bit);
3069         }
3070         return v;
3071 }
3072
3073
3074 ListOfBuffers Buffer::getDescendents() const
3075 {
3076         ListOfBuffers v;
3077         collectChildren(v, true);
3078         // Make sure we have not included ourselves.
3079         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3080         if (bit != v.end()) {
3081                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3082                 v.erase(bit);
3083         }
3084         return v;
3085 }
3086
3087
3088 template<typename M>
3089 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3090 {
3091         if (m.empty())
3092                 return m.end();
3093
3094         typename M::const_iterator it = m.lower_bound(x);
3095         if (it == m.begin())
3096                 return m.end();
3097
3098         it--;
3099         return it;
3100 }
3101
3102
3103 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3104                                          DocIterator const & pos) const
3105 {
3106         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3107
3108         // if paragraphs have no macro context set, pos will be empty
3109         if (pos.empty())
3110                 return 0;
3111
3112         // we haven't found anything yet
3113         DocIterator bestPos = owner_->par_iterator_begin();
3114         MacroData const * bestData = 0;
3115
3116         // find macro definitions for name
3117         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3118         if (nameIt != macros.end()) {
3119                 // find last definition in front of pos or at pos itself
3120                 PositionScopeMacroMap::const_iterator it
3121                         = greatest_below(nameIt->second, pos);
3122                 if (it != nameIt->second.end()) {
3123                         while (true) {
3124                                 // scope ends behind pos?
3125                                 if (pos < it->second.first) {
3126                                         // Looks good, remember this. If there
3127                                         // is no external macro behind this,
3128                                         // we found the right one already.
3129                                         bestPos = it->first;
3130                                         bestData = &it->second.second;
3131                                         break;
3132                                 }
3133
3134                                 // try previous macro if there is one
3135                                 if (it == nameIt->second.begin())
3136                                         break;
3137                                 --it;
3138                         }
3139                 }
3140         }
3141
3142         // find macros in included files
3143         PositionScopeBufferMap::const_iterator it
3144                 = greatest_below(position_to_children, pos);
3145         if (it == position_to_children.end())
3146                 // no children before
3147                 return bestData;
3148
3149         while (true) {
3150                 // do we know something better (i.e. later) already?
3151                 if (it->first < bestPos )
3152                         break;
3153
3154                 // scope ends behind pos?
3155                 if (pos < it->second.first
3156                         && (cloned_buffer_ ||
3157                             theBufferList().isLoaded(it->second.second))) {
3158                         // look for macro in external file
3159                         macro_lock = true;
3160                         MacroData const * data
3161                                 = it->second.second->getMacro(name, false);
3162                         macro_lock = false;
3163                         if (data) {
3164                                 bestPos = it->first;
3165                                 bestData = data;
3166                                 break;
3167                         }
3168                 }
3169
3170                 // try previous file if there is one
3171                 if (it == position_to_children.begin())
3172                         break;
3173                 --it;
3174         }
3175
3176         // return the best macro we have found
3177         return bestData;
3178 }
3179
3180
3181 MacroData const * Buffer::getMacro(docstring const & name,
3182         DocIterator const & pos, bool global) const
3183 {
3184         if (d->macro_lock)
3185                 return 0;
3186
3187         // query buffer macros
3188         MacroData const * data = d->getBufferMacro(name, pos);
3189         if (data != 0)
3190                 return data;
3191
3192         // If there is a master buffer, query that
3193         Buffer const * const pbuf = d->parent();
3194         if (pbuf) {
3195                 d->macro_lock = true;
3196                 MacroData const * macro = pbuf->getMacro(
3197                         name, *this, false);
3198                 d->macro_lock = false;
3199                 if (macro)
3200                         return macro;
3201         }
3202
3203         if (global) {
3204                 data = MacroTable::globalMacros().get(name);
3205                 if (data != 0)
3206                         return data;
3207         }
3208
3209         return 0;
3210 }
3211
3212
3213 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3214 {
3215         // set scope end behind the last paragraph
3216         DocIterator scope = par_iterator_begin();
3217         scope.pit() = scope.lastpit() + 1;
3218
3219         return getMacro(name, scope, global);
3220 }
3221
3222
3223 MacroData const * Buffer::getMacro(docstring const & name,
3224         Buffer const & child, bool global) const
3225 {
3226         // look where the child buffer is included first
3227         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3228         if (it == d->children_positions.end())
3229                 return 0;
3230
3231         // check for macros at the inclusion position
3232         return getMacro(name, it->second, global);
3233 }
3234
3235
3236 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3237 {
3238         pit_type const lastpit = it.lastpit();
3239
3240         // look for macros in each paragraph
3241         while (it.pit() <= lastpit) {
3242                 Paragraph & par = it.paragraph();
3243
3244                 // iterate over the insets of the current paragraph
3245                 InsetList const & insets = par.insetList();
3246                 InsetList::const_iterator iit = insets.begin();
3247                 InsetList::const_iterator end = insets.end();
3248                 for (; iit != end; ++iit) {
3249                         it.pos() = iit->pos;
3250
3251                         // is it a nested text inset?
3252                         if (iit->inset->asInsetText()) {
3253                                 // Inset needs its own scope?
3254                                 InsetText const * itext = iit->inset->asInsetText();
3255                                 bool newScope = itext->isMacroScope();
3256
3257                                 // scope which ends just behind the inset
3258                                 DocIterator insetScope = it;
3259                                 ++insetScope.pos();
3260
3261                                 // collect macros in inset
3262                                 it.push_back(CursorSlice(*iit->inset));
3263                                 updateMacros(it, newScope ? insetScope : scope);
3264                                 it.pop_back();
3265                                 continue;
3266                         }
3267
3268                         if (iit->inset->asInsetTabular()) {
3269                                 CursorSlice slice(*iit->inset);
3270                                 size_t const numcells = slice.nargs();
3271                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
3272                                         it.push_back(slice);
3273                                         updateMacros(it, scope);
3274                                         it.pop_back();
3275                                 }
3276                                 continue;
3277                         }
3278
3279                         // is it an external file?
3280                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
3281                                 // get buffer of external file
3282                                 InsetInclude const & inset =
3283                                         static_cast<InsetInclude const &>(*iit->inset);
3284                                 macro_lock = true;
3285                                 Buffer * child = inset.getChildBuffer();
3286                                 macro_lock = false;
3287                                 if (!child)
3288                                         continue;
3289
3290                                 // register its position, but only when it is
3291                                 // included first in the buffer
3292                                 if (children_positions.find(child) ==
3293                                         children_positions.end())
3294                                                 children_positions[child] = it;
3295
3296                                 // register child with its scope
3297                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3298                                 continue;
3299                         }
3300
3301                         InsetMath * im = iit->inset->asInsetMath();
3302                         if (doing_export && im)  {
3303                                 InsetMathHull * hull = im->asHullInset();
3304                                 if (hull)
3305                                         hull->recordLocation(it);
3306                         }
3307
3308                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
3309                                 continue;
3310
3311                         // get macro data
3312                         MathMacroTemplate & macroTemplate =
3313                                 *iit->inset->asInsetMath()->asMacroTemplate();
3314                         MacroContext mc(owner_, it);
3315                         macroTemplate.updateToContext(mc);
3316
3317                         // valid?
3318                         bool valid = macroTemplate.validMacro();
3319                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
3320                         // then the BufferView's cursor will be invalid in
3321                         // some cases which leads to crashes.
3322                         if (!valid)
3323                                 continue;
3324
3325                         // register macro
3326                         // FIXME (Abdel), I don't understandt why we pass 'it' here
3327                         // instead of 'macroTemplate' defined above... is this correct?
3328                         macros[macroTemplate.name()][it] =
3329                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3330                 }
3331
3332                 // next paragraph
3333                 it.pit()++;
3334                 it.pos() = 0;
3335         }
3336 }
3337
3338
3339 void Buffer::updateMacros() const
3340 {
3341         if (d->macro_lock)
3342                 return;
3343
3344         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3345
3346         // start with empty table
3347         d->macros.clear();
3348         d->children_positions.clear();
3349         d->position_to_children.clear();
3350
3351         // Iterate over buffer, starting with first paragraph
3352         // The scope must be bigger than any lookup DocIterator
3353         // later. For the global lookup, lastpit+1 is used, hence
3354         // we use lastpit+2 here.
3355         DocIterator it = par_iterator_begin();
3356         DocIterator outerScope = it;
3357         outerScope.pit() = outerScope.lastpit() + 2;
3358         d->updateMacros(it, outerScope);
3359 }
3360
3361
3362 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3363 {
3364         InsetIterator it  = inset_iterator_begin(inset());
3365         InsetIterator const end = inset_iterator_end(inset());
3366         for (; it != end; ++it) {
3367                 if (it->lyxCode() == BRANCH_CODE) {
3368                         InsetBranch & br = static_cast<InsetBranch &>(*it);
3369                         docstring const name = br.branch();
3370                         if (!from_master && !params().branchlist().find(name))
3371                                 result.push_back(name);
3372                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
3373                                 result.push_back(name);
3374                         continue;
3375                 }
3376                 if (it->lyxCode() == INCLUDE_CODE) {
3377                         // get buffer of external file
3378                         InsetInclude const & ins =
3379                                 static_cast<InsetInclude const &>(*it);
3380                         Buffer * child = ins.getChildBuffer();
3381                         if (!child)
3382                                 continue;
3383                         child->getUsedBranches(result, true);
3384                 }
3385         }
3386         // remove duplicates
3387         result.unique();
3388 }
3389
3390
3391 void Buffer::updateMacroInstances(UpdateType utype) const
3392 {
3393         LYXERR(Debug::MACROS, "updateMacroInstances for "
3394                 << d->filename.onlyFileName());
3395         DocIterator it = doc_iterator_begin(this);
3396         it.forwardInset();
3397         DocIterator const end = doc_iterator_end(this);
3398         for (; it != end; it.forwardInset()) {
3399                 // look for MathData cells in InsetMathNest insets
3400                 InsetMath * minset = it.nextInset()->asInsetMath();
3401                 if (!minset)
3402                         continue;
3403
3404                 // update macro in all cells of the InsetMathNest
3405                 DocIterator::idx_type n = minset->nargs();
3406                 MacroContext mc = MacroContext(this, it);
3407                 for (DocIterator::idx_type i = 0; i < n; ++i) {
3408                         MathData & data = minset->cell(i);
3409                         data.updateMacros(0, mc, utype);
3410                 }
3411         }
3412 }
3413
3414
3415 void Buffer::listMacroNames(MacroNameSet & macros) const
3416 {
3417         if (d->macro_lock)
3418                 return;
3419
3420         d->macro_lock = true;
3421
3422         // loop over macro names
3423         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3424         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3425         for (; nameIt != nameEnd; ++nameIt)
3426                 macros.insert(nameIt->first);
3427
3428         // loop over children
3429         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3430         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3431         for (; it != end; ++it)
3432                 it->first->listMacroNames(macros);
3433
3434         // call parent
3435         Buffer const * const pbuf = d->parent();
3436         if (pbuf)
3437                 pbuf->listMacroNames(macros);
3438
3439         d->macro_lock = false;
3440 }
3441
3442
3443 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3444 {
3445         Buffer const * const pbuf = d->parent();
3446         if (!pbuf)
3447                 return;
3448
3449         MacroNameSet names;
3450         pbuf->listMacroNames(names);
3451
3452         // resolve macros
3453         MacroNameSet::iterator it = names.begin();
3454         MacroNameSet::iterator end = names.end();
3455         for (; it != end; ++it) {
3456                 // defined?
3457                 MacroData const * data =
3458                 pbuf->getMacro(*it, *this, false);
3459                 if (data) {
3460                         macros.insert(data);
3461
3462                         // we cannot access the original MathMacroTemplate anymore
3463                         // here to calls validate method. So we do its work here manually.
3464                         // FIXME: somehow make the template accessible here.
3465                         if (data->optionals() > 0)
3466                                 features.require("xargs");
3467                 }
3468         }
3469 }
3470
3471
3472 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3473 {
3474         if (d->parent())
3475                 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3476
3477         RefCache::iterator it = d->ref_cache_.find(label);
3478         if (it != d->ref_cache_.end())
3479                 return it->second.second;
3480
3481         static InsetLabel const * dummy_il = 0;
3482         static References const dummy_refs;
3483         it = d->ref_cache_.insert(
3484                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3485         return it->second.second;
3486 }
3487
3488
3489 Buffer::References const & Buffer::references(docstring const & label) const
3490 {
3491         return const_cast<Buffer *>(this)->getReferenceCache(label);
3492 }
3493
3494
3495 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3496 {
3497         References & refs = getReferenceCache(label);
3498         refs.push_back(make_pair(inset, it));
3499 }
3500
3501
3502 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3503 {
3504         masterBuffer()->d->ref_cache_[label].first = il;
3505 }
3506
3507
3508 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3509 {
3510         return masterBuffer()->d->ref_cache_[label].first;
3511 }
3512
3513
3514 void Buffer::clearReferenceCache() const
3515 {
3516         if (!d->parent())
3517                 d->ref_cache_.clear();
3518 }
3519
3520
3521 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3522 {
3523         //FIXME: This does not work for child documents yet.
3524         reloadBibInfoCache();
3525
3526         // Check if the label 'from' appears more than once
3527         BiblioInfo const & keys = masterBibInfo();
3528         BiblioInfo::const_iterator bit  = keys.begin();
3529         BiblioInfo::const_iterator bend = keys.end();
3530         vector<docstring> labels;
3531
3532         for (; bit != bend; ++bit)
3533                 // FIXME UNICODE
3534                 labels.push_back(bit->first);
3535
3536         if (count(labels.begin(), labels.end(), from) > 1)
3537                 return;
3538
3539         string const paramName = "key";
3540         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3541                 if (it->lyxCode() != CITE_CODE)
3542                         continue;
3543                 InsetCommand * inset = it->asInsetCommand();
3544                 docstring const oldValue = inset->getParam(paramName);
3545                 if (oldValue == from)
3546                         inset->setParam(paramName, to);
3547         }
3548 }
3549
3550
3551 void Buffer::getSourceCode(odocstream & os, string const & format,
3552                            pit_type par_begin, pit_type par_end,
3553                            OutputWhat output, bool master) const
3554 {
3555         OutputParams runparams(&params().encoding());
3556         runparams.nice = true;
3557         runparams.flavor = params().getOutputFlavor(format);
3558         runparams.linelen = lyxrc.plaintext_linelen;
3559         // No side effect of file copying and image conversion
3560         runparams.dryrun = true;
3561
3562         if (output == CurrentParagraph) {
3563                 runparams.par_begin = par_begin;
3564                 runparams.par_end = par_end;
3565                 if (par_begin + 1 == par_end) {
3566                         os << "% "
3567                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3568                            << "\n\n";
3569                 } else {
3570                         os << "% "
3571                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3572                                         convert<docstring>(par_begin),
3573                                         convert<docstring>(par_end - 1))
3574                            << "\n\n";
3575                 }
3576                 // output paragraphs
3577                 if (runparams.flavor == OutputParams::LYX) {
3578                         Paragraph const & par = text().paragraphs()[par_begin];
3579                         ostringstream ods;
3580                         depth_type dt = par.getDepth();
3581                         par.write(ods, params(), dt);
3582                         os << from_utf8(ods.str());
3583                 } else if (runparams.flavor == OutputParams::HTML) {
3584                         XHTMLStream xs(os);
3585                         setMathFlavor(runparams);
3586                         xhtmlParagraphs(text(), *this, xs, runparams);
3587                 } else if (runparams.flavor == OutputParams::TEXT) {
3588                         bool dummy = false;
3589                         // FIXME Handles only one paragraph, unlike the others.
3590                         // Probably should have some routine with a signature like them.
3591                         writePlaintextParagraph(*this,
3592                                 text().paragraphs()[par_begin], os, runparams, dummy);
3593                 } else if (params().isDocBook()) {
3594                         docbookParagraphs(text(), *this, os, runparams);
3595                 } else {
3596                         // If we are previewing a paragraph, even if this is the
3597                         // child of some other buffer, let's cut the link here,
3598                         // so that no concurring settings from the master
3599                         // (e.g. branch state) interfere (see #8101).
3600                         if (!master)
3601                                 d->ignore_parent = true;
3602                         // We need to validate the Buffer params' features here
3603                         // in order to know if we should output polyglossia
3604                         // macros (instead of babel macros)
3605                         LaTeXFeatures features(*this, params(), runparams);
3606                         params().validate(features);
3607                         runparams.use_polyglossia = features.usePolyglossia();
3608                         TexRow texrow;
3609                         texrow.reset();
3610                         texrow.newline();
3611                         texrow.newline();
3612                         // latex or literate
3613                         otexstream ots(os, texrow);
3614
3615                         // the real stuff
3616                         latexParagraphs(*this, text(), ots, runparams);
3617
3618                         // Restore the parenthood
3619                         if (!master)
3620                                 d->ignore_parent = false;
3621                 }
3622         } else {
3623                 os << "% ";
3624                 if (output == FullSource)
3625                         os << _("Preview source code");
3626                 else if (output == OnlyPreamble)
3627                         os << _("Preview preamble");
3628                 else if (output == OnlyBody)
3629                         os << _("Preview body");
3630                 os << "\n\n";
3631                 if (runparams.flavor == OutputParams::LYX) {
3632                         ostringstream ods;
3633                         if (output == FullSource)
3634                                 write(ods);
3635                         else if (output == OnlyPreamble)
3636                                 params().writeFile(ods);
3637                         else if (output == OnlyBody)
3638                                 text().write(ods);
3639                         os << from_utf8(ods.str());
3640                 } else if (runparams.flavor == OutputParams::HTML) {
3641                         writeLyXHTMLSource(os, runparams, output);
3642                 } else if (runparams.flavor == OutputParams::TEXT) {
3643                         if (output == OnlyPreamble) {
3644                                 os << "% "<< _("Plain text does not have a preamble.");
3645                         } else
3646                                 writePlaintextFile(*this, os, runparams);
3647                 } else if (params().isDocBook()) {
3648                                 writeDocBookSource(os, absFileName(), runparams, output);
3649                 } else {
3650                         // latex or literate
3651                         d->texrow.reset();
3652                         d->texrow.newline();
3653                         d->texrow.newline();
3654                         otexstream ots(os, d->texrow);
3655                         if (master)
3656                                 runparams.is_child = true;
3657                         writeLaTeXSource(ots, string(), runparams, output);
3658                 }
3659         }
3660 }
3661
3662
3663 ErrorList & Buffer::errorList(string const & type) const
3664 {
3665         return d->errorLists[type];
3666 }
3667
3668
3669 void Buffer::updateTocItem(std::string const & type,
3670         DocIterator const & dit) const
3671 {
3672         if (d->gui_)
3673                 d->gui_->updateTocItem(type, dit);
3674 }
3675
3676
3677 void Buffer::structureChanged() const
3678 {
3679         if (d->gui_)
3680                 d->gui_->structureChanged();
3681 }
3682
3683
3684 void Buffer::errors(string const & err, bool from_master) const
3685 {
3686         if (d->gui_)
3687                 d->gui_->errors(err, from_master);
3688 }
3689
3690
3691 void Buffer::message(docstring const & msg) const
3692 {
3693         if (d->gui_)
3694                 d->gui_->message(msg);
3695 }
3696
3697
3698 void Buffer::setBusy(bool on) const
3699 {
3700         if (d->gui_)
3701                 d->gui_->setBusy(on);
3702 }
3703
3704
3705 void Buffer::updateTitles() const
3706 {
3707         if (d->wa_)
3708                 d->wa_->updateTitles();
3709 }
3710
3711
3712 void Buffer::resetAutosaveTimers() const
3713 {
3714         if (d->gui_)
3715                 d->gui_->resetAutosaveTimers();
3716 }
3717
3718
3719 bool Buffer::hasGuiDelegate() const
3720 {
3721         return d->gui_;
3722 }
3723
3724
3725 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3726 {
3727         d->gui_ = gui;
3728 }
3729
3730
3731
3732 namespace {
3733
3734 class AutoSaveBuffer : public ForkedProcess {
3735 public:
3736         ///
3737         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3738                 : buffer_(buffer), fname_(fname) {}
3739         ///
3740         virtual shared_ptr<ForkedProcess> clone() const
3741         {
3742                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3743         }
3744         ///
3745         int start()
3746         {
3747                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3748                                                  from_utf8(fname_.absFileName())));
3749                 return run(DontWait);
3750         }
3751 private:
3752         ///
3753         virtual int generateChild();
3754         ///
3755         Buffer const & buffer_;
3756         FileName fname_;
3757 };
3758
3759
3760 int AutoSaveBuffer::generateChild()
3761 {
3762 #if defined(__APPLE__)
3763         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3764          *   We should use something else like threads.
3765          *
3766          * Since I do not know how to determine at run time what is the OS X
3767          * version, I just disable forking altogether for now (JMarc)
3768          */
3769         pid_t const pid = -1;
3770 #else
3771         // tmp_ret will be located (usually) in /tmp
3772         // will that be a problem?
3773         // Note that this calls ForkedCalls::fork(), so it's
3774         // ok cross-platform.
3775         pid_t const pid = fork();
3776         // If you want to debug the autosave
3777         // you should set pid to -1, and comment out the fork.
3778         if (pid != 0 && pid != -1)
3779                 return pid;
3780 #endif
3781
3782         // pid = -1 signifies that lyx was unable
3783         // to fork. But we will do the save
3784         // anyway.
3785         bool failed = false;
3786         TempFile tempfile("lyxautoXXXXXX.lyx");
3787         tempfile.setAutoRemove(false);
3788         FileName const tmp_ret = tempfile.name();
3789         if (!tmp_ret.empty()) {
3790                 if (!buffer_.writeFile(tmp_ret))
3791                         failed = true;
3792                 else if (!tmp_ret.moveTo(fname_))
3793                         failed = true;
3794         } else
3795                 failed = true;
3796
3797         if (failed) {
3798                 // failed to write/rename tmp_ret so try writing direct
3799                 if (!buffer_.writeFile(fname_)) {
3800                         // It is dangerous to do this in the child,
3801                         // but safe in the parent, so...
3802                         if (pid == -1) // emit message signal.
3803                                 buffer_.message(_("Autosave failed!"));
3804                 }
3805         }
3806
3807         if (pid == 0) // we are the child so...
3808                 _exit(0);
3809
3810         return pid;
3811 }
3812
3813 } // namespace anon
3814
3815
3816 FileName Buffer::getEmergencyFileName() const
3817 {
3818         return FileName(d->filename.absFileName() + ".emergency");
3819 }
3820
3821
3822 FileName Buffer::getAutosaveFileName() const
3823 {
3824         // if the document is unnamed try to save in the backup dir, else
3825         // in the default document path, and as a last try in the filePath,
3826         // which will most often be the temporary directory
3827         string fpath;
3828         if (isUnnamed())
3829                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3830                         : lyxrc.backupdir_path;
3831         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3832                 fpath = filePath();
3833
3834         string const fname = "#" + d->filename.onlyFileName() + "#";
3835
3836         return makeAbsPath(fname, fpath);
3837 }
3838
3839
3840 void Buffer::removeAutosaveFile() const
3841 {
3842         FileName const f = getAutosaveFileName();
3843         if (f.exists())
3844                 f.removeFile();
3845 }
3846
3847
3848 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3849 {
3850         FileName const newauto = getAutosaveFileName();
3851         oldauto.refresh();
3852         if (newauto != oldauto && oldauto.exists())
3853                 if (!oldauto.moveTo(newauto))
3854                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3855 }
3856
3857
3858 bool Buffer::autoSave() const
3859 {
3860         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3861         if (buf->d->bak_clean || isReadonly())
3862                 return true;
3863
3864         message(_("Autosaving current document..."));
3865         buf->d->bak_clean = true;
3866
3867         FileName const fname = getAutosaveFileName();
3868         LASSERT(d->cloned_buffer_, return false);
3869
3870         // If this buffer is cloned, we assume that
3871         // we are running in a separate thread already.
3872         TempFile tempfile("lyxautoXXXXXX.lyx");
3873         tempfile.setAutoRemove(false);
3874         FileName const tmp_ret = tempfile.name();
3875         if (!tmp_ret.empty()) {
3876                 writeFile(tmp_ret);
3877                 // assume successful write of tmp_ret
3878                 if (tmp_ret.moveTo(fname))
3879                         return true;
3880         }
3881         // failed to write/rename tmp_ret so try writing direct
3882         return writeFile(fname);
3883 }
3884
3885
3886 void Buffer::setExportStatus(bool e) const
3887 {
3888         d->doing_export = e;
3889         ListOfBuffers clist = getDescendents();
3890         ListOfBuffers::const_iterator cit = clist.begin();
3891         ListOfBuffers::const_iterator const cen = clist.end();
3892         for (; cit != cen; ++cit)
3893                 (*cit)->d->doing_export = e;
3894 }
3895
3896
3897 bool Buffer::isExporting() const
3898 {
3899         return d->doing_export;
3900 }
3901
3902
3903 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3904         const
3905 {
3906         string result_file;
3907         return doExport(target, put_in_tempdir, result_file);
3908 }
3909
3910 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3911         string & result_file) const
3912 {
3913         bool const update_unincluded =
3914                         params().maintain_unincluded_children
3915                         && !params().getIncludedChildren().empty();
3916
3917         // (1) export with all included children (omit \includeonly)
3918         if (update_unincluded) {
3919                 ExportStatus const status =
3920                         doExport(target, put_in_tempdir, true, result_file);
3921                 if (status != ExportSuccess)
3922                         return status;
3923         }
3924         // (2) export with included children only
3925         return doExport(target, put_in_tempdir, false, result_file);
3926 }
3927
3928
3929 void Buffer::setMathFlavor(OutputParams & op) const
3930 {
3931         switch (params().html_math_output) {
3932         case BufferParams::MathML:
3933                 op.math_flavor = OutputParams::MathAsMathML;
3934                 break;
3935         case BufferParams::HTML:
3936                 op.math_flavor = OutputParams::MathAsHTML;
3937                 break;
3938         case BufferParams::Images:
3939                 op.math_flavor = OutputParams::MathAsImages;
3940                 break;
3941         case BufferParams::LaTeX:
3942                 op.math_flavor = OutputParams::MathAsLaTeX;
3943                 break;
3944         }
3945 }
3946
3947
3948 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3949         bool includeall, string & result_file) const
3950 {
3951         LYXERR(Debug::FILES, "target=" << target);
3952         OutputParams runparams(&params().encoding());
3953         string format = target;
3954         string dest_filename;
3955         size_t pos = target.find(' ');
3956         if (pos != string::npos) {
3957                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3958                 format = target.substr(0, pos);
3959                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3960                 FileName(dest_filename).onlyPath().createPath();
3961                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3962         }
3963         MarkAsExporting exporting(this);
3964         string backend_format;
3965         runparams.flavor = OutputParams::LATEX;
3966         runparams.linelen = lyxrc.plaintext_linelen;
3967         runparams.includeall = includeall;
3968         vector<string> backs = params().backends();
3969         Converters converters = theConverters();
3970         bool need_nice_file = false;
3971         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3972                 // Get shortest path to format
3973                 converters.buildGraph();
3974                 Graph::EdgePath path;
3975                 for (vector<string>::const_iterator it = backs.begin();
3976                      it != backs.end(); ++it) {
3977                         Graph::EdgePath p = converters.getPath(*it, format);
3978                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3979                                 backend_format = *it;
3980                                 path = p;
3981                         }
3982                 }
3983                 if (path.empty()) {
3984                         if (!put_in_tempdir) {
3985                                 // Only show this alert if this is an export to a non-temporary
3986                                 // file (not for previewing).
3987                                 Alert::error(_("Couldn't export file"), bformat(
3988                                         _("No information for exporting the format %1$s."),
3989                                         formats.prettyName(format)));
3990                         }
3991                         return ExportNoPathToFormat;
3992                 }
3993                 runparams.flavor = converters.getFlavor(path, this);
3994                 Graph::EdgePath::const_iterator it = path.begin();
3995                 Graph::EdgePath::const_iterator en = path.end();
3996                 for (; it != en; ++it)
3997                         if (theConverters().get(*it).nice()) {
3998                                 need_nice_file = true;
3999                                 break;
4000                         }
4001
4002         } else {
4003                 backend_format = format;
4004                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4005                 // FIXME: Don't hardcode format names here, but use a flag
4006                 if (backend_format == "pdflatex")
4007                         runparams.flavor = OutputParams::PDFLATEX;
4008                 else if (backend_format == "luatex")
4009                         runparams.flavor = OutputParams::LUATEX;
4010                 else if (backend_format == "dviluatex")
4011                         runparams.flavor = OutputParams::DVILUATEX;
4012                 else if (backend_format == "xetex")
4013                         runparams.flavor = OutputParams::XETEX;
4014         }
4015
4016         string filename = latexName(false);
4017         filename = addName(temppath(), filename);
4018         filename = changeExtension(filename,
4019                                    formats.extension(backend_format));
4020         LYXERR(Debug::FILES, "filename=" << filename);
4021
4022         // Plain text backend
4023         if (backend_format == "text") {
4024                 runparams.flavor = OutputParams::TEXT;
4025                 writePlaintextFile(*this, FileName(filename), runparams);
4026         }
4027         // HTML backend
4028         else if (backend_format == "xhtml") {
4029                 runparams.flavor = OutputParams::HTML;
4030                 setMathFlavor(runparams);
4031                 makeLyXHTMLFile(FileName(filename), runparams);
4032         } else if (backend_format == "lyx")
4033                 writeFile(FileName(filename));
4034         // Docbook backend
4035         else if (params().isDocBook()) {
4036                 runparams.nice = !put_in_tempdir;
4037                 makeDocBookFile(FileName(filename), runparams);
4038         }
4039         // LaTeX backend
4040         else if (backend_format == format || need_nice_file) {
4041                 runparams.nice = true;
4042                 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4043                 if (d->cloned_buffer_)
4044                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4045                 if (!success)
4046                         return ExportError;
4047         } else if (!lyxrc.tex_allows_spaces
4048                    && contains(filePath(), ' ')) {
4049                 Alert::error(_("File name error"),
4050                            _("The directory path to the document cannot contain spaces."));
4051                 return ExportTexPathHasSpaces;
4052         } else {
4053                 runparams.nice = false;
4054                 bool const success = makeLaTeXFile(
4055                         FileName(filename), filePath(), runparams);
4056                 if (d->cloned_buffer_)
4057                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4058                 if (!success)
4059                         return ExportError;
4060         }
4061
4062         string const error_type = (format == "program")
4063                 ? "Build" : params().bufferFormat();
4064         ErrorList & error_list = d->errorLists[error_type];
4065         string const ext = formats.extension(format);
4066         FileName const tmp_result_file(changeExtension(filename, ext));
4067         bool const success = converters.convert(this, FileName(filename),
4068                 tmp_result_file, FileName(absFileName()), backend_format, format,
4069                 error_list);
4070
4071         // Emit the signal to show the error list or copy it back to the
4072         // cloned Buffer so that it can be emitted afterwards.
4073         if (format != backend_format) {
4074                 if (runparams.silent)
4075                         error_list.clear();
4076                 else if (d->cloned_buffer_)
4077                         d->cloned_buffer_->d->errorLists[error_type] =
4078                                 d->errorLists[error_type];
4079                 else
4080                         errors(error_type);
4081                 // also to the children, in case of master-buffer-view
4082                 ListOfBuffers clist = getDescendents();
4083                 ListOfBuffers::const_iterator cit = clist.begin();
4084                 ListOfBuffers::const_iterator const cen = clist.end();
4085                 for (; cit != cen; ++cit) {
4086                         if (runparams.silent)
4087                                 (*cit)->d->errorLists[error_type].clear();
4088                         else if (d->cloned_buffer_) {
4089                                 // Enable reverse search by copying back the
4090                                 // texrow object to the cloned buffer.
4091                                 // FIXME: this is not thread safe.
4092                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4093                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4094                                         (*cit)->d->errorLists[error_type];
4095                         } else
4096                                 (*cit)->errors(error_type, true);
4097                 }
4098         }
4099
4100         if (d->cloned_buffer_) {
4101                 // Enable reverse dvi or pdf to work by copying back the texrow
4102                 // object to the cloned buffer.
4103                 // FIXME: There is a possibility of concurrent access to texrow
4104                 // here from the main GUI thread that should be securized.
4105                 d->cloned_buffer_->d->texrow = d->texrow;
4106                 string const error_type = params().bufferFormat();
4107                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4108         }
4109
4110         if (!success)
4111                 return ExportConverterError;
4112
4113         if (put_in_tempdir) {
4114                 result_file = tmp_result_file.absFileName();
4115                 return ExportSuccess;
4116         }
4117
4118         if (dest_filename.empty())
4119                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4120         else
4121                 result_file = dest_filename;
4122         // We need to copy referenced files (e. g. included graphics
4123         // if format == "dvi") to the result dir.
4124         vector<ExportedFile> const files =
4125                 runparams.exportdata->externalFiles(format);
4126         string const dest = runparams.export_folder.empty() ?
4127                 onlyPath(result_file) : runparams.export_folder;
4128         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4129                                  : force_overwrite == ALL_FILES;
4130         CopyStatus status = use_force ? FORCE : SUCCESS;
4131
4132         vector<ExportedFile>::const_iterator it = files.begin();
4133         vector<ExportedFile>::const_iterator const en = files.end();
4134         for (; it != en && status != CANCEL; ++it) {
4135                 string const fmt = formats.getFormatFromFile(it->sourceName);
4136                 string fixedName = it->exportName;
4137                 if (!runparams.export_folder.empty()) {
4138                         // Relative pathnames starting with ../ will be sanitized
4139                         // if exporting to a different folder
4140                         while (fixedName.substr(0, 3) == "../")
4141                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
4142                 }
4143                 FileName fixedFileName = makeAbsPath(fixedName, dest);
4144                 fixedFileName.onlyPath().createPath();
4145                 status = copyFile(fmt, it->sourceName,
4146                         fixedFileName,
4147                         it->exportName, status == FORCE,
4148                         runparams.export_folder.empty());
4149         }
4150
4151         if (status == CANCEL) {
4152                 message(_("Document export cancelled."));
4153                 return ExportCancel;
4154         }
4155
4156         if (tmp_result_file.exists()) {
4157                 // Finally copy the main file
4158                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4159                                     : force_overwrite != NO_FILES;
4160                 if (status == SUCCESS && use_force)
4161                         status = FORCE;
4162                 status = copyFile(format, tmp_result_file,
4163                         FileName(result_file), result_file,
4164                         status == FORCE);
4165                 if (status == CANCEL) {
4166                         message(_("Document export cancelled."));
4167                         return ExportCancel;
4168                 } else {
4169                         message(bformat(_("Document exported as %1$s "
4170                                 "to file `%2$s'"),
4171                                 formats.prettyName(format),
4172                                 makeDisplayPath(result_file)));
4173                 }
4174         } else {
4175                 // This must be a dummy converter like fax (bug 1888)
4176                 message(bformat(_("Document exported as %1$s"),
4177                         formats.prettyName(format)));
4178         }
4179
4180         return ExportSuccess;
4181 }
4182
4183
4184 Buffer::ExportStatus Buffer::preview(string const & format) const
4185 {
4186         bool const update_unincluded =
4187                         params().maintain_unincluded_children
4188                         && !params().getIncludedChildren().empty();
4189         return preview(format, update_unincluded);
4190 }
4191
4192
4193 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4194 {
4195         MarkAsExporting exporting(this);
4196         string result_file;
4197         // (1) export with all included children (omit \includeonly)
4198         if (includeall) {
4199                 ExportStatus const status = doExport(format, true, true, result_file);
4200                 if (status != ExportSuccess)
4201                         return status;
4202         }
4203         // (2) export with included children only
4204         ExportStatus const status = doExport(format, true, false, result_file);
4205         if (status != ExportSuccess)
4206                 return status;
4207         if (!formats.view(*this, FileName(result_file), format))
4208                 return PreviewError;
4209         return PreviewSuccess;
4210 }
4211
4212
4213 Buffer::ReadStatus Buffer::extractFromVC()
4214 {
4215         bool const found = LyXVC::file_not_found_hook(d->filename);
4216         if (!found)
4217                 return ReadFileNotFound;
4218         if (!d->filename.isReadableFile())
4219                 return ReadVCError;
4220         return ReadSuccess;
4221 }
4222
4223
4224 Buffer::ReadStatus Buffer::loadEmergency()
4225 {
4226         FileName const emergencyFile = getEmergencyFileName();
4227         if (!emergencyFile.exists()
4228                   || emergencyFile.lastModified() <= d->filename.lastModified())
4229                 return ReadFileNotFound;
4230
4231         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4232         docstring const text = bformat(_("An emergency save of the document "
4233                 "%1$s exists.\n\nRecover emergency save?"), file);
4234
4235         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4236                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4237
4238         switch (load_emerg)
4239         {
4240         case 0: {
4241                 docstring str;
4242                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4243                 bool const success = (ret_llf == ReadSuccess);
4244                 if (success) {
4245                         if (isReadonly()) {
4246                                 Alert::warning(_("File is read-only"),
4247                                         bformat(_("An emergency file is successfully loaded, "
4248                                         "but the original file %1$s is marked read-only. "
4249                                         "Please make sure to save the document as a different "
4250                                         "file."), from_utf8(d->filename.absFileName())));
4251                         }
4252                         markDirty();
4253                         lyxvc().file_found_hook(d->filename);
4254                         str = _("Document was successfully recovered.");
4255                 } else
4256                         str = _("Document was NOT successfully recovered.");
4257                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4258                         makeDisplayPath(emergencyFile.absFileName()));
4259
4260                 int const del_emerg =
4261                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4262                                 _("&Remove"), _("&Keep"));
4263                 if (del_emerg == 0) {
4264                         emergencyFile.removeFile();
4265                         if (success)
4266                                 Alert::warning(_("Emergency file deleted"),
4267                                         _("Do not forget to save your file now!"), true);
4268                         }
4269                 return success ? ReadSuccess : ReadEmergencyFailure;
4270         }
4271         case 1: {
4272                 int const del_emerg =
4273                         Alert::prompt(_("Delete emergency file?"),
4274                                 _("Remove emergency file now?"), 1, 1,
4275                                 _("&Remove"), _("&Keep"));
4276                 if (del_emerg == 0)
4277                         emergencyFile.removeFile();
4278                 return ReadOriginal;
4279         }
4280
4281         default:
4282                 break;
4283         }
4284         return ReadCancel;
4285 }
4286
4287
4288 Buffer::ReadStatus Buffer::loadAutosave()
4289 {
4290         // Now check if autosave file is newer.
4291         FileName const autosaveFile = getAutosaveFileName();
4292         if (!autosaveFile.exists()
4293                   || autosaveFile.lastModified() <= d->filename.lastModified())
4294                 return ReadFileNotFound;
4295
4296         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4297         docstring const text = bformat(_("The backup of the document %1$s "
4298                 "is newer.\n\nLoad the backup instead?"), file);
4299         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4300                 _("&Load backup"), _("Load &original"), _("&Cancel"));
4301
4302         switch (ret)
4303         {
4304         case 0: {
4305                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4306                 // the file is not saved if we load the autosave file.
4307                 if (ret_llf == ReadSuccess) {
4308                         if (isReadonly()) {
4309                                 Alert::warning(_("File is read-only"),
4310                                         bformat(_("A backup file is successfully loaded, "
4311                                         "but the original file %1$s is marked read-only. "
4312                                         "Please make sure to save the document as a "
4313                                         "different file."),
4314                                         from_utf8(d->filename.absFileName())));
4315                         }
4316                         markDirty();
4317                         lyxvc().file_found_hook(d->filename);
4318                         return ReadSuccess;
4319                 }
4320                 return ReadAutosaveFailure;
4321         }
4322         case 1:
4323                 // Here we delete the autosave
4324                 autosaveFile.removeFile();
4325                 return ReadOriginal;
4326         default:
4327                 break;
4328         }
4329         return ReadCancel;
4330 }
4331
4332
4333 Buffer::ReadStatus Buffer::loadLyXFile()
4334 {
4335         if (!d->filename.isReadableFile()) {
4336                 ReadStatus const ret_rvc = extractFromVC();
4337                 if (ret_rvc != ReadSuccess)
4338                         return ret_rvc;
4339         }
4340
4341         ReadStatus const ret_re = loadEmergency();
4342         if (ret_re == ReadSuccess || ret_re == ReadCancel)
4343                 return ret_re;
4344
4345         ReadStatus const ret_ra = loadAutosave();
4346         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4347                 return ret_ra;
4348
4349         return loadThisLyXFile(d->filename);
4350 }
4351
4352
4353 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4354 {
4355         return readFile(fn);
4356 }
4357
4358
4359 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4360 {
4361         TeXErrors::Errors::const_iterator it = terr.begin();
4362         TeXErrors::Errors::const_iterator end = terr.end();
4363         ListOfBuffers clist = getDescendents();
4364         ListOfBuffers::const_iterator cen = clist.end();
4365
4366         for (; it != end; ++it) {
4367                 int id_start = -1;
4368                 int pos_start = -1;
4369                 int errorRow = it->error_in_line;
4370                 Buffer const * buf = 0;
4371                 Impl const * p = d;
4372                 if (it->child_name.empty())
4373                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4374                 else {
4375                         // The error occurred in a child
4376                         ListOfBuffers::const_iterator cit = clist.begin();
4377                         for (; cit != cen; ++cit) {
4378                                 string const child_name =
4379                                         DocFileName(changeExtension(
4380                                                 (*cit)->absFileName(), "tex")).
4381                                                         mangledFileName();
4382                                 if (it->child_name != child_name)
4383                                         continue;
4384                                 (*cit)->d->texrow.getIdFromRow(errorRow,
4385                                                         id_start, pos_start);
4386                                 if (id_start != -1) {
4387                                         buf = d->cloned_buffer_
4388                                                 ? (*cit)->d->cloned_buffer_->d->owner_
4389                                                 : (*cit)->d->owner_;
4390                                         p = (*cit)->d;
4391                                         break;
4392                                 }
4393                         }
4394                 }
4395                 int id_end = -1;
4396                 int pos_end = -1;
4397                 bool found;
4398                 do {
4399                         ++errorRow;
4400                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4401                 } while (found && id_start == id_end && pos_start == pos_end);
4402
4403                 if (id_start != id_end) {
4404                         // Next registered position is outside the inset where
4405                         // the error occurred, so signal end-of-paragraph
4406                         pos_end = 0;
4407                 }
4408
4409                 errorList.push_back(ErrorItem(it->error_desc,
4410                         it->error_text, id_start, pos_start, pos_end, buf));
4411         }
4412 }
4413
4414
4415 void Buffer::setBuffersForInsets() const
4416 {
4417         inset().setBuffer(const_cast<Buffer &>(*this));
4418 }
4419
4420
4421 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4422 {
4423         LBUFERR(!text().paragraphs().empty());
4424
4425         // Use the master text class also for child documents
4426         Buffer const * const master = masterBuffer();
4427         DocumentClass const & textclass = master->params().documentClass();
4428
4429         // do this only if we are the top-level Buffer
4430         if (master == this) {
4431                 textclass.counters().reset(from_ascii("bibitem"));
4432                 reloadBibInfoCache();
4433         }
4434
4435         // keep the buffers to be children in this set. If the call from the
4436         // master comes back we can see which of them were actually seen (i.e.
4437         // via an InsetInclude). The remaining ones in the set need still be updated.
4438         static std::set<Buffer const *> bufToUpdate;
4439         if (scope == UpdateMaster) {
4440                 // If this is a child document start with the master
4441                 if (master != this) {
4442                         bufToUpdate.insert(this);
4443                         master->updateBuffer(UpdateMaster, utype);
4444                         // If the master buffer has no gui associated with it, then the TocModel is 
4445                         // not updated during the updateBuffer call and TocModel::toc_ is invalid 
4446                         // (bug 5699). The same happens if the master buffer is open in a different 
4447                         // window. This test catches both possibilities.
4448                         // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4449                         // There remains a problem here: If there is another child open in yet a third
4450                         // window, that TOC is not updated. So some more general solution is needed at
4451                         // some point.
4452                         if (master->d->gui_ != d->gui_)
4453                                 structureChanged();
4454
4455                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4456                         if (bufToUpdate.find(this) == bufToUpdate.end())
4457                                 return;
4458                 }
4459
4460                 // start over the counters in the master
4461                 textclass.counters().reset();
4462         }
4463
4464         // update will be done below for this buffer
4465         bufToUpdate.erase(this);
4466
4467         // update all caches
4468         clearReferenceCache();
4469         updateMacros();
4470
4471         Buffer & cbuf = const_cast<Buffer &>(*this);
4472
4473         // do the real work
4474         ParIterator parit = cbuf.par_iterator_begin();
4475         updateBuffer(parit, utype);
4476
4477         if (master != this)
4478                 // TocBackend update will be done later.
4479                 return;
4480
4481         d->bibinfo_cache_valid_ = true;
4482         d->cite_labels_valid_ = true;
4483         cbuf.tocBackend().update(utype == OutputUpdate);
4484         if (scope == UpdateMaster)
4485                 cbuf.structureChanged();
4486 }
4487
4488
4489 static depth_type getDepth(DocIterator const & it)
4490 {
4491         depth_type depth = 0;
4492         for (size_t i = 0 ; i < it.depth() ; ++i)
4493                 if (!it[i].inset().inMathed())
4494                         depth += it[i].paragraph().getDepth() + 1;
4495         // remove 1 since the outer inset does not count
4496         return depth - 1;
4497 }
4498
4499 static depth_type getItemDepth(ParIterator const & it)
4500 {
4501         Paragraph const & par = *it;
4502         LabelType const labeltype = par.layout().labeltype;
4503
4504         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4505                 return 0;
4506
4507         // this will hold the lowest depth encountered up to now.
4508         depth_type min_depth = getDepth(it);
4509         ParIterator prev_it = it;
4510         while (true) {
4511                 if (prev_it.pit())
4512                         --prev_it.top().pit();
4513                 else {
4514                         // start of nested inset: go to outer par
4515                         prev_it.pop_back();
4516                         if (prev_it.empty()) {
4517                                 // start of document: nothing to do
4518                                 return 0;
4519                         }
4520                 }
4521
4522                 // We search for the first paragraph with same label
4523                 // that is not more deeply nested.
4524                 Paragraph & prev_par = *prev_it;
4525                 depth_type const prev_depth = getDepth(prev_it);
4526                 if (labeltype == prev_par.layout().labeltype) {
4527                         if (prev_depth < min_depth)
4528                                 return prev_par.itemdepth + 1;
4529                         if (prev_depth == min_depth)
4530                                 return prev_par.itemdepth;
4531                 }
4532                 min_depth = min(min_depth, prev_depth);
4533                 // small optimization: if we are at depth 0, we won't
4534                 // find anything else
4535                 if (prev_depth == 0)
4536                         return 0;
4537         }
4538 }
4539
4540
4541 static bool needEnumCounterReset(ParIterator const & it)
4542 {
4543         Paragraph const & par = *it;
4544         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4545         depth_type const cur_depth = par.getDepth();
4546         ParIterator prev_it = it;
4547         while (prev_it.pit()) {
4548                 --prev_it.top().pit();
4549                 Paragraph const & prev_par = *prev_it;
4550                 if (prev_par.getDepth() <= cur_depth)
4551                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
4552         }
4553         // start of nested inset: reset
4554         return true;
4555 }
4556
4557
4558 // set the label of a paragraph. This includes the counters.
4559 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4560 {
4561         BufferParams const & bp = owner_->masterBuffer()->params();
4562         DocumentClass const & textclass = bp.documentClass();
4563         Paragraph & par = it.paragraph();
4564         Layout const & layout = par.layout();
4565         Counters & counters = textclass.counters();
4566
4567         if (par.params().startOfAppendix()) {
4568                 // We want to reset the counter corresponding to toplevel sectioning
4569                 Layout const & lay = textclass.getTOCLayout();
4570                 docstring const cnt = lay.counter;
4571                 if (!cnt.empty())
4572                         counters.reset(cnt);
4573                 counters.appendix(true);
4574         }
4575         par.params().appendix(counters.appendix());
4576
4577         // Compute the item depth of the paragraph
4578         par.itemdepth = getItemDepth(it);
4579
4580         if (layout.margintype == MARGIN_MANUAL) {
4581                 if (par.params().labelWidthString().empty())
4582                         par.params().labelWidthString(par.expandLabel(layout, bp));
4583         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4584                 // we do not need to do anything here, since the empty case is
4585                 // handled during export.
4586         } else {
4587                 par.params().labelWidthString(docstring());
4588         }
4589
4590         switch(layout.labeltype) {
4591         case LABEL_ITEMIZE: {
4592                 // At some point of time we should do something more
4593                 // clever here, like:
4594                 //   par.params().labelString(
4595                 //    bp.user_defined_bullet(par.itemdepth).getText());
4596                 // for now, use a simple hardcoded label
4597                 docstring itemlabel;
4598                 switch (par.itemdepth) {
4599                 case 0:
4600                         itemlabel = char_type(0x2022);
4601                         break;
4602                 case 1:
4603                         itemlabel = char_type(0x2013);
4604                         break;
4605                 case 2:
4606                         itemlabel = char_type(0x2217);
4607                         break;
4608                 case 3:
4609                         itemlabel = char_type(0x2219); // or 0x00b7
4610                         break;
4611                 }
4612                 par.params().labelString(itemlabel);
4613                 break;
4614         }
4615
4616         case LABEL_ENUMERATE: {
4617                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4618
4619                 switch (par.itemdepth) {
4620                 case 2:
4621                         enumcounter += 'i';
4622                 case 1:
4623                         enumcounter += 'i';
4624                 case 0:
4625                         enumcounter += 'i';
4626                         break;
4627                 case 3:
4628                         enumcounter += "iv";
4629                         break;
4630                 default:
4631                         // not a valid enumdepth...
4632                         break;
4633                 }
4634
4635                 // Maybe we have to reset the enumeration counter.
4636                 if (needEnumCounterReset(it))
4637                         counters.reset(enumcounter);
4638                 counters.step(enumcounter, utype);
4639
4640                 string const & lang = par.getParLanguage(bp)->code();
4641                 par.params().labelString(counters.theCounter(enumcounter, lang));
4642
4643                 break;
4644         }
4645
4646         case LABEL_SENSITIVE: {
4647                 string const & type = counters.current_float();
4648                 docstring full_label;
4649                 if (type.empty())
4650                         full_label = owner_->B_("Senseless!!! ");
4651                 else {
4652                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4653                         if (counters.hasCounter(from_utf8(type))) {
4654                                 string const & lang = par.getParLanguage(bp)->code();
4655                                 counters.step(from_utf8(type), utype);
4656                                 full_label = bformat(from_ascii("%1$s %2$s:"),
4657                                                      name,
4658                                                      counters.theCounter(from_utf8(type), lang));
4659                         } else
4660                                 full_label = bformat(from_ascii("%1$s #:"), name);
4661                 }
4662                 par.params().labelString(full_label);
4663                 break;
4664         }
4665
4666         case LABEL_NO_LABEL:
4667                 par.params().labelString(docstring());
4668                 break;
4669
4670         case LABEL_ABOVE:
4671         case LABEL_CENTERED:
4672         case LABEL_STATIC: {
4673                 docstring const & lcounter = layout.counter;
4674                 if (!lcounter.empty()) {
4675                         if (layout.toclevel <= bp.secnumdepth
4676                                                 && (layout.latextype != LATEX_ENVIRONMENT
4677                                         || it.text()->isFirstInSequence(it.pit()))) {
4678                                 if (counters.hasCounter(lcounter))
4679                                         counters.step(lcounter, utype);
4680                                 par.params().labelString(par.expandLabel(layout, bp));
4681                         } else
4682                                 par.params().labelString(docstring());
4683                 } else
4684                         par.params().labelString(par.expandLabel(layout, bp));
4685                 break;
4686         }
4687
4688         case LABEL_MANUAL:
4689         case LABEL_BIBLIO:
4690                 par.params().labelString(par.expandLabel(layout, bp));
4691         }
4692 }
4693
4694
4695 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4696 {
4697         // LASSERT: Is it safe to continue here, or should we just return?
4698         LASSERT(parit.pit() == 0, /**/);
4699
4700         // Set the position of the text in the buffer to be able
4701         // to resolve macros in it.
4702         parit.text()->setMacrocontextPosition(parit);
4703
4704         depth_type maxdepth = 0;
4705         pit_type const lastpit = parit.lastpit();
4706         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4707                 // reduce depth if necessary
4708                 if (parit->params().depth() > maxdepth) {
4709                         /** FIXME: this function is const, but
4710                          * nevertheless it modifies the buffer. To be
4711                          * cleaner, one should modify the buffer in
4712                          * another function, which is actually
4713                          * non-const. This would however be costly in
4714                          * terms of code duplication.
4715                          */
4716                         const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4717                         parit->params().depth(maxdepth);
4718                 }
4719                 maxdepth = parit->getMaxDepthAfter();
4720
4721                 if (utype == OutputUpdate) {
4722                         // track the active counters
4723                         // we have to do this for the master buffer, since the local
4724                         // buffer isn't tracking anything.
4725                         masterBuffer()->params().documentClass().counters().
4726                                         setActiveLayout(parit->layout());
4727                 }
4728
4729                 // set the counter for this paragraph
4730                 d->setLabel(parit, utype);
4731
4732                 // now the insets
4733                 InsetList::const_iterator iit = parit->insetList().begin();
4734                 InsetList::const_iterator end = parit->insetList().end();
4735                 for (; iit != end; ++iit) {
4736                         parit.pos() = iit->pos;
4737                         iit->inset->updateBuffer(parit, utype);
4738                 }
4739         }
4740 }
4741
4742
4743 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4744         WordLangTuple & word_lang, docstring_list & suggestions) const
4745 {
4746         int progress = 0;
4747         WordLangTuple wl;
4748         suggestions.clear();
4749         word_lang = WordLangTuple();
4750         bool const to_end = to.empty();
4751         DocIterator const end = to_end ? doc_iterator_end(this) : to;
4752         // OK, we start from here.
4753         for (; from != end; from.forwardPos()) {
4754                 // We are only interested in text so remove the math CursorSlice.
4755                 while (from.inMathed()) {
4756                         from.pop_back();
4757                         from.pos()++;
4758                 }
4759                 // If from is at the end of the document (which is possible
4760                 // when leaving the mathed) LyX will crash later otherwise.
4761                 if (from.atEnd() || (!to_end && from >= end))
4762                         break;
4763                 to = from;
4764                 from.paragraph().spellCheck();
4765                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4766                 if (SpellChecker::misspelled(res)) {
4767                         word_lang = wl;
4768                         break;
4769                 }
4770
4771                 // Do not increase progress when from == to, otherwise the word
4772                 // count will be wrong.
4773                 if (from != to) {
4774                         from = to;
4775                         ++progress;
4776                 }
4777         }
4778         return progress;
4779 }
4780
4781
4782 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4783 {
4784         bool inword = false;
4785         word_count_ = 0;
4786         char_count_ = 0;
4787         blank_count_ = 0;
4788
4789         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4790                 if (!dit.inTexted()) {
4791                         dit.forwardPos();
4792                         continue;
4793                 }
4794
4795                 Paragraph const & par = dit.paragraph();
4796                 pos_type const pos = dit.pos();
4797
4798                 // Copied and adapted from isWordSeparator() in Paragraph
4799                 if (pos == dit.lastpos()) {
4800                         inword = false;
4801                 } else {
4802                         Inset const * ins = par.getInset(pos);
4803                         if (ins && skipNoOutput && !ins->producesOutput()) {
4804                                 // skip this inset
4805                                 ++dit.top().pos();
4806                                 // stop if end of range was skipped
4807                                 if (!to.atEnd() && dit >= to)
4808                                         break;
4809                                 continue;
4810                         } else if (!par.isDeleted(pos)) {
4811                                 if (par.isWordSeparator(pos))
4812                                         inword = false;
4813                                 else if (!inword) {
4814                                         ++word_count_;
4815                                         inword = true;
4816                                 }
4817                                 if (ins && ins->isLetter())
4818                                         ++char_count_;
4819                                 else if (ins && ins->isSpace())
4820                                         ++blank_count_;
4821                                 else {
4822                                         char_type const c = par.getChar(pos);
4823                                         if (isPrintableNonspace(c))
4824                                                 ++char_count_;
4825                                         else if (isSpace(c))
4826                                                 ++blank_count_;
4827                                 }
4828                         }
4829                 }
4830                 dit.forwardPos();
4831         }
4832 }
4833
4834
4835 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4836 {
4837         d->updateStatistics(from, to, skipNoOutput);
4838 }
4839
4840
4841 int Buffer::wordCount() const
4842 {
4843         return d->wordCount();
4844 }
4845
4846
4847 int Buffer::charCount(bool with_blanks) const
4848 {
4849         return d->charCount(with_blanks);
4850 }
4851
4852
4853 Buffer::ReadStatus Buffer::reload()
4854 {
4855         setBusy(true);
4856         // c.f. bug http://www.lyx.org/trac/ticket/6587
4857         removeAutosaveFile();
4858         // e.g., read-only status could have changed due to version control
4859         d->filename.refresh();
4860         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4861
4862         // clear parent. this will get reset if need be.
4863         d->setParent(0);
4864         ReadStatus const status = loadLyXFile();
4865         if (status == ReadSuccess) {
4866                 updateBuffer();
4867                 changed(true);
4868                 updateTitles();
4869                 markClean();
4870                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4871                 d->undo_.clear();
4872         } else {
4873                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4874         }
4875         setBusy(false);
4876         removePreviews();
4877         updatePreviews();
4878         errors("Parse");
4879         return status;
4880 }
4881
4882
4883 bool Buffer::saveAs(FileName const & fn)
4884 {
4885         FileName const old_name = fileName();
4886         FileName const old_auto = getAutosaveFileName();
4887         bool const old_unnamed = isUnnamed();
4888
4889         setFileName(fn);
4890         markDirty();
4891         setUnnamed(false);
4892
4893         if (save()) {
4894                 // bring the autosave file with us, just in case.
4895                 moveAutosaveFile(old_auto);
4896                 // validate version control data and
4897                 // correct buffer title
4898                 lyxvc().file_found_hook(fileName());
4899                 updateTitles();
4900                 // the file has now been saved to the new location.
4901                 // we need to check that the locations of child buffers
4902                 // are still valid.
4903                 checkChildBuffers();
4904                 checkMasterBuffer();
4905                 return true;
4906         } else {
4907                 // save failed
4908                 // reset the old filename and unnamed state
4909                 setFileName(old_name);
4910                 setUnnamed(old_unnamed);
4911                 return false;
4912         }
4913 }
4914
4915
4916 // FIXME We could do better here, but it is complicated. What would be
4917 // nice is to offer either (a) to save the child buffer to an appropriate
4918 // location, so that it would "move with the master", or else (b) to update
4919 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4920 // complicated, because the code for this lives in GuiView.
4921 void Buffer::checkChildBuffers()
4922 {
4923         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4924         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4925         for (; it != en; ++it) {
4926                 DocIterator dit = it->second;
4927                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4928                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4929                         continue;
4930                 Inset * inset = dit.nextInset();
4931                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4932                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4933                 docstring const & incfile = inset_inc->getParam("filename");
4934                 string oldloc = cbuf->absFileName();
4935                 string newloc = makeAbsPath(to_utf8(incfile),
4936                                 onlyPath(absFileName())).absFileName();
4937                 if (oldloc == newloc)
4938                         continue;
4939                 // the location of the child file is incorrect.
4940                 Alert::warning(_("Included File Invalid"),
4941                                 bformat(_("Saving this document to a new location has made the file:\n"
4942                                 "  %1$s\n"
4943                                 "inaccessible. You will need to update the included filename."),
4944                                 from_utf8(oldloc)));
4945                 cbuf->setParent(0);
4946                 inset_inc->setChildBuffer(0);
4947         }
4948         // invalidate cache of children
4949         d->children_positions.clear();
4950         d->position_to_children.clear();
4951 }
4952
4953
4954 // If a child has been saved under a different name/path, it might have been
4955 // orphaned. Therefore the master needs to be reset (bug 8161).
4956 void Buffer::checkMasterBuffer()
4957 {
4958         Buffer const * const master = masterBuffer();
4959         if (master == this)
4960                 return;
4961
4962         // necessary to re-register the child (bug 5873)
4963         // FIXME: clean up updateMacros (here, only
4964         // child registering is needed).
4965         master->updateMacros();
4966         // (re)set master as master buffer, but only
4967         // if we are a real child
4968         if (master->isChild(this))
4969                 setParent(master);
4970         else
4971                 setParent(0);
4972 }
4973
4974 } // namespace lyx