3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
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"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.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"
59 #include "SpellChecker.h"
61 #include "texstream.h"
64 #include "TextClass.h"
65 #include "TocBackend.h"
67 #include "VCBackend.h"
69 #include "WordLangTuple.h"
72 #include "insets/InsetBibtex.h"
73 #include "insets/InsetBranch.h"
74 #include "insets/InsetInclude.h"
75 #include "insets/InsetTabular.h"
76 #include "insets/InsetText.h"
78 #include "mathed/InsetMathHull.h"
79 #include "mathed/MacroTable.h"
80 #include "mathed/InsetMathMacroTemplate.h"
81 #include "mathed/MathSupport.h"
83 #include "graphics/GraphicsCache.h"
84 #include "graphics/PreviewLoader.h"
86 #include "frontends/Application.h"
87 #include "frontends/alert.h"
88 #include "frontends/Delegates.h"
89 #include "frontends/WorkAreaManager.h"
91 #include "support/lassert.h"
92 #include "support/convert.h"
93 #include "support/debug.h"
94 #include "support/docstring_list.h"
95 #include "support/ExceptionMessage.h"
96 #include "support/FileMonitor.h"
97 #include "support/FileName.h"
98 #include "support/FileNameList.h"
99 #include "support/filetools.h"
100 #include "support/ForkedCalls.h"
101 #include "support/gettext.h"
102 #include "support/gzstream.h"
103 #include "support/lstrings.h"
104 #include "support/lyxalgo.h"
105 #include "support/mutex.h"
106 #include "support/os.h"
107 #include "support/Package.h"
108 #include "support/PathChanger.h"
109 #include "support/Systemcall.h"
110 #include "support/TempFile.h"
111 #include "support/textutils.h"
112 #include "support/types.h"
114 #include "support/bind.h"
126 using namespace lyx::support;
127 using namespace lyx::graphics;
131 namespace Alert = frontend::Alert;
132 namespace os = support::os;
136 int const LYX_FORMAT = LYX_FORMAT_LYX;
138 typedef map<string, bool> DepClean;
140 // Information about labels and their associated refs
145 InsetLabel const * inset;
146 /// associated references cache
147 Buffer::References references;
148 /// whether this label is active (i.e., not deleted)
152 typedef vector<LabelInfo> LabelCache;
154 typedef map<docstring, Buffer::References> RefCache;
156 // A storehouse for the cloned buffers.
157 typedef list<CloneList_ptr> CloneStore;
158 CloneStore cloned_buffers;
167 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
171 delete preview_loader_;
179 /// search for macro in local (buffer) table or in children
180 MacroData const * getBufferMacro(docstring const & name,
181 DocIterator const & pos) const;
183 /// Update macro table starting with position of it \param it in some
185 void updateMacros(DocIterator & it, DocIterator & scope);
187 void setLabel(ParIterator & it, UpdateType utype) const;
189 /** If we have branches that use the file suffix
190 feature, return the file name with suffix appended.
192 FileName exportFileName() const;
199 mutable TexRow texrow;
201 /// need to regenerate .tex?
204 /// name of the file the buffer is associated with.
208 mutable TocBackend toc_backend;
213 ScopeMacro(DocIterator const & s, MacroData const & m)
214 : scope(s), macro(m) {}
218 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
219 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
220 /// map from the macro name to the position map,
221 /// which maps the macro definition position to the scope and the MacroData.
222 NamePositionScopeMacroMap macros;
224 /// positions of child buffers in the buffer
225 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
227 ScopeBuffer() : buffer(nullptr) {}
228 ScopeBuffer(DocIterator const & s, Buffer const * b)
229 : scope(s), buffer(b) {}
231 Buffer const * buffer;
233 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
234 /// position of children buffers in this buffer
235 BufferPositionMap children_positions;
236 /// map from children inclusion positions to their scope and their buffer
237 PositionScopeBufferMap position_to_children;
239 /// Contains the old buffer filePath() while saving-as, or the
240 /// directory where the document was last saved while loading.
243 /** Keeps track of the path of local layout files.
244 * If possible, it is always relative to the buffer path.
245 * Empty for layouts in system or user directory.
247 string layout_position;
249 /// Container for all sort of Buffer dependant errors.
250 map<string, ErrorList> errorLists;
252 /// checksum used to test if the file has been externally modified. Used to
253 /// double check whether the file had been externally modified when saving.
254 unsigned long checksum_;
257 frontend::WorkAreaManager * wa_;
259 frontend::GuiBufferDelegate * gui_;
264 /// A cache for the bibfiles (including bibfiles of loaded child
265 /// documents), needed for appropriate update of natbib labels.
266 mutable docstring_list bibfiles_cache_;
268 // FIXME The caching mechanism could be improved. At present, we have a
269 // cache for each Buffer, that caches all the bibliography info for that
270 // Buffer. A more efficient solution would be to have a global cache per
271 // file, and then to construct the Buffer's bibinfo from that.
272 /// A cache for bibliography info
273 mutable BiblioInfo bibinfo_;
274 /// Cache of timestamps of .bib files
275 map<FileName, time_t> bibfile_status_;
277 /// These two hold the file name and format, written to by
278 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
279 FileName preview_file_;
280 string preview_format_;
282 /// Cache the references associated to a label and their positions
284 mutable RefCache ref_cache_;
285 /// Cache the label insets and their activity status.
286 mutable LabelCache label_cache_;
288 /// our Text that should be wrapped in an InsetText
292 PreviewLoader * preview_loader_;
294 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
295 /// This one is useful for preview detached in a thread.
296 Buffer const * cloned_buffer_;
298 CloneList_ptr clone_list_;
301 std::list<Buffer const *> include_list_;
303 /// So we can force access via the accessors.
304 mutable Buffer const * parent_buffer;
306 FileMonitorPtr file_monitor_;
308 /// ints and bools are all listed last so as to avoid alignment issues
310 /// original format of loaded file
313 /// are we in the process of exporting this buffer?
314 mutable bool doing_export;
316 /// If there was an error when previewing, on the next preview we do
317 /// a fresh compile (e.g. in case the user installed a package that
319 bool require_fresh_start_;
321 /// Indicates whether the bibinfo has changed since the last time
322 /// we ran updateBuffer(), i.e., whether citation labels may need
324 mutable bool cite_labels_valid_;
325 /// Do we have a bibliography environment?
326 mutable bool have_bibitems_;
329 mutable bool lyx_clean;
331 /// is autosave needed?
332 mutable bool bak_clean;
334 /// is this an unnamed file (New...)?
337 /// is this an internal bufffer?
338 bool internal_buffer;
343 /** Set to true only when the file is fully loaded.
344 * Used to prevent the premature generation of previews
345 * and by the citation inset.
347 bool file_fully_loaded;
349 /// if the file was originally loaded from an older format, do
350 /// we need to back it up still?
351 bool need_format_backup;
353 /// Ignore the parent (e.g. when exporting a child standalone)?
356 /// This seem to change the way Buffer::getMacro() works
357 mutable bool macro_lock;
359 /// has been externally modified? Can be reset by the user.
360 mutable bool externally_modified_;
362 /// whether the bibinfo cache is valid
363 mutable bool bibinfo_cache_valid_;
371 /// This is here to force the test to be done whenever parent_buffer
373 Buffer const * parent() const
375 // ignore_parent temporarily "orphans" a buffer
376 // (e.g. if a child is compiled standalone)
379 // if parent_buffer is not loaded, then it has been unloaded,
380 // which means that parent_buffer is an invalid pointer. So we
381 // set it to null in that case.
382 // however, the BufferList doesn't know about cloned buffers, so
383 // they will always be regarded as unloaded. in that case, we hope
385 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
386 parent_buffer = nullptr;
387 return parent_buffer;
391 void setParent(Buffer const * pb)
393 if (parent_buffer == pb)
396 if (!cloned_buffer_ && parent_buffer && pb)
397 LYXERR0("Warning: a buffer should not have two parents!");
399 if (!cloned_buffer_ && parent_buffer)
400 parent_buffer->invalidateBibinfoCache();
403 /// compute statistics
404 /// \p from initial position
405 /// \p to points to the end position
406 void updateStatistics(DocIterator & from, DocIterator & to,
407 bool skipNoOutput = true);
408 /// statistics accessor functions
409 int wordCount() const
413 int charCount(bool with_blanks) const
416 + (with_blanks ? blank_count_ : 0);
419 // Make sure the file monitor monitors the good file.
420 void refreshFileMonitor();
422 /// Notify or clear of external modification
423 void fileExternallyModified(bool exists);
425 ///Binding LaTeX lines with buffer positions.
426 //Common routine for LaTeX and Reference errors listing.
427 void traverseErrors(TeXErrors::Errors::const_iterator err,
428 TeXErrors::Errors::const_iterator end,
429 ErrorList & errorList) const;
433 /// Creates the per buffer temporary directory
434 static FileName createBufferTmpDir()
436 // FIXME This would be the ideal application for a TempDir class (like
437 // TempFile but for directories)
442 Mutex::Locker locker(&mutex);
443 counter = convert<string>(count++);
445 // We are in our own directory. Why bother to mangle name?
446 // In fact I wrote this code to circumvent a problematic behaviour
447 // (bug?) of EMX mkstemp().
448 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
451 if (!tmpfl.createDirectory(0777)) {
452 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
453 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
454 from_utf8(tmpfl.absFileName())));
460 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
461 Buffer const * cloned_buffer)
462 : owner_(owner), filename(file), toc_backend(owner), checksum_(0),
463 wa_(nullptr), gui_(nullptr), undo_(*owner), inset(nullptr),
464 preview_loader_(nullptr), cloned_buffer_(cloned_buffer),
465 clone_list_(nullptr), parent_buffer(nullptr), file_format(LYX_FORMAT),
466 doing_export(false), require_fresh_start_(false), cite_labels_valid_(false),
467 have_bibitems_(false), lyx_clean(true), bak_clean(true), unnamed(false),
468 internal_buffer(false), read_only(readonly_), file_fully_loaded(false),
469 need_format_backup(false), ignore_parent(false), macro_lock(false),
470 externally_modified_(false), bibinfo_cache_valid_(false),
471 word_count_(0), char_count_(0), blank_count_(0)
473 refreshFileMonitor();
474 if (!cloned_buffer_) {
475 temppath = createBufferTmpDir();
476 lyxvc.setBuffer(owner_);
477 Language const * inplang = theApp() ?
478 languages.getFromCode(theApp()->inputLanguageCode())
481 params.language = inplang;
483 wa_ = new frontend::WorkAreaManager;
486 temppath = cloned_buffer_->d->temppath;
487 file_fully_loaded = true;
488 params = cloned_buffer_->d->params;
489 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
490 bibinfo_ = cloned_buffer_->d->bibinfo_;
491 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
492 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
493 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
494 have_bibitems_ = cloned_buffer_->d->have_bibitems_;
495 unnamed = cloned_buffer_->d->unnamed;
496 internal_buffer = cloned_buffer_->d->internal_buffer;
497 layout_position = cloned_buffer_->d->layout_position;
498 preview_file_ = cloned_buffer_->d->preview_file_;
499 preview_format_ = cloned_buffer_->d->preview_format_;
500 require_fresh_start_ = cloned_buffer_->d->require_fresh_start_;
504 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
505 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
507 LYXERR(Debug::INFO, "Buffer::Buffer()");
509 d->inset = new InsetText(*cloned_buffer->d->inset);
510 d->inset->setBuffer(*this);
511 // FIXME: optimize this loop somewhat, maybe by creating a new
512 // general recursive Inset::setId().
513 DocIterator it = doc_iterator_begin(this);
514 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
515 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
516 it.paragraph().setId(cloned_it.paragraph().id());
518 d->inset = new InsetText(this);
519 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
525 LYXERR(Debug::INFO, "Buffer::~Buffer()");
526 // here the buffer should take care that it is
527 // saved properly, before it goes into the void.
529 // GuiView already destroyed
533 // No need to do additional cleanups for internal buffer.
539 // this is in case of recursive includes: we won't try to delete
540 // ourselves as a child.
541 d->clone_list_->erase(this);
542 // loop over children
543 for (auto const & p : d->children_positions) {
544 Buffer * child = const_cast<Buffer *>(p.first);
545 if (d->clone_list_->erase(child))
548 // if we're the master buffer, then we should get rid of the list
551 // If this is not empty, we have leaked something. Worse, one of the
552 // children still has a reference to this list. But we will try to
553 // continue, rather than shut down.
554 LATTEST(d->clone_list_->empty());
555 // The clone list itself is empty, but it's still referenced in our list
556 // of clones. So let's find it and remove it.
557 CloneStore::iterator it =
558 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
559 if (it == cloned_buffers.end()) {
560 // We will leak in this case, but it is safe to continue.
563 cloned_buffers.erase(it);
565 // FIXME Do we really need to do this right before we delete d?
566 // clear references to children in macro tables
567 d->children_positions.clear();
568 d->position_to_children.clear();
570 // loop over children
571 for (auto const & p : d->children_positions) {
572 Buffer * child = const_cast<Buffer *>(p.first);
573 if (theBufferList().isLoaded(child)) {
574 if (theBufferList().isOthersChild(this, child))
575 child->setParent(nullptr);
577 theBufferList().release(child);
582 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
584 msg += emergencyWrite();
586 msg += " " + _("Save failed! Document is lost.");
588 Alert::warning(_("Attempting to close changed document!"), msg);
591 // FIXME Do we really need to do this right before we delete d?
592 // clear references to children in macro tables
593 d->children_positions.clear();
594 d->position_to_children.clear();
596 if (!d->temppath.destroyDirectory()) {
597 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
598 from_utf8(d->temppath.absFileName())));
607 Buffer * Buffer::cloneWithChildren() const
610 cloned_buffers.emplace_back(new CloneList);
611 CloneList_ptr clones = cloned_buffers.back();
613 cloneWithChildren(bufmap, clones);
615 // make sure we got cloned
616 BufferMap::const_iterator bit = bufmap.find(this);
617 LASSERT(bit != bufmap.end(), return nullptr);
618 Buffer * cloned_buffer = bit->second;
620 return cloned_buffer;
624 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList_ptr clones) const
626 // have we already been cloned?
627 if (bufmap.find(this) != bufmap.end())
630 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
632 // The clone needs its own DocumentClass, since running updateBuffer() will
633 // modify it, and we would otherwise be sharing it with the original Buffer.
634 buffer_clone->params().makeDocumentClass(true);
636 cap::switchBetweenClasses(
637 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
638 static_cast<InsetText &>(buffer_clone->inset()), el);
640 bufmap[this] = buffer_clone;
641 clones->insert(buffer_clone);
642 buffer_clone->d->clone_list_ = clones;
643 buffer_clone->d->macro_lock = true;
644 buffer_clone->d->children_positions.clear();
646 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
647 // math macro caches need to be rethought and simplified.
648 // I am not sure wether we should handle Buffer cloning here or in BufferList.
649 // Right now BufferList knows nothing about buffer clones.
650 for (auto const & p : d->position_to_children) {
651 DocIterator dit = p.first.clone(buffer_clone);
652 dit.setBuffer(buffer_clone);
653 Buffer * child = const_cast<Buffer *>(p.second.buffer);
655 child->cloneWithChildren(bufmap, clones);
656 BufferMap::iterator const bit = bufmap.find(child);
657 LASSERT(bit != bufmap.end(), continue);
658 Buffer * child_clone = bit->second;
660 Inset * inset = dit.nextInset();
661 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
662 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
663 inset_inc->setChildBuffer(child_clone);
664 child_clone->d->setParent(buffer_clone);
665 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
666 buffer_clone->setChild(dit, child_clone);
668 buffer_clone->d->macro_lock = false;
673 Buffer * Buffer::cloneBufferOnly() const {
674 cloned_buffers.emplace_back(new CloneList);
675 CloneList_ptr clones = cloned_buffers.back();
676 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
678 // The clone needs its own DocumentClass, since running updateBuffer() will
679 // modify it, and we would otherwise be sharing it with the original Buffer.
680 buffer_clone->params().makeDocumentClass(true);
682 cap::switchBetweenClasses(
683 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
684 static_cast<InsetText &>(buffer_clone->inset()), el);
686 clones->insert(buffer_clone);
687 buffer_clone->d->clone_list_ = clones;
689 // we won't be cloning the children
690 buffer_clone->d->children_positions.clear();
695 bool Buffer::isClone() const
697 return d->cloned_buffer_;
701 void Buffer::changed(bool update_metrics) const
704 d->wa_->redrawAll(update_metrics);
708 frontend::WorkAreaManager & Buffer::workAreaManager() const
715 Text & Buffer::text() const
717 return d->inset->text();
721 Inset & Buffer::inset() const
727 BufferParams & Buffer::params()
733 BufferParams const & Buffer::params() const
739 BufferParams const & Buffer::masterParams() const
741 if (masterBuffer() == this)
744 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
745 // Copy child authors to the params. We need those pointers.
746 for (Author const & a : params().authors())
747 mparams.authors().record(a);
752 double Buffer::fontScalingFactor() const
754 return isExporting() ? 75.0 * params().html_math_img_scale
755 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
759 ParagraphList & Buffer::paragraphs()
761 return text().paragraphs();
765 ParagraphList const & Buffer::paragraphs() const
767 return text().paragraphs();
771 LyXVC & Buffer::lyxvc()
777 LyXVC const & Buffer::lyxvc() const
783 string const Buffer::temppath() const
785 return d->temppath.absFileName();
789 TexRow & Buffer::texrow()
795 TexRow const & Buffer::texrow() const
801 TocBackend & Buffer::tocBackend() const
803 return d->toc_backend;
807 Undo & Buffer::undo()
813 void Buffer::setChild(DocIterator const & dit, Buffer * child)
815 d->children_positions[child] = dit;
819 string Buffer::latexName(bool const no_path) const
821 FileName latex_name =
822 makeLatexName(d->exportFileName());
823 return no_path ? latex_name.onlyFileName()
824 : latex_name.absFileName();
828 FileName Buffer::Impl::exportFileName() const
830 docstring const branch_suffix =
831 params.branchlist().getFileNameSuffix();
832 if (branch_suffix.empty())
835 string const name = addExtension(filename.onlyFileNameWithoutExt()
836 + to_utf8(branch_suffix), filename.extension());
837 FileName res(filename.onlyPath().absFileName() + "/" + name);
843 string Buffer::logName(LogType * type) const
845 string const filename = latexName(false);
847 if (filename.empty()) {
853 string const path = temppath();
855 FileName const fname(addName(temppath(),
856 onlyFileName(changeExtension(filename,
859 // FIXME: how do we know this is the name of the build log?
860 FileName const bname(
861 addName(path, onlyFileName(
862 changeExtension(filename,
863 theFormats().extension(params().bufferFormat()) + ".out"))));
865 // Also consider the master buffer log file
866 FileName masterfname = fname;
867 LogType mtype = latexlog;
868 if (masterBuffer() != this) {
869 string const mlogfile = masterBuffer()->logName(&mtype);
870 masterfname = FileName(mlogfile);
873 // If no Latex log or Build log is newer, show Build log
874 if (bname.exists() &&
875 ((!fname.exists() && !masterfname.exists())
876 || (fname.lastModified() < bname.lastModified()
877 && masterfname.lastModified() < bname.lastModified()))) {
878 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
881 return bname.absFileName();
882 // If we have a newer master file log or only a master log, show this
883 } else if (fname != masterfname
884 && (!fname.exists() && (masterfname.exists()
885 || fname.lastModified() < masterfname.lastModified()))) {
886 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
889 return masterfname.absFileName();
891 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
894 return fname.absFileName();
898 void Buffer::setReadonly(bool const flag)
900 if (d->read_only != flag) {
907 void Buffer::setFileName(FileName const & fname)
909 bool const changed = fname != d->filename;
911 d->refreshFileMonitor();
913 lyxvc().file_found_hook(fname);
914 setReadonly(d->filename.isReadOnly());
920 int Buffer::readHeader(Lexer & lex)
922 int unknown_tokens = 0;
924 int begin_header_line = -1;
926 // Initialize parameters that may be/go lacking in header:
927 params().branchlist().clear();
928 params().preamble.erase();
929 params().options.erase();
930 params().master.erase();
931 params().float_placement.erase();
932 params().float_alignment.erase();
933 params().paperwidth.erase();
934 params().paperheight.erase();
935 params().leftmargin.erase();
936 params().rightmargin.erase();
937 params().topmargin.erase();
938 params().bottommargin.erase();
939 params().headheight.erase();
940 params().headsep.erase();
941 params().footskip.erase();
942 params().columnsep.erase();
943 params().font_roman_opts.erase();
944 params().font_sans_opts.erase();
945 params().font_typewriter_opts.erase();
946 params().fonts_cjk.erase();
947 params().listings_params.clear();
948 params().clearLayoutModules();
949 params().clearRemovedModules();
950 params().clearIncludedChildren();
951 params().pdfoptions().clear();
952 params().indiceslist().clear();
953 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
954 params().isbackgroundcolor = false;
955 params().fontcolor = RGBColor(0, 0, 0);
956 params().isfontcolor = false;
957 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
958 params().boxbgcolor = RGBColor(0xFF, 0, 0);
959 params().html_latex_start.clear();
960 params().html_latex_end.clear();
961 params().html_math_img_scale = 1.0;
962 params().output_sync_macro.erase();
963 params().setLocalLayout(docstring(), false);
964 params().setLocalLayout(docstring(), true);
965 params().biblio_opts.erase();
966 params().biblatex_bibstyle.erase();
967 params().biblatex_citestyle.erase();
968 params().multibib.erase();
969 params().lineno_opts.clear();
971 for (int i = 0; i < 4; ++i) {
972 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
973 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
976 ErrorList & errorList = d->errorLists["Parse"];
985 if (token == "\\end_header")
989 if (token == "\\begin_header") {
990 begin_header_line = line;
994 LYXERR(Debug::PARSER, "Handling document header token: `"
997 string const result =
998 params().readToken(lex, token, d->filename.onlyPath());
999 if (!result.empty()) {
1000 if (token == "\\textclass") {
1001 d->layout_position = result;
1004 docstring const s = bformat(_("Unknown token: "
1007 lex.getDocString());
1008 errorList.push_back(ErrorItem(_("Document header error"), s));
1012 if (begin_header_line) {
1013 docstring const s = _("\\begin_header is missing");
1014 errorList.push_back(ErrorItem(_("Document header error"), s));
1017 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
1019 params().makeDocumentClass();
1021 return unknown_tokens;
1026 // changed to be public and have one parameter
1027 // Returns true if "\end_document" is not read (Asger)
1028 bool Buffer::readDocument(Lexer & lex)
1030 ErrorList & errorList = d->errorLists["Parse"];
1033 // remove dummy empty par
1034 paragraphs().clear();
1036 if (!lex.checkFor("\\begin_document")) {
1037 docstring const s = _("\\begin_document is missing");
1038 errorList.push_back(ErrorItem(_("Document header error"), s));
1043 if (params().output_changes) {
1044 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1045 LaTeXFeatures::isAvailable("xcolor");
1048 Alert::warning(_("Changes not shown in LaTeX output"),
1049 _("Changes will not be highlighted in LaTeX output, "
1050 "because xcolor and ulem are not installed.\n"
1051 "Please install both packages or redefine "
1052 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1056 if (!parent() && !params().master.empty()) {
1057 FileName const master_file = makeAbsPath(params().master,
1058 onlyPath(absFileName()));
1059 if (isLyXFileName(master_file.absFileName())) {
1061 checkAndLoadLyXFile(master_file, true);
1063 // necessary e.g. after a reload
1064 // to re-register the child (bug 5873)
1065 // FIXME: clean up updateMacros (here, only
1066 // child registering is needed).
1067 master->updateMacros();
1068 // set master as master buffer, but only
1069 // if we are a real child
1070 if (master->isChild(this))
1072 // if the master is not fully loaded
1073 // it is probably just loading this
1074 // child. No warning needed then.
1075 else if (master->isFullyLoaded())
1076 LYXERR0("The master '"
1078 << "' assigned to this document ("
1080 << ") does not include "
1081 "this document. Ignoring the master assignment.");
1082 // If the master has just been created, un-hide it (#11162)
1083 if (!master->fileName().exists())
1084 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1085 master->absFileName()));
1090 // assure we have a default index
1091 params().indiceslist().addDefault(B_("Index"));
1094 if (FileName::isAbsolute(params().origin))
1095 d->old_position = params().origin;
1097 d->old_position = filePath();
1098 bool const res = text().read(lex, errorList, d->inset);
1099 d->old_position.clear();
1101 // inform parent buffer about local macros
1103 Buffer const * pbuf = parent();
1104 for (auto const & m : usermacros)
1105 pbuf->usermacros.insert(m);
1109 updateMacroInstances(InternalUpdate);
1114 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1116 Format const * fmt = theFormats().getFormat(format);
1119 // It is important to use the correct extension here, since some
1120 // converters create a wrong output file otherwise (e.g. html2latex)
1121 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1122 ofdocstream os(name.toFilesystemEncoding().c_str());
1123 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1124 bool const success = !(os << contents).fail();
1127 bool converted = false;
1129 params().compressed = false;
1131 // remove dummy empty par
1132 paragraphs().clear();
1134 converted = importFile(format, name, errorList);
1137 removeTempFile(name);
1142 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1144 if (!theConverters().isReachable(format, "lyx"))
1147 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1148 Converters::RetVal const retval =
1149 theConverters().convert(nullptr, name, lyx, name, format, "lyx", errorList);
1150 if (retval == Converters::SUCCESS) {
1151 bool const success = readFile(lyx) == ReadSuccess;
1152 removeTempFile(lyx);
1160 bool Buffer::readString(string const & s)
1162 params().compressed = false;
1165 istringstream is(s);
1167 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1168 FileName const fn = tempfile.name();
1171 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1173 if (success && file_format != LYX_FORMAT) {
1174 // We need to call lyx2lyx, so write the input to a file
1175 ofstream os(fn.toFilesystemEncoding().c_str());
1178 // lyxvc in readFile
1179 if (readFile(fn) != ReadSuccess)
1183 if (readDocument(lex))
1189 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1193 if (!lex.setFile(fname)) {
1194 Alert::error(_("File Not Found"),
1195 bformat(_("Unable to open file `%1$s'."),
1196 from_utf8(fn.absFileName())));
1197 return ReadFileNotFound;
1201 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1202 if (ret_plf != ReadSuccess)
1205 if (file_format != LYX_FORMAT) {
1207 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1208 if (ret_clf != ReadSuccess)
1210 ret_clf = readFile(tmpFile);
1211 if (ret_clf == ReadSuccess) {
1212 d->file_format = file_format;
1213 d->need_format_backup = true;
1218 // FIXME: InsetInfo needs to know whether the file is under VCS
1219 // during the parse process, so this has to be done before.
1220 lyxvc().file_found_hook(d->filename);
1222 if (readDocument(lex)) {
1223 Alert::error(_("Document format failure"),
1224 bformat(_("%1$s ended unexpectedly, which means"
1225 " that it is probably corrupted."),
1226 from_utf8(fn.absFileName())));
1227 return ReadDocumentFailure;
1230 d->file_fully_loaded = true;
1231 d->read_only = !d->filename.isWritable();
1232 params().compressed = theFormats().isZippedFile(d->filename);
1238 bool Buffer::isFullyLoaded() const
1240 return d->file_fully_loaded;
1244 void Buffer::setFullyLoaded(bool value)
1246 d->file_fully_loaded = value;
1250 bool Buffer::freshStartRequired() const
1252 return d->require_fresh_start_;
1255 void Buffer::requireFreshStart(bool const b) const
1257 d->require_fresh_start_ = b;
1261 PreviewLoader * Buffer::loader() const
1263 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1265 if (!d->preview_loader_)
1266 d->preview_loader_ = new PreviewLoader(*this);
1267 return d->preview_loader_;
1271 void Buffer::removePreviews() const
1273 delete d->preview_loader_;
1274 d->preview_loader_ = nullptr;
1278 void Buffer::updatePreviews() const
1280 PreviewLoader * ploader = loader();
1284 InsetIterator it = inset_iterator_begin(*d->inset);
1285 InsetIterator const end = inset_iterator_end(*d->inset);
1286 for (; it != end; ++it)
1287 it->addPreview(it, *ploader);
1289 ploader->startLoading();
1293 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1294 FileName const & fn, int & file_format) const
1296 if(!lex.checkFor("\\lyxformat")) {
1297 Alert::error(_("Document format failure"),
1298 bformat(_("%1$s is not a readable LyX document."),
1299 from_utf8(fn.absFileName())));
1300 return ReadNoLyXFormat;
1306 // LyX formats 217 and earlier were written as 2.17. This corresponds
1307 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1308 // these cases. See also: www.lyx.org/trac/changeset/1313.
1309 size_t dot = tmp_format.find_first_of(".,");
1310 if (dot != string::npos)
1311 tmp_format.erase(dot, 1);
1313 file_format = convert<int>(tmp_format);
1318 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1319 FileName & tmpfile, int from_format)
1321 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1322 tempfile.setAutoRemove(false);
1323 tmpfile = tempfile.name();
1324 if(tmpfile.empty()) {
1325 Alert::error(_("Conversion failed"),
1326 bformat(_("%1$s is from a different"
1327 " version of LyX, but a temporary"
1328 " file for converting it could"
1329 " not be created."),
1330 from_utf8(fn.absFileName())));
1331 return LyX2LyXNoTempFile;
1334 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1335 if (lyx2lyx.empty()) {
1336 Alert::error(_("Conversion script not found"),
1337 bformat(_("%1$s is from a different"
1338 " version of LyX, but the"
1339 " conversion script lyx2lyx"
1340 " could not be found."),
1341 from_utf8(fn.absFileName())));
1342 return LyX2LyXNotFound;
1346 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1347 ostringstream command;
1348 command << os::python()
1349 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1350 << " -t " << convert<string>(LYX_FORMAT)
1351 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1352 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1353 string const command_str = command.str();
1355 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1357 cmd_ret const ret = runCommand(command_str);
1358 if (ret.first != 0) {
1359 if (from_format < LYX_FORMAT) {
1360 Alert::error(_("Conversion script failed"),
1361 bformat(_("%1$s is from an older version"
1362 " of LyX and the lyx2lyx script"
1363 " failed to convert it."),
1364 from_utf8(fn.absFileName())));
1365 return LyX2LyXOlderFormat;
1367 Alert::error(_("Conversion script failed"),
1368 bformat(_("%1$s is from a newer version"
1369 " of LyX and the lyx2lyx script"
1370 " failed to convert it."),
1371 from_utf8(fn.absFileName())));
1372 return LyX2LyXNewerFormat;
1379 FileName Buffer::getBackupName() const {
1380 map<int, string> const file_formats = {
1397 FileName const & fn = fileName();
1398 string const fname = fn.onlyFileNameWithoutExt();
1399 string const fext = fn.extension() + "~";
1400 string const fpath = lyxrc.backupdir_path.empty() ?
1401 fn.onlyPath().absFileName() :
1402 lyxrc.backupdir_path;
1403 string backup_suffix;
1404 // If file format is from a stable series use version instead of file format
1405 auto const it = file_formats.find(d->file_format);
1406 if (it != file_formats.end())
1407 backup_suffix = "-lyx" + it->second;
1409 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1410 string const backname = fname + backup_suffix;
1411 FileName backup(addName(fpath, addExtension(backname, fext)));
1413 // limit recursion, just in case
1415 unsigned long orig_checksum = 0;
1416 while (backup.exists() && v < 100) {
1417 if (orig_checksum == 0)
1418 orig_checksum = fn.checksum();
1419 unsigned long new_checksum = backup.checksum();
1420 if (orig_checksum == new_checksum) {
1421 LYXERR(Debug::FILES, "Not backing up " << fn <<
1422 "since " << backup << "has the same checksum.");
1423 // a bit of a hack, but we have to check this anyway
1424 // below, and setting this is simpler than introducing
1425 // a special boolean for this purpose.
1429 string const newbackname = backname + "-" + convert<string>(v);
1430 backup.set(addName(fpath, addExtension(newbackname, fext)));
1433 return v < 100 ? backup : FileName();
1437 // Should probably be moved to somewhere else: BufferView? GuiView?
1438 bool Buffer::save() const
1440 docstring const file = makeDisplayPath(absFileName(), 20);
1441 d->filename.refresh();
1443 // check the read-only status before moving the file as a backup
1444 if (d->filename.exists()) {
1445 bool const read_only = !d->filename.isWritable();
1447 Alert::warning(_("File is read-only"),
1448 bformat(_("The file %1$s cannot be written because it "
1449 "is marked as read-only."), file));
1454 // ask if the disk file has been externally modified (use checksum method)
1455 if (fileName().exists() && isChecksumModified()) {
1457 bformat(_("Document %1$s has been externally modified. "
1458 "Are you sure you want to overwrite this file?"), file);
1459 int const ret = Alert::prompt(_("Overwrite modified file?"),
1460 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1465 // We don't need autosaves in the immediate future. (Asger)
1466 resetAutosaveTimers();
1468 // if the file does not yet exist, none of the backup activity
1469 // that follows is necessary
1470 if (!fileName().exists()) {
1471 if (!writeFile(fileName()))
1477 // we first write the file to a new name, then move it to its
1478 // proper location once that has been done successfully. that
1479 // way we preserve the original file if something goes wrong.
1480 string const justname = fileName().onlyFileNameWithoutExt();
1481 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1482 justname + "-XXXXXX.lyx");
1483 bool const symlink = fileName().isSymLink();
1485 tempfile->setAutoRemove(false);
1487 FileName savefile(tempfile->name());
1488 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1489 if (!savefile.clonePermissions(fileName()))
1490 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1492 if (!writeFile(savefile))
1495 // we will set this to false if we fail
1496 bool made_backup = true;
1498 FileName backupName;
1499 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1501 if (d->need_format_backup)
1502 backupName = getBackupName();
1504 // If we for some reason failed to find a backup name in case of
1505 // a format change, this will still set one. It's the best we can
1507 if (backupName.empty()) {
1508 backupName.set(fileName().absFileName() + "~");
1509 if (!lyxrc.backupdir_path.empty()) {
1510 string const mangledName =
1511 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1512 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1516 LYXERR(Debug::FILES, "Backing up original file to " <<
1517 backupName.absFileName());
1518 // Except file is symlink do not copy because of #6587.
1519 // Hard links have bad luck.
1520 made_backup = symlink ?
1521 fileName().copyTo(backupName):
1522 fileName().moveTo(backupName);
1525 Alert::error(_("Backup failure"),
1526 bformat(_("Cannot create backup file %1$s.\n"
1527 "Please check whether the directory exists and is writable."),
1528 from_utf8(backupName.absFileName())));
1529 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1530 } else if (d->need_format_backup) {
1531 // the original file has been backed up successfully, so we
1532 // will not need to do that again
1533 d->need_format_backup = false;
1537 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1538 // Only do this if tempfile is not in autoremove mode
1541 // If we have no symlink, we can simply rename the temp file.
1542 // Otherwise, we need to copy it so the symlink stays intact.
1543 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1544 savefile.moveTo(fileName()))
1546 // saveCheckSum() was already called by writeFile(), but the
1547 // time stamp is invalidated by copying/moving
1550 if (d->file_format != LYX_FORMAT)
1551 // the file associated with this buffer is now in the current format
1552 d->file_format = LYX_FORMAT;
1555 // else we saved the file, but failed to move it to the right location.
1557 if (needBackup && made_backup && !symlink) {
1558 // the original file was moved to some new location, so it will look
1559 // to the user as if it was deleted. (see bug #9234.) we could try
1560 // to restore it, but that would basically mean trying to do again
1561 // what we just failed to do. better to leave things as they are.
1562 Alert::error(_("Write failure"),
1563 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1564 "But LyX could not move it to:\n %2$s.\n"
1565 "Your original file has been backed up to:\n %3$s"),
1566 from_utf8(savefile.absFileName()),
1567 from_utf8(fileName().absFileName()),
1568 from_utf8(backupName.absFileName())));
1570 // either we did not try to make a backup, or else we tried and failed,
1571 // or else the original file was a symlink, in which case it was copied,
1572 // not moved. so the original file is intact.
1573 Alert::error(_("Write failure"),
1574 bformat(_("Cannot move saved file to:\n %1$s.\n"
1575 "But the file has successfully been saved as:\n %2$s."),
1576 from_utf8(fileName().absFileName()),
1577 from_utf8(savefile.absFileName())));
1583 bool Buffer::writeFile(FileName const & fname) const
1585 if (d->read_only && fname == d->filename)
1588 bool retval = false;
1590 docstring const str = bformat(_("Saving document %1$s..."),
1591 makeDisplayPath(fname.absFileName()));
1594 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1596 if (params().compressed) {
1597 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1598 retval = ofs && write(ofs);
1600 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1601 retval = ofs && write(ofs);
1605 message(str + _(" could not write file!"));
1610 // removeAutosaveFile();
1613 message(str + _(" done."));
1619 docstring Buffer::emergencyWrite()
1621 // No need to save if the buffer has not changed.
1625 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1627 docstring user_message = bformat(
1628 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1630 // We try to save three places:
1631 // 1) Same place as document. Unless it is an unnamed doc.
1633 string s = absFileName();
1636 if (writeFile(FileName(s))) {
1638 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1639 return user_message;
1641 user_message += " " + _("Save failed! Trying again...\n");
1645 // 2) In HOME directory.
1646 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1648 lyxerr << ' ' << s << endl;
1649 if (writeFile(FileName(s))) {
1651 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1652 return user_message;
1655 user_message += " " + _("Save failed! Trying yet again...\n");
1657 // 3) In "/tmp" directory.
1658 // MakeAbsPath to prepend the current
1659 // drive letter on OS/2
1660 s = addName(package().temp_dir().absFileName(), absFileName());
1662 lyxerr << ' ' << s << endl;
1663 if (writeFile(FileName(s))) {
1665 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1666 return user_message;
1669 user_message += " " + _("Save failed! Document is lost.");
1672 return user_message;
1676 bool Buffer::write(ostream & ofs) const
1679 // Use the standard "C" locale for file output.
1680 ofs.imbue(locale::classic());
1683 // The top of the file should not be written by params().
1685 // write out a comment in the top of the file
1686 // Important: Keep the version formatting in sync with lyx2lyx and
1687 // tex2lyx (bug 7951)
1688 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1689 << " created this file. For more info see https://www.lyx.org/\n"
1690 << "\\lyxformat " << LYX_FORMAT << "\n"
1691 << "\\begin_document\n";
1693 /// For each author, set 'used' to true if there is a change
1694 /// by this author in the document; otherwise set it to 'false'.
1695 for (Author const & a : params().authors())
1698 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1699 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1700 for ( ; it != end; ++it)
1701 it->checkAuthors(params().authors());
1703 // now write out the buffer parameters.
1704 ofs << "\\begin_header\n";
1705 params().writeFile(ofs, this);
1706 ofs << "\\end_header\n";
1709 ofs << "\n\\begin_body\n";
1711 ofs << "\n\\end_body\n";
1713 // Write marker that shows file is complete
1714 ofs << "\\end_document" << endl;
1716 // Shouldn't really be needed....
1719 // how to check if close went ok?
1720 // Following is an attempt... (BE 20001011)
1722 // good() returns false if any error occurred, including some
1723 // formatting error.
1724 // bad() returns true if something bad happened in the buffer,
1725 // which should include file system full errors.
1730 lyxerr << "File was not closed properly." << endl;
1737 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1738 string const & original_path,
1739 OutputParams const & runparams_in,
1740 OutputWhat output) const
1742 OutputParams runparams = runparams_in;
1744 string const encoding = runparams.encoding->iconvName();
1745 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1748 try { ofs.reset(encoding); }
1749 catch (iconv_codecvt_facet_exception const & e) {
1750 lyxerr << "Caught iconv exception: " << e.what() << endl;
1751 Alert::error(_("Iconv software exception Detected"),
1752 bformat(_("Please verify that the `iconv' support software is"
1753 " properly installed and supports the selected encoding"
1754 " (%1$s), or change the encoding in"
1755 " Document>Settings>Language."), from_ascii(encoding)));
1758 if (!openFileWrite(ofs, fname))
1761 ErrorList & errorList = d->errorLists["Export"];
1763 ExportStatus status = ExportSuccess;
1766 // make sure we are ready to export
1767 // this needs to be done before we validate
1768 // FIXME Do we need to do this all the time? I.e., in children
1769 // of a master we are exporting?
1771 updateMacroInstances(OutputUpdate);
1773 ExportStatus retval;
1775 retval = writeLaTeXSource(os, original_path, runparams, output);
1776 if (retval == ExportKilled)
1777 return ExportKilled;
1779 catch (EncodingException const & e) {
1780 docstring const failed(1, e.failed_char);
1782 oss << "0x" << hex << e.failed_char << dec;
1783 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1784 docstring msg = bformat(_("Uncodable character '%1$s'"
1785 " (code point %2$s)"),
1786 failed, from_utf8(oss.str()));
1787 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1788 "representable in specific verbatim contexts.\n"
1789 "Changing the document encoding to utf8 could help."),
1790 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1792 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1793 " (code point %2$s)"),
1794 failed, from_utf8(oss.str()));
1795 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1796 "representable in the chosen encoding.\n"
1797 "Changing the document encoding to utf8 could help."),
1798 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1800 status = ExportError;
1802 catch (iconv_codecvt_facet_exception const & e) {
1803 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1805 status = ExportError;
1807 catch (exception const & e) {
1808 errorList.push_back(ErrorItem(_("conversion failed"),
1810 lyxerr << e.what() << endl;
1811 status = ExportError;
1814 lyxerr << "Caught some really weird exception..." << endl;
1818 d->texrow = move(os.texrow());
1822 status = ExportError;
1823 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1826 if (runparams_in.silent)
1834 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1835 string const & original_path,
1836 OutputParams const & runparams_in,
1837 OutputWhat output) const
1839 // The child documents, if any, shall be already loaded at this point.
1841 OutputParams runparams = runparams_in;
1843 // Some macros rely on font encoding
1844 runparams.main_fontenc = params().main_font_encoding();
1846 // If we are compiling a file standalone, even if this is the
1847 // child of some other buffer, let's cut the link here, so the
1848 // file is really independent and no concurring settings from
1849 // the master (e.g. branch state) interfere (see #8100).
1850 if (!runparams.is_child)
1851 d->ignore_parent = true;
1853 // Classify the unicode characters appearing in math insets
1854 BufferEncodings::initUnicodeMath(*this);
1856 // validate the buffer.
1857 LYXERR(Debug::LATEX, " Validating buffer...");
1858 LaTeXFeatures features(*this, params(), runparams);
1860 // This is only set once per document (in master)
1861 if (!runparams.is_child) {
1862 runparams.use_polyglossia = features.usePolyglossia();
1863 runparams.use_hyperref = features.isRequired("hyperref");
1864 runparams.use_CJK = features.mustProvide("CJK");
1866 LYXERR(Debug::LATEX, " Buffer validation done.");
1868 bool const output_preamble =
1869 output == FullSource || output == OnlyPreamble;
1870 bool const output_body =
1871 output == FullSource || output == OnlyBody;
1873 // The starting paragraph of the coming rows is the
1874 // first paragraph of the document. (Asger)
1875 if (output_preamble && runparams.nice) {
1876 os << "%% LyX " << lyx_version << " created this file. "
1877 "For more info, see https://www.lyx.org/.\n"
1878 "%% Do not edit unless you really know what "
1881 LYXERR(Debug::INFO, "lyx document header finished");
1883 // There are a few differences between nice LaTeX and usual files:
1884 // usual files have \batchmode and special input@path to allow
1885 // inclusion of figures specified by an explicitly relative path
1886 // (i.e., a path starting with './' or '../') with either \input or
1887 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1888 // input@path is set when the actual parameter original_path is set.
1889 // This is done for usual tex-file, but not for nice-latex-file.
1890 // (Matthias 250696)
1891 // Note that input@path is only needed for something the user does
1892 // in the preamble, included .tex files or ERT, files included by
1893 // LyX work without it.
1894 if (output_preamble) {
1895 if (!runparams.nice) {
1896 // code for usual, NOT nice-latex-file
1897 os << "\\batchmode\n"; // changed from \nonstopmode
1899 if (!original_path.empty()) {
1901 // We don't know the encoding of inputpath
1902 docstring const inputpath = from_utf8(original_path);
1903 docstring uncodable_glyphs;
1904 Encoding const * const enc = runparams.encoding;
1906 for (size_t n = 0; n < inputpath.size(); ++n) {
1907 if (!enc->encodable(inputpath[n])) {
1908 docstring const glyph(1, inputpath[n]);
1909 LYXERR0("Uncodable character '"
1911 << "' in input path!");
1912 uncodable_glyphs += glyph;
1917 // warn user if we found uncodable glyphs.
1918 if (!uncodable_glyphs.empty()) {
1919 frontend::Alert::warning(
1920 _("Uncodable character in file path"),
1922 _("The path of your document\n"
1924 "contains glyphs that are unknown "
1925 "in the current document encoding "
1926 "(namely %2$s). This may result in "
1927 "incomplete output, unless "
1928 "TEXINPUTS contains the document "
1929 "directory and you don't use "
1930 "explicitly relative paths (i.e., "
1931 "paths starting with './' or "
1932 "'../') in the preamble or in ERT."
1933 "\n\nIn case of problems, choose "
1934 "an appropriate document encoding\n"
1935 "(such as utf8) or change the "
1937 inputpath, uncodable_glyphs));
1939 string docdir = os::latex_path(original_path);
1940 if (contains(docdir, '#')) {
1941 docdir = subst(docdir, "#", "\\#");
1942 os << "\\catcode`\\#=11"
1943 "\\def\\#{#}\\catcode`\\#=6\n";
1945 if (contains(docdir, '%')) {
1946 docdir = subst(docdir, "%", "\\%");
1947 os << "\\catcode`\\%=11"
1948 "\\def\\%{%}\\catcode`\\%=14\n";
1950 if (contains(docdir, '~'))
1951 docdir = subst(docdir, "~", "\\string~");
1952 bool const nonascii = !isAscii(from_utf8(docdir));
1953 // LaTeX 2019/10/01 handles non-ascii path without detokenize
1954 bool const utfpathlatex = features.isAvailable("LaTeX-2019/10/01");
1955 bool const detokenize = !utfpathlatex && nonascii;
1956 bool const quote = contains(docdir, ' ');
1957 if (utfpathlatex && nonascii)
1958 os << "\\UseRawInputEncoding\n";
1959 os << "\\makeatletter\n"
1960 << "\\def\\input@path{{";
1962 os << "\\detokenize{";
1971 << "\\makeatother\n";
1975 // get parent macros (if this buffer has a parent) which will be
1976 // written at the document begin further down.
1977 MacroSet parentMacros;
1978 listParentMacros(parentMacros, features);
1980 // Write the preamble
1981 runparams.use_babel = params().writeLaTeX(os, features,
1982 d->filename.onlyPath());
1984 // Active characters
1985 runparams.active_chars = features.getActiveChars();
1987 // Biblatex bibliographies are loaded here
1988 if (params().useBiblatex()) {
1989 vector<pair<docstring, string>> const bibfiles =
1990 prepareBibFilePaths(runparams, getBibfiles(), true);
1991 for (pair<docstring, string> const & file: bibfiles) {
1992 os << "\\addbibresource";
1993 if (!file.second.empty())
1994 os << "[bibencoding=" << file.second << "]";
1995 os << "{" << file.first << "}\n";
1999 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
2000 && !features.hasOnlyPolyglossiaLanguages()) {
2003 vector<string> bll = features.getBabelExclusiveLanguages();
2004 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
2007 for (string const & sit : bll) {
2012 blangs = bll.size() > 1 ?
2013 bformat(_("The languages %1$s are only supported by Babel."), langs)
2014 : bformat(_("The language %1$s is only supported by Babel."), langs);
2018 for (string const & pit : pll) {
2023 plangs = pll.size() > 1 ?
2024 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
2025 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
2026 if (!blangs.empty())
2030 frontend::Alert::warning(
2031 _("Incompatible Languages!"),
2033 _("You cannot use the following languages "
2034 "together in one LaTeX document because "
2035 "they require conflicting language packages:\n"
2040 // Japanese might be required only in some children of a document,
2041 // but once required, we must keep use_japanese true.
2042 runparams.use_japanese |= features.isRequired("japanese");
2045 // Restore the parenthood if needed
2046 if (!runparams.is_child)
2047 d->ignore_parent = false;
2048 return ExportSuccess;
2052 // mark the beginning of the body to separate it from InPreamble insets
2053 os.texrow().start(TexRow::beginDocument());
2054 os << "\\begin{document}\n";
2056 // mark the start of a new paragraph by simulating a newline,
2057 // so that os.afterParbreak() returns true at document start
2060 // output the parent macros
2061 for (auto const & mac : parentMacros) {
2062 int num_lines = mac->write(os.os(), true);
2063 os.texrow().newlines(num_lines);
2066 } // output_preamble
2068 LYXERR(Debug::INFO, "preamble finished, now the body.");
2072 latexParagraphs(*this, text(), os, runparams);
2074 catch (ConversionException const &) { return ExportKilled; }
2076 // Restore the parenthood if needed
2077 if (!runparams.is_child)
2078 d->ignore_parent = false;
2080 // add this just in case after all the paragraphs
2083 if (output_preamble) {
2084 os << "\\end{document}\n";
2085 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2087 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2089 runparams_in.encoding = runparams.encoding;
2091 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2092 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2093 return ExportSuccess;
2097 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2098 OutputParams const & runparams,
2099 OutputWhat output) const
2101 LYXERR(Debug::LATEX, "makeDocBookFile...");
2104 if (!openFileWrite(ofs, fname))
2107 // make sure we are ready to export
2108 // this needs to be done before we validate
2110 updateMacroInstances(OutputUpdate);
2112 ExportStatus const retval =
2113 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2114 if (retval == ExportKilled)
2115 return ExportKilled;
2119 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2120 return ExportSuccess;
2124 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os, string const & fname,
2125 OutputParams const & runparams,
2126 OutputWhat output) const
2128 LaTeXFeatures features(*this, params(), runparams);
2133 DocumentClass const & tclass = params().documentClass();
2134 string const & top_element = tclass.latexname();
2136 bool const output_preamble =
2137 output == FullSource || output == OnlyPreamble;
2138 bool const output_body =
2139 output == FullSource || output == OnlyBody;
2141 if (output_preamble) {
2142 if (runparams.flavor == OutputParams::XML)
2143 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2146 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2149 if (! tclass.class_header().empty())
2150 os << from_ascii(tclass.class_header());
2151 else if (runparams.flavor == OutputParams::XML)
2152 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2153 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2155 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2157 docstring preamble = params().preamble;
2158 if (runparams.flavor != OutputParams::XML ) {
2159 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2160 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2161 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2162 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2165 string const name = runparams.nice
2166 ? changeExtension(absFileName(), ".sgml") : fname;
2167 preamble += features.getIncludedFiles(name);
2168 preamble += features.getLyXSGMLEntities();
2170 if (!preamble.empty()) {
2171 os << "\n [ " << preamble << " ]";
2177 string top = top_element;
2179 if (runparams.flavor == OutputParams::XML)
2180 top += params().language->code();
2182 top += params().language->code().substr(0, 2);
2185 if (!params().options.empty()) {
2187 top += params().options;
2190 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2191 << " file was created by LyX " << lyx_version
2192 << "\n See https://www.lyx.org/ for more information -->\n";
2194 params().documentClass().counters().reset();
2196 sgml::openTag(os, top);
2199 docbookParagraphs(text(), *this, os, runparams);
2201 catch (ConversionException const &) { return ExportKilled; }
2202 sgml::closeTag(os, top_element);
2204 return ExportSuccess;
2208 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2209 OutputParams const & runparams) const
2211 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2214 if (!openFileWrite(ofs, fname))
2217 // make sure we are ready to export
2218 // this has to be done before we validate
2219 updateBuffer(UpdateMaster, OutputUpdate);
2220 updateMacroInstances(OutputUpdate);
2222 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2223 if (retval == ExportKilled)
2228 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2233 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2234 OutputParams const & runparams,
2235 OutputWhat output) const
2237 LaTeXFeatures features(*this, params(), runparams);
2239 d->bibinfo_.makeCitationLabels(*this);
2241 bool const output_preamble =
2242 output == FullSource || output == OnlyPreamble;
2243 bool const output_body =
2244 output == FullSource || output == OnlyBody || output == IncludedFile;
2246 if (output_preamble) {
2247 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2248 << "<!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"
2249 // FIXME Language should be set properly.
2250 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2252 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2253 // FIXME Presumably need to set this right
2254 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2256 docstring const & doctitle = features.htmlTitle();
2258 << (doctitle.empty() ?
2259 from_ascii("LyX Document") :
2260 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2263 docstring styles = features.getTClassHTMLPreamble();
2264 if (!styles.empty())
2265 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2267 // we will collect CSS information in a stream, and then output it
2268 // either here, as part of the header, or else in a separate file.
2269 odocstringstream css;
2270 styles = features.getCSSSnippets();
2271 if (!styles.empty())
2272 css << "/* LyX Provided Styles */\n" << styles << '\n';
2274 styles = features.getTClassHTMLStyles();
2275 if (!styles.empty())
2276 css << "/* Layout-provided Styles */\n" << styles << '\n';
2278 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2279 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2280 if (needfg || needbg) {
2281 css << "\nbody {\n";
2284 << from_ascii(X11hexname(params().fontcolor))
2287 css << " background-color: "
2288 << from_ascii(X11hexname(params().backgroundcolor))
2293 docstring const dstyles = css.str();
2294 if (!dstyles.empty()) {
2295 bool written = false;
2296 if (params().html_css_as_file) {
2297 // open a file for CSS info
2299 string const fcssname = addName(temppath(), "docstyle.css");
2300 FileName const fcssfile = FileName(fcssname);
2301 if (openFileWrite(ocss, fcssfile)) {
2305 // write link to header
2306 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2308 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2311 // we are here if the CSS is supposed to be written to the header
2312 // or if we failed to write it to an external file.
2314 os << "<style type='text/css'>\n"
2323 bool const output_body_tag = (output != IncludedFile);
2324 if (output_body_tag)
2325 os << "<body dir=\"auto\">\n";
2327 if (output != IncludedFile)
2328 // if we're an included file, the counters are in the master.
2329 params().documentClass().counters().reset();
2331 xhtmlParagraphs(text(), *this, xs, runparams);
2333 catch (ConversionException const &) { return ExportKilled; }
2334 if (output_body_tag)
2338 if (output_preamble)
2341 return ExportSuccess;
2345 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2346 // Other flags: -wall -v0 -x
2347 int Buffer::runChktex()
2351 // get LaTeX-Filename
2352 FileName const path(temppath());
2353 string const name = addName(path.absFileName(), latexName());
2354 string const org_path = filePath();
2356 PathChanger p(path); // path to LaTeX file
2357 message(_("Running chktex..."));
2359 // Generate the LaTeX file if neccessary
2360 OutputParams runparams(¶ms().encoding());
2361 runparams.flavor = OutputParams::LATEX;
2362 runparams.nice = false;
2363 runparams.linelen = lyxrc.plaintext_linelen;
2364 ExportStatus const retval =
2365 makeLaTeXFile(FileName(name), org_path, runparams);
2366 if (retval != ExportSuccess) {
2367 // error code on failure
2372 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2373 int const res = chktex.run(terr); // run chktex
2376 Alert::error(_("chktex failure"),
2377 _("Could not run chktex successfully."));
2379 ErrorList & errlist = d->errorLists["ChkTeX"];
2381 bufferErrors(terr, errlist);
2386 if (runparams.silent)
2387 d->errorLists["ChkTeX"].clear();
2395 void Buffer::validate(LaTeXFeatures & features) const
2397 // Validate the buffer params, but not for included
2398 // files, since they also use the parent buffer's
2400 if (!features.runparams().is_child)
2401 params().validate(features);
2403 for (Paragraph const & p : paragraphs())
2404 p.validate(features);
2406 if (lyxerr.debugging(Debug::LATEX)) {
2407 features.showStruct();
2412 void Buffer::getLabelList(vector<docstring> & list) const
2414 // If this is a child document, use the master's list instead.
2416 masterBuffer()->getLabelList(list);
2421 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2422 for (auto const & tocit : *toc) {
2423 if (tocit.depth() == 0)
2424 list.push_back(tocit.str());
2429 void Buffer::invalidateBibinfoCache() const
2431 d->bibinfo_cache_valid_ = false;
2432 d->cite_labels_valid_ = false;
2433 removeBiblioTempFiles();
2434 // also invalidate the cache for the parent buffer
2435 Buffer const * const pbuf = d->parent();
2437 pbuf->invalidateBibinfoCache();
2441 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2443 // FIXME This is probably unnecessary, given where we call this.
2444 // If this is a child document, use the master instead.
2445 Buffer const * const pbuf = masterBuffer();
2446 if (pbuf != this && scope != UpdateChildOnly)
2447 return pbuf->getBibfiles();
2449 // In 2.3.x, we have:
2450 //if (!d->bibfile_cache_valid_)
2451 // this->updateBibfilesCache(scope);
2452 // I think that is a leftover, but there have been so many back-
2453 // and-forths with this, due to Windows issues, that I am not sure.
2455 return d->bibfiles_cache_;
2459 BiblioInfo const & Buffer::masterBibInfo() const
2461 Buffer const * const tmp = masterBuffer();
2463 return tmp->masterBibInfo();
2468 BiblioInfo const & Buffer::bibInfo() const
2474 void Buffer::registerBibfiles(const docstring_list & bf) const
2476 // We register the bib files in the master buffer,
2477 // if there is one, but also in every single buffer,
2478 // in case a child is compiled alone.
2479 Buffer const * const tmp = masterBuffer();
2481 tmp->registerBibfiles(bf);
2483 for (auto const & p : bf) {
2484 docstring_list::const_iterator temp =
2485 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2486 if (temp == d->bibfiles_cache_.end())
2487 d->bibfiles_cache_.push_back(p);
2492 static map<docstring, FileName> bibfileCache;
2494 FileName Buffer::getBibfilePath(docstring const & bibid) const
2496 map<docstring, FileName>::const_iterator it =
2497 bibfileCache.find(bibid);
2498 if (it != bibfileCache.end()) {
2499 // i.e., return bibfileCache[bibid];
2503 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2504 string const texfile = changeExtension(to_utf8(bibid), "bib");
2505 // we need to check first if this file exists where it's said to be.
2506 // there's a weird bug that occurs otherwise: if the file is in the
2507 // Buffer's directory but has the same name as some file that would be
2508 // found by kpsewhich, then we find the latter, not the former.
2509 FileName const local_file = makeAbsPath(texfile, filePath());
2510 FileName file = local_file;
2511 if (!file.exists()) {
2512 // there's no need now to check whether the file can be found
2514 file = findtexfile(texfile, "bib", true);
2518 LYXERR(Debug::FILES, "Found at: " << file);
2520 bibfileCache[bibid] = file;
2521 return bibfileCache[bibid];
2525 void Buffer::checkIfBibInfoCacheIsValid() const
2527 // use the master's cache
2528 Buffer const * const tmp = masterBuffer();
2530 tmp->checkIfBibInfoCacheIsValid();
2534 // If we already know the cache is invalid, stop here.
2535 // This is important in the case when the bibliography
2536 // environment (rather than Bib[la]TeX) is used.
2537 // In that case, the timestamp check below gives no
2538 // sensible result. Rather than that, the cache will
2539 // be invalidated explicitly via invalidateBibInfoCache()
2540 // by the Bibitem inset.
2541 // Same applies for bib encoding changes, which trigger
2542 // invalidateBibInfoCache() by InsetBibtex.
2543 if (!d->bibinfo_cache_valid_)
2546 if (d->have_bibitems_) {
2547 // We have a bibliography environment.
2548 // Invalidate the bibinfo cache unconditionally.
2549 // Cite labels will get invalidated by the inset if needed.
2550 d->bibinfo_cache_valid_ = false;
2554 // OK. This is with Bib(la)tex. We'll assume the cache
2555 // is valid and change this if we find changes in the bibs.
2556 d->bibinfo_cache_valid_ = true;
2557 d->cite_labels_valid_ = true;
2559 // compare the cached timestamps with the actual ones.
2560 docstring_list const & bibfiles_cache = getBibfiles();
2561 for (auto const & bf : bibfiles_cache) {
2562 FileName const fn = getBibfilePath(bf);
2563 time_t lastw = fn.lastModified();
2564 time_t prevw = d->bibfile_status_[fn];
2565 if (lastw != prevw) {
2566 d->bibinfo_cache_valid_ = false;
2567 d->cite_labels_valid_ = false;
2568 d->bibfile_status_[fn] = lastw;
2574 void Buffer::clearBibFileCache() const
2576 bibfileCache.clear();
2580 void Buffer::reloadBibInfoCache(bool const force) const
2582 // we should not need to do this for internal buffers
2586 // use the master's cache
2587 Buffer const * const tmp = masterBuffer();
2589 tmp->reloadBibInfoCache(force);
2594 checkIfBibInfoCacheIsValid();
2595 if (d->bibinfo_cache_valid_)
2599 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2600 // re-read file locations when this info changes
2601 // FIXME Is this sufficient? Or should we also force that
2602 // in some other cases? If so, then it is easy enough to
2603 // add the following line in some other places.
2604 clearBibFileCache();
2605 d->bibinfo_.clear();
2606 FileNameList checkedFiles;
2607 d->have_bibitems_ = false;
2608 collectBibKeys(checkedFiles);
2609 d->bibinfo_cache_valid_ = true;
2613 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2615 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2616 it->collectBibKeys(it, checkedFiles);
2617 if (it->lyxCode() == BIBITEM_CODE) {
2618 if (parent() != nullptr)
2619 parent()->d->have_bibitems_ = true;
2621 d->have_bibitems_ = true;
2627 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2629 // We add the biblio info to the master buffer,
2630 // if there is one, but also to every single buffer,
2631 // in case a child is compiled alone.
2632 BiblioInfo & bi = d->bibinfo_;
2633 bi.mergeBiblioInfo(bin);
2635 if (parent() != nullptr) {
2636 BiblioInfo & masterbi = parent()->d->bibinfo_;
2637 masterbi.mergeBiblioInfo(bin);
2642 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2644 // We add the bibtex info to the master buffer,
2645 // if there is one, but also to every single buffer,
2646 // in case a child is compiled alone.
2647 BiblioInfo & bi = d->bibinfo_;
2650 if (parent() != nullptr) {
2651 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2652 masterbi[key] = bin;
2657 void Buffer::makeCitationLabels() const
2659 Buffer const * const master = masterBuffer();
2660 return d->bibinfo_.makeCitationLabels(*master);
2664 void Buffer::invalidateCiteLabels() const
2666 masterBuffer()->d->cite_labels_valid_ = false;
2669 bool Buffer::citeLabelsValid() const
2671 return masterBuffer()->d->cite_labels_valid_;
2675 void Buffer::removeBiblioTempFiles() const
2677 // We remove files that contain LaTeX commands specific to the
2678 // particular bibliographic style being used, in order to avoid
2679 // LaTeX errors when we switch style.
2680 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2681 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2682 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2683 aux_file.removeFile();
2684 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2685 bbl_file.removeFile();
2686 // Also for the parent buffer
2687 Buffer const * const pbuf = parent();
2689 pbuf->removeBiblioTempFiles();
2693 bool Buffer::isDepClean(string const & name) const
2695 DepClean::const_iterator const it = d->dep_clean.find(name);
2696 if (it == d->dep_clean.end())
2702 void Buffer::markDepClean(string const & name)
2704 d->dep_clean[name] = true;
2708 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2711 // FIXME? if there is an Buffer LFUN that can be dispatched even
2712 // if internal, put a switch '(cmd.action)' here.
2718 switch (cmd.action()) {
2720 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2721 flag.setOnOff(hasReadonlyFlag());
2724 // FIXME: There is need for a command-line import.
2725 //case LFUN_BUFFER_IMPORT:
2727 case LFUN_BUFFER_AUTO_SAVE:
2730 case LFUN_BUFFER_EXPORT_CUSTOM:
2731 // FIXME: Nothing to check here?
2734 case LFUN_BUFFER_EXPORT: {
2735 docstring const arg = cmd.argument();
2736 if (arg == "custom") {
2740 string format = (arg.empty() || arg == "default") ?
2741 params().getDefaultOutputFormat() : to_utf8(arg);
2742 size_t pos = format.find(' ');
2743 if (pos != string::npos)
2744 format = format.substr(0, pos);
2745 enable = params().isExportable(format, false);
2747 flag.message(bformat(
2748 _("Don't know how to export to format: %1$s"), arg));
2752 case LFUN_BUILD_PROGRAM:
2753 enable = params().isExportable("program", false);
2756 case LFUN_BRANCH_ACTIVATE:
2757 case LFUN_BRANCH_DEACTIVATE:
2758 case LFUN_BRANCH_MASTER_ACTIVATE:
2759 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2760 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2761 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2762 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2763 : params().branchlist();
2764 docstring const branchName = cmd.argument();
2765 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2769 case LFUN_BRANCH_ADD:
2770 case LFUN_BRANCHES_RENAME:
2771 // if no Buffer is present, then of course we won't be called!
2774 case LFUN_BUFFER_LANGUAGE:
2775 enable = !isReadonly();
2778 case LFUN_BUFFER_VIEW_CACHE:
2779 (d->preview_file_).refresh();
2780 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2783 case LFUN_CHANGES_TRACK:
2784 flag.setEnabled(true);
2785 flag.setOnOff(params().track_changes);
2788 case LFUN_CHANGES_OUTPUT:
2789 flag.setEnabled(true);
2790 flag.setOnOff(params().output_changes);
2793 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2794 flag.setOnOff(params().compressed);
2797 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2798 flag.setOnOff(params().output_sync);
2801 case LFUN_BUFFER_ANONYMIZE:
2807 flag.setEnabled(enable);
2812 void Buffer::dispatch(string const & command, DispatchResult & result)
2814 return dispatch(lyxaction.lookupFunc(command), result);
2818 // NOTE We can end up here even if we have no GUI, because we are called
2819 // by LyX::exec to handled command-line requests. So we may need to check
2820 // whether we have a GUI or not. The boolean use_gui holds this information.
2821 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2824 // FIXME? if there is an Buffer LFUN that can be dispatched even
2825 // if internal, put a switch '(cmd.action())' here.
2826 dr.dispatched(false);
2829 string const argument = to_utf8(func.argument());
2830 // We'll set this back to false if need be.
2831 bool dispatched = true;
2832 // This handles undo groups automagically
2833 UndoGroupHelper ugh(this);
2835 switch (func.action()) {
2836 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2837 if (lyxvc().inUse()) {
2838 string log = lyxvc().toggleReadOnly();
2843 setReadonly(!hasReadonlyFlag());
2846 case LFUN_BUFFER_EXPORT: {
2847 string const format = (argument.empty() || argument == "default") ?
2848 params().getDefaultOutputFormat() : argument;
2849 ExportStatus const status = doExport(format, false);
2850 dr.setError(status != ExportSuccess);
2851 if (status != ExportSuccess)
2852 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2853 from_utf8(format)));
2857 case LFUN_BUILD_PROGRAM: {
2858 ExportStatus const status = doExport("program", true);
2859 dr.setError(status != ExportSuccess);
2860 if (status != ExportSuccess)
2861 dr.setMessage(_("Error generating literate programming code."));
2865 case LFUN_BUFFER_EXPORT_CUSTOM: {
2867 string command = split(argument, format_name, ' ');
2868 Format const * format = theFormats().getFormat(format_name);
2870 lyxerr << "Format \"" << format_name
2871 << "\" not recognized!"
2876 // The name of the file created by the conversion process
2879 // Output to filename
2880 if (format->name() == "lyx") {
2881 string const latexname = latexName(false);
2882 filename = changeExtension(latexname,
2883 format->extension());
2884 filename = addName(temppath(), filename);
2886 if (!writeFile(FileName(filename)))
2890 doExport(format_name, true, filename);
2893 // Substitute $$FName for filename
2894 if (!contains(command, "$$FName"))
2895 command = "( " + command + " ) < $$FName";
2896 command = subst(command, "$$FName", filename);
2898 // Execute the command in the background
2900 call.startscript(Systemcall::DontWait, command,
2901 filePath(), layoutPos());
2905 // FIXME: There is need for a command-line import.
2907 case LFUN_BUFFER_IMPORT:
2912 case LFUN_BUFFER_AUTO_SAVE:
2914 resetAutosaveTimers();
2917 case LFUN_BRANCH_ACTIVATE:
2918 case LFUN_BRANCH_DEACTIVATE:
2919 case LFUN_BRANCH_MASTER_ACTIVATE:
2920 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2921 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2922 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2923 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2926 docstring const branch_name = func.argument();
2927 // the case without a branch name is handled elsewhere
2928 if (branch_name.empty()) {
2932 Branch * branch = buf->params().branchlist().find(branch_name);
2934 LYXERR0("Branch " << branch_name << " does not exist.");
2936 docstring const msg =
2937 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2941 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2942 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2943 if (branch->isSelected() != activate) {
2944 buf->undo().recordUndoBufferParams(CursorData());
2945 branch->setSelected(activate);
2947 dr.screenUpdate(Update::Force);
2948 dr.forceBufferUpdate();
2953 case LFUN_BRANCH_ADD: {
2954 docstring branchnames = func.argument();
2955 if (branchnames.empty()) {
2959 BranchList & branch_list = params().branchlist();
2960 vector<docstring> const branches =
2961 getVectorFromString(branchnames, branch_list.separator());
2963 for (docstring const & branch_name : branches) {
2964 Branch * branch = branch_list.find(branch_name);
2966 LYXERR0("Branch " << branch_name << " already exists.");
2970 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2972 undo().recordUndoBufferParams(CursorData());
2973 branch_list.add(branch_name);
2974 branch = branch_list.find(branch_name);
2975 string const x11hexname = X11hexname(branch->color());
2976 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2977 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2979 dr.screenUpdate(Update::Force);
2987 case LFUN_BRANCHES_RENAME: {
2988 if (func.argument().empty())
2991 docstring const oldname = from_utf8(func.getArg(0));
2992 docstring const newname = from_utf8(func.getArg(1));
2993 InsetIterator it = inset_iterator_begin(inset());
2994 InsetIterator const end = inset_iterator_end(inset());
2995 bool success = false;
2996 for (; it != end; ++it) {
2997 if (it->lyxCode() == BRANCH_CODE) {
2998 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2999 if (ins.branch() == oldname) {
3000 undo().recordUndo(CursorData(it));
3001 ins.rename(newname);
3006 if (it->lyxCode() == INCLUDE_CODE) {
3007 // get buffer of external file
3008 InsetInclude const & ins =
3009 static_cast<InsetInclude const &>(*it);
3010 Buffer * child = ins.getChildBuffer();
3013 child->dispatch(func, dr);
3018 dr.screenUpdate(Update::Force);
3019 dr.forceBufferUpdate();
3024 case LFUN_BUFFER_VIEW_CACHE:
3025 if (!theFormats().view(*this, d->preview_file_,
3026 d->preview_format_))
3027 dr.setMessage(_("Error viewing the output file."));
3030 case LFUN_CHANGES_TRACK:
3031 if (params().save_transient_properties)
3032 undo().recordUndoBufferParams(CursorData());
3033 params().track_changes = !params().track_changes;
3036 case LFUN_CHANGES_OUTPUT:
3037 if (params().save_transient_properties)
3038 undo().recordUndoBufferParams(CursorData());
3039 params().output_changes = !params().output_changes;
3040 if (params().output_changes) {
3041 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
3042 LaTeXFeatures::isAvailable("xcolor");
3045 Alert::warning(_("Changes not shown in LaTeX output"),
3046 _("Changes will not be highlighted in LaTeX output, "
3047 "because xcolor and ulem are not installed.\n"
3048 "Please install both packages or redefine "
3049 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3054 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3055 // turn compression on/off
3056 undo().recordUndoBufferParams(CursorData());
3057 params().compressed = !params().compressed;
3060 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3061 undo().recordUndoBufferParams(CursorData());
3062 params().output_sync = !params().output_sync;
3065 case LFUN_BUFFER_ANONYMIZE: {
3066 undo().recordUndoFullBuffer(CursorData());
3067 CursorData cur(doc_iterator_begin(this));
3068 for ( ; cur ; cur.forwardPar())
3069 cur.paragraph().anonymize();
3070 dr.forceBufferUpdate();
3071 dr.screenUpdate(Update::Force);
3079 dr.dispatched(dispatched);
3083 void Buffer::changeLanguage(Language const * from, Language const * to)
3085 LASSERT(from, return);
3086 LASSERT(to, return);
3088 for_each(par_iterator_begin(),
3090 bind(&Paragraph::changeLanguage, _1, params(), from, to));
3094 bool Buffer::isMultiLingual() const
3096 ParConstIterator end = par_iterator_end();
3097 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3098 if (it->isMultiLingual(params()))
3105 std::set<Language const *> Buffer::getLanguages() const
3107 std::set<Language const *> langs;
3108 getLanguages(langs);
3113 void Buffer::getLanguages(std::set<Language const *> & langs) const
3115 ParConstIterator end = par_iterator_end();
3116 // add the buffer language, even if it's not actively used
3117 langs.insert(language());
3118 // iterate over the paragraphs
3119 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3120 it->getLanguages(langs);
3122 ListOfBuffers clist = getDescendants();
3123 for (auto const & cit : clist)
3124 cit->getLanguages(langs);
3128 DocIterator Buffer::getParFromID(int const id) const
3130 Buffer * buf = const_cast<Buffer *>(this);
3132 // This means non-existent
3133 return doc_iterator_end(buf);
3135 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3136 if (it.paragraph().id() == id)
3139 return doc_iterator_end(buf);
3143 bool Buffer::hasParWithID(int const id) const
3145 return !getParFromID(id).atEnd();
3149 ParIterator Buffer::par_iterator_begin()
3151 return ParIterator(doc_iterator_begin(this));
3155 ParIterator Buffer::par_iterator_end()
3157 return ParIterator(doc_iterator_end(this));
3161 ParConstIterator Buffer::par_iterator_begin() const
3163 return ParConstIterator(doc_iterator_begin(this));
3167 ParConstIterator Buffer::par_iterator_end() const
3169 return ParConstIterator(doc_iterator_end(this));
3173 Language const * Buffer::language() const
3175 return params().language;
3179 docstring Buffer::B_(string const & l10n) const
3181 return params().B_(l10n);
3185 bool Buffer::isClean() const
3187 return d->lyx_clean;
3191 bool Buffer::isChecksumModified() const
3193 LASSERT(d->filename.exists(), return false);
3194 return d->checksum_ != d->filename.checksum();
3198 void Buffer::saveCheckSum() const
3200 FileName const & file = d->filename;
3202 d->checksum_ = file.exists() ? file.checksum()
3203 : 0; // in the case of save to a new file.
3207 void Buffer::markClean() const
3209 if (!d->lyx_clean) {
3210 d->lyx_clean = true;
3213 // if the .lyx file has been saved, we don't need an
3215 d->bak_clean = true;
3216 d->undo_.markDirty();
3217 clearExternalModification();
3221 void Buffer::setUnnamed(bool flag)
3227 bool Buffer::isUnnamed() const
3234 /// Don't check unnamed, here: isInternal() is used in
3235 /// newBuffer(), where the unnamed flag has not been set by anyone
3236 /// yet. Also, for an internal buffer, there should be no need for
3237 /// retrieving fileName() nor for checking if it is unnamed or not.
3238 bool Buffer::isInternal() const
3240 return d->internal_buffer;
3244 void Buffer::setInternal(bool flag)
3246 d->internal_buffer = flag;
3250 void Buffer::markDirty()
3253 d->lyx_clean = false;
3256 d->bak_clean = false;
3258 for (auto & depit : d->dep_clean)
3259 depit.second = false;
3263 FileName Buffer::fileName() const
3269 string Buffer::absFileName() const
3271 return d->filename.absFileName();
3275 string Buffer::filePath() const
3277 string const abs = d->filename.onlyPath().absFileName();
3280 int last = abs.length() - 1;
3282 return abs[last] == '/' ? abs : abs + '/';
3286 DocFileName Buffer::getReferencedFileName(string const & fn) const
3289 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3290 result.set(fn, filePath());
3292 // filePath() ends with a path separator
3293 FileName const test(filePath() + fn);
3295 result.set(fn, filePath());
3297 result.set(fn, params().origin);
3304 string const Buffer::prepareFileNameForLaTeX(string const & name,
3305 string const & ext, bool nice) const
3307 string const fname = makeAbsPath(name, filePath()).absFileName();
3308 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3314 return to_utf8(makeRelPath(from_utf8(fname),
3315 from_utf8(masterBuffer()->filePath())));
3319 vector<pair<docstring, string>> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3320 docstring_list const & bibfilelist,
3321 bool const add_extension) const
3323 // If we are processing the LaTeX file in a temp directory then
3324 // copy the .bib databases to this temp directory, mangling their
3325 // names in the process. Store this mangled name in the list of
3327 // (We need to do all this because BibTeX *really*, *really*
3328 // can't handle "files with spaces" and Windows users tend to
3329 // use such filenames.)
3330 // Otherwise, store the (maybe absolute) path to the original,
3331 // unmangled database name.
3333 vector<pair<docstring, string>> res;
3335 // determine the export format
3336 string const tex_format = flavor2format(runparams.flavor);
3338 // check for spaces in paths
3339 bool found_space = false;
3341 for (auto const & bit : bibfilelist) {
3342 string utf8input = to_utf8(bit);
3344 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3345 FileName try_in_file =
3346 makeAbsPath(database + ".bib", filePath());
3347 bool not_from_texmf = try_in_file.isReadableFile();
3348 // If the file has not been found, try with the real file name
3349 // (it might come from a child in a sub-directory)
3350 if (!not_from_texmf) {
3351 try_in_file = getBibfilePath(bit);
3352 if (try_in_file.isReadableFile()) {
3353 // Check if the file is in texmf
3354 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3355 not_from_texmf = kpsefile.empty()
3356 || kpsefile.absFileName() != try_in_file.absFileName();
3358 // If this exists, make path relative to the master
3361 removeExtension(prepareFileNameForLaTeX(
3362 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3363 from_utf8(filePath()))),
3364 ".bib", runparams.nice));
3368 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3370 // mangledFileName() needs the extension
3371 DocFileName const in_file = DocFileName(try_in_file);
3372 database = removeExtension(in_file.mangledFileName());
3373 FileName const out_file = makeAbsPath(database + ".bib",
3374 masterBuffer()->temppath());
3375 bool const success = in_file.copyTo(out_file);
3377 LYXERR0("Failed to copy '" << in_file
3378 << "' to '" << out_file << "'");
3380 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3381 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3382 if (!isValidLaTeXFileName(database)) {
3383 frontend::Alert::warning(_("Invalid filename"),
3384 _("The following filename will cause troubles "
3385 "when running the exported file through LaTeX: ") +
3386 from_utf8(database));
3388 if (!isValidDVIFileName(database)) {
3389 frontend::Alert::warning(_("Problematic filename for DVI"),
3390 _("The following filename can cause troubles "
3391 "when running the exported file through LaTeX "
3392 "and opening the resulting DVI: ") +
3393 from_utf8(database), true);
3401 docstring const path = from_utf8(latex_path(database));
3403 if (contains(path, ' '))
3406 if (params().useBiblatex() && !params().bibFileEncoding(utf8input).empty())
3407 enc = params().bibFileEncoding(utf8input);
3409 bool recorded = false;
3410 for (auto const & pe : res) {
3411 if (pe.first == path) {
3418 res.push_back(make_pair(path, enc));
3421 // Check if there are spaces in the path and warn BibTeX users, if so.
3422 // (biber can cope with such paths)
3423 if (!prefixIs(runparams.bibtex_command, "biber")) {
3424 // Post this warning only once.
3425 static bool warned_about_spaces = false;
3426 if (!warned_about_spaces &&
3427 runparams.nice && found_space) {
3428 warned_about_spaces = true;
3429 Alert::warning(_("Export Warning!"),
3430 _("There are spaces in the paths to your BibTeX databases.\n"
3431 "BibTeX will be unable to find them."));
3440 string Buffer::layoutPos() const
3442 return d->layout_position;
3446 void Buffer::setLayoutPos(string const & path)
3449 d->layout_position.clear();
3453 LATTEST(FileName::isAbsolute(path));
3455 d->layout_position =
3456 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3458 if (d->layout_position.empty())
3459 d->layout_position = ".";
3463 bool Buffer::hasReadonlyFlag() const
3465 return d->read_only;
3469 bool Buffer::isReadonly() const
3471 return hasReadonlyFlag() || notifiesExternalModification();
3475 void Buffer::setParent(Buffer const * buffer)
3477 // Avoids recursive include.
3478 d->setParent(buffer == this ? nullptr : buffer);
3483 Buffer const * Buffer::parent() const
3489 ListOfBuffers Buffer::allRelatives() const
3491 ListOfBuffers lb = masterBuffer()->getDescendants();
3492 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3497 Buffer const * Buffer::masterBuffer() const
3499 // FIXME Should be make sure we are not in some kind
3500 // of recursive include? A -> B -> A will crash this.
3501 Buffer const * const pbuf = d->parent();
3505 return pbuf->masterBuffer();
3509 bool Buffer::isChild(Buffer * child) const
3511 return d->children_positions.find(child) != d->children_positions.end();
3515 DocIterator Buffer::firstChildPosition(Buffer const * child)
3517 Impl::BufferPositionMap::iterator it;
3518 it = d->children_positions.find(child);
3519 if (it == d->children_positions.end())
3520 return DocIterator(this);
3525 bool Buffer::hasChildren() const
3527 return !d->children_positions.empty();
3531 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3533 // loop over children
3534 for (auto const & p : d->children_positions) {
3535 Buffer * child = const_cast<Buffer *>(p.first);
3537 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3538 if (bit != clist.end())
3540 clist.push_back(child);
3542 // there might be grandchildren
3543 child->collectChildren(clist, true);
3548 ListOfBuffers Buffer::getChildren() const
3551 collectChildren(v, false);
3552 // Make sure we have not included ourselves.
3553 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3554 if (bit != v.end()) {
3555 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3562 ListOfBuffers Buffer::getDescendants() const
3565 collectChildren(v, true);
3566 // Make sure we have not included ourselves.
3567 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3568 if (bit != v.end()) {
3569 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3576 template<typename M>
3577 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3582 typename M::const_iterator it = m.lower_bound(x);
3583 if (it == m.begin())
3591 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3592 DocIterator const & pos) const
3594 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3596 // if paragraphs have no macro context set, pos will be empty
3600 // we haven't found anything yet
3601 DocIterator bestPos = owner_->par_iterator_begin();
3602 MacroData const * bestData = nullptr;
3604 // find macro definitions for name
3605 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3606 if (nameIt != macros.end()) {
3607 // find last definition in front of pos or at pos itself
3608 PositionScopeMacroMap::const_iterator it
3609 = greatest_below(nameIt->second, pos);
3610 if (it != nameIt->second.end()) {
3612 // scope ends behind pos?
3613 if (pos < it->second.scope) {
3614 // Looks good, remember this. If there
3615 // is no external macro behind this,
3616 // we found the right one already.
3617 bestPos = it->first;
3618 bestData = &it->second.macro;
3622 // try previous macro if there is one
3623 if (it == nameIt->second.begin())
3630 // find macros in included files
3631 PositionScopeBufferMap::const_iterator it
3632 = greatest_below(position_to_children, pos);
3633 if (it == position_to_children.end())
3634 // no children before
3638 // do we know something better (i.e. later) already?
3639 if (it->first < bestPos )
3642 // scope ends behind pos?
3643 if (pos < it->second.scope
3644 && (cloned_buffer_ ||
3645 theBufferList().isLoaded(it->second.buffer))) {
3646 // look for macro in external file
3648 MacroData const * data
3649 = it->second.buffer->getMacro(name, false);
3652 bestPos = it->first;
3658 // try previous file if there is one
3659 if (it == position_to_children.begin())
3664 // return the best macro we have found
3669 MacroData const * Buffer::getMacro(docstring const & name,
3670 DocIterator const & pos, bool global) const
3675 // query buffer macros
3676 MacroData const * data = d->getBufferMacro(name, pos);
3677 if (data != nullptr)
3680 // If there is a master buffer, query that
3681 Buffer const * const pbuf = d->parent();
3683 d->macro_lock = true;
3684 MacroData const * macro = pbuf->getMacro(
3685 name, *this, false);
3686 d->macro_lock = false;
3692 data = MacroTable::globalMacros().get(name);
3693 if (data != nullptr)
3701 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3703 // set scope end behind the last paragraph
3704 DocIterator scope = par_iterator_begin();
3705 scope.pit() = scope.lastpit() + 1;
3707 return getMacro(name, scope, global);
3711 MacroData const * Buffer::getMacro(docstring const & name,
3712 Buffer const & child, bool global) const
3714 // look where the child buffer is included first
3715 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3716 if (it == d->children_positions.end())
3719 // check for macros at the inclusion position
3720 return getMacro(name, it->second, global);
3724 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3726 pit_type const lastpit = it.lastpit();
3728 // look for macros in each paragraph
3729 while (it.pit() <= lastpit) {
3730 Paragraph & par = it.paragraph();
3732 // FIXME Can this be done with the new-style iterators?
3733 // iterate over the insets of the current paragraph
3734 for (auto const & insit : par.insetList()) {
3735 it.pos() = insit.pos;
3737 // is it a nested text inset?
3738 if (insit.inset->asInsetText()) {
3739 // Inset needs its own scope?
3740 InsetText const * itext = insit.inset->asInsetText();
3741 bool newScope = itext->isMacroScope();
3743 // scope which ends just behind the inset
3744 DocIterator insetScope = it;
3747 // collect macros in inset
3748 it.push_back(CursorSlice(*insit.inset));
3749 updateMacros(it, newScope ? insetScope : scope);
3754 if (insit.inset->asInsetTabular()) {
3755 CursorSlice slice(*insit.inset);
3756 size_t const numcells = slice.nargs();
3757 for (; slice.idx() < numcells; slice.forwardIdx()) {
3758 it.push_back(slice);
3759 updateMacros(it, scope);
3765 // is it an external file?
3766 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3767 // get buffer of external file
3768 InsetInclude const & incinset =
3769 static_cast<InsetInclude const &>(*insit.inset);
3771 Buffer * child = incinset.getChildBuffer();
3776 // register its position, but only when it is
3777 // included first in the buffer
3778 if (children_positions.find(child) ==
3779 children_positions.end())
3780 children_positions[child] = it;
3782 // register child with its scope
3783 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3787 InsetMath * im = insit.inset->asInsetMath();
3788 if (doing_export && im) {
3789 InsetMathHull * hull = im->asHullInset();
3791 hull->recordLocation(it);
3794 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3798 InsetMathMacroTemplate & macroTemplate =
3799 *insit.inset->asInsetMath()->asMacroTemplate();
3800 MacroContext mc(owner_, it);
3801 macroTemplate.updateToContext(mc);
3804 bool valid = macroTemplate.validMacro();
3805 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3806 // then the BufferView's cursor will be invalid in
3807 // some cases which leads to crashes.
3812 // FIXME (Abdel), I don't understand why we pass 'it' here
3813 // instead of 'macroTemplate' defined above... is this correct?
3814 macros[macroTemplate.name()][it] =
3815 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3825 void Buffer::updateMacros() const
3830 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3832 // start with empty table
3834 d->children_positions.clear();
3835 d->position_to_children.clear();
3837 // Iterate over buffer, starting with first paragraph
3838 // The scope must be bigger than any lookup DocIterator
3839 // later. For the global lookup, lastpit+1 is used, hence
3840 // we use lastpit+2 here.
3841 DocIterator it = par_iterator_begin();
3842 DocIterator outerScope = it;
3843 outerScope.pit() = outerScope.lastpit() + 2;
3844 d->updateMacros(it, outerScope);
3848 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3850 InsetIterator it = inset_iterator_begin(inset());
3851 InsetIterator const end = inset_iterator_end(inset());
3852 for (; it != end; ++it) {
3853 if (it->lyxCode() == BRANCH_CODE) {
3854 InsetBranch & br = static_cast<InsetBranch &>(*it);
3855 docstring const name = br.branch();
3856 if (!from_master && !params().branchlist().find(name))
3857 result.push_back(name);
3858 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3859 result.push_back(name);
3862 if (it->lyxCode() == INCLUDE_CODE) {
3863 // get buffer of external file
3864 InsetInclude const & ins =
3865 static_cast<InsetInclude const &>(*it);
3866 Buffer * child = ins.getChildBuffer();
3869 child->getUsedBranches(result, true);
3872 // remove duplicates
3877 void Buffer::updateMacroInstances(UpdateType utype) const
3879 LYXERR(Debug::MACROS, "updateMacroInstances for "
3880 << d->filename.onlyFileName());
3881 DocIterator it = doc_iterator_begin(this);
3883 DocIterator const end = doc_iterator_end(this);
3884 for (; it != end; it.forwardInset()) {
3885 // look for MathData cells in InsetMathNest insets
3886 InsetMath * minset = it.nextInset()->asInsetMath();
3890 // update macro in all cells of the InsetMathNest
3891 DocIterator::idx_type n = minset->nargs();
3892 MacroContext mc = MacroContext(this, it);
3893 for (DocIterator::idx_type i = 0; i < n; ++i) {
3894 MathData & data = minset->cell(i);
3895 data.updateMacros(nullptr, mc, utype, 0);
3901 void Buffer::listMacroNames(MacroNameSet & macros) const
3906 d->macro_lock = true;
3908 // loop over macro names
3909 for (auto const & nameit : d->macros)
3910 macros.insert(nameit.first);
3912 // loop over children
3913 for (auto const & p : d->children_positions) {
3914 Buffer * child = const_cast<Buffer *>(p.first);
3915 // The buffer might have been closed (see #10766).
3916 if (theBufferList().isLoaded(child))
3917 child->listMacroNames(macros);
3921 Buffer const * const pbuf = d->parent();
3923 pbuf->listMacroNames(macros);
3925 d->macro_lock = false;
3929 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3931 Buffer const * const pbuf = d->parent();
3936 pbuf->listMacroNames(names);
3939 for (auto const & mit : names) {
3941 MacroData const * data = pbuf->getMacro(mit, *this, false);
3943 macros.insert(data);
3945 // we cannot access the original InsetMathMacroTemplate anymore
3946 // here to calls validate method. So we do its work here manually.
3947 // FIXME: somehow make the template accessible here.
3948 if (data->optionals() > 0)
3949 features.require("xargs");
3955 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3958 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3960 RefCache::iterator it = d->ref_cache_.find(label);
3961 if (it != d->ref_cache_.end())
3964 static References const dummy_refs = References();
3965 it = d->ref_cache_.insert(
3966 make_pair(label, dummy_refs)).first;
3971 Buffer::References const & Buffer::references(docstring const & label) const
3973 return const_cast<Buffer *>(this)->getReferenceCache(label);
3977 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3979 References & refs = getReferenceCache(label);
3980 refs.push_back(make_pair(inset, it));
3984 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3988 linfo.label = label;
3990 linfo.active = active;
3991 masterBuffer()->d->label_cache_.push_back(linfo);
3995 InsetLabel const * Buffer::insetLabel(docstring const & label,
3996 bool const active) const
3998 for (auto const & rc : masterBuffer()->d->label_cache_) {
3999 if (rc.label == label && (rc.active || !active))
4006 bool Buffer::activeLabel(docstring const & label) const
4008 if (!insetLabel(label, true))
4015 void Buffer::clearReferenceCache() const
4018 d->ref_cache_.clear();
4019 d->label_cache_.clear();
4024 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
4026 //FIXME: This does not work for child documents yet.
4027 reloadBibInfoCache();
4029 // Check if the label 'from' appears more than once
4030 vector<docstring> labels;
4031 for (auto const & bibit : masterBibInfo())
4032 labels.push_back(bibit.first);
4034 if (count(labels.begin(), labels.end(), from) > 1)
4037 string const paramName = "key";
4038 UndoGroupHelper ugh(this);
4039 InsetIterator it = inset_iterator_begin(inset());
4041 if (it->lyxCode() != CITE_CODE)
4043 InsetCommand * inset = it->asInsetCommand();
4044 docstring const oldValue = inset->getParam(paramName);
4045 if (oldValue == from) {
4046 undo().recordUndo(CursorData(it));
4047 inset->setParam(paramName, to);
4052 // returns NULL if id-to-row conversion is unsupported
4053 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4054 pit_type par_begin, pit_type par_end,
4055 OutputWhat output, bool master) const
4057 unique_ptr<TexRow> texrow;
4058 OutputParams runparams(¶ms().encoding());
4059 runparams.nice = true;
4060 runparams.flavor = params().getOutputFlavor(format);
4061 runparams.linelen = lyxrc.plaintext_linelen;
4062 // No side effect of file copying and image conversion
4063 runparams.dryrun = true;
4065 // Some macros rely on font encoding
4066 runparams.main_fontenc = params().main_font_encoding();
4068 if (output == CurrentParagraph) {
4069 runparams.par_begin = par_begin;
4070 runparams.par_end = par_end;
4071 if (par_begin + 1 == par_end) {
4073 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4077 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4078 convert<docstring>(par_begin),
4079 convert<docstring>(par_end - 1))
4082 // output paragraphs
4083 if (runparams.flavor == OutputParams::LYX) {
4084 Paragraph const & par = text().paragraphs()[par_begin];
4086 depth_type dt = par.getDepth();
4087 par.write(ods, params(), dt);
4088 os << from_utf8(ods.str());
4089 } else if (runparams.flavor == OutputParams::HTML) {
4091 setMathFlavor(runparams);
4092 xhtmlParagraphs(text(), *this, xs, runparams);
4093 } else if (runparams.flavor == OutputParams::TEXT) {
4095 // FIXME Handles only one paragraph, unlike the others.
4096 // Probably should have some routine with a signature like them.
4097 writePlaintextParagraph(*this,
4098 text().paragraphs()[par_begin], os, runparams, dummy);
4099 } else if (params().isDocBook()) {
4100 docbookParagraphs(text(), *this, os, runparams);
4102 // If we are previewing a paragraph, even if this is the
4103 // child of some other buffer, let's cut the link here,
4104 // so that no concurring settings from the master
4105 // (e.g. branch state) interfere (see #8101).
4107 d->ignore_parent = true;
4108 // We need to validate the Buffer params' features here
4109 // in order to know if we should output polyglossia
4110 // macros (instead of babel macros)
4111 LaTeXFeatures features(*this, params(), runparams);
4113 runparams.use_polyglossia = features.usePolyglossia();
4114 runparams.use_hyperref = features.isRequired("hyperref");
4115 // latex or literate
4118 ots.texrow().newlines(2);
4120 latexParagraphs(*this, text(), ots, runparams);
4121 texrow = ots.releaseTexRow();
4123 // Restore the parenthood
4125 d->ignore_parent = false;
4129 if (output == FullSource)
4130 os << _("Preview source code");
4131 else if (output == OnlyPreamble)
4132 os << _("Preview preamble");
4133 else if (output == OnlyBody)
4134 os << _("Preview body");
4136 if (runparams.flavor == OutputParams::LYX) {
4138 if (output == FullSource)
4140 else if (output == OnlyPreamble)
4141 params().writeFile(ods, this);
4142 else if (output == OnlyBody)
4144 os << from_utf8(ods.str());
4145 } else if (runparams.flavor == OutputParams::HTML) {
4146 writeLyXHTMLSource(os, runparams, output);
4147 } else if (runparams.flavor == OutputParams::TEXT) {
4148 if (output == OnlyPreamble) {
4149 os << "% "<< _("Plain text does not have a preamble.");
4151 writePlaintextFile(*this, os, runparams);
4152 } else if (params().isDocBook()) {
4153 writeDocBookSource(os, absFileName(), runparams, output);
4155 // latex or literate
4158 ots.texrow().newlines(2);
4160 runparams.is_child = true;
4162 writeLaTeXSource(ots, string(), runparams, output);
4163 texrow = ots.releaseTexRow();
4170 ErrorList & Buffer::errorList(string const & type) const
4172 return d->errorLists[type];
4176 void Buffer::updateTocItem(std::string const & type,
4177 DocIterator const & dit) const
4180 d->gui_->updateTocItem(type, dit);
4184 void Buffer::structureChanged() const
4187 d->gui_->structureChanged();
4191 void Buffer::errors(string const & err, bool from_master) const
4194 d->gui_->errors(err, from_master);
4198 void Buffer::message(docstring const & msg) const
4201 d->gui_->message(msg);
4205 void Buffer::setBusy(bool on) const
4208 d->gui_->setBusy(on);
4212 void Buffer::updateTitles() const
4215 d->wa_->updateTitles();
4219 void Buffer::resetAutosaveTimers() const
4222 d->gui_->resetAutosaveTimers();
4226 bool Buffer::hasGuiDelegate() const
4232 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4238 FileName Buffer::getEmergencyFileName() const
4240 return FileName(d->filename.absFileName() + ".emergency");
4244 FileName Buffer::getAutosaveFileName() const
4246 // if the document is unnamed try to save in the backup dir, else
4247 // in the default document path, and as a last try in the filePath,
4248 // which will most often be the temporary directory
4251 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4252 : lyxrc.backupdir_path;
4253 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4256 string const fname = "#" + d->filename.onlyFileName() + "#";
4258 return makeAbsPath(fname, fpath);
4262 void Buffer::removeAutosaveFile() const
4264 FileName const f = getAutosaveFileName();
4270 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4272 FileName const newauto = getAutosaveFileName();
4274 if (newauto != oldauto && oldauto.exists())
4275 if (!oldauto.moveTo(newauto))
4276 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4280 bool Buffer::autoSave() const
4282 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4283 if (buf->d->bak_clean || hasReadonlyFlag())
4286 message(_("Autosaving current document..."));
4287 buf->d->bak_clean = true;
4289 FileName const fname = getAutosaveFileName();
4290 LASSERT(d->cloned_buffer_, return false);
4292 // If this buffer is cloned, we assume that
4293 // we are running in a separate thread already.
4294 TempFile tempfile("lyxautoXXXXXX.lyx");
4295 tempfile.setAutoRemove(false);
4296 FileName const tmp_ret = tempfile.name();
4297 if (!tmp_ret.empty()) {
4299 // assume successful write of tmp_ret
4300 if (tmp_ret.moveTo(fname))
4303 // failed to write/rename tmp_ret so try writing direct
4304 return writeFile(fname);
4308 void Buffer::setExportStatus(bool e) const
4310 d->doing_export = e;
4311 ListOfBuffers clist = getDescendants();
4312 for (auto const & bit : clist)
4313 bit->d->doing_export = e;
4317 bool Buffer::isExporting() const
4319 return d->doing_export;
4323 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4327 return doExport(target, put_in_tempdir, result_file);
4330 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4331 string & result_file) const
4333 bool const update_unincluded =
4334 params().maintain_unincluded_children != BufferParams::CM_None
4335 && !params().getIncludedChildren().empty();
4337 // (1) export with all included children (omit \includeonly)
4338 if (update_unincluded) {
4339 ExportStatus const status =
4340 doExport(target, put_in_tempdir, true, result_file);
4341 if (status != ExportSuccess)
4344 // (2) export with included children only
4345 return doExport(target, put_in_tempdir, false, result_file);
4349 void Buffer::setMathFlavor(OutputParams & op) const
4351 switch (params().html_math_output) {
4352 case BufferParams::MathML:
4353 op.math_flavor = OutputParams::MathAsMathML;
4355 case BufferParams::HTML:
4356 op.math_flavor = OutputParams::MathAsHTML;
4358 case BufferParams::Images:
4359 op.math_flavor = OutputParams::MathAsImages;
4361 case BufferParams::LaTeX:
4362 op.math_flavor = OutputParams::MathAsLaTeX;
4368 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4369 bool includeall, string & result_file) const
4371 LYXERR(Debug::FILES, "target=" << target);
4372 OutputParams runparams(¶ms().encoding());
4373 string format = target;
4374 string dest_filename;
4375 size_t pos = target.find(' ');
4376 if (pos != string::npos) {
4377 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4378 format = target.substr(0, pos);
4379 if (format == "default")
4380 format = params().getDefaultOutputFormat();
4381 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4382 FileName(dest_filename).onlyPath().createPath();
4383 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4385 MarkAsExporting exporting(this);
4386 string backend_format;
4387 runparams.flavor = OutputParams::LATEX;
4388 runparams.linelen = lyxrc.plaintext_linelen;
4389 runparams.includeall = includeall;
4390 vector<string> backs = params().backends();
4391 Converters converters = theConverters();
4392 bool need_nice_file = false;
4393 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4394 // Get shortest path to format
4395 converters.buildGraph();
4396 Graph::EdgePath path;
4397 for (string const & sit : backs) {
4398 Graph::EdgePath p = converters.getPath(sit, format);
4399 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4400 backend_format = sit;
4405 if (!put_in_tempdir) {
4406 // Only show this alert if this is an export to a non-temporary
4407 // file (not for previewing).
4408 docstring s = bformat(_("No information for exporting the format %1$s."),
4409 theFormats().prettyName(format));
4410 if (format == "pdf4")
4412 + bformat(_("Hint: use non-TeX fonts or set input encoding "
4413 " to '%1$s'"), from_utf8(encodings.fromLyXName("ascii")->guiName()));
4414 Alert::error(_("Couldn't export file"), s);
4416 return ExportNoPathToFormat;
4418 runparams.flavor = converters.getFlavor(path, this);
4419 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4420 for (auto const & edge : path)
4421 if (theConverters().get(edge).nice()) {
4422 need_nice_file = true;
4427 backend_format = format;
4428 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4429 // FIXME: Don't hardcode format names here, but use a flag
4430 if (backend_format == "pdflatex")
4431 runparams.flavor = OutputParams::PDFLATEX;
4432 else if (backend_format == "luatex")
4433 runparams.flavor = OutputParams::LUATEX;
4434 else if (backend_format == "dviluatex")
4435 runparams.flavor = OutputParams::DVILUATEX;
4436 else if (backend_format == "xetex")
4437 runparams.flavor = OutputParams::XETEX;
4440 string filename = latexName(false);
4441 filename = addName(temppath(), filename);
4442 filename = changeExtension(filename,
4443 theFormats().extension(backend_format));
4444 LYXERR(Debug::FILES, "filename=" << filename);
4446 // Plain text backend
4447 if (backend_format == "text") {
4448 runparams.flavor = OutputParams::TEXT;
4450 writePlaintextFile(*this, FileName(filename), runparams);
4452 catch (ConversionException const &) { return ExportCancel; }
4455 else if (backend_format == "xhtml") {
4456 runparams.flavor = OutputParams::HTML;
4457 setMathFlavor(runparams);
4458 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4459 return ExportKilled;
4460 } else if (backend_format == "lyx")
4461 writeFile(FileName(filename));
4463 else if (params().isDocBook()) {
4464 runparams.nice = !put_in_tempdir;
4465 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4466 return ExportKilled;
4469 else if (backend_format == format || need_nice_file) {
4470 runparams.nice = true;
4471 ExportStatus const retval =
4472 makeLaTeXFile(FileName(filename), string(), runparams);
4473 if (retval == ExportKilled)
4474 return ExportKilled;
4475 if (d->cloned_buffer_)
4476 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4477 if (retval != ExportSuccess)
4479 } else if (!lyxrc.tex_allows_spaces
4480 && contains(filePath(), ' ')) {
4481 Alert::error(_("File name error"),
4482 bformat(_("The directory path to the document\n%1$s\n"
4483 "contains spaces, but your TeX installation does "
4484 "not allow them. You should save the file to a directory "
4485 "whose name does not contain spaces."), from_utf8(filePath())));
4486 return ExportTexPathHasSpaces;
4488 runparams.nice = false;
4489 ExportStatus const retval =
4490 makeLaTeXFile(FileName(filename), filePath(), runparams);
4491 if (retval == ExportKilled)
4492 return ExportKilled;
4493 if (d->cloned_buffer_)
4494 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4495 if (retval != ExportSuccess)
4499 string const error_type = (format == "program")
4500 ? "Build" : params().bufferFormat();
4501 ErrorList & error_list = d->errorLists[error_type];
4502 string const ext = theFormats().extension(format);
4503 FileName const tmp_result_file(changeExtension(filename, ext));
4504 Converters::RetVal const retval =
4505 converters.convert(this, FileName(filename), tmp_result_file,
4506 FileName(absFileName()), backend_format, format,
4507 error_list, Converters::none, includeall);
4508 if (retval == Converters::KILLED)
4509 return ExportCancel;
4510 bool success = (retval == Converters::SUCCESS);
4512 // Emit the signal to show the error list or copy it back to the
4513 // cloned Buffer so that it can be emitted afterwards.
4514 if (format != backend_format) {
4515 if (runparams.silent)
4517 else if (d->cloned_buffer_)
4518 d->cloned_buffer_->d->errorLists[error_type] =
4519 d->errorLists[error_type];
4522 // also to the children, in case of master-buffer-view
4523 ListOfBuffers clist = getDescendants();
4524 for (auto const & bit : clist) {
4525 if (runparams.silent)
4526 bit->d->errorLists[error_type].clear();
4527 else if (d->cloned_buffer_) {
4528 // Enable reverse search by copying back the
4529 // texrow object to the cloned buffer.
4530 // FIXME: this is not thread safe.
4531 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4532 bit->d->cloned_buffer_->d->errorLists[error_type] =
4533 bit->d->errorLists[error_type];
4535 bit->errors(error_type, true);
4539 if (d->cloned_buffer_) {
4540 // Enable reverse dvi or pdf to work by copying back the texrow
4541 // object to the cloned buffer.
4542 // FIXME: There is a possibility of concurrent access to texrow
4543 // here from the main GUI thread that should be securized.
4544 d->cloned_buffer_->d->texrow = d->texrow;
4545 string const err_type = params().bufferFormat();
4546 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4550 if (put_in_tempdir) {
4551 result_file = tmp_result_file.absFileName();
4552 return success ? ExportSuccess : ExportConverterError;
4555 if (dest_filename.empty())
4556 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4558 result_file = dest_filename;
4559 // We need to copy referenced files (e. g. included graphics
4560 // if format == "dvi") to the result dir.
4561 vector<ExportedFile> const extfiles =
4562 runparams.exportdata->externalFiles(format);
4563 string const dest = runparams.export_folder.empty() ?
4564 onlyPath(result_file) : runparams.export_folder;
4565 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4566 : force_overwrite == ALL_FILES;
4567 CopyStatus status = use_force ? FORCE : SUCCESS;
4569 for (ExportedFile const & exp : extfiles) {
4570 if (status == CANCEL) {
4571 message(_("Document export cancelled."));
4572 return ExportCancel;
4574 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4575 string fixedName = exp.exportName;
4576 if (!runparams.export_folder.empty()) {
4577 // Relative pathnames starting with ../ will be sanitized
4578 // if exporting to a different folder
4579 while (fixedName.substr(0, 3) == "../")
4580 fixedName = fixedName.substr(3, fixedName.length() - 3);
4582 FileName fixedFileName = makeAbsPath(fixedName, dest);
4583 fixedFileName.onlyPath().createPath();
4584 status = copyFile(fmt, exp.sourceName,
4586 exp.exportName, status == FORCE,
4587 runparams.export_folder.empty());
4591 if (tmp_result_file.exists()) {
4592 // Finally copy the main file
4593 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4594 : force_overwrite != NO_FILES;
4595 if (status == SUCCESS && use_force)
4597 status = copyFile(format, tmp_result_file,
4598 FileName(result_file), result_file,
4600 if (status == CANCEL) {
4601 message(_("Document export cancelled."));
4602 return ExportCancel;
4604 message(bformat(_("Document exported as %1$s "
4606 theFormats().prettyName(format),
4607 makeDisplayPath(result_file)));
4610 // This must be a dummy converter like fax (bug 1888)
4611 message(bformat(_("Document exported as %1$s"),
4612 theFormats().prettyName(format)));
4615 return success ? ExportSuccess : ExportConverterError;
4619 Buffer::ExportStatus Buffer::preview(string const & format) const
4621 bool const update_unincluded =
4622 params().maintain_unincluded_children != BufferParams::CM_None
4623 && !params().getIncludedChildren().empty();
4624 return preview(format, update_unincluded);
4628 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4630 MarkAsExporting exporting(this);
4632 // (1) export with all included children (omit \includeonly)
4634 ExportStatus const status = doExport(format, true, true, result_file);
4635 if (status != ExportSuccess)
4638 // (2) export with included children only
4639 ExportStatus const status = doExport(format, true, false, result_file);
4640 FileName const previewFile(result_file);
4642 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4643 theimpl->preview_file_ = previewFile;
4644 theimpl->preview_format_ = format;
4645 theimpl->require_fresh_start_ = (status != ExportSuccess);
4647 if (status != ExportSuccess)
4650 if (previewFile.exists())
4651 return theFormats().view(*this, previewFile, format) ?
4652 PreviewSuccess : PreviewError;
4654 // Successful export but no output file?
4655 // Probably a bug in error detection.
4656 LATTEST(status != ExportSuccess);
4661 Buffer::ReadStatus Buffer::extractFromVC()
4663 bool const found = LyXVC::file_not_found_hook(d->filename);
4665 return ReadFileNotFound;
4666 if (!d->filename.isReadableFile())
4672 Buffer::ReadStatus Buffer::loadEmergency()
4674 FileName const emergencyFile = getEmergencyFileName();
4675 if (!emergencyFile.exists()
4676 || emergencyFile.lastModified() <= d->filename.lastModified())
4677 return ReadFileNotFound;
4679 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4680 docstring const text = bformat(_("An emergency save of the document "
4681 "%1$s exists.\n\nRecover emergency save?"), file);
4683 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4684 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4690 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4691 bool const success = (ret_llf == ReadSuccess);
4693 if (hasReadonlyFlag()) {
4694 Alert::warning(_("File is read-only"),
4695 bformat(_("An emergency file is successfully loaded, "
4696 "but the original file %1$s is marked read-only. "
4697 "Please make sure to save the document as a different "
4698 "file."), from_utf8(d->filename.absFileName())));
4701 lyxvc().file_found_hook(d->filename);
4702 str = _("Document was successfully recovered.");
4704 str = _("Document was NOT successfully recovered.");
4705 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4706 makeDisplayPath(emergencyFile.absFileName()));
4708 int const del_emerg =
4709 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4710 _("&Remove"), _("&Keep"));
4711 if (del_emerg == 0) {
4712 emergencyFile.removeFile();
4714 Alert::warning(_("Emergency file deleted"),
4715 _("Do not forget to save your file now!"), true);
4717 return success ? ReadSuccess : ReadEmergencyFailure;
4720 int const del_emerg =
4721 Alert::prompt(_("Delete emergency file?"),
4722 _("Remove emergency file now?"), 1, 1,
4723 _("&Remove"), _("&Keep"));
4725 emergencyFile.removeFile();
4729 string const ename = emergencyFile.absFileName();
4731 // Surely we can find one in 100 tries?
4732 for (int i = 1; i < 100; ++i) {
4733 newname.set(ename + to_string(i) + ".lyx");
4734 if (!newname.exists()) {
4740 // renameTo returns true on success. So inverting that
4741 // will give us true if we fail.
4742 noname = !emergencyFile.renameTo(newname);
4745 Alert::warning(_("Can't rename emergency file!"),
4746 _("LyX was unable to rename the emergency file. "
4747 "You should do so manually. Otherwise, you will be "
4748 "asked about it again the next time you try to load "
4749 "this file, and may over-write your own work."));
4751 Alert::warning(_("Emergency File Renames"),
4752 bformat(_("Emergency file renamed as:\n %1$s"),
4753 from_utf8(newname.onlyFileName())));
4756 return ReadOriginal;
4766 Buffer::ReadStatus Buffer::loadAutosave()
4768 // Now check if autosave file is newer.
4769 FileName const autosaveFile = getAutosaveFileName();
4770 if (!autosaveFile.exists()
4771 || autosaveFile.lastModified() <= d->filename.lastModified())
4772 return ReadFileNotFound;
4774 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4775 docstring const text = bformat(_("The backup of the document %1$s "
4776 "is newer.\n\nLoad the backup instead?"), file);
4777 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4778 _("&Load backup"), _("Load &original"), _("&Cancel"));
4783 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4784 // the file is not saved if we load the autosave file.
4785 if (ret_llf == ReadSuccess) {
4786 if (hasReadonlyFlag()) {
4787 Alert::warning(_("File is read-only"),
4788 bformat(_("A backup file is successfully loaded, "
4789 "but the original file %1$s is marked read-only. "
4790 "Please make sure to save the document as a "
4792 from_utf8(d->filename.absFileName())));
4795 lyxvc().file_found_hook(d->filename);
4798 return ReadAutosaveFailure;
4801 // Here we delete the autosave
4802 autosaveFile.removeFile();
4803 return ReadOriginal;
4811 Buffer::ReadStatus Buffer::loadLyXFile()
4813 if (!d->filename.isReadableFile()) {
4814 ReadStatus const ret_rvc = extractFromVC();
4815 if (ret_rvc != ReadSuccess)
4819 ReadStatus const ret_re = loadEmergency();
4820 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4823 ReadStatus const ret_ra = loadAutosave();
4824 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4827 return loadThisLyXFile(d->filename);
4831 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4833 return readFile(fn);
4837 void Buffer::Impl::traverseErrors(TeXErrors::Errors::const_iterator err, TeXErrors::Errors::const_iterator end, ErrorList & errorList) const
4839 for (; err != end; ++err) {
4840 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4841 int errorRow = err->error_in_line;
4842 Buffer const * buf = nullptr;
4843 Impl const * p = this;
4844 if (err->child_name.empty())
4845 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4847 // The error occurred in a child
4848 for (Buffer const * child : owner_->getDescendants()) {
4849 string const child_name =
4850 DocFileName(changeExtension(child->absFileName(), "tex")).
4852 if (err->child_name != child_name)
4854 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4855 if (!TexRow::isNone(start)) {
4856 buf = this->cloned_buffer_
4857 ? child->d->cloned_buffer_->d->owner_
4864 errorList.push_back(ErrorItem(err->error_desc, err->error_text,
4870 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4872 TeXErrors::Errors::const_iterator err = terr.begin();
4873 TeXErrors::Errors::const_iterator end = terr.end();
4875 d->traverseErrors(err, end, errorList);
4879 void Buffer::bufferRefs(TeXErrors const & terr, ErrorList & errorList) const
4881 TeXErrors::Errors::const_iterator err = terr.begin_ref();
4882 TeXErrors::Errors::const_iterator end = terr.end_ref();
4884 d->traverseErrors(err, end, errorList);
4888 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4890 LBUFERR(!text().paragraphs().empty());
4892 // Use the master text class also for child documents
4893 Buffer const * const master = masterBuffer();
4894 DocumentClass const & textclass = master->params().documentClass();
4896 docstring_list old_bibfiles;
4897 // Do this only if we are the top-level Buffer. We also need to account
4898 // for the case of a previewed child with ignored parent here.
4899 if (master == this && !d->ignore_parent) {
4900 textclass.counters().reset(from_ascii("bibitem"));
4901 reloadBibInfoCache();
4902 // we will re-read this cache as we go through, but we need
4903 // to know whether it's changed to know whether we need to
4904 // update the bibinfo cache.
4905 old_bibfiles = d->bibfiles_cache_;
4906 d->bibfiles_cache_.clear();
4909 // keep the buffers to be children in this set. If the call from the
4910 // master comes back we can see which of them were actually seen (i.e.
4911 // via an InsetInclude). The remaining ones in the set need still be updated.
4912 static std::set<Buffer const *> bufToUpdate;
4913 if (scope == UpdateMaster) {
4914 // If this is a child document start with the master
4915 if (master != this) {
4916 bufToUpdate.insert(this);
4917 master->updateBuffer(UpdateMaster, utype);
4918 // If the master buffer has no gui associated with it, then the TocModel is
4919 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4920 // (bug 5699). The same happens if the master buffer is open in a different
4921 // window. This test catches both possibilities.
4922 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4923 // There remains a problem here: If there is another child open in yet a third
4924 // window, that TOC is not updated. So some more general solution is needed at
4926 if (master->d->gui_ != d->gui_)
4929 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4930 if (bufToUpdate.find(this) == bufToUpdate.end())
4934 // start over the counters in the master
4935 textclass.counters().reset();
4938 // update will be done below for this buffer
4939 bufToUpdate.erase(this);
4941 // update all caches
4942 clearReferenceCache();
4945 Buffer & cbuf = const_cast<Buffer &>(*this);
4946 // if we are reloading, then we could have a dangling TOC,
4947 // in effect. so we need to go ahead and reset, even though
4948 // we will do so again when we rebuild the TOC later.
4949 cbuf.tocBackend().reset();
4952 ParIterator parit = cbuf.par_iterator_begin();
4953 updateBuffer(parit, utype);
4955 // If this document has siblings, then update the TocBackend later. The
4956 // reason is to ensure that later siblings are up to date when e.g. the
4957 // broken or not status of references is computed. The update is called
4958 // in InsetInclude::addToToc.
4962 // if the bibfiles changed, the cache of bibinfo is invalid
4963 docstring_list new_bibfiles = d->bibfiles_cache_;
4964 // this is a trick to determine whether the two vectors have
4965 // the same elements.
4966 sort(new_bibfiles.begin(), new_bibfiles.end());
4967 sort(old_bibfiles.begin(), old_bibfiles.end());
4968 if (old_bibfiles != new_bibfiles) {
4969 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4970 invalidateBibinfoCache();
4971 reloadBibInfoCache();
4972 // We relied upon the bibinfo cache when recalculating labels. But that
4973 // cache was invalid, although we didn't find that out until now. So we
4974 // have to do it all again.
4975 // That said, the only thing we really need to do is update the citation
4976 // labels. Nothing else will have changed. So we could create a new
4977 // UpdateType that would signal that fact, if we needed to do so.
4978 parit = cbuf.par_iterator_begin();
4979 // we will be re-doing the counters and references and such.
4980 textclass.counters().reset();
4981 clearReferenceCache();
4982 // we should not need to do this again?
4984 updateBuffer(parit, utype);
4985 // this will already have been done by reloadBibInfoCache();
4986 // d->bibinfo_cache_valid_ = true;
4989 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4990 // this is also set to true on the other path, by reloadBibInfoCache.
4991 d->bibinfo_cache_valid_ = true;
4993 d->cite_labels_valid_ = true;
4995 cbuf.tocBackend().update(true, utype);
4996 if (scope == UpdateMaster)
4997 cbuf.structureChanged();
5001 static depth_type getDepth(DocIterator const & it)
5003 depth_type depth = 0;
5004 for (size_t i = 0 ; i < it.depth() ; ++i)
5005 if (!it[i].inset().inMathed())
5006 depth += it[i].paragraph().getDepth() + 1;
5007 // remove 1 since the outer inset does not count
5008 // we should have at least one non-math inset, so
5009 // depth should nevery be 0. but maybe it is worth
5010 // marking this, just in case.
5012 // coverity[INTEGER_OVERFLOW]
5016 static depth_type getItemDepth(ParIterator const & it)
5018 Paragraph const & par = *it;
5019 LabelType const labeltype = par.layout().labeltype;
5021 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5024 // this will hold the lowest depth encountered up to now.
5025 depth_type min_depth = getDepth(it);
5026 ParIterator prev_it = it;
5029 --prev_it.top().pit();
5031 // start of nested inset: go to outer par
5033 if (prev_it.empty()) {
5034 // start of document: nothing to do
5039 // We search for the first paragraph with same label
5040 // that is not more deeply nested.
5041 Paragraph & prev_par = *prev_it;
5042 depth_type const prev_depth = getDepth(prev_it);
5043 if (labeltype == prev_par.layout().labeltype) {
5044 if (prev_depth < min_depth)
5045 return prev_par.itemdepth + 1;
5046 if (prev_depth == min_depth)
5047 return prev_par.itemdepth;
5049 min_depth = min(min_depth, prev_depth);
5050 // small optimization: if we are at depth 0, we won't
5051 // find anything else
5052 if (prev_depth == 0)
5058 static bool needEnumCounterReset(ParIterator const & it)
5060 Paragraph const & par = *it;
5061 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5062 depth_type const cur_depth = par.getDepth();
5063 ParIterator prev_it = it;
5064 while (prev_it.pit()) {
5065 --prev_it.top().pit();
5066 Paragraph const & prev_par = *prev_it;
5067 if (prev_par.getDepth() <= cur_depth)
5068 return prev_par.layout().name() != par.layout().name();
5070 // start of nested inset: reset
5075 // set the label of a paragraph. This includes the counters.
5076 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5078 BufferParams const & bp = owner_->masterBuffer()->params();
5079 DocumentClass const & textclass = bp.documentClass();
5080 Paragraph & par = it.paragraph();
5081 Layout const & layout = par.layout();
5082 Counters & counters = textclass.counters();
5084 if (par.params().startOfAppendix()) {
5085 // We want to reset the counter corresponding to toplevel sectioning
5086 Layout const & lay = textclass.getTOCLayout();
5087 docstring const cnt = lay.counter;
5089 counters.reset(cnt);
5090 counters.appendix(true);
5092 par.params().appendix(counters.appendix());
5094 // Compute the item depth of the paragraph
5095 par.itemdepth = getItemDepth(it);
5097 if (layout.margintype == MARGIN_MANUAL) {
5098 if (par.params().labelWidthString().empty())
5099 par.params().labelWidthString(par.expandLabel(layout, bp));
5100 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5101 // we do not need to do anything here, since the empty case is
5102 // handled during export.
5104 par.params().labelWidthString(docstring());
5107 switch(layout.labeltype) {
5108 case LABEL_ITEMIZE: {
5109 // At some point of time we should do something more
5110 // clever here, like:
5111 // par.params().labelString(
5112 // bp.user_defined_bullet(par.itemdepth).getText());
5113 // for now, use a simple hardcoded label
5114 docstring itemlabel;
5115 switch (par.itemdepth) {
5118 itemlabel = char_type(0x2022);
5122 itemlabel = char_type(0x2013);
5125 // ∗ U+2217 ASTERISK OPERATOR
5126 itemlabel = char_type(0x2217);
5129 // · U+00B7 MIDDLE DOT
5130 itemlabel = char_type(0x00b7);
5133 par.params().labelString(itemlabel);
5137 case LABEL_ENUMERATE: {
5138 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5140 switch (par.itemdepth) {
5151 enumcounter += "iv";
5154 // not a valid enumdepth...
5158 if (needEnumCounterReset(it)) {
5159 // Increase the master counter?
5160 if (layout.stepmastercounter)
5161 counters.stepMaster(enumcounter, utype);
5162 // Maybe we have to reset the enumeration counter.
5163 if (!layout.resumecounter)
5164 counters.reset(enumcounter);
5166 counters.step(enumcounter, utype);
5168 string const & lang = par.getParLanguage(bp)->code();
5169 par.params().labelString(counters.theCounter(enumcounter, lang));
5174 case LABEL_SENSITIVE: {
5175 string const & type = counters.current_float();
5176 docstring full_label;
5178 full_label = owner_->B_("Senseless!!! ");
5180 docstring name = owner_->B_(textclass.floats().getType(type).name());
5181 if (counters.hasCounter(from_utf8(type))) {
5182 string const & lang = par.getParLanguage(bp)->code();
5183 counters.step(from_utf8(type), utype);
5184 full_label = bformat(from_ascii("%1$s %2$s:"),
5186 counters.theCounter(from_utf8(type), lang));
5188 full_label = bformat(from_ascii("%1$s #:"), name);
5190 par.params().labelString(full_label);
5194 case LABEL_NO_LABEL:
5195 par.params().labelString(docstring());
5199 case LABEL_CENTERED:
5200 case LABEL_STATIC: {
5201 docstring const & lcounter = layout.counter;
5202 if (!lcounter.empty()) {
5203 if (layout.toclevel <= bp.secnumdepth
5204 && (layout.latextype != LATEX_ENVIRONMENT
5205 || it.text()->isFirstInSequence(it.pit()))) {
5206 if (counters.hasCounter(lcounter))
5207 counters.step(lcounter, utype);
5208 par.params().labelString(par.expandLabel(layout, bp));
5210 par.params().labelString(docstring());
5212 par.params().labelString(par.expandLabel(layout, bp));
5218 par.params().labelString(par.expandLabel(layout, bp));
5223 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype, bool const deleted) const
5225 // LASSERT: Is it safe to continue here, or should we just return?
5226 LASSERT(parit.pit() == 0, /**/);
5228 // Set the position of the text in the buffer to be able
5229 // to resolve macros in it.
5230 parit.text()->setMacrocontextPosition(parit);
5232 // Reset bibitem counter in master (#8499)
5233 Buffer const * const master = masterBuffer();
5234 if (master == this && !d->ignore_parent)
5235 master->params().documentClass().counters().reset(from_ascii("bibitem"));
5237 depth_type maxdepth = 0;
5238 pit_type const lastpit = parit.lastpit();
5239 bool changed = false;
5240 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5241 // reduce depth if necessary
5242 if (parit->params().depth() > maxdepth) {
5243 /** FIXME: this function is const, but
5244 * nevertheless it modifies the buffer. To be
5245 * cleaner, one should modify the buffer in
5246 * another function, which is actually
5247 * non-const. This would however be costly in
5248 * terms of code duplication.
5250 CursorData(parit).recordUndo();
5251 parit->params().depth(maxdepth);
5253 maxdepth = parit->getMaxDepthAfter();
5255 if (utype == OutputUpdate) {
5256 // track the active counters
5257 // we have to do this for the master buffer, since the local
5258 // buffer isn't tracking anything.
5259 masterBuffer()->params().documentClass().counters().
5260 setActiveLayout(parit->layout());
5263 // set the counter for this paragraph
5264 d->setLabel(parit, utype);
5267 for (auto const & insit : parit->insetList()) {
5268 parit.pos() = insit.pos;
5269 insit.inset->updateBuffer(parit, utype, deleted || parit->isDeleted(insit.pos));
5270 changed |= insit.inset->isChanged();
5273 // are there changes in this paragraph?
5274 changed |= parit->isChanged();
5277 // set change indicator for the inset (or the cell that the iterator
5278 // points to, if applicable).
5279 parit.text()->inset().isChanged(changed);
5283 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5284 WordLangTuple & word_lang, docstring_list & suggestions) const
5288 suggestions.clear();
5289 word_lang = WordLangTuple();
5290 bool const to_end = to.empty();
5291 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5292 // OK, we start from here.
5293 for (; from != end; from.forwardPos()) {
5294 // This skips all insets with spell check disabled.
5295 while (!from.allowSpellCheck()) {
5299 // If from is at the end of the document (which is possible
5300 // when "from" was changed above) LyX will crash later otherwise.
5301 if (from.atEnd() || (!to_end && from >= end))
5304 from.paragraph().spellCheck();
5305 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5306 if (SpellChecker::misspelled(res)) {
5310 // Do not increase progress when from == to, otherwise the word
5311 // count will be wrong.
5321 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5323 bool inword = false;
5328 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5329 if (!dit.inTexted()) {
5334 Paragraph const & par = dit.paragraph();
5335 pos_type const pos = dit.pos();
5337 // Copied and adapted from isWordSeparator() in Paragraph
5338 if (pos == dit.lastpos()) {
5341 Inset const * ins = par.getInset(pos);
5342 if (ins && skipNoOutput && !ins->producesOutput()) {
5345 // stop if end of range was skipped
5346 if (!to.atEnd() && dit >= to)
5349 } else if (!par.isDeleted(pos)) {
5350 if (par.isWordSeparator(pos))
5356 if (ins && ins->isLetter())
5358 else if (ins && ins->isSpace())
5361 char_type const c = par.getChar(pos);
5362 if (isPrintableNonspace(c))
5364 else if (isSpace(c))
5374 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5376 d->updateStatistics(from, to, skipNoOutput);
5380 int Buffer::wordCount() const
5382 return d->wordCount();
5386 int Buffer::charCount(bool with_blanks) const
5388 return d->charCount(with_blanks);
5392 bool Buffer::areChangesPresent() const
5394 return inset().isChanged();
5398 Buffer::ReadStatus Buffer::reload()
5401 // c.f. bug https://www.lyx.org/trac/ticket/6587
5402 removeAutosaveFile();
5403 // e.g., read-only status could have changed due to version control
5404 d->filename.refresh();
5405 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5407 // clear parent. this will get reset if need be.
5408 d->setParent(nullptr);
5409 ReadStatus const status = loadLyXFile();
5410 if (status == ReadSuccess) {
5415 message(bformat(_("Document %1$s reloaded."), disp_fn));
5418 message(bformat(_("Could not reload document %1$s."), disp_fn));
5428 bool Buffer::saveAs(FileName const & fn)
5430 FileName const old_name = fileName();
5431 FileName const old_auto = getAutosaveFileName();
5432 bool const old_unnamed = isUnnamed();
5433 bool success = true;
5434 d->old_position = filePath();
5441 // bring the autosave file with us, just in case.
5442 moveAutosaveFile(old_auto);
5443 // validate version control data and
5444 // correct buffer title
5445 lyxvc().file_found_hook(fileName());
5447 // the file has now been saved to the new location.
5448 // we need to check that the locations of child buffers
5450 checkChildBuffers();
5451 checkMasterBuffer();
5454 // reset the old filename and unnamed state
5455 setFileName(old_name);
5456 setUnnamed(old_unnamed);
5460 d->old_position.clear();
5465 void Buffer::checkChildBuffers()
5467 for (auto const & bit : d->children_positions) {
5468 DocIterator dit = bit.second;
5469 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5470 if (!cbuf || !theBufferList().isLoaded(cbuf))
5472 Inset * inset = dit.nextInset();
5473 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5474 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5475 docstring const & incfile = inset_inc->getParam("filename");
5476 string oldloc = cbuf->absFileName();
5477 string newloc = makeAbsPath(to_utf8(incfile),
5478 onlyPath(absFileName())).absFileName();
5479 if (oldloc == newloc)
5481 // the location of the child file is incorrect.
5482 cbuf->setParent(nullptr);
5483 inset_inc->setChildBuffer(nullptr);
5485 // invalidate cache of children
5486 d->children_positions.clear();
5487 d->position_to_children.clear();
5491 // If a child has been saved under a different name/path, it might have been
5492 // orphaned. Therefore the master needs to be reset (bug 8161).
5493 void Buffer::checkMasterBuffer()
5495 Buffer const * const master = masterBuffer();
5499 // necessary to re-register the child (bug 5873)
5500 // FIXME: clean up updateMacros (here, only
5501 // child registering is needed).
5502 master->updateMacros();
5503 // (re)set master as master buffer, but only
5504 // if we are a real child
5505 if (master->isChild(this))
5512 string Buffer::includedFilePath(string const & name, string const & ext) const
5514 if (d->old_position.empty() ||
5515 equivalent(FileName(d->old_position), FileName(filePath())))
5518 bool isabsolute = FileName::isAbsolute(name);
5519 // both old_position and filePath() end with a path separator
5520 string absname = isabsolute ? name : d->old_position + name;
5522 // if old_position is set to origin, we need to do the equivalent of
5523 // getReferencedFileName() (see readDocument())
5524 if (!isabsolute && d->old_position == params().origin) {
5525 FileName const test(addExtension(filePath() + name, ext));
5527 absname = filePath() + name;
5530 if (!FileName(addExtension(absname, ext)).exists())
5534 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5536 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5537 from_utf8(filePath())));
5541 void Buffer::Impl::refreshFileMonitor()
5543 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5544 file_monitor_->refresh();
5548 // The previous file monitor is invalid
5549 // This also destroys the previous file monitor and all its connections
5550 file_monitor_ = FileSystemWatcher::monitor(filename);
5551 // file_monitor_ will be destroyed with *this, so it is not going to call a
5552 // destroyed object method.
5553 file_monitor_->connect([this](bool exists) {
5554 fileExternallyModified(exists);
5559 void Buffer::Impl::fileExternallyModified(bool const exists)
5561 // ignore notifications after our own saving operations
5562 if (checksum_ == filename.checksum()) {
5563 LYXERR(Debug::FILES, "External modification but "
5564 "checksum unchanged: " << filename);
5567 // If the file has been deleted, only mark the file as dirty since it is
5568 // pointless to prompt for reloading. If later a file is moved into this
5569 // location, then the externally modified warning will appear then.
5571 externally_modified_ = true;
5572 // Update external modification notification.
5573 // Dirty buffers must be visible at all times.
5574 if (wa_ && wa_->unhide(owner_))
5575 wa_->updateTitles();
5577 // Unable to unhide the buffer (e.g. no GUI or not current View)
5582 bool Buffer::notifiesExternalModification() const
5584 return d->externally_modified_;
5588 void Buffer::clearExternalModification() const
5590 d->externally_modified_ = false;
5592 d->wa_->updateTitles();
5596 void Buffer::pushIncludedBuffer(Buffer const * buf) const
5598 masterBuffer()->d->include_list_.push_back(buf);
5599 if (lyxerr.debugging(Debug::FILES)) {
5600 LYXERR0("Pushed. Stack now:");
5601 if (masterBuffer()->d->include_list_.empty())
5604 for (auto const & b : masterBuffer()->d->include_list_)
5605 LYXERR0(b->fileName());
5610 void Buffer::popIncludedBuffer() const
5612 masterBuffer()->d->include_list_.pop_back();
5613 if (lyxerr.debugging(Debug::FILES)) {
5614 LYXERR0("Popped. Stack now:");
5615 if (masterBuffer()->d->include_list_.empty())
5618 for (auto const & b : masterBuffer()->d->include_list_)
5619 LYXERR0(b->fileName());
5624 bool Buffer::isBufferIncluded(Buffer const * buf) const
5628 if (lyxerr.debugging(Debug::FILES)) {
5629 LYXERR0("Checking for " << buf->fileName() << ". Stack now:");
5630 if (masterBuffer()->d->include_list_.empty())
5633 for (auto const & b : masterBuffer()->d->include_list_)
5634 LYXERR0(b->fileName());
5636 list<Buffer const *> const & blist = masterBuffer()->d->include_list_;
5637 return find(blist.begin(), blist.end(), buf) != blist.end();
5641 void Buffer::clearIncludeList() const
5643 LYXERR(Debug::FILES, "Clearing include list for " << fileName());
5644 d->include_list_.clear();