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