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