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