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"
50 #include "output_latex.h"
51 #include "output_docbook.h"
52 #include "output_plaintext.h"
53 #include "output_xhtml.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"
124 using namespace lyx::support;
125 using namespace lyx::graphics;
129 namespace Alert = frontend::Alert;
130 namespace os = support::os;
134 int const LYX_FORMAT = LYX_FORMAT_LYX;
136 typedef map<string, bool> DepClean;
138 // Information about labels and their associated refs
143 InsetLabel const * inset;
144 /// associated references cache
145 Buffer::References references;
146 /// whether this label is active (i.e., not deleted)
150 typedef vector<LabelInfo> LabelCache;
152 typedef map<docstring, Buffer::References> RefCache;
154 // A storehouse for the cloned buffers.
155 typedef list<CloneList_ptr> CloneStore;
156 CloneStore cloned_buffers;
165 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
169 delete preview_loader_;
177 /// search for macro in local (buffer) table or in children
178 MacroData const * getBufferMacro(docstring const & name,
179 DocIterator const & pos) const;
181 /// Update macro table starting with position of it \param it in some
183 void updateMacros(DocIterator & it, DocIterator & scope);
185 void setLabel(ParIterator & it, UpdateType utype) const;
187 /** If we have branches that use the file suffix
188 feature, return the file name with suffix appended.
190 FileName exportFileName() const;
197 mutable TexRow texrow;
199 /// need to regenerate .tex?
202 /// name of the file the buffer is associated with.
206 mutable TocBackend toc_backend;
211 ScopeMacro(DocIterator const & s, MacroData const & m)
212 : scope(s), macro(m) {}
216 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
217 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
218 /// map from the macro name to the position map,
219 /// which maps the macro definition position to the scope and the MacroData.
220 NamePositionScopeMacroMap macros;
222 /// positions of child buffers in the buffer
223 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
225 ScopeBuffer() : buffer(nullptr) {}
226 ScopeBuffer(DocIterator const & s, Buffer const * b)
227 : scope(s), buffer(b) {}
229 Buffer const * buffer;
231 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
232 /// position of children buffers in this buffer
233 BufferPositionMap children_positions;
234 /// map from children inclusion positions to their scope and their buffer
235 PositionScopeBufferMap position_to_children;
237 /// Contains the old buffer filePath() while saving-as, or the
238 /// directory where the document was last saved while loading.
241 /** Keeps track of the path of local layout files.
242 * If possible, it is always relative to the buffer path.
243 * Empty for layouts in system or user directory.
245 string layout_position;
247 /// Container for all sort of Buffer dependant errors.
248 map<string, ErrorList> errorLists;
250 /// checksum used to test if the file has been externally modified. Used to
251 /// double check whether the file had been externally modified when saving.
252 unsigned long checksum_;
255 frontend::WorkAreaManager * wa_;
257 frontend::GuiBufferDelegate * gui_;
262 /// A cache for the bibfiles (including bibfiles of loaded child
263 /// documents), needed for appropriate update of natbib labels.
264 mutable docstring_list bibfiles_cache_;
266 // FIXME The caching mechanism could be improved. At present, we have a
267 // cache for each Buffer, that caches all the bibliography info for that
268 // Buffer. A more efficient solution would be to have a global cache per
269 // file, and then to construct the Buffer's bibinfo from that.
270 /// A cache for bibliography info
271 mutable BiblioInfo bibinfo_;
272 /// Cache of timestamps of .bib files
273 map<FileName, time_t> bibfile_status_;
275 /// These two hold the file name and format, written to by
276 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
277 FileName preview_file_;
278 string preview_format_;
280 /// Cache the references associated to a label and their positions
282 mutable RefCache ref_cache_;
283 /// Cache the label insets and their activity status.
284 mutable LabelCache label_cache_;
286 /// our Text that should be wrapped in an InsetText
290 PreviewLoader * preview_loader_;
292 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
293 /// This one is useful for preview detached in a thread.
294 Buffer const * cloned_buffer_;
296 CloneList_ptr clone_list_;
299 std::list<Buffer const *> include_list_;
301 /// So we can force access via the accessors.
302 mutable Buffer const * parent_buffer;
304 FileMonitorPtr file_monitor_;
306 /// ints and bools are all listed last so as to avoid alignment issues
308 /// original format of loaded file
311 /// are we in the process of exporting this buffer?
312 mutable bool doing_export;
314 /// If there was an error when previewing, on the next preview we do
315 /// a fresh compile (e.g. in case the user installed a package that
317 bool require_fresh_start_;
319 /// Indicates whether the bibinfo has changed since the last time
320 /// we ran updateBuffer(), i.e., whether citation labels may need
322 mutable bool cite_labels_valid_;
323 /// Do we have a bibliography environment?
324 mutable bool have_bibitems_;
327 mutable bool lyx_clean;
329 /// is autosave needed?
330 mutable bool bak_clean;
332 /// is this an unnamed file (New...)?
335 /// is this an internal bufffer?
336 bool internal_buffer;
341 /** Set to true only when the file is fully loaded.
342 * Used to prevent the premature generation of previews
343 * and by the citation inset.
345 bool file_fully_loaded;
347 /// if the file was originally loaded from an older format, do
348 /// we need to back it up still?
349 bool need_format_backup;
351 /// Ignore the parent (e.g. when exporting a child standalone)?
354 /// This seem to change the way Buffer::getMacro() works
355 mutable bool macro_lock;
357 /// has been externally modified? Can be reset by the user.
358 mutable bool externally_modified_;
360 /// whether the bibinfo cache is valid
361 mutable bool bibinfo_cache_valid_;
369 /// This is here to force the test to be done whenever parent_buffer
371 Buffer const * parent() const
373 // ignore_parent temporarily "orphans" a buffer
374 // (e.g. if a child is compiled standalone)
377 // if parent_buffer is not loaded, then it has been unloaded,
378 // which means that parent_buffer is an invalid pointer. So we
379 // set it to null in that case.
380 // however, the BufferList doesn't know about cloned buffers, so
381 // they will always be regarded as unloaded. in that case, we hope
383 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
384 parent_buffer = nullptr;
385 return parent_buffer;
389 void setParent(Buffer const * pb)
391 if (parent_buffer == pb)
394 if (!cloned_buffer_ && parent_buffer && pb)
395 LYXERR0("Warning: a buffer should not have two parents!");
397 if (!cloned_buffer_ && parent_buffer)
398 parent_buffer->invalidateBibinfoCache();
401 /// compute statistics
402 /// \p from initial position
403 /// \p to points to the end position
404 void updateStatistics(DocIterator & from, DocIterator & to,
405 bool skipNoOutput = true);
406 /// statistics accessor functions
407 int wordCount() const
411 int charCount(bool with_blanks) const
414 + (with_blanks ? blank_count_ : 0);
417 // Make sure the file monitor monitors the good file.
418 void refreshFileMonitor();
420 /// Notify or clear of external modification
421 void fileExternallyModified(bool exists);
423 ///Binding LaTeX lines with buffer positions.
424 //Common routine for LaTeX and Reference errors listing.
425 void traverseErrors(TeXErrors::Errors::const_iterator err,
426 TeXErrors::Errors::const_iterator end,
427 ErrorList & errorList) const;
431 /// Creates the per buffer temporary directory
432 static FileName createBufferTmpDir()
434 // FIXME This would be the ideal application for a TempDir class (like
435 // TempFile but for directories)
440 Mutex::Locker locker(&mutex);
441 counter = convert<string>(count++);
443 // We are in our own directory. Why bother to mangle name?
444 // In fact I wrote this code to circumvent a problematic behaviour
445 // (bug?) of EMX mkstemp().
446 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
449 if (!tmpfl.createDirectory(0777)) {
450 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
451 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
452 from_utf8(tmpfl.absFileName())));
458 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
459 Buffer const * cloned_buffer)
460 : owner_(owner), filename(file), toc_backend(owner), checksum_(0),
461 wa_(nullptr), gui_(nullptr), undo_(*owner), inset(nullptr),
462 preview_loader_(nullptr), cloned_buffer_(cloned_buffer),
463 clone_list_(nullptr), parent_buffer(nullptr), file_format(LYX_FORMAT),
464 doing_export(false), require_fresh_start_(false), cite_labels_valid_(false),
465 have_bibitems_(false), lyx_clean(true), bak_clean(true), unnamed(false),
466 internal_buffer(false), read_only(readonly_), file_fully_loaded(false),
467 need_format_backup(false), ignore_parent(false), macro_lock(false),
468 externally_modified_(false), bibinfo_cache_valid_(false),
469 word_count_(0), char_count_(0), blank_count_(0)
471 refreshFileMonitor();
472 if (!cloned_buffer_) {
473 temppath = createBufferTmpDir();
474 lyxvc.setBuffer(owner_);
475 Language const * inplang = theApp() ?
476 languages.getFromCode(theApp()->inputLanguageCode())
479 params.language = inplang;
481 wa_ = new frontend::WorkAreaManager;
484 temppath = cloned_buffer_->d->temppath;
485 file_fully_loaded = true;
486 params = cloned_buffer_->d->params;
487 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
488 bibinfo_ = cloned_buffer_->d->bibinfo_;
489 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
490 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
491 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
492 have_bibitems_ = cloned_buffer_->d->have_bibitems_;
493 unnamed = cloned_buffer_->d->unnamed;
494 internal_buffer = cloned_buffer_->d->internal_buffer;
495 layout_position = cloned_buffer_->d->layout_position;
496 preview_file_ = cloned_buffer_->d->preview_file_;
497 preview_format_ = cloned_buffer_->d->preview_format_;
498 require_fresh_start_ = cloned_buffer_->d->require_fresh_start_;
502 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
503 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
505 LYXERR(Debug::INFO, "Buffer::Buffer()");
507 d->inset = new InsetText(*cloned_buffer->d->inset);
508 d->inset->setBuffer(*this);
509 // FIXME: optimize this loop somewhat, maybe by creating a new
510 // general recursive Inset::setId().
511 DocIterator it = doc_iterator_begin(this);
512 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
513 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
514 it.paragraph().setId(cloned_it.paragraph().id());
516 d->inset = new InsetText(this);
517 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
523 LYXERR(Debug::INFO, "Buffer::~Buffer()");
524 // here the buffer should take care that it is
525 // saved properly, before it goes into the void.
527 // GuiView already destroyed
531 // No need to do additional cleanups for internal buffer.
537 // this is in case of recursive includes: we won't try to delete
538 // ourselves as a child.
539 d->clone_list_->erase(this);
540 // loop over children
541 for (auto const & p : d->children_positions) {
542 Buffer * child = const_cast<Buffer *>(p.first);
543 if (d->clone_list_->erase(child))
546 // if we're the master buffer, then we should get rid of the list
549 // If this is not empty, we have leaked something. Worse, one of the
550 // children still has a reference to this list. But we will try to
551 // continue, rather than shut down.
552 LATTEST(d->clone_list_->empty());
553 // The clone list itself is empty, but it's still referenced in our list
554 // of clones. So let's find it and remove it.
555 CloneStore::iterator it =
556 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
557 if (it == cloned_buffers.end()) {
558 // We will leak in this case, but it is safe to continue.
561 cloned_buffers.erase(it);
563 // FIXME Do we really need to do this right before we delete d?
564 // clear references to children in macro tables
565 d->children_positions.clear();
566 d->position_to_children.clear();
568 // loop over children
569 for (auto const & p : d->children_positions) {
570 Buffer * child = const_cast<Buffer *>(p.first);
571 if (theBufferList().isLoaded(child)) {
572 if (theBufferList().isOthersChild(this, child))
573 child->setParent(nullptr);
575 theBufferList().release(child);
580 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
582 msg += emergencyWrite();
584 msg += " " + _("Save failed! Document is lost.");
586 Alert::warning(_("Attempting to close changed document!"), msg);
589 // FIXME Do we really need to do this right before we delete d?
590 // clear references to children in macro tables
591 d->children_positions.clear();
592 d->position_to_children.clear();
594 if (!d->temppath.destroyDirectory()) {
595 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
596 from_utf8(d->temppath.absFileName())));
605 Buffer * Buffer::cloneWithChildren() const
608 cloned_buffers.emplace_back(new CloneList);
609 CloneList_ptr clones = cloned_buffers.back();
611 cloneWithChildren(bufmap, clones);
613 // make sure we got cloned
614 BufferMap::const_iterator bit = bufmap.find(this);
615 LASSERT(bit != bufmap.end(), return nullptr);
616 Buffer * cloned_buffer = bit->second;
618 return cloned_buffer;
622 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList_ptr clones) const
624 // have we already been cloned?
625 if (bufmap.find(this) != bufmap.end())
628 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
630 // The clone needs its own DocumentClass, since running updateBuffer() will
631 // modify it, and we would otherwise be sharing it with the original Buffer.
632 buffer_clone->params().makeDocumentClass(true);
634 cap::switchBetweenClasses(
635 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
636 static_cast<InsetText &>(buffer_clone->inset()), el);
638 bufmap[this] = buffer_clone;
639 clones->insert(buffer_clone);
640 buffer_clone->d->clone_list_ = clones;
641 buffer_clone->d->macro_lock = true;
642 buffer_clone->d->children_positions.clear();
644 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
645 // math macro caches need to be rethought and simplified.
646 // I am not sure wether we should handle Buffer cloning here or in BufferList.
647 // Right now BufferList knows nothing about buffer clones.
648 for (auto const & p : d->position_to_children) {
649 DocIterator dit = p.first.clone(buffer_clone);
650 dit.setBuffer(buffer_clone);
651 Buffer * child = const_cast<Buffer *>(p.second.buffer);
653 child->cloneWithChildren(bufmap, clones);
654 BufferMap::iterator const bit = bufmap.find(child);
655 LASSERT(bit != bufmap.end(), continue);
656 Buffer * child_clone = bit->second;
658 Inset * inset = dit.nextInset();
659 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
660 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
661 inset_inc->setChildBuffer(child_clone);
662 child_clone->d->setParent(buffer_clone);
663 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
664 buffer_clone->setChild(dit, child_clone);
666 buffer_clone->d->macro_lock = false;
671 Buffer * Buffer::cloneBufferOnly() const {
672 cloned_buffers.emplace_back(new CloneList);
673 CloneList_ptr clones = cloned_buffers.back();
674 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
676 // The clone needs its own DocumentClass, since running updateBuffer() will
677 // modify it, and we would otherwise be sharing it with the original Buffer.
678 buffer_clone->params().makeDocumentClass(true);
680 cap::switchBetweenClasses(
681 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
682 static_cast<InsetText &>(buffer_clone->inset()), el);
684 clones->insert(buffer_clone);
685 buffer_clone->d->clone_list_ = clones;
687 // we won't be cloning the children
688 buffer_clone->d->children_positions.clear();
693 bool Buffer::isClone() const
695 return d->cloned_buffer_;
699 void Buffer::changed(bool update_metrics) const
702 d->wa_->redrawAll(update_metrics);
706 frontend::WorkAreaManager & Buffer::workAreaManager() const
713 Text & Buffer::text() const
715 return d->inset->text();
719 Inset & Buffer::inset() const
725 BufferParams & Buffer::params()
731 BufferParams const & Buffer::params() const
737 BufferParams const & Buffer::masterParams() const
739 if (masterBuffer() == this)
742 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
743 // Copy child authors to the params. We need those pointers.
744 for (Author const & a : params().authors())
745 mparams.authors().record(a);
750 double Buffer::fontScalingFactor() const
752 return isExporting() ? 75.0 * params().html_math_img_scale
753 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
757 ParagraphList & Buffer::paragraphs()
759 return text().paragraphs();
763 ParagraphList const & Buffer::paragraphs() const
765 return text().paragraphs();
769 LyXVC & Buffer::lyxvc()
775 LyXVC const & Buffer::lyxvc() const
781 string const Buffer::temppath() const
783 return d->temppath.absFileName();
787 TexRow & Buffer::texrow()
793 TexRow const & Buffer::texrow() const
799 TocBackend & Buffer::tocBackend() const
801 return d->toc_backend;
805 Undo & Buffer::undo()
811 void Buffer::setChild(DocIterator const & dit, Buffer * child)
813 d->children_positions[child] = dit;
817 string Buffer::latexName(bool const no_path) const
819 FileName latex_name =
820 makeLatexName(d->exportFileName());
821 return no_path ? latex_name.onlyFileName()
822 : latex_name.absFileName();
826 FileName Buffer::Impl::exportFileName() const
828 docstring const branch_suffix =
829 params.branchlist().getFileNameSuffix();
830 if (branch_suffix.empty())
833 string const name = addExtension(filename.onlyFileNameWithoutExt()
834 + to_utf8(branch_suffix), filename.extension());
835 FileName res(filename.onlyPath().absFileName() + "/" + name);
841 string Buffer::logName(LogType * type) const
843 string const filename = latexName(false);
845 if (filename.empty()) {
851 string const path = temppath();
853 FileName const fname(addName(temppath(),
854 onlyFileName(changeExtension(filename,
857 // FIXME: how do we know this is the name of the build log?
858 FileName const bname(
859 addName(path, onlyFileName(
860 changeExtension(filename,
861 theFormats().extension(params().bufferFormat()) + ".out"))));
863 // Also consider the master buffer log file
864 FileName masterfname = fname;
865 LogType mtype = latexlog;
866 if (masterBuffer() != this) {
867 string const mlogfile = masterBuffer()->logName(&mtype);
868 masterfname = FileName(mlogfile);
871 // If no Latex log or Build log is newer, show Build log
872 if (bname.exists() &&
873 ((!fname.exists() && !masterfname.exists())
874 || (fname.lastModified() < bname.lastModified()
875 && masterfname.lastModified() < bname.lastModified()))) {
876 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
879 return bname.absFileName();
880 // If we have a newer master file log or only a master log, show this
881 } else if (fname != masterfname
882 && (!fname.exists() && (masterfname.exists()
883 || fname.lastModified() < masterfname.lastModified()))) {
884 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
887 return masterfname.absFileName();
889 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
892 return fname.absFileName();
896 void Buffer::setReadonly(bool const flag)
898 if (d->read_only != flag) {
905 void Buffer::setFileName(FileName const & fname)
907 bool const changed = fname != d->filename;
909 d->refreshFileMonitor();
911 lyxvc().file_found_hook(fname);
912 setReadonly(d->filename.isReadOnly());
918 int Buffer::readHeader(Lexer & lex)
920 int unknown_tokens = 0;
922 int begin_header_line = -1;
924 // Initialize parameters that may be/go lacking in header:
925 params().branchlist().clear();
926 params().preamble.erase();
927 params().options.erase();
928 params().master.erase();
929 params().float_placement.erase();
930 params().float_alignment.erase();
931 params().paperwidth.erase();
932 params().paperheight.erase();
933 params().leftmargin.erase();
934 params().rightmargin.erase();
935 params().topmargin.erase();
936 params().bottommargin.erase();
937 params().headheight.erase();
938 params().headsep.erase();
939 params().footskip.erase();
940 params().columnsep.erase();
941 params().font_roman_opts.erase();
942 params().font_sans_opts.erase();
943 params().font_typewriter_opts.erase();
944 params().fonts_cjk.erase();
945 params().listings_params.clear();
946 params().clearLayoutModules();
947 params().clearRemovedModules();
948 params().clearIncludedChildren();
949 params().pdfoptions().clear();
950 params().indiceslist().clear();
951 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
952 params().isbackgroundcolor = false;
953 params().fontcolor = RGBColor(0, 0, 0);
954 params().isfontcolor = false;
955 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
956 params().boxbgcolor = RGBColor(0xFF, 0, 0);
957 params().html_latex_start.clear();
958 params().html_latex_end.clear();
959 params().html_math_img_scale = 1.0;
960 params().output_sync_macro.erase();
961 params().setLocalLayout(docstring(), false);
962 params().setLocalLayout(docstring(), true);
963 params().biblio_opts.erase();
964 params().biblatex_bibstyle.erase();
965 params().biblatex_citestyle.erase();
966 params().multibib.erase();
967 params().lineno_opts.clear();
969 for (int i = 0; i < 4; ++i) {
970 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
971 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
974 ErrorList & errorList = d->errorLists["Parse"];
983 if (token == "\\end_header")
987 if (token == "\\begin_header") {
988 begin_header_line = line;
992 LYXERR(Debug::PARSER, "Handling document header token: `"
995 string const result =
996 params().readToken(lex, token, d->filename.onlyPath());
997 if (!result.empty()) {
998 if (token == "\\textclass") {
999 d->layout_position = result;
1002 docstring const s = bformat(_("Unknown token: "
1005 lex.getDocString());
1006 errorList.push_back(ErrorItem(_("Document header error"), s));
1010 if (begin_header_line) {
1011 docstring const s = _("\\begin_header is missing");
1012 errorList.push_back(ErrorItem(_("Document header error"), s));
1015 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
1017 params().makeDocumentClass();
1019 return unknown_tokens;
1024 // changed to be public and have one parameter
1025 // Returns true if "\end_document" is not read (Asger)
1026 bool Buffer::readDocument(Lexer & lex)
1028 ErrorList & errorList = d->errorLists["Parse"];
1031 // remove dummy empty par
1032 paragraphs().clear();
1034 if (!lex.checkFor("\\begin_document")) {
1035 docstring const s = _("\\begin_document is missing");
1036 errorList.push_back(ErrorItem(_("Document header error"), s));
1041 if (params().output_changes) {
1042 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1043 LaTeXFeatures::isAvailable("xcolor");
1046 Alert::warning(_("Changes not shown in LaTeX output"),
1047 _("Changes will not be highlighted in LaTeX output, "
1048 "because xcolor and ulem are not installed.\n"
1049 "Please install both packages or redefine "
1050 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1054 if (!parent() && !params().master.empty()) {
1055 FileName const master_file = makeAbsPath(params().master,
1056 onlyPath(absFileName()));
1057 if (isLyXFileName(master_file.absFileName())) {
1059 checkAndLoadLyXFile(master_file, true);
1061 // necessary e.g. after a reload
1062 // to re-register the child (bug 5873)
1063 // FIXME: clean up updateMacros (here, only
1064 // child registering is needed).
1065 master->updateMacros();
1066 // set master as master buffer, but only
1067 // if we are a real child
1068 if (master->isChild(this))
1070 // if the master is not fully loaded
1071 // it is probably just loading this
1072 // child. No warning needed then.
1073 else if (master->isFullyLoaded())
1074 LYXERR0("The master '"
1076 << "' assigned to this document ("
1078 << ") does not include "
1079 "this document. Ignoring the master assignment.");
1080 // If the master has just been created, un-hide it (#11162)
1081 if (!master->fileName().exists())
1082 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1083 master->absFileName()));
1088 // assure we have a default index
1089 params().indiceslist().addDefault(B_("Index"));
1092 if (FileName::isAbsolute(params().origin))
1093 d->old_position = params().origin;
1095 d->old_position = filePath();
1100 bool const res = text().read(lex, errorList, d->inset);
1101 d->old_position.clear();
1103 // inform parent buffer about local macros
1105 Buffer const * pbuf = parent();
1106 for (auto const & m : usermacros)
1107 pbuf->usermacros.insert(m);
1111 updateMacroInstances(InternalUpdate);
1116 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1118 Format const * fmt = theFormats().getFormat(format);
1121 // It is important to use the correct extension here, since some
1122 // converters create a wrong output file otherwise (e.g. html2latex)
1123 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1124 ofdocstream os(name.toFilesystemEncoding().c_str());
1125 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1126 bool const success = !(os << contents).fail();
1129 bool converted = false;
1131 params().compressed = false;
1133 // remove dummy empty par
1134 paragraphs().clear();
1136 converted = importFile(format, name, errorList);
1139 removeTempFile(name);
1144 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1146 if (!theConverters().isReachable(format, "lyx"))
1149 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1150 Converters::RetVal const retval =
1151 theConverters().convert(nullptr, name, lyx, name, format, "lyx", errorList);
1152 if (retval == Converters::SUCCESS) {
1153 bool const success = readFile(lyx) == ReadSuccess;
1154 removeTempFile(lyx);
1162 bool Buffer::readString(string const & s)
1164 params().compressed = false;
1167 istringstream is(s);
1169 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1170 FileName const fn = tempfile.name();
1173 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1175 if (success && file_format != LYX_FORMAT) {
1176 // We need to call lyx2lyx, so write the input to a file
1177 ofstream os(fn.toFilesystemEncoding().c_str());
1180 // lyxvc in readFile
1181 if (readFile(fn) != ReadSuccess)
1185 if (readDocument(lex))
1191 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1195 if (!lex.setFile(fname)) {
1196 Alert::error(_("File Not Found"),
1197 bformat(_("Unable to open file `%1$s'."),
1198 from_utf8(fn.absFileName())));
1199 return ReadFileNotFound;
1203 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1204 if (ret_plf != ReadSuccess)
1207 if (file_format != LYX_FORMAT) {
1209 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1210 if (ret_clf != ReadSuccess)
1212 ret_clf = readFile(tmpFile);
1213 if (ret_clf == ReadSuccess) {
1214 d->file_format = file_format;
1215 d->need_format_backup = true;
1220 // FIXME: InsetInfo needs to know whether the file is under VCS
1221 // during the parse process, so this has to be done before.
1222 lyxvc().file_found_hook(d->filename);
1224 if (readDocument(lex)) {
1225 Alert::error(_("Document format failure"),
1226 bformat(_("%1$s ended unexpectedly, which means"
1227 " that it is probably corrupted."),
1228 from_utf8(fn.absFileName())));
1229 return ReadDocumentFailure;
1232 d->file_fully_loaded = true;
1233 d->read_only = !d->filename.isWritable();
1234 params().compressed = theFormats().isZippedFile(d->filename);
1240 bool Buffer::isFullyLoaded() const
1242 return d->file_fully_loaded;
1246 void Buffer::setFullyLoaded(bool value)
1248 d->file_fully_loaded = value;
1252 bool Buffer::freshStartRequired() const
1254 return d->require_fresh_start_;
1257 void Buffer::requireFreshStart(bool const b) const
1259 d->require_fresh_start_ = b;
1263 PreviewLoader * Buffer::loader() const
1265 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1267 if (!d->preview_loader_)
1268 d->preview_loader_ = new PreviewLoader(*this);
1269 return d->preview_loader_;
1273 void Buffer::removePreviews() const
1275 delete d->preview_loader_;
1276 d->preview_loader_ = nullptr;
1280 void Buffer::updatePreviews() const
1282 PreviewLoader * ploader = loader();
1286 InsetIterator it = inset_iterator_begin(*d->inset);
1287 InsetIterator const end = inset_iterator_end(*d->inset);
1288 for (; it != end; ++it)
1289 it->addPreview(it, *ploader);
1291 ploader->startLoading();
1295 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1296 FileName const & fn, int & file_format) const
1298 if(!lex.checkFor("\\lyxformat")) {
1299 Alert::error(_("Document format failure"),
1300 bformat(_("%1$s is not a readable LyX document."),
1301 from_utf8(fn.absFileName())));
1302 return ReadNoLyXFormat;
1308 // LyX formats 217 and earlier were written as 2.17. This corresponds
1309 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1310 // these cases. See also: www.lyx.org/trac/changeset/1313.
1311 size_t dot = tmp_format.find_first_of(".,");
1312 if (dot != string::npos)
1313 tmp_format.erase(dot, 1);
1315 file_format = convert<int>(tmp_format);
1320 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1321 FileName & tmpfile, int from_format)
1323 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1324 tempfile.setAutoRemove(false);
1325 tmpfile = tempfile.name();
1326 if(tmpfile.empty()) {
1327 Alert::error(_("Conversion failed"),
1328 bformat(_("%1$s is from a different"
1329 " version of LyX, but a temporary"
1330 " file for converting it could"
1331 " not be created."),
1332 from_utf8(fn.absFileName())));
1333 return LyX2LyXNoTempFile;
1336 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1337 if (lyx2lyx.empty()) {
1338 Alert::error(_("Conversion script not found"),
1339 bformat(_("%1$s is from a different"
1340 " version of LyX, but the"
1341 " conversion script lyx2lyx"
1342 " could not be found."),
1343 from_utf8(fn.absFileName())));
1344 return LyX2LyXNotFound;
1348 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1349 ostringstream command;
1350 command << os::python()
1351 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1352 << " -t " << convert<string>(LYX_FORMAT)
1353 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1354 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1355 string const command_str = command.str();
1357 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1359 cmd_ret const ret = runCommand(command_str);
1360 if (ret.first != 0) {
1361 if (from_format < LYX_FORMAT) {
1362 Alert::error(_("Conversion script failed"),
1363 bformat(_("%1$s is from an older version"
1364 " of LyX and the lyx2lyx script"
1365 " failed to convert it."),
1366 from_utf8(fn.absFileName())));
1367 return LyX2LyXOlderFormat;
1369 Alert::error(_("Conversion script failed"),
1370 bformat(_("%1$s is from a newer version"
1371 " of LyX and the lyx2lyx script"
1372 " failed to convert it."),
1373 from_utf8(fn.absFileName())));
1374 return LyX2LyXNewerFormat;
1381 FileName Buffer::getBackupName() const {
1382 map<int, string> const file_formats = {
1399 FileName const & fn = fileName();
1400 string const fname = fn.onlyFileNameWithoutExt();
1401 string const fext = fn.extension() + "~";
1402 string const fpath = lyxrc.backupdir_path.empty() ?
1403 fn.onlyPath().absFileName() :
1404 lyxrc.backupdir_path;
1405 string backup_suffix;
1406 // If file format is from a stable series use version instead of file format
1407 auto const it = file_formats.find(d->file_format);
1408 if (it != file_formats.end())
1409 backup_suffix = "-lyx" + it->second;
1411 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1412 string const backname = fname + backup_suffix;
1413 FileName backup(addName(fpath, addExtension(backname, fext)));
1415 // limit recursion, just in case
1417 unsigned long orig_checksum = 0;
1418 while (backup.exists() && v < 100) {
1419 if (orig_checksum == 0)
1420 orig_checksum = fn.checksum();
1421 unsigned long new_checksum = backup.checksum();
1422 if (orig_checksum == new_checksum) {
1423 LYXERR(Debug::FILES, "Not backing up " << fn <<
1424 "since " << backup << "has the same checksum.");
1425 // a bit of a hack, but we have to check this anyway
1426 // below, and setting this is simpler than introducing
1427 // a special boolean for this purpose.
1431 string const newbackname = backname + "-" + convert<string>(v);
1432 backup.set(addName(fpath, addExtension(newbackname, fext)));
1435 return v < 100 ? backup : FileName();
1439 // Should probably be moved to somewhere else: BufferView? GuiView?
1440 bool Buffer::save() const
1442 docstring const file = makeDisplayPath(absFileName(), 20);
1443 d->filename.refresh();
1445 // check the read-only status before moving the file as a backup
1446 if (d->filename.exists()) {
1447 bool const read_only = !d->filename.isWritable();
1449 Alert::warning(_("File is read-only"),
1450 bformat(_("The file %1$s cannot be written because it "
1451 "is marked as read-only."), file));
1456 // ask if the disk file has been externally modified (use checksum method)
1457 if (fileName().exists() && isChecksumModified()) {
1459 bformat(_("Document %1$s has been externally modified. "
1460 "Are you sure you want to overwrite this file?"), file);
1461 int const ret = Alert::prompt(_("Overwrite modified file?"),
1462 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1467 // We don't need autosaves in the immediate future. (Asger)
1468 resetAutosaveTimers();
1470 // if the file does not yet exist, none of the backup activity
1471 // that follows is necessary
1472 if (!fileName().exists()) {
1473 if (!writeFile(fileName()))
1479 // we first write the file to a new name, then move it to its
1480 // proper location once that has been done successfully. that
1481 // way we preserve the original file if something goes wrong.
1482 string const justname = fileName().onlyFileNameWithoutExt();
1483 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1484 justname + "-XXXXXX.lyx");
1485 bool const symlink = fileName().isSymLink();
1487 tempfile->setAutoRemove(false);
1489 FileName savefile(tempfile->name());
1490 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1491 if (!savefile.clonePermissions(fileName()))
1492 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1494 if (!writeFile(savefile))
1497 // we will set this to false if we fail
1498 bool made_backup = true;
1500 FileName backupName;
1501 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1503 if (d->need_format_backup)
1504 backupName = getBackupName();
1506 // If we for some reason failed to find a backup name in case of
1507 // a format change, this will still set one. It's the best we can
1509 if (backupName.empty()) {
1510 backupName.set(fileName().absFileName() + "~");
1511 if (!lyxrc.backupdir_path.empty()) {
1512 string const mangledName =
1513 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1514 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1518 LYXERR(Debug::FILES, "Backing up original file to " <<
1519 backupName.absFileName());
1520 // Except file is symlink do not copy because of #6587.
1521 // Hard links have bad luck.
1522 made_backup = symlink ?
1523 fileName().copyTo(backupName):
1524 fileName().moveTo(backupName);
1527 Alert::error(_("Backup failure"),
1528 bformat(_("Cannot create backup file %1$s.\n"
1529 "Please check whether the directory exists and is writable."),
1530 from_utf8(backupName.absFileName())));
1531 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1532 } else if (d->need_format_backup) {
1533 // the original file has been backed up successfully, so we
1534 // will not need to do that again
1535 d->need_format_backup = false;
1539 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1540 // Only do this if tempfile is not in autoremove mode
1543 // If we have no symlink, we can simply rename the temp file.
1544 // Otherwise, we need to copy it so the symlink stays intact.
1545 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1546 savefile.moveTo(fileName()))
1548 // saveCheckSum() was already called by writeFile(), but the
1549 // time stamp is invalidated by copying/moving
1552 if (d->file_format != LYX_FORMAT)
1553 // the file associated with this buffer is now in the current format
1554 d->file_format = LYX_FORMAT;
1557 // else we saved the file, but failed to move it to the right location.
1559 if (needBackup && made_backup && !symlink) {
1560 // the original file was moved to some new location, so it will look
1561 // to the user as if it was deleted. (see bug #9234.) we could try
1562 // to restore it, but that would basically mean trying to do again
1563 // what we just failed to do. better to leave things as they are.
1564 Alert::error(_("Write failure"),
1565 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1566 "But LyX could not move it to:\n %2$s.\n"
1567 "Your original file has been backed up to:\n %3$s"),
1568 from_utf8(savefile.absFileName()),
1569 from_utf8(fileName().absFileName()),
1570 from_utf8(backupName.absFileName())));
1572 // either we did not try to make a backup, or else we tried and failed,
1573 // or else the original file was a symlink, in which case it was copied,
1574 // not moved. so the original file is intact.
1575 Alert::error(_("Write failure"),
1576 bformat(_("Cannot move saved file to:\n %1$s.\n"
1577 "But the file has successfully been saved as:\n %2$s."),
1578 from_utf8(fileName().absFileName()),
1579 from_utf8(savefile.absFileName())));
1585 bool Buffer::writeFile(FileName const & fname) const
1587 if (d->read_only && fname == d->filename)
1590 bool retval = false;
1592 docstring const str = bformat(_("Saving document %1$s..."),
1593 makeDisplayPath(fname.absFileName()));
1596 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1598 if (params().compressed) {
1599 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1600 retval = ofs && write(ofs);
1602 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1603 retval = ofs && write(ofs);
1607 message(str + _(" could not write file!"));
1612 // removeAutosaveFile();
1615 message(str + _(" done."));
1621 docstring Buffer::emergencyWrite()
1623 // No need to save if the buffer has not changed.
1627 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1629 docstring user_message = bformat(
1630 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1632 // We try to save three places:
1633 // 1) Same place as document. Unless it is an unnamed doc.
1635 string s = absFileName();
1638 if (writeFile(FileName(s))) {
1640 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1641 return user_message;
1643 user_message += " " + _("Save failed! Trying again...\n");
1647 // 2) In HOME directory.
1648 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1650 lyxerr << ' ' << s << endl;
1651 if (writeFile(FileName(s))) {
1653 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1654 return user_message;
1657 user_message += " " + _("Save failed! Trying yet again...\n");
1659 // 3) In "/tmp" directory.
1660 // MakeAbsPath to prepend the current
1661 // drive letter on OS/2
1662 s = addName(package().temp_dir().absFileName(), absFileName());
1664 lyxerr << ' ' << s << endl;
1665 if (writeFile(FileName(s))) {
1667 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1668 return user_message;
1671 user_message += " " + _("Save failed! Document is lost.");
1674 return user_message;
1678 bool Buffer::write(ostream & ofs) const
1681 // Use the standard "C" locale for file output.
1682 ofs.imbue(locale::classic());
1685 // The top of the file should not be written by params().
1687 // write out a comment in the top of the file
1688 // Important: Keep the version formatting in sync with lyx2lyx and
1689 // tex2lyx (bug 7951)
1690 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1691 << " created this file. For more info see https://www.lyx.org/\n"
1692 << "\\lyxformat " << LYX_FORMAT << "\n"
1693 << "\\begin_document\n";
1695 /// For each author, set 'used' to true if there is a change
1696 /// by this author in the document; otherwise set it to 'false'.
1697 for (Author const & a : params().authors())
1700 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1701 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1702 for ( ; it != end; ++it)
1703 it->checkAuthors(params().authors());
1705 // now write out the buffer parameters.
1706 ofs << "\\begin_header\n";
1707 params().writeFile(ofs, this);
1708 ofs << "\\end_header\n";
1711 ofs << "\n\\begin_body\n";
1713 ofs << "\n\\end_body\n";
1715 // Write marker that shows file is complete
1716 ofs << "\\end_document" << endl;
1718 // Shouldn't really be needed....
1721 // how to check if close went ok?
1722 // Following is an attempt... (BE 20001011)
1724 // good() returns false if any error occurred, including some
1725 // formatting error.
1726 // bad() returns true if something bad happened in the buffer,
1727 // which should include file system full errors.
1732 lyxerr << "File was not closed properly." << endl;
1739 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1740 string const & original_path,
1741 OutputParams const & runparams_in,
1742 OutputWhat output) const
1744 OutputParams runparams = runparams_in;
1746 string const encoding = runparams.encoding->iconvName();
1747 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1750 try { ofs.reset(encoding); }
1751 catch (iconv_codecvt_facet_exception const & e) {
1752 lyxerr << "Caught iconv exception: " << e.what() << endl;
1753 Alert::error(_("Iconv software exception Detected"),
1754 bformat(_("Please verify that the `iconv' support software is"
1755 " properly installed and supports the selected encoding"
1756 " (%1$s), or change the encoding in"
1757 " Document>Settings>Language."), from_ascii(encoding)));
1760 if (!openFileWrite(ofs, fname))
1763 ErrorList & errorList = d->errorLists["Export"];
1765 ExportStatus status = ExportSuccess;
1768 // make sure we are ready to export
1769 // this needs to be done before we validate
1770 // FIXME Do we need to do this all the time? I.e., in children
1771 // of a master we are exporting?
1773 updateMacroInstances(OutputUpdate);
1775 ExportStatus retval;
1777 retval = writeLaTeXSource(os, original_path, runparams, output);
1778 if (retval == ExportKilled)
1779 return ExportKilled;
1781 catch (EncodingException const & e) {
1782 docstring const failed(1, e.failed_char);
1784 oss << "0x" << hex << e.failed_char << dec;
1785 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1786 docstring msg = bformat(_("Uncodable character '%1$s'"
1787 " (code point %2$s)"),
1788 failed, from_utf8(oss.str()));
1789 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1790 "representable in specific verbatim contexts.\n"
1791 "Changing the document encoding to utf8 could help."),
1792 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1794 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1795 " (code point %2$s)"),
1796 failed, from_utf8(oss.str()));
1797 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1798 "representable in the chosen encoding.\n"
1799 "Changing the document encoding to utf8 could help."),
1800 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1802 status = ExportError;
1804 catch (iconv_codecvt_facet_exception const & e) {
1805 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1807 status = ExportError;
1809 catch (exception const & e) {
1810 errorList.push_back(ErrorItem(_("conversion failed"),
1812 lyxerr << e.what() << endl;
1813 status = ExportError;
1816 lyxerr << "Caught some really weird exception..." << endl;
1820 d->texrow = move(os.texrow());
1824 status = ExportError;
1825 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1828 if (runparams_in.silent)
1836 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1837 string const & original_path,
1838 OutputParams const & runparams_in,
1839 OutputWhat output) const
1841 // The child documents, if any, shall be already loaded at this point.
1843 OutputParams runparams = runparams_in;
1845 // Some macros rely on font encoding
1846 runparams.main_fontenc = params().main_font_encoding();
1848 // If we are compiling a file standalone, even if this is the
1849 // child of some other buffer, let's cut the link here, so the
1850 // file is really independent and no concurring settings from
1851 // the master (e.g. branch state) interfere (see #8100).
1852 if (!runparams.is_child)
1853 d->ignore_parent = true;
1855 // Classify the unicode characters appearing in math insets
1856 BufferEncodings::initUnicodeMath(*this);
1858 // validate the buffer.
1859 LYXERR(Debug::LATEX, " Validating buffer...");
1860 LaTeXFeatures features(*this, params(), runparams);
1862 // This is only set once per document (in master)
1863 if (!runparams.is_child) {
1864 runparams.use_polyglossia = features.usePolyglossia();
1865 runparams.use_hyperref = features.isRequired("hyperref");
1866 runparams.use_CJK = features.mustProvide("CJK");
1868 LYXERR(Debug::LATEX, " Buffer validation done.");
1870 bool const output_preamble =
1871 output == FullSource || output == OnlyPreamble;
1872 bool const output_body =
1873 output == FullSource || output == OnlyBody;
1875 // The starting paragraph of the coming rows is the
1876 // first paragraph of the document. (Asger)
1877 if (output_preamble && runparams.nice) {
1878 os << "%% LyX " << lyx_version << " created this file. "
1879 "For more info, see https://www.lyx.org/.\n"
1880 "%% Do not edit unless you really know what "
1883 LYXERR(Debug::INFO, "lyx document header finished");
1885 // There are a few differences between nice LaTeX and usual files:
1886 // usual files have \batchmode and special input@path to allow
1887 // inclusion of figures specified by an explicitly relative path
1888 // (i.e., a path starting with './' or '../') with either \input or
1889 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1890 // input@path is set when the actual parameter original_path is set.
1891 // This is done for usual tex-file, but not for nice-latex-file.
1892 // (Matthias 250696)
1893 // Note that input@path is only needed for something the user does
1894 // in the preamble, included .tex files or ERT, files included by
1895 // LyX work without it.
1896 if (output_preamble) {
1897 if (!runparams.nice) {
1898 // code for usual, NOT nice-latex-file
1899 os << "\\batchmode\n"; // changed from \nonstopmode
1901 if (!original_path.empty()) {
1903 // We don't know the encoding of inputpath
1904 docstring const inputpath = from_utf8(original_path);
1905 docstring uncodable_glyphs;
1906 Encoding const * const enc = runparams.encoding;
1908 for (size_t n = 0; n < inputpath.size(); ++n) {
1909 if (!enc->encodable(inputpath[n])) {
1910 docstring const glyph(1, inputpath[n]);
1911 LYXERR0("Uncodable character '"
1913 << "' in input path!");
1914 uncodable_glyphs += glyph;
1919 // warn user if we found uncodable glyphs.
1920 if (!uncodable_glyphs.empty()) {
1921 frontend::Alert::warning(
1922 _("Uncodable character in file path"),
1924 _("The path of your document\n"
1926 "contains glyphs that are unknown "
1927 "in the current document encoding "
1928 "(namely %2$s). This may result in "
1929 "incomplete output, unless "
1930 "TEXINPUTS contains the document "
1931 "directory and you don't use "
1932 "explicitly relative paths (i.e., "
1933 "paths starting with './' or "
1934 "'../') in the preamble or in ERT."
1935 "\n\nIn case of problems, choose "
1936 "an appropriate document encoding\n"
1937 "(such as utf8) or change the "
1939 inputpath, uncodable_glyphs));
1941 string docdir = os::latex_path(original_path);
1942 if (contains(docdir, '#')) {
1943 docdir = subst(docdir, "#", "\\#");
1944 os << "\\catcode`\\#=11"
1945 "\\def\\#{#}\\catcode`\\#=6\n";
1947 if (contains(docdir, '%')) {
1948 docdir = subst(docdir, "%", "\\%");
1949 os << "\\catcode`\\%=11"
1950 "\\def\\%{%}\\catcode`\\%=14\n";
1952 if (contains(docdir, '~'))
1953 docdir = subst(docdir, "~", "\\string~");
1954 bool const nonascii = !isAscii(from_utf8(docdir));
1955 // LaTeX 2019/10/01 handles non-ascii path without detokenize
1956 bool const utfpathlatex = features.isAvailable("LaTeX-2019/10/01");
1957 bool const detokenize = !utfpathlatex && nonascii;
1958 bool const quote = contains(docdir, ' ');
1959 if (utfpathlatex && nonascii)
1960 os << "\\UseRawInputEncoding\n";
1961 os << "\\makeatletter\n"
1962 << "\\def\\input@path{{";
1964 os << "\\detokenize{";
1973 << "\\makeatother\n";
1977 // get parent macros (if this buffer has a parent) which will be
1978 // written at the document begin further down.
1979 MacroSet parentMacros;
1980 listParentMacros(parentMacros, features);
1982 // Write the preamble
1983 runparams.use_babel = params().writeLaTeX(os, features,
1984 d->filename.onlyPath());
1986 // Active characters
1987 runparams.active_chars = features.getActiveChars();
1989 // Biblatex bibliographies are loaded here
1990 if (params().useBiblatex()) {
1991 vector<pair<docstring, string>> const bibfiles =
1992 prepareBibFilePaths(runparams, getBibfiles(), true);
1993 for (pair<docstring, string> const & file: bibfiles) {
1994 os << "\\addbibresource";
1995 if (!file.second.empty())
1996 os << "[bibencoding=" << file.second << "]";
1997 os << "{" << file.first << "}\n";
2001 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
2002 && !features.hasOnlyPolyglossiaLanguages()) {
2005 vector<string> bll = features.getBabelExclusiveLanguages();
2006 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
2009 for (string const & sit : bll) {
2014 blangs = bll.size() > 1 ?
2015 bformat(_("The languages %1$s are only supported by Babel."), langs)
2016 : bformat(_("The language %1$s is only supported by Babel."), langs);
2020 for (string const & pit : pll) {
2025 plangs = pll.size() > 1 ?
2026 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
2027 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
2028 if (!blangs.empty())
2032 frontend::Alert::warning(
2033 _("Incompatible Languages!"),
2035 _("You cannot use the following languages "
2036 "together in one LaTeX document because "
2037 "they require conflicting language packages:\n"
2042 // Japanese might be required only in some children of a document,
2043 // but once required, we must keep use_japanese true.
2044 runparams.use_japanese |= features.isRequired("japanese");
2047 // Restore the parenthood if needed
2048 if (!runparams.is_child)
2049 d->ignore_parent = false;
2050 return ExportSuccess;
2054 // mark the beginning of the body to separate it from InPreamble insets
2055 os.texrow().start(TexRow::beginDocument());
2056 os << "\\begin{document}\n";
2058 // mark the start of a new paragraph by simulating a newline,
2059 // so that os.afterParbreak() returns true at document start
2062 // output the parent macros
2063 for (auto const & mac : parentMacros) {
2064 int num_lines = mac->write(os.os(), true);
2065 os.texrow().newlines(num_lines);
2068 } // output_preamble
2070 LYXERR(Debug::INFO, "preamble finished, now the body.");
2074 latexParagraphs(*this, text(), os, runparams);
2076 catch (ConversionException const &) { return ExportKilled; }
2078 // Restore the parenthood if needed
2079 if (!runparams.is_child)
2080 d->ignore_parent = false;
2082 // add this just in case after all the paragraphs
2085 if (output_preamble) {
2086 os << "\\end{document}\n";
2087 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2089 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2091 runparams_in.encoding = runparams.encoding;
2093 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2094 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2095 return ExportSuccess;
2099 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2100 OutputParams const & runparams,
2101 OutputWhat output) const
2103 LYXERR(Debug::LATEX, "makeDocBookFile...");
2106 if (!openFileWrite(ofs, fname))
2109 // make sure we are ready to export
2110 // this needs to be done before we validate
2112 updateMacroInstances(OutputUpdate);
2114 ExportStatus const retval =
2115 writeDocBookSource(ofs, runparams, output);
2116 if (retval == ExportKilled)
2117 return ExportKilled;
2121 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2122 return ExportSuccess;
2126 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os,
2127 OutputParams const & runparams,
2128 OutputWhat output) const
2130 LaTeXFeatures features(*this, params(), runparams);
2132 d->bibinfo_.makeCitationLabels(*this);
2136 DocumentClass const & tclass = params().documentClass();
2138 bool const output_preamble =
2139 output == FullSource || output == OnlyPreamble;
2140 bool const output_body =
2141 output == FullSource || output == OnlyBody;
2145 if (output_preamble) {
2146 // XML preamble, no doctype needed.
2147 // Not using XMLStream for this, as the root tag would be in the tag stack and make troubles with the error
2148 // detection mechanisms (these are called before the end tag is output, and thus interact with the canary
2149 // parsep in output_docbook.cpp).
2150 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2151 << "<!-- This DocBook file was created by LyX " << lyx_version
2152 << "\n See http://www.lyx.org/ for more information -->\n";
2154 // Directly output the root tag, based on the current type of document.
2155 string languageCode = params().language->code();
2156 string params = "xml:lang=\"" + languageCode + '"'
2157 + " xmlns=\"http://docbook.org/ns/docbook\""
2158 + " xmlns:xlink=\"http://www.w3.org/1999/xlink\""
2159 + " xmlns:m=\"http://www.w3.org/1998/Math/MathML\""
2160 + " xmlns:xi=\"http://www.w3.org/2001/XInclude\""
2161 + " version=\"5.2\"";
2163 os << "<" << from_ascii(tclass.docbookroot()) << " " << from_ascii(params) << ">\n";
2167 params().documentClass().counters().reset();
2169 // Start to output the document.
2170 docbookParagraphs(text(), *this, xs, runparams);
2173 if (output_preamble) {
2174 // Close the root element.
2175 os << "\n</" << from_ascii(tclass.docbookroot()) << ">";
2177 return ExportSuccess;
2181 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2182 OutputParams const & runparams) const
2184 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2187 if (!openFileWrite(ofs, fname))
2190 // make sure we are ready to export
2191 // this has to be done before we validate
2192 updateBuffer(UpdateMaster, OutputUpdate);
2193 updateMacroInstances(OutputUpdate);
2195 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2196 if (retval == ExportKilled)
2201 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2206 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2207 OutputParams const & runparams,
2208 OutputWhat output) const
2210 LaTeXFeatures features(*this, params(), runparams);
2212 d->bibinfo_.makeCitationLabels(*this);
2214 bool const output_preamble =
2215 output == FullSource || output == OnlyPreamble;
2216 bool const output_body =
2217 output == FullSource || output == OnlyBody || output == IncludedFile;
2219 if (output_preamble) {
2220 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2221 << "<!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"
2222 // FIXME Language should be set properly.
2223 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2225 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2226 // FIXME Presumably need to set this right
2227 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2229 docstring const & doctitle = features.htmlTitle();
2231 << (doctitle.empty() ?
2232 from_ascii("LyX Document") :
2233 xml::escapeString(doctitle, XMLStream::ESCAPE_ALL))
2236 docstring styles = features.getTClassHTMLPreamble();
2237 if (!styles.empty())
2238 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2240 // we will collect CSS information in a stream, and then output it
2241 // either here, as part of the header, or else in a separate file.
2242 odocstringstream css;
2243 styles = features.getCSSSnippets();
2244 if (!styles.empty())
2245 css << "/* LyX Provided Styles */\n" << styles << '\n';
2247 styles = features.getTClassHTMLStyles();
2248 if (!styles.empty())
2249 css << "/* Layout-provided Styles */\n" << styles << '\n';
2251 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2252 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2253 if (needfg || needbg) {
2254 css << "\nbody {\n";
2257 << from_ascii(X11hexname(params().fontcolor))
2260 css << " background-color: "
2261 << from_ascii(X11hexname(params().backgroundcolor))
2266 docstring const dstyles = css.str();
2267 if (!dstyles.empty()) {
2268 bool written = false;
2269 if (params().html_css_as_file) {
2270 // open a file for CSS info
2272 string const fcssname = addName(temppath(), "docstyle.css");
2273 FileName const fcssfile = FileName(fcssname);
2274 if (openFileWrite(ocss, fcssfile)) {
2278 // write link to header
2279 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2281 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2284 // we are here if the CSS is supposed to be written to the header
2285 // or if we failed to write it to an external file.
2287 os << "<style type='text/css'>\n"
2296 bool const output_body_tag = (output != IncludedFile);
2297 if (output_body_tag)
2298 os << "<body dir=\"auto\">\n";
2300 if (output != IncludedFile)
2301 // if we're an included file, the counters are in the master.
2302 params().documentClass().counters().reset();
2304 xhtmlParagraphs(text(), *this, xs, runparams);
2306 catch (ConversionException const &) { return ExportKilled; }
2307 if (output_body_tag)
2311 if (output_preamble)
2314 return ExportSuccess;
2318 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2319 // Other flags: -wall -v0 -x
2320 int Buffer::runChktex()
2324 // get LaTeX-Filename
2325 FileName const path(temppath());
2326 string const name = addName(path.absFileName(), latexName());
2327 string const org_path = filePath();
2329 PathChanger p(path); // path to LaTeX file
2330 message(_("Running chktex..."));
2332 // Generate the LaTeX file if neccessary
2333 OutputParams runparams(¶ms().encoding());
2334 runparams.flavor = OutputParams::LATEX;
2335 runparams.nice = false;
2336 runparams.linelen = lyxrc.plaintext_linelen;
2337 ExportStatus const retval =
2338 makeLaTeXFile(FileName(name), org_path, runparams);
2339 if (retval != ExportSuccess) {
2340 // error code on failure
2345 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2346 int const res = chktex.run(terr); // run chktex
2349 Alert::error(_("chktex failure"),
2350 _("Could not run chktex successfully."));
2352 ErrorList & errlist = d->errorLists["ChkTeX"];
2354 bufferErrors(terr, errlist);
2359 if (runparams.silent)
2360 d->errorLists["ChkTeX"].clear();
2368 void Buffer::validate(LaTeXFeatures & features) const
2370 // Validate the buffer params, but not for included
2371 // files, since they also use the parent buffer's
2373 if (!features.runparams().is_child)
2374 params().validate(features);
2379 for (Paragraph const & p : paragraphs())
2380 p.validate(features);
2382 if (lyxerr.debugging(Debug::LATEX)) {
2383 features.showStruct();
2388 void Buffer::getLabelList(vector<docstring> & list) const
2390 // If this is a child document, use the master's list instead.
2392 masterBuffer()->getLabelList(list);
2397 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2398 for (auto const & tocit : *toc) {
2399 if (tocit.depth() == 0)
2400 list.push_back(tocit.str());
2405 void Buffer::invalidateBibinfoCache() const
2407 d->bibinfo_cache_valid_ = false;
2408 d->cite_labels_valid_ = false;
2409 removeBiblioTempFiles();
2410 // also invalidate the cache for the parent buffer
2411 Buffer const * const pbuf = d->parent();
2413 pbuf->invalidateBibinfoCache();
2417 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2419 // FIXME This is probably unnecessary, given where we call this.
2420 // If this is a child document, use the master instead.
2421 Buffer const * const pbuf = masterBuffer();
2422 if (pbuf != this && scope != UpdateChildOnly)
2423 return pbuf->getBibfiles();
2425 // In 2.3.x, we have:
2426 //if (!d->bibfile_cache_valid_)
2427 // this->updateBibfilesCache(scope);
2428 // I think that is a leftover, but there have been so many back-
2429 // and-forths with this, due to Windows issues, that I am not sure.
2431 return d->bibfiles_cache_;
2435 BiblioInfo const & Buffer::masterBibInfo() const
2437 Buffer const * const tmp = masterBuffer();
2439 return tmp->masterBibInfo();
2444 BiblioInfo const & Buffer::bibInfo() const
2450 void Buffer::registerBibfiles(const docstring_list & bf) const
2452 // We register the bib files in the master buffer,
2453 // if there is one, but also in every single buffer,
2454 // in case a child is compiled alone.
2455 Buffer const * const tmp = masterBuffer();
2457 tmp->registerBibfiles(bf);
2459 for (auto const & p : bf) {
2460 docstring_list::const_iterator temp =
2461 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2462 if (temp == d->bibfiles_cache_.end())
2463 d->bibfiles_cache_.push_back(p);
2468 static map<docstring, FileName> bibfileCache;
2470 FileName Buffer::getBibfilePath(docstring const & bibid) const
2472 map<docstring, FileName>::const_iterator it =
2473 bibfileCache.find(bibid);
2474 if (it != bibfileCache.end()) {
2475 // i.e., return bibfileCache[bibid];
2479 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2480 string const texfile = changeExtension(to_utf8(bibid), "bib");
2481 // we need to check first if this file exists where it's said to be.
2482 // there's a weird bug that occurs otherwise: if the file is in the
2483 // Buffer's directory but has the same name as some file that would be
2484 // found by kpsewhich, then we find the latter, not the former.
2485 FileName const local_file = makeAbsPath(texfile, filePath());
2486 FileName file = local_file;
2487 if (!file.exists()) {
2488 // there's no need now to check whether the file can be found
2490 file = findtexfile(texfile, "bib", true);
2494 LYXERR(Debug::FILES, "Found at: " << file);
2496 bibfileCache[bibid] = file;
2497 return bibfileCache[bibid];
2501 void Buffer::checkIfBibInfoCacheIsValid() const
2503 // use the master's cache
2504 Buffer const * const tmp = masterBuffer();
2506 tmp->checkIfBibInfoCacheIsValid();
2510 // If we already know the cache is invalid, stop here.
2511 // This is important in the case when the bibliography
2512 // environment (rather than Bib[la]TeX) is used.
2513 // In that case, the timestamp check below gives no
2514 // sensible result. Rather than that, the cache will
2515 // be invalidated explicitly via invalidateBibInfoCache()
2516 // by the Bibitem inset.
2517 // Same applies for bib encoding changes, which trigger
2518 // invalidateBibInfoCache() by InsetBibtex.
2519 if (!d->bibinfo_cache_valid_)
2522 if (d->have_bibitems_) {
2523 // We have a bibliography environment.
2524 // Invalidate the bibinfo cache unconditionally.
2525 // Cite labels will get invalidated by the inset if needed.
2526 d->bibinfo_cache_valid_ = false;
2530 // OK. This is with Bib(la)tex. We'll assume the cache
2531 // is valid and change this if we find changes in the bibs.
2532 d->bibinfo_cache_valid_ = true;
2533 d->cite_labels_valid_ = true;
2535 // compare the cached timestamps with the actual ones.
2536 docstring_list const & bibfiles_cache = getBibfiles();
2537 for (auto const & bf : bibfiles_cache) {
2538 FileName const fn = getBibfilePath(bf);
2539 time_t lastw = fn.lastModified();
2540 time_t prevw = d->bibfile_status_[fn];
2541 if (lastw != prevw) {
2542 d->bibinfo_cache_valid_ = false;
2543 d->cite_labels_valid_ = false;
2544 d->bibfile_status_[fn] = lastw;
2550 void Buffer::clearBibFileCache() const
2552 bibfileCache.clear();
2556 void Buffer::reloadBibInfoCache(bool const force) const
2558 // we should not need to do this for internal buffers
2562 // use the master's cache
2563 Buffer const * const tmp = masterBuffer();
2565 tmp->reloadBibInfoCache(force);
2570 checkIfBibInfoCacheIsValid();
2571 if (d->bibinfo_cache_valid_)
2575 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2576 // re-read file locations when this info changes
2577 // FIXME Is this sufficient? Or should we also force that
2578 // in some other cases? If so, then it is easy enough to
2579 // add the following line in some other places.
2580 clearBibFileCache();
2581 d->bibinfo_.clear();
2582 FileNameList checkedFiles;
2583 d->have_bibitems_ = false;
2584 collectBibKeys(checkedFiles);
2585 d->bibinfo_cache_valid_ = true;
2589 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2594 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2595 it->collectBibKeys(it, checkedFiles);
2596 if (it->lyxCode() == BIBITEM_CODE) {
2597 if (parent() != nullptr)
2598 parent()->d->have_bibitems_ = true;
2600 d->have_bibitems_ = true;
2606 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2608 // We add the biblio info to the master buffer,
2609 // if there is one, but also to every single buffer,
2610 // in case a child is compiled alone.
2611 BiblioInfo & bi = d->bibinfo_;
2612 bi.mergeBiblioInfo(bin);
2614 if (parent() != nullptr) {
2615 BiblioInfo & masterbi = parent()->d->bibinfo_;
2616 masterbi.mergeBiblioInfo(bin);
2621 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2623 // We add the bibtex info to the master buffer,
2624 // if there is one, but also to every single buffer,
2625 // in case a child is compiled alone.
2626 BiblioInfo & bi = d->bibinfo_;
2629 if (parent() != nullptr) {
2630 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2631 masterbi[key] = bin;
2636 void Buffer::makeCitationLabels() const
2638 Buffer const * const master = masterBuffer();
2639 return d->bibinfo_.makeCitationLabels(*master);
2643 void Buffer::invalidateCiteLabels() const
2645 masterBuffer()->d->cite_labels_valid_ = false;
2648 bool Buffer::citeLabelsValid() const
2650 return masterBuffer()->d->cite_labels_valid_;
2654 void Buffer::removeBiblioTempFiles() const
2656 // We remove files that contain LaTeX commands specific to the
2657 // particular bibliographic style being used, in order to avoid
2658 // LaTeX errors when we switch style.
2659 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2660 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2661 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2662 aux_file.removeFile();
2663 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2664 bbl_file.removeFile();
2665 // Also for the parent buffer
2666 Buffer const * const pbuf = parent();
2668 pbuf->removeBiblioTempFiles();
2672 bool Buffer::isDepClean(string const & name) const
2674 DepClean::const_iterator const it = d->dep_clean.find(name);
2675 if (it == d->dep_clean.end())
2681 void Buffer::markDepClean(string const & name)
2683 d->dep_clean[name] = true;
2687 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2690 // FIXME? if there is an Buffer LFUN that can be dispatched even
2691 // if internal, put a switch '(cmd.action)' here.
2697 switch (cmd.action()) {
2699 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2700 flag.setOnOff(hasReadonlyFlag());
2703 // FIXME: There is need for a command-line import.
2704 //case LFUN_BUFFER_IMPORT:
2706 case LFUN_BUFFER_AUTO_SAVE:
2709 case LFUN_BUFFER_EXPORT_CUSTOM:
2710 // FIXME: Nothing to check here?
2713 case LFUN_BUFFER_EXPORT: {
2714 docstring const arg = cmd.argument();
2715 if (arg == "custom") {
2719 string format = (arg.empty() || arg == "default") ?
2720 params().getDefaultOutputFormat() : to_utf8(arg);
2721 size_t pos = format.find(' ');
2722 if (pos != string::npos)
2723 format = format.substr(0, pos);
2724 enable = params().isExportable(format, false);
2726 flag.message(bformat(
2727 _("Don't know how to export to format: %1$s"), arg));
2731 case LFUN_BUILD_PROGRAM:
2732 enable = params().isExportable("program", false);
2735 case LFUN_BRANCH_ACTIVATE:
2736 case LFUN_BRANCH_DEACTIVATE:
2737 case LFUN_BRANCH_MASTER_ACTIVATE:
2738 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2739 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2740 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2741 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2742 : params().branchlist();
2743 docstring const branchName = cmd.argument();
2744 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2748 case LFUN_BRANCH_ADD:
2749 case LFUN_BRANCHES_RENAME:
2750 // if no Buffer is present, then of course we won't be called!
2753 case LFUN_BUFFER_LANGUAGE:
2754 enable = !isReadonly();
2757 case LFUN_BUFFER_VIEW_CACHE:
2758 (d->preview_file_).refresh();
2759 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2762 case LFUN_CHANGES_TRACK:
2763 flag.setEnabled(true);
2764 flag.setOnOff(params().track_changes);
2767 case LFUN_CHANGES_OUTPUT:
2768 flag.setEnabled(true);
2769 flag.setOnOff(params().output_changes);
2772 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2773 flag.setOnOff(params().compressed);
2776 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2777 flag.setOnOff(params().output_sync);
2780 case LFUN_BUFFER_ANONYMIZE:
2786 flag.setEnabled(enable);
2791 void Buffer::dispatch(string const & command, DispatchResult & result)
2793 return dispatch(lyxaction.lookupFunc(command), result);
2797 // NOTE We can end up here even if we have no GUI, because we are called
2798 // by LyX::exec to handled command-line requests. So we may need to check
2799 // whether we have a GUI or not. The boolean use_gui holds this information.
2800 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2803 // FIXME? if there is an Buffer LFUN that can be dispatched even
2804 // if internal, put a switch '(cmd.action())' here.
2805 dr.dispatched(false);
2808 string const argument = to_utf8(func.argument());
2809 // We'll set this back to false if need be.
2810 bool dispatched = true;
2811 // This handles undo groups automagically
2812 UndoGroupHelper ugh(this);
2814 switch (func.action()) {
2815 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2816 if (lyxvc().inUse()) {
2817 string log = lyxvc().toggleReadOnly();
2822 setReadonly(!hasReadonlyFlag());
2825 case LFUN_BUFFER_EXPORT: {
2826 string const format = (argument.empty() || argument == "default") ?
2827 params().getDefaultOutputFormat() : argument;
2828 ExportStatus const status = doExport(format, false);
2829 dr.setError(status != ExportSuccess);
2830 if (status != ExportSuccess)
2831 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2832 from_utf8(format)));
2836 case LFUN_BUILD_PROGRAM: {
2837 ExportStatus const status = doExport("program", true);
2838 dr.setError(status != ExportSuccess);
2839 if (status != ExportSuccess)
2840 dr.setMessage(_("Error generating literate programming code."));
2844 case LFUN_BUFFER_EXPORT_CUSTOM: {
2846 string command = split(argument, format_name, ' ');
2847 Format const * format = theFormats().getFormat(format_name);
2849 lyxerr << "Format \"" << format_name
2850 << "\" not recognized!"
2855 // The name of the file created by the conversion process
2858 // Output to filename
2859 if (format->name() == "lyx") {
2860 string const latexname = latexName(false);
2861 filename = changeExtension(latexname,
2862 format->extension());
2863 filename = addName(temppath(), filename);
2865 if (!writeFile(FileName(filename)))
2869 doExport(format_name, true, filename);
2872 // Substitute $$FName for filename
2873 if (!contains(command, "$$FName"))
2874 command = "( " + command + " ) < $$FName";
2875 command = subst(command, "$$FName", filename);
2877 // Execute the command in the background
2879 call.startscript(Systemcall::DontWait, command,
2880 filePath(), layoutPos());
2884 // FIXME: There is need for a command-line import.
2886 case LFUN_BUFFER_IMPORT:
2891 case LFUN_BUFFER_AUTO_SAVE:
2893 resetAutosaveTimers();
2896 case LFUN_BRANCH_ACTIVATE:
2897 case LFUN_BRANCH_DEACTIVATE:
2898 case LFUN_BRANCH_MASTER_ACTIVATE:
2899 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2900 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2901 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2902 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2905 docstring const branch_name = func.argument();
2906 // the case without a branch name is handled elsewhere
2907 if (branch_name.empty()) {
2911 Branch * branch = buf->params().branchlist().find(branch_name);
2913 LYXERR0("Branch " << branch_name << " does not exist.");
2915 docstring const msg =
2916 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2920 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2921 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2922 if (branch->isSelected() != activate) {
2923 buf->undo().recordUndoBufferParams(CursorData());
2924 branch->setSelected(activate);
2926 dr.screenUpdate(Update::Force);
2927 dr.forceBufferUpdate();
2932 case LFUN_BRANCH_ADD: {
2933 docstring branchnames = func.argument();
2934 if (branchnames.empty()) {
2938 BranchList & branch_list = params().branchlist();
2939 vector<docstring> const branches =
2940 getVectorFromString(branchnames, branch_list.separator());
2942 for (docstring const & branch_name : branches) {
2943 Branch * branch = branch_list.find(branch_name);
2945 LYXERR0("Branch " << branch_name << " already exists.");
2949 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2951 undo().recordUndoBufferParams(CursorData());
2952 branch_list.add(branch_name);
2953 branch = branch_list.find(branch_name);
2954 string const x11hexname = X11hexname(branch->color());
2955 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2956 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2958 dr.screenUpdate(Update::Force);
2966 case LFUN_BRANCHES_RENAME: {
2967 if (func.argument().empty())
2970 docstring const oldname = from_utf8(func.getArg(0));
2971 docstring const newname = from_utf8(func.getArg(1));
2972 InsetIterator it = inset_iterator_begin(inset());
2973 InsetIterator const end = inset_iterator_end(inset());
2974 bool success = false;
2975 for (; it != end; ++it) {
2976 if (it->lyxCode() == BRANCH_CODE) {
2977 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2978 if (ins.branch() == oldname) {
2979 undo().recordUndo(CursorData(it));
2980 ins.rename(newname);
2985 if (it->lyxCode() == INCLUDE_CODE) {
2986 // get buffer of external file
2987 InsetInclude const & ins =
2988 static_cast<InsetInclude const &>(*it);
2989 Buffer * child = ins.loadIfNeeded();
2992 child->dispatch(func, dr);
2997 dr.screenUpdate(Update::Force);
2998 dr.forceBufferUpdate();
3003 case LFUN_BUFFER_VIEW_CACHE:
3004 if (!theFormats().view(*this, d->preview_file_,
3005 d->preview_format_))
3006 dr.setMessage(_("Error viewing the output file."));
3009 case LFUN_CHANGES_TRACK:
3010 if (params().save_transient_properties)
3011 undo().recordUndoBufferParams(CursorData());
3012 params().track_changes = !params().track_changes;
3015 case LFUN_CHANGES_OUTPUT:
3016 if (params().save_transient_properties)
3017 undo().recordUndoBufferParams(CursorData());
3018 params().output_changes = !params().output_changes;
3019 if (params().output_changes) {
3020 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
3021 LaTeXFeatures::isAvailable("xcolor");
3024 Alert::warning(_("Changes not shown in LaTeX output"),
3025 _("Changes will not be highlighted in LaTeX output, "
3026 "because xcolor and ulem are not installed.\n"
3027 "Please install both packages or redefine "
3028 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3033 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3034 // turn compression on/off
3035 undo().recordUndoBufferParams(CursorData());
3036 params().compressed = !params().compressed;
3039 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3040 undo().recordUndoBufferParams(CursorData());
3041 params().output_sync = !params().output_sync;
3044 case LFUN_BUFFER_ANONYMIZE: {
3045 undo().recordUndoFullBuffer(CursorData());
3046 CursorData cur(doc_iterator_begin(this));
3047 for ( ; cur ; cur.forwardPar())
3048 cur.paragraph().anonymize();
3049 dr.forceBufferUpdate();
3050 dr.screenUpdate(Update::Force);
3058 dr.dispatched(dispatched);
3062 void Buffer::changeLanguage(Language const * from, Language const * to)
3064 LASSERT(from, return);
3065 LASSERT(to, return);
3067 ParIterator it = par_iterator_begin();
3068 ParIterator eit = par_iterator_end();
3069 for (; it != eit; ++it)
3070 it->changeLanguage(params(), from, to);
3074 bool Buffer::isMultiLingual() const
3076 ParConstIterator end = par_iterator_end();
3077 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3078 if (it->isMultiLingual(params()))
3085 std::set<Language const *> Buffer::getLanguages() const
3087 std::set<Language const *> langs;
3088 getLanguages(langs);
3093 void Buffer::getLanguages(std::set<Language const *> & langs) const
3095 ParConstIterator end = par_iterator_end();
3096 // add the buffer language, even if it's not actively used
3097 langs.insert(language());
3098 // iterate over the paragraphs
3099 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3100 it->getLanguages(langs);
3102 ListOfBuffers clist = getDescendants();
3103 for (auto const & cit : clist)
3104 cit->getLanguages(langs);
3108 DocIterator Buffer::getParFromID(int const id) const
3110 Buffer * buf = const_cast<Buffer *>(this);
3112 // This means non-existent
3113 return doc_iterator_end(buf);
3115 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3116 if (it.paragraph().id() == id)
3119 return doc_iterator_end(buf);
3123 bool Buffer::hasParWithID(int const id) const
3125 return !getParFromID(id).atEnd();
3129 ParIterator Buffer::par_iterator_begin()
3131 return ParIterator(doc_iterator_begin(this));
3135 ParIterator Buffer::par_iterator_end()
3137 return ParIterator(doc_iterator_end(this));
3141 ParConstIterator Buffer::par_iterator_begin() const
3143 return ParConstIterator(doc_iterator_begin(this));
3147 ParConstIterator Buffer::par_iterator_end() const
3149 return ParConstIterator(doc_iterator_end(this));
3153 Language const * Buffer::language() const
3155 return params().language;
3159 docstring Buffer::B_(string const & l10n) const
3161 return params().B_(l10n);
3165 bool Buffer::isClean() const
3167 return d->lyx_clean;
3171 bool Buffer::isChecksumModified() const
3173 LASSERT(d->filename.exists(), return false);
3174 return d->checksum_ != d->filename.checksum();
3178 void Buffer::saveCheckSum() const
3180 FileName const & file = d->filename;
3182 d->checksum_ = file.exists() ? file.checksum()
3183 : 0; // in the case of save to a new file.
3187 void Buffer::markClean() const
3189 if (!d->lyx_clean) {
3190 d->lyx_clean = true;
3193 // if the .lyx file has been saved, we don't need an
3195 d->bak_clean = true;
3196 d->undo_.markDirty();
3197 clearExternalModification();
3201 void Buffer::setUnnamed(bool flag)
3207 bool Buffer::isUnnamed() const
3214 /// Don't check unnamed, here: isInternal() is used in
3215 /// newBuffer(), where the unnamed flag has not been set by anyone
3216 /// yet. Also, for an internal buffer, there should be no need for
3217 /// retrieving fileName() nor for checking if it is unnamed or not.
3218 bool Buffer::isInternal() const
3220 return d->internal_buffer;
3224 void Buffer::setInternal(bool flag)
3226 d->internal_buffer = flag;
3230 void Buffer::markDirty()
3233 d->lyx_clean = false;
3236 d->bak_clean = false;
3238 for (auto & depit : d->dep_clean)
3239 depit.second = false;
3243 FileName Buffer::fileName() const
3249 string Buffer::absFileName() const
3251 return d->filename.absFileName();
3255 string Buffer::filePath() const
3257 string const abs = d->filename.onlyPath().absFileName();
3260 int last = abs.length() - 1;
3262 return abs[last] == '/' ? abs : abs + '/';
3266 DocFileName Buffer::getReferencedFileName(string const & fn) const
3269 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3270 result.set(fn, filePath());
3272 // filePath() ends with a path separator
3273 FileName const test(filePath() + fn);
3275 result.set(fn, filePath());
3277 result.set(fn, params().origin);
3284 string const Buffer::prepareFileNameForLaTeX(string const & name,
3285 string const & ext, bool nice) const
3287 string const fname = makeAbsPath(name, filePath()).absFileName();
3288 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3294 return to_utf8(makeRelPath(from_utf8(fname),
3295 from_utf8(masterBuffer()->filePath())));
3299 vector<pair<docstring, string>> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3300 docstring_list const & bibfilelist,
3301 bool const add_extension) const
3303 // If we are processing the LaTeX file in a temp directory then
3304 // copy the .bib databases to this temp directory, mangling their
3305 // names in the process. Store this mangled name in the list of
3307 // (We need to do all this because BibTeX *really*, *really*
3308 // can't handle "files with spaces" and Windows users tend to
3309 // use such filenames.)
3310 // Otherwise, store the (maybe absolute) path to the original,
3311 // unmangled database name.
3313 vector<pair<docstring, string>> res;
3315 // determine the export format
3316 string const tex_format = flavor2format(runparams.flavor);
3318 // check for spaces in paths
3319 bool found_space = false;
3321 for (auto const & bit : bibfilelist) {
3322 string utf8input = to_utf8(bit);
3324 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3325 FileName try_in_file =
3326 makeAbsPath(database + ".bib", filePath());
3327 bool not_from_texmf = try_in_file.isReadableFile();
3328 // If the file has not been found, try with the real file name
3329 // (it might come from a child in a sub-directory)
3330 if (!not_from_texmf) {
3331 try_in_file = getBibfilePath(bit);
3332 if (try_in_file.isReadableFile()) {
3333 // Check if the file is in texmf
3334 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3335 not_from_texmf = kpsefile.empty()
3336 || kpsefile.absFileName() != try_in_file.absFileName();
3338 // If this exists, make path relative to the master
3341 removeExtension(prepareFileNameForLaTeX(
3342 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3343 from_utf8(filePath()))),
3344 ".bib", runparams.nice));
3348 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3350 // mangledFileName() needs the extension
3351 DocFileName const in_file = DocFileName(try_in_file);
3352 database = removeExtension(in_file.mangledFileName());
3353 FileName const out_file = makeAbsPath(database + ".bib",
3354 masterBuffer()->temppath());
3355 bool const success = in_file.copyTo(out_file);
3357 LYXERR0("Failed to copy '" << in_file
3358 << "' to '" << out_file << "'");
3360 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3361 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3362 if (!isValidLaTeXFileName(database)) {
3363 frontend::Alert::warning(_("Invalid filename"),
3364 _("The following filename will cause troubles "
3365 "when running the exported file through LaTeX: ") +
3366 from_utf8(database));
3368 if (!isValidDVIFileName(database)) {
3369 frontend::Alert::warning(_("Problematic filename for DVI"),
3370 _("The following filename can cause troubles "
3371 "when running the exported file through LaTeX "
3372 "and opening the resulting DVI: ") +
3373 from_utf8(database), true);
3381 docstring const path = from_utf8(latex_path(database));
3383 if (contains(path, ' '))
3386 if (params().useBiblatex() && !params().bibFileEncoding(utf8input).empty())
3387 enc = params().bibFileEncoding(utf8input);
3389 bool recorded = false;
3390 for (auto const & pe : res) {
3391 if (pe.first == path) {
3398 res.push_back(make_pair(path, enc));
3401 // Check if there are spaces in the path and warn BibTeX users, if so.
3402 // (biber can cope with such paths)
3403 if (!prefixIs(runparams.bibtex_command, "biber")) {
3404 // Post this warning only once.
3405 static bool warned_about_spaces = false;
3406 if (!warned_about_spaces &&
3407 runparams.nice && found_space) {
3408 warned_about_spaces = true;
3409 Alert::warning(_("Export Warning!"),
3410 _("There are spaces in the paths to your BibTeX databases.\n"
3411 "BibTeX will be unable to find them."));
3420 string Buffer::layoutPos() const
3422 return d->layout_position;
3426 void Buffer::setLayoutPos(string const & path)
3429 d->layout_position.clear();
3433 LATTEST(FileName::isAbsolute(path));
3435 d->layout_position =
3436 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3438 if (d->layout_position.empty())
3439 d->layout_position = ".";
3443 bool Buffer::hasReadonlyFlag() const
3445 return d->read_only;
3449 bool Buffer::isReadonly() const
3451 return hasReadonlyFlag() || notifiesExternalModification();
3455 void Buffer::setParent(Buffer const * buffer)
3457 // We need to do some work here to avoid recursive parent structures.
3458 // This is the easy case.
3459 if (buffer == this) {
3460 LYXERR0("Ignoring attempt to set self as parent in\n" << fileName());
3463 // Now we check parents going upward, to make sure that IF we set the
3464 // parent as requested, we would not generate a recursive include.
3465 set<Buffer const *> sb;
3466 Buffer const * b = buffer;
3467 bool found_recursion = false;
3469 if (sb.find(b) != sb.end()) {
3470 found_recursion = true;
3477 if (found_recursion) {
3478 LYXERR0("Ignoring attempt to set parent of\n" <<
3481 buffer->fileName() <<
3482 "\nbecause that would create a recursive inclusion.");
3486 // We should be safe now.
3487 d->setParent(buffer);
3492 Buffer const * Buffer::parent() const
3498 ListOfBuffers Buffer::allRelatives() const
3500 ListOfBuffers lb = masterBuffer()->getDescendants();
3501 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3506 Buffer const * Buffer::masterBuffer() const
3508 Buffer const * const pbuf = d->parent();
3512 return pbuf->masterBuffer();
3516 bool Buffer::isChild(Buffer * child) const
3518 return d->children_positions.find(child) != d->children_positions.end();
3522 DocIterator Buffer::firstChildPosition(Buffer const * child)
3524 Impl::BufferPositionMap::iterator it;
3525 it = d->children_positions.find(child);
3526 if (it == d->children_positions.end())
3527 return DocIterator(this);
3532 bool Buffer::hasChildren() const
3534 return !d->children_positions.empty();
3538 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3540 // loop over children
3541 for (auto const & p : d->children_positions) {
3542 Buffer * child = const_cast<Buffer *>(p.first);
3544 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3545 if (bit != clist.end())
3547 clist.push_back(child);
3549 // there might be grandchildren
3550 child->collectChildren(clist, true);
3555 ListOfBuffers Buffer::getChildren() const
3558 collectChildren(v, false);
3559 // Make sure we have not included ourselves.
3560 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3561 if (bit != v.end()) {
3562 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3569 ListOfBuffers Buffer::getDescendants() const
3572 collectChildren(v, true);
3573 // Make sure we have not included ourselves.
3574 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3575 if (bit != v.end()) {
3576 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3583 template<typename M>
3584 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3589 typename M::const_iterator it = m.lower_bound(x);
3590 if (it == m.begin())
3598 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3599 DocIterator const & pos) const
3601 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3603 // if paragraphs have no macro context set, pos will be empty
3607 // we haven't found anything yet
3608 DocIterator bestPos = owner_->par_iterator_begin();
3609 MacroData const * bestData = nullptr;
3611 // find macro definitions for name
3612 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3613 if (nameIt != macros.end()) {
3614 // find last definition in front of pos or at pos itself
3615 PositionScopeMacroMap::const_iterator it
3616 = greatest_below(nameIt->second, pos);
3617 if (it != nameIt->second.end()) {
3619 // scope ends behind pos?
3620 if (pos < it->second.scope) {
3621 // Looks good, remember this. If there
3622 // is no external macro behind this,
3623 // we found the right one already.
3624 bestPos = it->first;
3625 bestData = &it->second.macro;
3629 // try previous macro if there is one
3630 if (it == nameIt->second.begin())
3637 // find macros in included files
3638 PositionScopeBufferMap::const_iterator it
3639 = greatest_below(position_to_children, pos);
3640 if (it == position_to_children.end())
3641 // no children before
3645 // do we know something better (i.e. later) already?
3646 if (it->first < bestPos )
3649 // scope ends behind pos?
3650 if (pos < it->second.scope
3651 && (cloned_buffer_ ||
3652 theBufferList().isLoaded(it->second.buffer))) {
3653 // look for macro in external file
3655 MacroData const * data
3656 = it->second.buffer->getMacro(name, false);
3659 bestPos = it->first;
3665 // try previous file if there is one
3666 if (it == position_to_children.begin())
3671 // return the best macro we have found
3676 MacroData const * Buffer::getMacro(docstring const & name,
3677 DocIterator const & pos, bool global) const
3682 // query buffer macros
3683 MacroData const * data = d->getBufferMacro(name, pos);
3684 if (data != nullptr)
3687 // If there is a master buffer, query that
3688 Buffer const * const pbuf = d->parent();
3690 d->macro_lock = true;
3691 MacroData const * macro = pbuf->getMacro(
3692 name, *this, false);
3693 d->macro_lock = false;
3699 data = MacroTable::globalMacros().get(name);
3700 if (data != nullptr)
3708 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3710 // set scope end behind the last paragraph
3711 DocIterator scope = par_iterator_begin();
3712 scope.pit() = scope.lastpit() + 1;
3714 return getMacro(name, scope, global);
3718 MacroData const * Buffer::getMacro(docstring const & name,
3719 Buffer const & child, bool global) const
3721 // look where the child buffer is included first
3722 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3723 if (it == d->children_positions.end())
3726 // check for macros at the inclusion position
3727 return getMacro(name, it->second, global);
3731 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3733 pit_type const lastpit = it.lastpit();
3735 // look for macros in each paragraph
3736 while (it.pit() <= lastpit) {
3737 Paragraph & par = it.paragraph();
3739 // FIXME Can this be done with the new-style iterators?
3740 // iterate over the insets of the current paragraph
3741 for (auto const & insit : par.insetList()) {
3742 it.pos() = insit.pos;
3744 // is it a nested text inset?
3745 if (insit.inset->asInsetText()) {
3746 // Inset needs its own scope?
3747 InsetText const * itext = insit.inset->asInsetText();
3748 bool newScope = itext->isMacroScope();
3750 // scope which ends just behind the inset
3751 DocIterator insetScope = it;
3754 // collect macros in inset
3755 it.push_back(CursorSlice(*insit.inset));
3756 updateMacros(it, newScope ? insetScope : scope);
3761 if (insit.inset->asInsetTabular()) {
3762 CursorSlice slice(*insit.inset);
3763 size_t const numcells = slice.nargs();
3764 for (; slice.idx() < numcells; slice.forwardIdx()) {
3765 it.push_back(slice);
3766 updateMacros(it, scope);
3772 // is it an external file?
3773 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3774 // get buffer of external file
3775 InsetInclude const & incinset =
3776 static_cast<InsetInclude const &>(*insit.inset);
3778 Buffer * child = incinset.loadIfNeeded();
3783 // register its position, but only when it is
3784 // included first in the buffer
3785 if (children_positions.find(child) ==
3786 children_positions.end())
3787 children_positions[child] = it;
3789 // register child with its scope
3790 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3794 InsetMath * im = insit.inset->asInsetMath();
3795 if (doing_export && im) {
3796 InsetMathHull * hull = im->asHullInset();
3798 hull->recordLocation(it);
3801 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3805 InsetMathMacroTemplate & macroTemplate =
3806 *insit.inset->asInsetMath()->asMacroTemplate();
3807 MacroContext mc(owner_, it);
3808 macroTemplate.updateToContext(mc);
3811 bool valid = macroTemplate.validMacro();
3812 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3813 // then the BufferView's cursor will be invalid in
3814 // some cases which leads to crashes.
3819 // FIXME (Abdel), I don't understand why we pass 'it' here
3820 // instead of 'macroTemplate' defined above... is this correct?
3821 macros[macroTemplate.name()][it] =
3822 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3832 void Buffer::updateMacros() const
3837 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3839 // start with empty table
3841 d->children_positions.clear();
3842 d->position_to_children.clear();
3844 // Iterate over buffer, starting with first paragraph
3845 // The scope must be bigger than any lookup DocIterator
3846 // later. For the global lookup, lastpit+1 is used, hence
3847 // we use lastpit+2 here.
3848 DocIterator it = par_iterator_begin();
3849 DocIterator outerScope = it;
3850 outerScope.pit() = outerScope.lastpit() + 2;
3851 d->updateMacros(it, outerScope);
3855 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3857 InsetIterator it = inset_iterator_begin(inset());
3858 InsetIterator const end = inset_iterator_end(inset());
3859 for (; it != end; ++it) {
3860 if (it->lyxCode() == BRANCH_CODE) {
3861 InsetBranch & br = static_cast<InsetBranch &>(*it);
3862 docstring const name = br.branch();
3863 if (!from_master && !params().branchlist().find(name))
3864 result.push_back(name);
3865 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3866 result.push_back(name);
3869 if (it->lyxCode() == INCLUDE_CODE) {
3870 // get buffer of external file
3871 InsetInclude const & ins =
3872 static_cast<InsetInclude const &>(*it);
3873 Buffer * child = ins.loadIfNeeded();
3876 child->getUsedBranches(result, true);
3879 // remove duplicates
3884 void Buffer::updateMacroInstances(UpdateType utype) const
3886 LYXERR(Debug::MACROS, "updateMacroInstances for "
3887 << d->filename.onlyFileName());
3888 DocIterator it = doc_iterator_begin(this);
3890 DocIterator const end = doc_iterator_end(this);
3891 for (; it != end; it.forwardInset()) {
3892 // look for MathData cells in InsetMathNest insets
3893 InsetMath * minset = it.nextInset()->asInsetMath();
3897 // update macro in all cells of the InsetMathNest
3898 DocIterator::idx_type n = minset->nargs();
3899 MacroContext mc = MacroContext(this, it);
3900 for (DocIterator::idx_type i = 0; i < n; ++i) {
3901 MathData & data = minset->cell(i);
3902 data.updateMacros(nullptr, mc, utype, 0);
3908 void Buffer::listMacroNames(MacroNameSet & macros) const
3913 d->macro_lock = true;
3915 // loop over macro names
3916 for (auto const & nameit : d->macros)
3917 macros.insert(nameit.first);
3919 // loop over children
3920 for (auto const & p : d->children_positions) {
3921 Buffer * child = const_cast<Buffer *>(p.first);
3922 // The buffer might have been closed (see #10766).
3923 if (theBufferList().isLoaded(child))
3924 child->listMacroNames(macros);
3928 Buffer const * const pbuf = d->parent();
3930 pbuf->listMacroNames(macros);
3932 d->macro_lock = false;
3936 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3938 Buffer const * const pbuf = d->parent();
3943 pbuf->listMacroNames(names);
3946 for (auto const & mit : names) {
3948 MacroData const * data = pbuf->getMacro(mit, *this, false);
3950 macros.insert(data);
3952 // we cannot access the original InsetMathMacroTemplate anymore
3953 // here to calls validate method. So we do its work here manually.
3954 // FIXME: somehow make the template accessible here.
3955 if (data->optionals() > 0)
3956 features.require("xargs");
3962 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3965 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3967 RefCache::iterator it = d->ref_cache_.find(label);
3968 if (it != d->ref_cache_.end())
3971 static References const dummy_refs = References();
3972 it = d->ref_cache_.insert(
3973 make_pair(label, dummy_refs)).first;
3978 Buffer::References const & Buffer::references(docstring const & label) const
3980 return const_cast<Buffer *>(this)->getReferenceCache(label);
3984 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3986 References & refs = getReferenceCache(label);
3987 refs.push_back(make_pair(inset, it));
3991 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3995 linfo.label = label;
3997 linfo.active = active;
3998 masterBuffer()->d->label_cache_.push_back(linfo);
4002 InsetLabel const * Buffer::insetLabel(docstring const & label,
4003 bool const active) const
4005 for (auto const & rc : masterBuffer()->d->label_cache_) {
4006 if (rc.label == label && (rc.active || !active))
4013 bool Buffer::activeLabel(docstring const & label) const
4015 if (!insetLabel(label, true))
4022 void Buffer::clearReferenceCache() const
4025 d->ref_cache_.clear();
4026 d->label_cache_.clear();
4031 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
4033 //FIXME: This does not work for child documents yet.
4034 reloadBibInfoCache();
4036 // Check if the label 'from' appears more than once
4037 vector<docstring> labels;
4038 for (auto const & bibit : masterBibInfo())
4039 labels.push_back(bibit.first);
4041 if (count(labels.begin(), labels.end(), from) > 1)
4044 string const paramName = "key";
4045 UndoGroupHelper ugh(this);
4046 InsetIterator it = inset_iterator_begin(inset());
4048 if (it->lyxCode() != CITE_CODE)
4050 InsetCommand * inset = it->asInsetCommand();
4051 docstring const oldValue = inset->getParam(paramName);
4052 if (oldValue == from) {
4053 undo().recordUndo(CursorData(it));
4054 inset->setParam(paramName, to);
4059 // returns NULL if id-to-row conversion is unsupported
4060 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4061 pit_type par_begin, pit_type par_end,
4062 OutputWhat output, bool master) const
4064 unique_ptr<TexRow> texrow;
4065 OutputParams runparams(¶ms().encoding());
4066 runparams.nice = true;
4067 runparams.flavor = params().getOutputFlavor(format);
4068 runparams.linelen = lyxrc.plaintext_linelen;
4069 // No side effect of file copying and image conversion
4070 runparams.dryrun = true;
4072 // Some macros rely on font encoding
4073 runparams.main_fontenc = params().main_font_encoding();
4075 if (output == CurrentParagraph) {
4076 runparams.par_begin = par_begin;
4077 runparams.par_end = par_end;
4078 if (par_begin + 1 == par_end) {
4080 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4084 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4085 convert<docstring>(par_begin),
4086 convert<docstring>(par_end - 1))
4089 // output paragraphs
4090 if (runparams.flavor == OutputParams::LYX) {
4091 Paragraph const & par = text().paragraphs()[par_begin];
4093 depth_type dt = par.getDepth();
4094 par.write(ods, params(), dt);
4095 os << from_utf8(ods.str());
4096 } else if (runparams.flavor == OutputParams::HTML) {
4098 setMathFlavor(runparams);
4099 xhtmlParagraphs(text(), *this, xs, runparams);
4100 } else if (runparams.flavor == OutputParams::TEXT) {
4102 // FIXME Handles only one paragraph, unlike the others.
4103 // Probably should have some routine with a signature like them.
4104 writePlaintextParagraph(*this,
4105 text().paragraphs()[par_begin], os, runparams, dummy);
4106 } else if (runparams.flavor == OutputParams::DOCBOOK5) {
4108 docbookParagraphs(text(), *this, xs, runparams);
4110 // If we are previewing a paragraph, even if this is the
4111 // child of some other buffer, let's cut the link here,
4112 // so that no concurring settings from the master
4113 // (e.g. branch state) interfere (see #8101).
4115 d->ignore_parent = true;
4116 // We need to validate the Buffer params' features here
4117 // in order to know if we should output polyglossia
4118 // macros (instead of babel macros)
4119 LaTeXFeatures features(*this, params(), runparams);
4121 runparams.use_polyglossia = features.usePolyglossia();
4122 runparams.use_hyperref = features.isRequired("hyperref");
4123 // latex or literate
4126 ots.texrow().newlines(2);
4128 latexParagraphs(*this, text(), ots, runparams);
4129 texrow = ots.releaseTexRow();
4131 // Restore the parenthood
4133 d->ignore_parent = false;
4137 if (output == FullSource)
4138 os << _("Preview source code");
4139 else if (output == OnlyPreamble)
4140 os << _("Preview preamble");
4141 else if (output == OnlyBody)
4142 os << _("Preview body");
4144 if (runparams.flavor == OutputParams::LYX) {
4146 if (output == FullSource)
4148 else if (output == OnlyPreamble)
4149 params().writeFile(ods, this);
4150 else if (output == OnlyBody)
4152 os << from_utf8(ods.str());
4153 } else if (runparams.flavor == OutputParams::HTML) {
4154 writeLyXHTMLSource(os, runparams, output);
4155 } else if (runparams.flavor == OutputParams::TEXT) {
4156 if (output == OnlyPreamble) {
4157 os << "% "<< _("Plain text does not have a preamble.");
4159 writePlaintextFile(*this, os, runparams);
4160 } else if (runparams.flavor == OutputParams::DOCBOOK5) {
4161 writeDocBookSource(os, runparams, output);
4163 // latex or literate
4166 ots.texrow().newlines(2);
4168 runparams.is_child = true;
4170 writeLaTeXSource(ots, string(), runparams, output);
4171 texrow = ots.releaseTexRow();
4178 ErrorList & Buffer::errorList(string const & type) const
4180 return d->errorLists[type];
4184 void Buffer::updateTocItem(std::string const & type,
4185 DocIterator const & dit) const
4188 d->gui_->updateTocItem(type, dit);
4192 void Buffer::structureChanged() const
4195 d->gui_->structureChanged();
4199 void Buffer::errors(string const & err, bool from_master) const
4202 d->gui_->errors(err, from_master);
4206 void Buffer::message(docstring const & msg) const
4209 d->gui_->message(msg);
4213 void Buffer::setBusy(bool on) const
4216 d->gui_->setBusy(on);
4220 void Buffer::updateTitles() const
4223 d->wa_->updateTitles();
4227 void Buffer::resetAutosaveTimers() const
4230 d->gui_->resetAutosaveTimers();
4234 bool Buffer::hasGuiDelegate() const
4240 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4246 FileName Buffer::getEmergencyFileName() const
4248 return FileName(d->filename.absFileName() + ".emergency");
4252 FileName Buffer::getAutosaveFileName() const
4254 // if the document is unnamed try to save in the backup dir, else
4255 // in the default document path, and as a last try in the filePath,
4256 // which will most often be the temporary directory
4259 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4260 : lyxrc.backupdir_path;
4261 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4264 string const fname = "#" + d->filename.onlyFileName() + "#";
4266 return makeAbsPath(fname, fpath);
4270 void Buffer::removeAutosaveFile() const
4272 FileName const f = getAutosaveFileName();
4278 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4280 FileName const newauto = getAutosaveFileName();
4282 if (newauto != oldauto && oldauto.exists())
4283 if (!oldauto.moveTo(newauto))
4284 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4288 bool Buffer::autoSave() const
4290 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4291 if (buf->d->bak_clean || hasReadonlyFlag())
4294 message(_("Autosaving current document..."));
4295 buf->d->bak_clean = true;
4297 FileName const fname = getAutosaveFileName();
4298 LASSERT(d->cloned_buffer_, return false);
4300 // If this buffer is cloned, we assume that
4301 // we are running in a separate thread already.
4302 TempFile tempfile("lyxautoXXXXXX.lyx");
4303 tempfile.setAutoRemove(false);
4304 FileName const tmp_ret = tempfile.name();
4305 if (!tmp_ret.empty()) {
4307 // assume successful write of tmp_ret
4308 if (tmp_ret.moveTo(fname))
4311 // failed to write/rename tmp_ret so try writing direct
4312 return writeFile(fname);
4316 void Buffer::setExportStatus(bool e) const
4318 d->doing_export = e;
4319 ListOfBuffers clist = getDescendants();
4320 for (auto const & bit : clist)
4321 bit->d->doing_export = e;
4325 bool Buffer::isExporting() const
4327 return d->doing_export;
4331 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4335 return doExport(target, put_in_tempdir, result_file);
4338 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4339 string & result_file) const
4341 bool const update_unincluded =
4342 params().maintain_unincluded_children != BufferParams::CM_None
4343 && !params().getIncludedChildren().empty();
4345 // (1) export with all included children (omit \includeonly)
4346 if (update_unincluded) {
4347 ExportStatus const status =
4348 doExport(target, put_in_tempdir, true, result_file);
4349 if (status != ExportSuccess)
4352 // (2) export with included children only
4353 return doExport(target, put_in_tempdir, false, result_file);
4357 void Buffer::setMathFlavor(OutputParams & op) const
4359 switch (params().html_math_output) {
4360 case BufferParams::MathML:
4361 op.math_flavor = OutputParams::MathAsMathML;
4363 case BufferParams::HTML:
4364 op.math_flavor = OutputParams::MathAsHTML;
4366 case BufferParams::Images:
4367 op.math_flavor = OutputParams::MathAsImages;
4369 case BufferParams::LaTeX:
4370 op.math_flavor = OutputParams::MathAsLaTeX;
4376 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4377 bool includeall, string & result_file) const
4379 LYXERR(Debug::FILES, "target=" << target);
4380 OutputParams runparams(¶ms().encoding());
4381 string format = target;
4382 string dest_filename;
4383 size_t pos = target.find(' ');
4384 if (pos != string::npos) {
4385 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4386 format = target.substr(0, pos);
4387 if (format == "default")
4388 format = params().getDefaultOutputFormat();
4389 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4390 FileName(dest_filename).onlyPath().createPath();
4391 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4393 MarkAsExporting exporting(this);
4394 string backend_format;
4395 runparams.flavor = OutputParams::LATEX;
4396 runparams.linelen = lyxrc.plaintext_linelen;
4397 runparams.includeall = includeall;
4398 vector<string> backs = params().backends();
4399 Converters converters = theConverters();
4400 bool need_nice_file = false;
4401 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4402 // Get shortest path to format
4403 converters.buildGraph();
4404 Graph::EdgePath path;
4405 for (string const & sit : backs) {
4406 Graph::EdgePath p = converters.getPath(sit, format);
4407 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4408 backend_format = sit;
4413 if (!put_in_tempdir) {
4414 // Only show this alert if this is an export to a non-temporary
4415 // file (not for previewing).
4416 docstring s = bformat(_("No information for exporting the format %1$s."),
4417 theFormats().prettyName(format));
4418 if (format == "pdf4")
4420 + bformat(_("Hint: use non-TeX fonts or set input encoding "
4421 " to '%1$s'"), from_utf8(encodings.fromLyXName("ascii")->guiName()));
4422 Alert::error(_("Couldn't export file"), s);
4424 return ExportNoPathToFormat;
4426 runparams.flavor = converters.getFlavor(path, this);
4427 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4428 for (auto const & edge : path)
4429 if (theConverters().get(edge).nice()) {
4430 need_nice_file = true;
4435 backend_format = format;
4436 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4437 // FIXME: Don't hardcode format names here, but use a flag
4438 if (backend_format == "pdflatex")
4439 runparams.flavor = OutputParams::PDFLATEX;
4440 else if (backend_format == "luatex")
4441 runparams.flavor = OutputParams::LUATEX;
4442 else if (backend_format == "dviluatex")
4443 runparams.flavor = OutputParams::DVILUATEX;
4444 else if (backend_format == "xetex")
4445 runparams.flavor = OutputParams::XETEX;
4448 string filename = latexName(false);
4449 filename = addName(temppath(), filename);
4450 filename = changeExtension(filename,
4451 theFormats().extension(backend_format));
4452 LYXERR(Debug::FILES, "filename=" << filename);
4454 // Plain text backend
4455 if (backend_format == "text") {
4456 runparams.flavor = OutputParams::TEXT;
4458 writePlaintextFile(*this, FileName(filename), runparams);
4460 catch (ConversionException const &) { return ExportCancel; }
4463 else if (backend_format == "xhtml") {
4464 runparams.flavor = OutputParams::HTML;
4465 setMathFlavor(runparams);
4466 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4467 return ExportKilled;
4468 } else if (backend_format == "lyx")
4469 writeFile(FileName(filename));
4471 else if (backend_format == "docbook5") {
4472 runparams.flavor = OutputParams::DOCBOOK5;
4473 runparams.nice = !put_in_tempdir;
4474 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4475 return ExportKilled;
4478 else if (backend_format == format || need_nice_file) {
4479 runparams.nice = true;
4480 ExportStatus const retval =
4481 makeLaTeXFile(FileName(filename), string(), runparams);
4482 if (retval == ExportKilled)
4483 return ExportKilled;
4484 if (d->cloned_buffer_)
4485 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4486 if (retval != ExportSuccess)
4488 } else if (!lyxrc.tex_allows_spaces
4489 && contains(filePath(), ' ')) {
4490 Alert::error(_("File name error"),
4491 bformat(_("The directory path to the document\n%1$s\n"
4492 "contains spaces, but your TeX installation does "
4493 "not allow them. You should save the file to a directory "
4494 "whose name does not contain spaces."), from_utf8(filePath())));
4495 return ExportTexPathHasSpaces;
4497 runparams.nice = false;
4498 ExportStatus const retval =
4499 makeLaTeXFile(FileName(filename), filePath(), runparams);
4500 if (retval == ExportKilled)
4501 return ExportKilled;
4502 if (d->cloned_buffer_)
4503 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4504 if (retval != ExportSuccess)
4508 string const error_type = (format == "program")
4509 ? "Build" : params().bufferFormat();
4510 ErrorList & error_list = d->errorLists[error_type];
4511 string const ext = theFormats().extension(format);
4512 FileName const tmp_result_file(changeExtension(filename, ext));
4513 Converters::RetVal const retval =
4514 converters.convert(this, FileName(filename), tmp_result_file,
4515 FileName(absFileName()), backend_format, format,
4516 error_list, Converters::none, includeall);
4517 if (retval == Converters::KILLED)
4518 return ExportCancel;
4519 bool success = (retval == Converters::SUCCESS);
4521 // Emit the signal to show the error list or copy it back to the
4522 // cloned Buffer so that it can be emitted afterwards.
4523 if (format != backend_format) {
4524 if (runparams.silent)
4526 else if (d->cloned_buffer_)
4527 d->cloned_buffer_->d->errorLists[error_type] =
4528 d->errorLists[error_type];
4531 // also to the children, in case of master-buffer-view
4532 ListOfBuffers clist = getDescendants();
4533 for (auto const & bit : clist) {
4534 if (runparams.silent)
4535 bit->d->errorLists[error_type].clear();
4536 else if (d->cloned_buffer_) {
4537 // Enable reverse search by copying back the
4538 // texrow object to the cloned buffer.
4539 // FIXME: this is not thread safe.
4540 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4541 bit->d->cloned_buffer_->d->errorLists[error_type] =
4542 bit->d->errorLists[error_type];
4544 bit->errors(error_type, true);
4548 if (d->cloned_buffer_) {
4549 // Enable reverse dvi or pdf to work by copying back the texrow
4550 // object to the cloned buffer.
4551 // FIXME: There is a possibility of concurrent access to texrow
4552 // here from the main GUI thread that should be securized.
4553 d->cloned_buffer_->d->texrow = d->texrow;
4554 string const err_type = params().bufferFormat();
4555 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4559 if (put_in_tempdir) {
4560 result_file = tmp_result_file.absFileName();
4561 return success ? ExportSuccess : ExportConverterError;
4564 if (dest_filename.empty())
4565 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4567 result_file = dest_filename;
4568 // We need to copy referenced files (e. g. included graphics
4569 // if format == "dvi") to the result dir.
4570 vector<ExportedFile> const extfiles =
4571 runparams.exportdata->externalFiles(format);
4572 string const dest = runparams.export_folder.empty() ?
4573 onlyPath(result_file) : runparams.export_folder;
4574 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4575 : force_overwrite == ALL_FILES;
4576 CopyStatus status = use_force ? FORCE : SUCCESS;
4578 for (ExportedFile const & exp : extfiles) {
4579 if (status == CANCEL) {
4580 message(_("Document export cancelled."));
4581 return ExportCancel;
4583 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4584 string fixedName = exp.exportName;
4585 if (!runparams.export_folder.empty()) {
4586 // Relative pathnames starting with ../ will be sanitized
4587 // if exporting to a different folder
4588 while (fixedName.substr(0, 3) == "../")
4589 fixedName = fixedName.substr(3, fixedName.length() - 3);
4591 FileName fixedFileName = makeAbsPath(fixedName, dest);
4592 fixedFileName.onlyPath().createPath();
4593 status = copyFile(fmt, exp.sourceName,
4595 exp.exportName, status == FORCE,
4596 runparams.export_folder.empty());
4600 if (tmp_result_file.exists()) {
4601 // Finally copy the main file
4602 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4603 : force_overwrite != NO_FILES;
4604 if (status == SUCCESS && use_force)
4606 status = copyFile(format, tmp_result_file,
4607 FileName(result_file), result_file,
4609 if (status == CANCEL) {
4610 message(_("Document export cancelled."));
4611 return ExportCancel;
4613 message(bformat(_("Document exported as %1$s "
4615 theFormats().prettyName(format),
4616 makeDisplayPath(result_file)));
4619 // This must be a dummy converter like fax (bug 1888)
4620 message(bformat(_("Document exported as %1$s"),
4621 theFormats().prettyName(format)));
4624 return success ? ExportSuccess : ExportConverterError;
4628 Buffer::ExportStatus Buffer::preview(string const & format) const
4630 bool const update_unincluded =
4631 params().maintain_unincluded_children != BufferParams::CM_None
4632 && !params().getIncludedChildren().empty();
4633 return preview(format, update_unincluded);
4637 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4639 MarkAsExporting exporting(this);
4641 // (1) export with all included children (omit \includeonly)
4643 ExportStatus const status = doExport(format, true, true, result_file);
4644 if (status != ExportSuccess)
4647 // (2) export with included children only
4648 ExportStatus const status = doExport(format, true, false, result_file);
4649 FileName const previewFile(result_file);
4651 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4652 theimpl->preview_file_ = previewFile;
4653 theimpl->preview_format_ = format;
4654 theimpl->require_fresh_start_ = (status != ExportSuccess);
4656 if (status != ExportSuccess)
4659 if (previewFile.exists())
4660 return theFormats().view(*this, previewFile, format) ?
4661 PreviewSuccess : PreviewError;
4663 // Successful export but no output file?
4664 // Probably a bug in error detection.
4665 LATTEST(status != ExportSuccess);
4670 Buffer::ReadStatus Buffer::extractFromVC()
4672 bool const found = LyXVC::file_not_found_hook(d->filename);
4674 return ReadFileNotFound;
4675 if (!d->filename.isReadableFile())
4681 Buffer::ReadStatus Buffer::loadEmergency()
4683 FileName const emergencyFile = getEmergencyFileName();
4684 if (!emergencyFile.exists()
4685 || emergencyFile.lastModified() <= d->filename.lastModified())
4686 return ReadFileNotFound;
4688 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4689 docstring const text = bformat(_("An emergency save of the document "
4690 "%1$s exists.\n\nRecover emergency save?"), file);
4692 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4693 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4699 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4700 bool const success = (ret_llf == ReadSuccess);
4702 if (hasReadonlyFlag()) {
4703 Alert::warning(_("File is read-only"),
4704 bformat(_("An emergency file is successfully loaded, "
4705 "but the original file %1$s is marked read-only. "
4706 "Please make sure to save the document as a different "
4707 "file."), from_utf8(d->filename.absFileName())));
4710 lyxvc().file_found_hook(d->filename);
4711 str = _("Document was successfully recovered.");
4713 str = _("Document was NOT successfully recovered.");
4714 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4715 makeDisplayPath(emergencyFile.absFileName()));
4717 int const del_emerg =
4718 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4719 _("&Remove"), _("&Keep"));
4720 if (del_emerg == 0) {
4721 emergencyFile.removeFile();
4723 Alert::warning(_("Emergency file deleted"),
4724 _("Do not forget to save your file now!"), true);
4726 return success ? ReadSuccess : ReadEmergencyFailure;
4729 int const del_emerg =
4730 Alert::prompt(_("Delete emergency file?"),
4731 _("Remove emergency file now?"), 1, 1,
4732 _("&Remove"), _("&Keep"));
4734 emergencyFile.removeFile();
4738 string const ename = emergencyFile.absFileName();
4740 // Surely we can find one in 100 tries?
4741 for (int i = 1; i < 100; ++i) {
4742 newname.set(ename + to_string(i) + ".lyx");
4743 if (!newname.exists()) {
4749 // renameTo returns true on success. So inverting that
4750 // will give us true if we fail.
4751 noname = !emergencyFile.renameTo(newname);
4754 Alert::warning(_("Can't rename emergency file!"),
4755 _("LyX was unable to rename the emergency file. "
4756 "You should do so manually. Otherwise, you will be "
4757 "asked about it again the next time you try to load "
4758 "this file, and may over-write your own work."));
4760 Alert::warning(_("Emergency File Renames"),
4761 bformat(_("Emergency file renamed as:\n %1$s"),
4762 from_utf8(newname.onlyFileName())));
4765 return ReadOriginal;
4775 Buffer::ReadStatus Buffer::loadAutosave()
4777 // Now check if autosave file is newer.
4778 FileName const autosaveFile = getAutosaveFileName();
4779 if (!autosaveFile.exists()
4780 || autosaveFile.lastModified() <= d->filename.lastModified())
4781 return ReadFileNotFound;
4783 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4784 docstring const text = bformat(_("The backup of the document %1$s "
4785 "is newer.\n\nLoad the backup instead?"), file);
4786 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4787 _("&Load backup"), _("Load &original"), _("&Cancel"));
4792 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4793 // the file is not saved if we load the autosave file.
4794 if (ret_llf == ReadSuccess) {
4795 if (hasReadonlyFlag()) {
4796 Alert::warning(_("File is read-only"),
4797 bformat(_("A backup file is successfully loaded, "
4798 "but the original file %1$s is marked read-only. "
4799 "Please make sure to save the document as a "
4801 from_utf8(d->filename.absFileName())));
4804 lyxvc().file_found_hook(d->filename);
4807 return ReadAutosaveFailure;
4810 // Here we delete the autosave
4811 autosaveFile.removeFile();
4812 return ReadOriginal;
4820 Buffer::ReadStatus Buffer::loadLyXFile()
4822 if (!d->filename.isReadableFile()) {
4823 ReadStatus const ret_rvc = extractFromVC();
4824 if (ret_rvc != ReadSuccess)
4828 ReadStatus const ret_re = loadEmergency();
4829 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4832 ReadStatus const ret_ra = loadAutosave();
4833 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4836 return loadThisLyXFile(d->filename);
4840 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4842 return readFile(fn);
4846 void Buffer::Impl::traverseErrors(TeXErrors::Errors::const_iterator err, TeXErrors::Errors::const_iterator end, ErrorList & errorList) const
4848 for (; err != end; ++err) {
4849 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4850 int errorRow = err->error_in_line;
4851 Buffer const * buf = nullptr;
4852 Impl const * p = this;
4853 if (err->child_name.empty())
4854 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4856 // The error occurred in a child
4857 for (Buffer const * child : owner_->getDescendants()) {
4858 string const child_name =
4859 DocFileName(changeExtension(child->absFileName(), "tex")).
4861 if (err->child_name != child_name)
4863 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4864 if (!TexRow::isNone(start)) {
4865 buf = this->cloned_buffer_
4866 ? child->d->cloned_buffer_->d->owner_
4873 errorList.push_back(ErrorItem(err->error_desc, err->error_text,
4879 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4881 TeXErrors::Errors::const_iterator err = terr.begin();
4882 TeXErrors::Errors::const_iterator end = terr.end();
4884 d->traverseErrors(err, end, errorList);
4888 void Buffer::bufferRefs(TeXErrors const & terr, ErrorList & errorList) const
4890 TeXErrors::Errors::const_iterator err = terr.begin_ref();
4891 TeXErrors::Errors::const_iterator end = terr.end_ref();
4893 d->traverseErrors(err, end, errorList);
4897 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4899 LBUFERR(!text().paragraphs().empty());
4901 // Use the master text class also for child documents
4902 Buffer const * const master = masterBuffer();
4903 DocumentClass const & textclass = master->params().documentClass();
4905 docstring_list old_bibfiles;
4906 // Do this only if we are the top-level Buffer. We also need to account
4907 // for the case of a previewed child with ignored parent here.
4908 if (master == this && !d->ignore_parent) {
4909 textclass.counters().reset(from_ascii("bibitem"));
4910 reloadBibInfoCache();
4911 // we will re-read this cache as we go through, but we need
4912 // to know whether it's changed to know whether we need to
4913 // update the bibinfo cache.
4914 old_bibfiles = d->bibfiles_cache_;
4915 d->bibfiles_cache_.clear();
4918 // keep the buffers to be children in this set. If the call from the
4919 // master comes back we can see which of them were actually seen (i.e.
4920 // via an InsetInclude). The remaining ones in the set need still be updated.
4921 static std::set<Buffer const *> bufToUpdate;
4922 if (scope == UpdateMaster) {
4923 // If this is a child document start with the master
4924 if (master != this) {
4925 bufToUpdate.insert(this);
4926 master->updateBuffer(UpdateMaster, utype);
4927 // If the master buffer has no gui associated with it, then the TocModel is
4928 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4929 // (bug 5699). The same happens if the master buffer is open in a different
4930 // window. This test catches both possibilities.
4931 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4932 // There remains a problem here: If there is another child open in yet a third
4933 // window, that TOC is not updated. So some more general solution is needed at
4935 if (master->d->gui_ != d->gui_)
4938 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4939 if (bufToUpdate.find(this) == bufToUpdate.end())
4943 // start over the counters in the master
4944 textclass.counters().reset();
4947 // update will be done below for this buffer
4948 bufToUpdate.erase(this);
4950 // update all caches
4951 clearReferenceCache();
4954 Buffer & cbuf = const_cast<Buffer &>(*this);
4955 // if we are reloading, then we could have a dangling TOC,
4956 // in effect. so we need to go ahead and reset, even though
4957 // we will do so again when we rebuild the TOC later.
4958 cbuf.tocBackend().reset();
4961 ParIterator parit = cbuf.par_iterator_begin();
4962 if (scope == UpdateMaster)
4964 updateBuffer(parit, utype);
4966 // If this document has siblings, then update the TocBackend later. The
4967 // reason is to ensure that later siblings are up to date when e.g. the
4968 // broken or not status of references is computed. The update is called
4969 // in InsetInclude::addToToc.
4973 // if the bibfiles changed, the cache of bibinfo is invalid
4974 docstring_list new_bibfiles = d->bibfiles_cache_;
4975 // this is a trick to determine whether the two vectors have
4976 // the same elements.
4977 sort(new_bibfiles.begin(), new_bibfiles.end());
4978 sort(old_bibfiles.begin(), old_bibfiles.end());
4979 if (old_bibfiles != new_bibfiles) {
4980 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4981 invalidateBibinfoCache();
4982 reloadBibInfoCache();
4983 // We relied upon the bibinfo cache when recalculating labels. But that
4984 // cache was invalid, although we didn't find that out until now. So we
4985 // have to do it all again.
4986 // That said, the only thing we really need to do is update the citation
4987 // labels. Nothing else will have changed. So we could create a new
4988 // UpdateType that would signal that fact, if we needed to do so.
4989 parit = cbuf.par_iterator_begin();
4990 // we will be re-doing the counters and references and such.
4991 textclass.counters().reset();
4992 clearReferenceCache();
4993 // we should not need to do this again?
4995 updateBuffer(parit, utype);
4996 // this will already have been done by reloadBibInfoCache();
4997 // d->bibinfo_cache_valid_ = true;
5000 LYXERR(Debug::FILES, "Bibfiles unchanged.");
5001 // this is also set to true on the other path, by reloadBibInfoCache.
5002 d->bibinfo_cache_valid_ = true;
5004 d->cite_labels_valid_ = true;
5007 cbuf.tocBackend().update(true, utype);
5008 if (scope == UpdateMaster)
5009 cbuf.structureChanged();
5013 static depth_type getDepth(DocIterator const & it)
5015 depth_type depth = 0;
5016 for (size_t i = 0 ; i < it.depth() ; ++i)
5017 if (!it[i].inset().inMathed())
5018 depth += it[i].paragraph().getDepth() + 1;
5019 // remove 1 since the outer inset does not count
5020 // we should have at least one non-math inset, so
5021 // depth should nevery be 0. but maybe it is worth
5022 // marking this, just in case.
5024 // coverity[INTEGER_OVERFLOW]
5028 static depth_type getItemDepth(ParIterator const & it)
5030 Paragraph const & par = *it;
5031 LabelType const labeltype = par.layout().labeltype;
5033 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5036 // this will hold the lowest depth encountered up to now.
5037 depth_type min_depth = getDepth(it);
5038 ParIterator prev_it = it;
5041 --prev_it.top().pit();
5043 // start of nested inset: go to outer par
5045 if (prev_it.empty()) {
5046 // start of document: nothing to do
5051 // We search for the first paragraph with same label
5052 // that is not more deeply nested.
5053 Paragraph & prev_par = *prev_it;
5054 depth_type const prev_depth = getDepth(prev_it);
5055 if (labeltype == prev_par.layout().labeltype) {
5056 if (prev_depth < min_depth)
5057 return prev_par.itemdepth + 1;
5058 if (prev_depth == min_depth)
5059 return prev_par.itemdepth;
5061 min_depth = min(min_depth, prev_depth);
5062 // small optimization: if we are at depth 0, we won't
5063 // find anything else
5064 if (prev_depth == 0)
5070 static bool needEnumCounterReset(ParIterator const & it)
5072 Paragraph const & par = *it;
5073 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5074 depth_type const cur_depth = par.getDepth();
5075 ParIterator prev_it = it;
5076 while (prev_it.pit()) {
5077 --prev_it.top().pit();
5078 Paragraph const & prev_par = *prev_it;
5079 if (prev_par.getDepth() <= cur_depth)
5080 return prev_par.layout().name() != par.layout().name();
5082 // start of nested inset: reset
5087 // set the label of a paragraph. This includes the counters.
5088 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5090 BufferParams const & bp = owner_->masterBuffer()->params();
5091 DocumentClass const & textclass = bp.documentClass();
5092 Paragraph & par = it.paragraph();
5093 Layout const & layout = par.layout();
5094 Counters & counters = textclass.counters();
5096 if (par.params().startOfAppendix()) {
5097 // We want to reset the counter corresponding to toplevel sectioning
5098 Layout const & lay = textclass.getTOCLayout();
5099 docstring const cnt = lay.counter;
5101 counters.reset(cnt);
5102 counters.appendix(true);
5104 par.params().appendix(counters.appendix());
5106 // Compute the item depth of the paragraph
5107 par.itemdepth = getItemDepth(it);
5109 if (layout.margintype == MARGIN_MANUAL) {
5110 if (par.params().labelWidthString().empty())
5111 par.params().labelWidthString(par.expandLabel(layout, bp));
5112 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5113 // we do not need to do anything here, since the empty case is
5114 // handled during export.
5116 par.params().labelWidthString(docstring());
5119 switch(layout.labeltype) {
5120 case LABEL_ITEMIZE: {
5121 // At some point of time we should do something more
5122 // clever here, like:
5123 // par.params().labelString(
5124 // bp.user_defined_bullet(par.itemdepth).getText());
5125 // for now, use a simple hardcoded label
5126 docstring itemlabel;
5127 switch (par.itemdepth) {
5130 itemlabel = char_type(0x2022);
5134 itemlabel = char_type(0x2013);
5137 // ∗ U+2217 ASTERISK OPERATOR
5138 itemlabel = char_type(0x2217);
5141 // · U+00B7 MIDDLE DOT
5142 itemlabel = char_type(0x00b7);
5145 par.params().labelString(itemlabel);
5149 case LABEL_ENUMERATE: {
5150 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5152 switch (par.itemdepth) {
5163 enumcounter += "iv";
5166 // not a valid enumdepth...
5170 if (needEnumCounterReset(it)) {
5171 // Increase the master counter?
5172 if (layout.stepmastercounter)
5173 counters.stepMaster(enumcounter, utype);
5174 // Maybe we have to reset the enumeration counter.
5175 if (!layout.resumecounter)
5176 counters.reset(enumcounter);
5178 counters.step(enumcounter, utype);
5180 string const & lang = par.getParLanguage(bp)->code();
5181 par.params().labelString(counters.theCounter(enumcounter, lang));
5186 case LABEL_SENSITIVE: {
5187 string const & type = counters.current_float();
5188 docstring full_label;
5190 full_label = owner_->B_("Senseless!!! ");
5192 docstring name = owner_->B_(textclass.floats().getType(type).name());
5193 if (counters.hasCounter(from_utf8(type))) {
5194 string const & lang = par.getParLanguage(bp)->code();
5195 counters.step(from_utf8(type), utype);
5196 full_label = bformat(from_ascii("%1$s %2$s:"),
5198 counters.theCounter(from_utf8(type), lang));
5200 full_label = bformat(from_ascii("%1$s #:"), name);
5202 par.params().labelString(full_label);
5206 case LABEL_NO_LABEL:
5207 par.params().labelString(docstring());
5211 case LABEL_CENTERED:
5212 case LABEL_STATIC: {
5213 docstring const & lcounter = layout.counter;
5214 if (!lcounter.empty()) {
5215 if (layout.toclevel <= bp.secnumdepth
5216 && (layout.latextype != LATEX_ENVIRONMENT
5217 || it.text()->isFirstInSequence(it.pit()))) {
5218 if (counters.hasCounter(lcounter))
5219 counters.step(lcounter, utype);
5220 par.params().labelString(par.expandLabel(layout, bp));
5222 par.params().labelString(docstring());
5224 par.params().labelString(par.expandLabel(layout, bp));
5230 par.params().labelString(par.expandLabel(layout, bp));
5235 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype, bool const deleted) const
5237 pushIncludedBuffer(this);
5238 // LASSERT: Is it safe to continue here, or should we just return?
5239 LASSERT(parit.pit() == 0, /**/);
5241 // Set the position of the text in the buffer to be able
5242 // to resolve macros in it.
5243 parit.text()->setMacrocontextPosition(parit);
5245 depth_type maxdepth = 0;
5246 pit_type const lastpit = parit.lastpit();
5247 bool changed = false;
5248 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5249 // reduce depth if necessary
5250 if (parit->params().depth() > maxdepth) {
5251 /** FIXME: this function is const, but
5252 * nevertheless it modifies the buffer. To be
5253 * cleaner, one should modify the buffer in
5254 * another function, which is actually
5255 * non-const. This would however be costly in
5256 * terms of code duplication.
5258 CursorData(parit).recordUndo();
5259 parit->params().depth(maxdepth);
5261 maxdepth = parit->getMaxDepthAfter();
5263 if (utype == OutputUpdate) {
5264 // track the active counters
5265 // we have to do this for the master buffer, since the local
5266 // buffer isn't tracking anything.
5267 masterBuffer()->params().documentClass().counters().
5268 setActiveLayout(parit->layout());
5271 // set the counter for this paragraph
5272 d->setLabel(parit, utype);
5275 for (auto const & insit : parit->insetList()) {
5276 parit.pos() = insit.pos;
5277 insit.inset->updateBuffer(parit, utype, deleted || parit->isDeleted(insit.pos));
5278 changed |= insit.inset->isChanged();
5281 // are there changes in this paragraph?
5282 changed |= parit->isChanged();
5285 // set change indicator for the inset (or the cell that the iterator
5286 // points to, if applicable).
5287 parit.text()->inset().isChanged(changed);
5288 popIncludedBuffer();
5292 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5293 WordLangTuple & word_lang, docstring_list & suggestions) const
5297 suggestions.clear();
5298 word_lang = WordLangTuple();
5299 bool const to_end = to.empty();
5300 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5301 // OK, we start from here.
5302 for (; from != end; from.forwardPos()) {
5303 // This skips all insets with spell check disabled.
5304 while (!from.allowSpellCheck()) {
5308 // If from is at the end of the document (which is possible
5309 // when "from" was changed above) LyX will crash later otherwise.
5310 if (from.atEnd() || (!to_end && from >= end))
5313 from.paragraph().spellCheck();
5314 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5315 if (SpellChecker::misspelled(res)) {
5319 // Do not increase progress when from == to, otherwise the word
5320 // count will be wrong.
5330 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5332 bool inword = false;
5337 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5338 if (!dit.inTexted()) {
5343 Paragraph const & par = dit.paragraph();
5344 pos_type const pos = dit.pos();
5346 // Copied and adapted from isWordSeparator() in Paragraph
5347 if (pos == dit.lastpos()) {
5350 Inset const * ins = par.getInset(pos);
5351 if (ins && skipNoOutput && !ins->producesOutput()) {
5354 // stop if end of range was skipped
5355 if (!to.atEnd() && dit >= to)
5358 } else if (!par.isDeleted(pos)) {
5359 if (par.isWordSeparator(pos))
5365 if (ins && ins->isLetter()) {
5366 odocstringstream os;
5368 char_count_ += os.str().length();
5370 else if (ins && ins->isSpace())
5373 char_type const c = par.getChar(pos);
5374 if (isPrintableNonspace(c))
5376 else if (isSpace(c))
5386 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5388 d->updateStatistics(from, to, skipNoOutput);
5392 int Buffer::wordCount() const
5394 return d->wordCount();
5398 int Buffer::charCount(bool with_blanks) const
5400 return d->charCount(with_blanks);
5404 bool Buffer::areChangesPresent() const
5406 return inset().isChanged();
5410 Buffer::ReadStatus Buffer::reload()
5413 // c.f. bug https://www.lyx.org/trac/ticket/6587
5414 removeAutosaveFile();
5415 // e.g., read-only status could have changed due to version control
5416 d->filename.refresh();
5417 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5419 // clear parent. this will get reset if need be.
5420 d->setParent(nullptr);
5421 ReadStatus const status = loadLyXFile();
5422 if (status == ReadSuccess) {
5427 message(bformat(_("Document %1$s reloaded."), disp_fn));
5430 message(bformat(_("Could not reload document %1$s."), disp_fn));
5440 bool Buffer::saveAs(FileName const & fn)
5442 FileName const old_name = fileName();
5443 FileName const old_auto = getAutosaveFileName();
5444 bool const old_unnamed = isUnnamed();
5445 bool success = true;
5446 d->old_position = filePath();
5453 // bring the autosave file with us, just in case.
5454 moveAutosaveFile(old_auto);
5455 // validate version control data and
5456 // correct buffer title
5457 lyxvc().file_found_hook(fileName());
5459 // the file has now been saved to the new location.
5460 // we need to check that the locations of child buffers
5462 checkChildBuffers();
5463 checkMasterBuffer();
5466 // reset the old filename and unnamed state
5467 setFileName(old_name);
5468 setUnnamed(old_unnamed);
5472 d->old_position.clear();
5477 void Buffer::checkChildBuffers()
5479 for (auto const & bit : d->children_positions) {
5480 DocIterator dit = bit.second;
5481 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5482 if (!cbuf || !theBufferList().isLoaded(cbuf))
5484 Inset * inset = dit.nextInset();
5485 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5486 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5487 docstring const & incfile = inset_inc->getParam("filename");
5488 string oldloc = cbuf->absFileName();
5489 string newloc = makeAbsPath(to_utf8(incfile),
5490 onlyPath(absFileName())).absFileName();
5491 if (oldloc == newloc)
5493 // the location of the child file is incorrect.
5494 cbuf->setParent(nullptr);
5495 inset_inc->setChildBuffer(nullptr);
5497 // invalidate cache of children
5498 d->children_positions.clear();
5499 d->position_to_children.clear();
5503 // If a child has been saved under a different name/path, it might have been
5504 // orphaned. Therefore the master needs to be reset (bug 8161).
5505 void Buffer::checkMasterBuffer()
5507 Buffer const * const master = masterBuffer();
5511 // necessary to re-register the child (bug 5873)
5512 // FIXME: clean up updateMacros (here, only
5513 // child registering is needed).
5514 master->updateMacros();
5515 // (re)set master as master buffer, but only
5516 // if we are a real child
5517 if (master->isChild(this))
5524 string Buffer::includedFilePath(string const & name, string const & ext) const
5526 if (d->old_position.empty() ||
5527 equivalent(FileName(d->old_position), FileName(filePath())))
5530 bool isabsolute = FileName::isAbsolute(name);
5531 // both old_position and filePath() end with a path separator
5532 string absname = isabsolute ? name : d->old_position + name;
5534 // if old_position is set to origin, we need to do the equivalent of
5535 // getReferencedFileName() (see readDocument())
5536 if (!isabsolute && d->old_position == params().origin) {
5537 FileName const test(addExtension(filePath() + name, ext));
5539 absname = filePath() + name;
5542 if (!FileName(addExtension(absname, ext)).exists())
5546 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5548 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5549 from_utf8(filePath())));
5553 void Buffer::Impl::refreshFileMonitor()
5555 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5556 file_monitor_->refresh();
5560 // The previous file monitor is invalid
5561 // This also destroys the previous file monitor and all its connections
5562 file_monitor_ = FileSystemWatcher::monitor(filename);
5563 // file_monitor_ will be destroyed with *this, so it is not going to call a
5564 // destroyed object method.
5565 file_monitor_->connect([this](bool exists) {
5566 fileExternallyModified(exists);
5571 void Buffer::Impl::fileExternallyModified(bool const exists)
5573 // ignore notifications after our own saving operations
5574 if (checksum_ == filename.checksum()) {
5575 LYXERR(Debug::FILES, "External modification but "
5576 "checksum unchanged: " << filename);
5579 // If the file has been deleted, only mark the file as dirty since it is
5580 // pointless to prompt for reloading. If later a file is moved into this
5581 // location, then the externally modified warning will appear then.
5583 externally_modified_ = true;
5584 // Update external modification notification.
5585 // Dirty buffers must be visible at all times.
5586 if (wa_ && wa_->unhide(owner_))
5587 wa_->updateTitles();
5589 // Unable to unhide the buffer (e.g. no GUI or not current View)
5594 bool Buffer::notifiesExternalModification() const
5596 return d->externally_modified_;
5600 void Buffer::clearExternalModification() const
5602 d->externally_modified_ = false;
5604 d->wa_->updateTitles();
5608 void Buffer::pushIncludedBuffer(Buffer const * buf) const
5610 masterBuffer()->d->include_list_.push_back(buf);
5611 if (lyxerr.debugging(Debug::FILES)) {
5612 LYXERR0("Pushed. Stack now:");
5613 if (masterBuffer()->d->include_list_.empty())
5616 for (auto const & b : masterBuffer()->d->include_list_)
5617 LYXERR0(b->fileName());
5622 void Buffer::popIncludedBuffer() const
5624 masterBuffer()->d->include_list_.pop_back();
5625 if (lyxerr.debugging(Debug::FILES)) {
5626 LYXERR0("Popped. Stack now:");
5627 if (masterBuffer()->d->include_list_.empty())
5630 for (auto const & b : masterBuffer()->d->include_list_)
5631 LYXERR0(b->fileName());
5636 bool Buffer::isBufferIncluded(Buffer const * buf) const
5640 if (lyxerr.debugging(Debug::FILES)) {
5641 LYXERR0("Checking for " << buf->fileName() << ". Stack now:");
5642 if (masterBuffer()->d->include_list_.empty())
5645 for (auto const & b : masterBuffer()->d->include_list_)
5646 LYXERR0(b->fileName());
5648 list<Buffer const *> const & blist = masterBuffer()->d->include_list_;
5649 return find(blist.begin(), blist.end(), buf) != blist.end();
5653 void Buffer::clearIncludeList() const
5655 LYXERR(Debug::FILES, "Clearing include list for " << fileName());
5656 d->include_list_.clear();