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