3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
59 #include "SpellChecker.h"
61 #include "texstream.h"
64 #include "TextClass.h"
65 #include "TocBackend.h"
67 #include "VCBackend.h"
69 #include "WordLangTuple.h"
72 #include "insets/InsetBibtex.h"
73 #include "insets/InsetBranch.h"
74 #include "insets/InsetInclude.h"
75 #include "insets/InsetTabular.h"
76 #include "insets/InsetText.h"
78 #include "mathed/InsetMathHull.h"
79 #include "mathed/MacroTable.h"
80 #include "mathed/InsetMathMacroTemplate.h"
81 #include "mathed/MathSupport.h"
83 #include "graphics/GraphicsCache.h"
84 #include "graphics/PreviewLoader.h"
86 #include "frontends/Application.h"
87 #include "frontends/alert.h"
88 #include "frontends/Delegates.h"
89 #include "frontends/WorkAreaManager.h"
91 #include "support/lassert.h"
92 #include "support/convert.h"
93 #include "support/debug.h"
94 #include "support/docstring_list.h"
95 #include "support/ExceptionMessage.h"
96 #include "support/FileMonitor.h"
97 #include "support/FileName.h"
98 #include "support/FileNameList.h"
99 #include "support/filetools.h"
100 #include "support/ForkedCalls.h"
101 #include "support/gettext.h"
102 #include "support/gzstream.h"
103 #include "support/lstrings.h"
104 #include "support/lyxalgo.h"
105 #include "support/mutex.h"
106 #include "support/os.h"
107 #include "support/Package.h"
108 #include "support/PathChanger.h"
109 #include "support/Systemcall.h"
110 #include "support/TempFile.h"
111 #include "support/textutils.h"
112 #include "support/types.h"
114 #include "support/bind.h"
126 using namespace lyx::support;
127 using namespace lyx::graphics;
131 namespace Alert = frontend::Alert;
132 namespace os = support::os;
136 int const LYX_FORMAT = LYX_FORMAT_LYX;
138 typedef map<string, bool> DepClean;
140 // Information about labels and their associated refs
145 InsetLabel const * inset;
146 /// associated references cache
147 Buffer::References references;
148 /// whether this label is active (i.e., not deleted)
152 typedef vector<LabelInfo> LabelCache;
154 typedef map<docstring, Buffer::References> RefCache;
156 // A storehouse for the cloned buffers.
157 typedef list<CloneList_ptr> CloneStore;
158 CloneStore cloned_buffers;
167 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
171 delete preview_loader_;
179 /// search for macro in local (buffer) table or in children
180 MacroData const * getBufferMacro(docstring const & name,
181 DocIterator const & pos) const;
183 /// Update macro table starting with position of it \param it in some
185 void updateMacros(DocIterator & it, DocIterator & scope);
187 void setLabel(ParIterator & it, UpdateType utype) const;
189 /** If we have branches that use the file suffix
190 feature, return the file name with suffix appended.
192 FileName exportFileName() const;
199 mutable TexRow texrow;
201 /// need to regenerate .tex?
204 /// name of the file the buffer is associated with.
208 mutable TocBackend toc_backend;
213 ScopeMacro(DocIterator const & s, MacroData const & m)
214 : scope(s), macro(m) {}
218 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
219 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
220 /// map from the macro name to the position map,
221 /// which maps the macro definition position to the scope and the MacroData.
222 NamePositionScopeMacroMap macros;
224 /// positions of child buffers in the buffer
225 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
227 ScopeBuffer() : buffer(nullptr) {}
228 ScopeBuffer(DocIterator const & s, Buffer const * b)
229 : scope(s), buffer(b) {}
231 Buffer const * buffer;
233 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
234 /// position of children buffers in this buffer
235 BufferPositionMap children_positions;
236 /// map from children inclusion positions to their scope and their buffer
237 PositionScopeBufferMap position_to_children;
239 /// Contains the old buffer filePath() while saving-as, or the
240 /// directory where the document was last saved while loading.
243 /** Keeps track of the path of local layout files.
244 * If possible, it is always relative to the buffer path.
245 * Empty for layouts in system or user directory.
247 string layout_position;
249 /// Container for all sort of Buffer dependant errors.
250 map<string, ErrorList> errorLists;
252 /// checksum used to test if the file has been externally modified. Used to
253 /// double check whether the file had been externally modified when saving.
254 unsigned long checksum_;
257 frontend::WorkAreaManager * wa_;
259 frontend::GuiBufferDelegate * gui_;
264 /// A cache for the bibfiles (including bibfiles of loaded child
265 /// documents), needed for appropriate update of natbib labels.
266 mutable docstring_list bibfiles_cache_;
268 // FIXME The caching mechanism could be improved. At present, we have a
269 // cache for each Buffer, that caches all the bibliography info for that
270 // Buffer. A more efficient solution would be to have a global cache per
271 // file, and then to construct the Buffer's bibinfo from that.
272 /// A cache for bibliography info
273 mutable BiblioInfo bibinfo_;
274 /// Cache of timestamps of .bib files
275 map<FileName, time_t> bibfile_status_;
277 /// These two hold the file name and format, written to by
278 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
279 FileName preview_file_;
280 string preview_format_;
282 /// Cache the references associated to a label and their positions
284 mutable RefCache ref_cache_;
285 /// Cache the label insets and their activity status.
286 mutable LabelCache label_cache_;
288 /// our Text that should be wrapped in an InsetText
292 PreviewLoader * preview_loader_;
294 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
295 /// This one is useful for preview detached in a thread.
296 Buffer const * cloned_buffer_;
298 CloneList_ptr clone_list_;
301 std::list<Buffer const *> include_list_;
303 /// So we can force access via the accessors.
304 mutable Buffer const * parent_buffer;
306 FileMonitorPtr file_monitor_;
308 /// ints and bools are all listed last so as to avoid alignment issues
310 /// original format of loaded file
313 /// are we in the process of exporting this buffer?
314 mutable bool doing_export;
316 /// If there was an error when previewing, on the next preview we do
317 /// a fresh compile (e.g. in case the user installed a package that
319 bool require_fresh_start_;
321 /// Indicates whether the bibinfo has changed since the last time
322 /// we ran updateBuffer(), i.e., whether citation labels may need
324 mutable bool cite_labels_valid_;
325 /// Do we have a bibliography environment?
326 mutable bool have_bibitems_;
329 mutable bool lyx_clean;
331 /// is autosave needed?
332 mutable bool bak_clean;
334 /// is this an unnamed file (New...)?
337 /// is this an internal bufffer?
338 bool internal_buffer;
343 /** Set to true only when the file is fully loaded.
344 * Used to prevent the premature generation of previews
345 * and by the citation inset.
347 bool file_fully_loaded;
349 /// if the file was originally loaded from an older format, do
350 /// we need to back it up still?
351 bool need_format_backup;
353 /// Ignore the parent (e.g. when exporting a child standalone)?
356 /// This seem to change the way Buffer::getMacro() works
357 mutable bool macro_lock;
359 /// has been externally modified? Can be reset by the user.
360 mutable bool externally_modified_;
362 /// whether the bibinfo cache is valid
363 mutable bool bibinfo_cache_valid_;
371 /// This is here to force the test to be done whenever parent_buffer
373 Buffer const * parent() const
375 // ignore_parent temporarily "orphans" a buffer
376 // (e.g. if a child is compiled standalone)
379 // if parent_buffer is not loaded, then it has been unloaded,
380 // which means that parent_buffer is an invalid pointer. So we
381 // set it to null in that case.
382 // however, the BufferList doesn't know about cloned buffers, so
383 // they will always be regarded as unloaded. in that case, we hope
385 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
386 parent_buffer = nullptr;
387 return parent_buffer;
391 void setParent(Buffer const * pb)
393 if (parent_buffer == pb)
396 if (!cloned_buffer_ && parent_buffer && pb)
397 LYXERR0("Warning: a buffer should not have two parents!");
399 if (!cloned_buffer_ && parent_buffer)
400 parent_buffer->invalidateBibinfoCache();
403 /// compute statistics
404 /// \p from initial position
405 /// \p to points to the end position
406 void updateStatistics(DocIterator & from, DocIterator & to,
407 bool skipNoOutput = true);
408 /// statistics accessor functions
409 int wordCount() const
413 int charCount(bool with_blanks) const
416 + (with_blanks ? blank_count_ : 0);
419 // Make sure the file monitor monitors the good file.
420 void refreshFileMonitor();
422 /// Notify or clear of external modification
423 void fileExternallyModified(bool exists);
425 ///Binding LaTeX lines with buffer positions.
426 //Common routine for LaTeX and Reference errors listing.
427 void traverseErrors(TeXErrors::Errors::const_iterator err,
428 TeXErrors::Errors::const_iterator end,
429 ErrorList & errorList) const;
433 /// Creates the per buffer temporary directory
434 static FileName createBufferTmpDir()
436 // FIXME This would be the ideal application for a TempDir class (like
437 // TempFile but for directories)
442 Mutex::Locker locker(&mutex);
443 counter = convert<string>(count++);
445 // We are in our own directory. Why bother to mangle name?
446 // In fact I wrote this code to circumvent a problematic behaviour
447 // (bug?) of EMX mkstemp().
448 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
451 if (!tmpfl.createDirectory(0777)) {
452 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
453 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
454 from_utf8(tmpfl.absFileName())));
460 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
461 Buffer const * cloned_buffer)
462 : owner_(owner), filename(file), toc_backend(owner), checksum_(0),
463 wa_(nullptr), gui_(nullptr), undo_(*owner), inset(nullptr),
464 preview_loader_(nullptr), cloned_buffer_(cloned_buffer),
465 clone_list_(nullptr), parent_buffer(nullptr), file_format(LYX_FORMAT),
466 doing_export(false), require_fresh_start_(false), cite_labels_valid_(false),
467 have_bibitems_(false), lyx_clean(true), bak_clean(true), unnamed(false),
468 internal_buffer(false), read_only(readonly_), file_fully_loaded(false),
469 need_format_backup(false), ignore_parent(false), macro_lock(false),
470 externally_modified_(false), bibinfo_cache_valid_(false),
471 word_count_(0), char_count_(0), blank_count_(0)
473 refreshFileMonitor();
474 if (!cloned_buffer_) {
475 temppath = createBufferTmpDir();
476 lyxvc.setBuffer(owner_);
477 Language const * inplang = theApp() ?
478 languages.getFromCode(theApp()->inputLanguageCode())
481 params.language = inplang;
483 wa_ = new frontend::WorkAreaManager;
486 temppath = cloned_buffer_->d->temppath;
487 file_fully_loaded = true;
488 params = cloned_buffer_->d->params;
489 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
490 bibinfo_ = cloned_buffer_->d->bibinfo_;
491 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
492 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
493 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
494 have_bibitems_ = cloned_buffer_->d->have_bibitems_;
495 unnamed = cloned_buffer_->d->unnamed;
496 internal_buffer = cloned_buffer_->d->internal_buffer;
497 layout_position = cloned_buffer_->d->layout_position;
498 preview_file_ = cloned_buffer_->d->preview_file_;
499 preview_format_ = cloned_buffer_->d->preview_format_;
500 require_fresh_start_ = cloned_buffer_->d->require_fresh_start_;
504 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
505 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
507 LYXERR(Debug::INFO, "Buffer::Buffer()");
509 d->inset = new InsetText(*cloned_buffer->d->inset);
510 d->inset->setBuffer(*this);
511 // FIXME: optimize this loop somewhat, maybe by creating a new
512 // general recursive Inset::setId().
513 DocIterator it = doc_iterator_begin(this);
514 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
515 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
516 it.paragraph().setId(cloned_it.paragraph().id());
518 d->inset = new InsetText(this);
519 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
525 LYXERR(Debug::INFO, "Buffer::~Buffer()");
526 // here the buffer should take care that it is
527 // saved properly, before it goes into the void.
529 // GuiView already destroyed
533 // No need to do additional cleanups for internal buffer.
539 // this is in case of recursive includes: we won't try to delete
540 // ourselves as a child.
541 d->clone_list_->erase(this);
542 // loop over children
543 for (auto const & p : d->children_positions) {
544 Buffer * child = const_cast<Buffer *>(p.first);
545 if (d->clone_list_->erase(child))
548 // if we're the master buffer, then we should get rid of the list
551 // If this is not empty, we have leaked something. Worse, one of the
552 // children still has a reference to this list. But we will try to
553 // continue, rather than shut down.
554 LATTEST(d->clone_list_->empty());
555 // The clone list itself is empty, but it's still referenced in our list
556 // of clones. So let's find it and remove it.
557 CloneStore::iterator it =
558 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
559 if (it == cloned_buffers.end()) {
560 // We will leak in this case, but it is safe to continue.
563 cloned_buffers.erase(it);
565 // FIXME Do we really need to do this right before we delete d?
566 // clear references to children in macro tables
567 d->children_positions.clear();
568 d->position_to_children.clear();
570 // loop over children
571 for (auto const & p : d->children_positions) {
572 Buffer * child = const_cast<Buffer *>(p.first);
573 if (theBufferList().isLoaded(child)) {
574 if (theBufferList().isOthersChild(this, child))
575 child->setParent(nullptr);
577 theBufferList().release(child);
582 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
584 msg += emergencyWrite();
586 msg += " " + _("Save failed! Document is lost.");
588 Alert::warning(_("Attempting to close changed document!"), msg);
591 // FIXME Do we really need to do this right before we delete d?
592 // clear references to children in macro tables
593 d->children_positions.clear();
594 d->position_to_children.clear();
596 if (!d->temppath.destroyDirectory()) {
597 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
598 from_utf8(d->temppath.absFileName())));
607 Buffer * Buffer::cloneWithChildren() const
610 cloned_buffers.emplace_back(new CloneList);
611 CloneList_ptr clones = cloned_buffers.back();
613 cloneWithChildren(bufmap, clones);
615 // make sure we got cloned
616 BufferMap::const_iterator bit = bufmap.find(this);
617 LASSERT(bit != bufmap.end(), return nullptr);
618 Buffer * cloned_buffer = bit->second;
620 return cloned_buffer;
624 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList_ptr clones) const
626 // have we already been cloned?
627 if (bufmap.find(this) != bufmap.end())
630 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
632 // The clone needs its own DocumentClass, since running updateBuffer() will
633 // modify it, and we would otherwise be sharing it with the original Buffer.
634 buffer_clone->params().makeDocumentClass(true);
636 cap::switchBetweenClasses(
637 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
638 static_cast<InsetText &>(buffer_clone->inset()), el);
640 bufmap[this] = buffer_clone;
641 clones->insert(buffer_clone);
642 buffer_clone->d->clone_list_ = clones;
643 buffer_clone->d->macro_lock = true;
644 buffer_clone->d->children_positions.clear();
646 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
647 // math macro caches need to be rethought and simplified.
648 // I am not sure wether we should handle Buffer cloning here or in BufferList.
649 // Right now BufferList knows nothing about buffer clones.
650 for (auto const & p : d->position_to_children) {
651 DocIterator dit = p.first.clone(buffer_clone);
652 dit.setBuffer(buffer_clone);
653 Buffer * child = const_cast<Buffer *>(p.second.buffer);
655 child->cloneWithChildren(bufmap, clones);
656 BufferMap::iterator const bit = bufmap.find(child);
657 LASSERT(bit != bufmap.end(), continue);
658 Buffer * child_clone = bit->second;
660 Inset * inset = dit.nextInset();
661 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
662 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
663 inset_inc->setChildBuffer(child_clone);
664 child_clone->d->setParent(buffer_clone);
665 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
666 buffer_clone->setChild(dit, child_clone);
668 buffer_clone->d->macro_lock = false;
673 Buffer * Buffer::cloneBufferOnly() const {
674 cloned_buffers.emplace_back(new CloneList);
675 CloneList_ptr clones = cloned_buffers.back();
676 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
678 // The clone needs its own DocumentClass, since running updateBuffer() will
679 // modify it, and we would otherwise be sharing it with the original Buffer.
680 buffer_clone->params().makeDocumentClass(true);
682 cap::switchBetweenClasses(
683 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
684 static_cast<InsetText &>(buffer_clone->inset()), el);
686 clones->insert(buffer_clone);
687 buffer_clone->d->clone_list_ = clones;
689 // we won't be cloning the children
690 buffer_clone->d->children_positions.clear();
695 bool Buffer::isClone() const
697 return d->cloned_buffer_;
701 void Buffer::changed(bool update_metrics) const
704 d->wa_->redrawAll(update_metrics);
708 frontend::WorkAreaManager & Buffer::workAreaManager() const
715 Text & Buffer::text() const
717 return d->inset->text();
721 Inset & Buffer::inset() const
727 BufferParams & Buffer::params()
733 BufferParams const & Buffer::params() const
739 BufferParams const & Buffer::masterParams() const
741 if (masterBuffer() == this)
744 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
745 // Copy child authors to the params. We need those pointers.
746 for (Author const & a : params().authors())
747 mparams.authors().record(a);
752 double Buffer::fontScalingFactor() const
754 return isExporting() ? 75.0 * params().html_math_img_scale
755 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
759 ParagraphList & Buffer::paragraphs()
761 return text().paragraphs();
765 ParagraphList const & Buffer::paragraphs() const
767 return text().paragraphs();
771 LyXVC & Buffer::lyxvc()
777 LyXVC const & Buffer::lyxvc() const
783 string const Buffer::temppath() const
785 return d->temppath.absFileName();
789 TexRow & Buffer::texrow()
795 TexRow const & Buffer::texrow() const
801 TocBackend & Buffer::tocBackend() const
803 return d->toc_backend;
807 Undo & Buffer::undo()
813 void Buffer::setChild(DocIterator const & dit, Buffer * child)
815 d->children_positions[child] = dit;
819 string Buffer::latexName(bool const no_path) const
821 FileName latex_name =
822 makeLatexName(d->exportFileName());
823 return no_path ? latex_name.onlyFileName()
824 : latex_name.absFileName();
828 FileName Buffer::Impl::exportFileName() const
830 docstring const branch_suffix =
831 params.branchlist().getFileNameSuffix();
832 if (branch_suffix.empty())
835 string const name = addExtension(filename.onlyFileNameWithoutExt()
836 + to_utf8(branch_suffix), filename.extension());
837 FileName res(filename.onlyPath().absFileName() + "/" + name);
843 string Buffer::logName(LogType * type) const
845 string const filename = latexName(false);
847 if (filename.empty()) {
853 string const path = temppath();
855 FileName const fname(addName(temppath(),
856 onlyFileName(changeExtension(filename,
859 // FIXME: how do we know this is the name of the build log?
860 FileName const bname(
861 addName(path, onlyFileName(
862 changeExtension(filename,
863 theFormats().extension(params().bufferFormat()) + ".out"))));
865 // Also consider the master buffer log file
866 FileName masterfname = fname;
867 LogType mtype = latexlog;
868 if (masterBuffer() != this) {
869 string const mlogfile = masterBuffer()->logName(&mtype);
870 masterfname = FileName(mlogfile);
873 // If no Latex log or Build log is newer, show Build log
874 if (bname.exists() &&
875 ((!fname.exists() && !masterfname.exists())
876 || (fname.lastModified() < bname.lastModified()
877 && masterfname.lastModified() < bname.lastModified()))) {
878 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
881 return bname.absFileName();
882 // If we have a newer master file log or only a master log, show this
883 } else if (fname != masterfname
884 && (!fname.exists() && (masterfname.exists()
885 || fname.lastModified() < masterfname.lastModified()))) {
886 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
889 return masterfname.absFileName();
891 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
894 return fname.absFileName();
898 void Buffer::setReadonly(bool const flag)
900 if (d->read_only != flag) {
907 void Buffer::setFileName(FileName const & fname)
909 bool const changed = fname != d->filename;
911 d->refreshFileMonitor();
913 lyxvc().file_found_hook(fname);
914 setReadonly(d->filename.isReadOnly());
920 int Buffer::readHeader(Lexer & lex)
922 int unknown_tokens = 0;
924 int begin_header_line = -1;
926 // Initialize parameters that may be/go lacking in header:
927 params().branchlist().clear();
928 params().preamble.erase();
929 params().options.erase();
930 params().master.erase();
931 params().float_placement.erase();
932 params().float_alignment.erase();
933 params().paperwidth.erase();
934 params().paperheight.erase();
935 params().leftmargin.erase();
936 params().rightmargin.erase();
937 params().topmargin.erase();
938 params().bottommargin.erase();
939 params().headheight.erase();
940 params().headsep.erase();
941 params().footskip.erase();
942 params().columnsep.erase();
943 params().font_roman_opts.erase();
944 params().font_sans_opts.erase();
945 params().font_typewriter_opts.erase();
946 params().fonts_cjk.erase();
947 params().listings_params.clear();
948 params().clearLayoutModules();
949 params().clearRemovedModules();
950 params().clearIncludedChildren();
951 params().pdfoptions().clear();
952 params().indiceslist().clear();
953 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
954 params().isbackgroundcolor = false;
955 params().fontcolor = RGBColor(0, 0, 0);
956 params().isfontcolor = false;
957 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
958 params().boxbgcolor = RGBColor(0xFF, 0, 0);
959 params().html_latex_start.clear();
960 params().html_latex_end.clear();
961 params().html_math_img_scale = 1.0;
962 params().output_sync_macro.erase();
963 params().setLocalLayout(docstring(), false);
964 params().setLocalLayout(docstring(), true);
965 params().biblio_opts.erase();
966 params().biblatex_bibstyle.erase();
967 params().biblatex_citestyle.erase();
968 params().multibib.erase();
969 params().lineno_opts.clear();
971 for (int i = 0; i < 4; ++i) {
972 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
973 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
976 ErrorList & errorList = d->errorLists["Parse"];
985 if (token == "\\end_header")
989 if (token == "\\begin_header") {
990 begin_header_line = line;
994 LYXERR(Debug::PARSER, "Handling document header token: `"
997 string const result =
998 params().readToken(lex, token, d->filename.onlyPath());
999 if (!result.empty()) {
1000 if (token == "\\textclass") {
1001 d->layout_position = result;
1004 docstring const s = bformat(_("Unknown token: "
1007 lex.getDocString());
1008 errorList.push_back(ErrorItem(_("Document header error"), s));
1012 if (begin_header_line) {
1013 docstring const s = _("\\begin_header is missing");
1014 errorList.push_back(ErrorItem(_("Document header error"), s));
1017 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
1019 params().makeDocumentClass();
1021 return unknown_tokens;
1026 // changed to be public and have one parameter
1027 // Returns true if "\end_document" is not read (Asger)
1028 bool Buffer::readDocument(Lexer & lex)
1030 ErrorList & errorList = d->errorLists["Parse"];
1033 // remove dummy empty par
1034 paragraphs().clear();
1036 if (!lex.checkFor("\\begin_document")) {
1037 docstring const s = _("\\begin_document is missing");
1038 errorList.push_back(ErrorItem(_("Document header error"), s));
1043 if (params().output_changes) {
1044 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1045 LaTeXFeatures::isAvailable("xcolor");
1048 Alert::warning(_("Changes not shown in LaTeX output"),
1049 _("Changes will not be highlighted in LaTeX output, "
1050 "because xcolor and ulem are not installed.\n"
1051 "Please install both packages or redefine "
1052 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1056 if (!parent() && !params().master.empty()) {
1057 FileName const master_file = makeAbsPath(params().master,
1058 onlyPath(absFileName()));
1059 if (isLyXFileName(master_file.absFileName())) {
1061 checkAndLoadLyXFile(master_file, true);
1063 // necessary e.g. after a reload
1064 // to re-register the child (bug 5873)
1065 // FIXME: clean up updateMacros (here, only
1066 // child registering is needed).
1067 master->updateMacros();
1068 // set master as master buffer, but only
1069 // if we are a real child
1070 if (master->isChild(this))
1072 // if the master is not fully loaded
1073 // it is probably just loading this
1074 // child. No warning needed then.
1075 else if (master->isFullyLoaded())
1076 LYXERR0("The master '"
1078 << "' assigned to this document ("
1080 << ") does not include "
1081 "this document. Ignoring the master assignment.");
1082 // If the master has just been created, un-hide it (#11162)
1083 if (!master->fileName().exists())
1084 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1085 master->absFileName()));
1090 // assure we have a default index
1091 params().indiceslist().addDefault(B_("Index"));
1094 if (FileName::isAbsolute(params().origin))
1095 d->old_position = params().origin;
1097 d->old_position = filePath();
1102 bool const res = text().read(lex, errorList, d->inset);
1103 d->old_position.clear();
1105 // inform parent buffer about local macros
1107 Buffer const * pbuf = parent();
1108 for (auto const & m : usermacros)
1109 pbuf->usermacros.insert(m);
1113 updateMacroInstances(InternalUpdate);
1118 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1120 Format const * fmt = theFormats().getFormat(format);
1123 // It is important to use the correct extension here, since some
1124 // converters create a wrong output file otherwise (e.g. html2latex)
1125 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1126 ofdocstream os(name.toFilesystemEncoding().c_str());
1127 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1128 bool const success = !(os << contents).fail();
1131 bool converted = false;
1133 params().compressed = false;
1135 // remove dummy empty par
1136 paragraphs().clear();
1138 converted = importFile(format, name, errorList);
1141 removeTempFile(name);
1146 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1148 if (!theConverters().isReachable(format, "lyx"))
1151 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1152 Converters::RetVal const retval =
1153 theConverters().convert(nullptr, name, lyx, name, format, "lyx", errorList);
1154 if (retval == Converters::SUCCESS) {
1155 bool const success = readFile(lyx) == ReadSuccess;
1156 removeTempFile(lyx);
1164 bool Buffer::readString(string const & s)
1166 params().compressed = false;
1169 istringstream is(s);
1171 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1172 FileName const fn = tempfile.name();
1175 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1177 if (success && file_format != LYX_FORMAT) {
1178 // We need to call lyx2lyx, so write the input to a file
1179 ofstream os(fn.toFilesystemEncoding().c_str());
1182 // lyxvc in readFile
1183 if (readFile(fn) != ReadSuccess)
1187 if (readDocument(lex))
1193 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1197 if (!lex.setFile(fname)) {
1198 Alert::error(_("File Not Found"),
1199 bformat(_("Unable to open file `%1$s'."),
1200 from_utf8(fn.absFileName())));
1201 return ReadFileNotFound;
1205 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1206 if (ret_plf != ReadSuccess)
1209 if (file_format != LYX_FORMAT) {
1211 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1212 if (ret_clf != ReadSuccess)
1214 ret_clf = readFile(tmpFile);
1215 if (ret_clf == ReadSuccess) {
1216 d->file_format = file_format;
1217 d->need_format_backup = true;
1222 // FIXME: InsetInfo needs to know whether the file is under VCS
1223 // during the parse process, so this has to be done before.
1224 lyxvc().file_found_hook(d->filename);
1226 if (readDocument(lex)) {
1227 Alert::error(_("Document format failure"),
1228 bformat(_("%1$s ended unexpectedly, which means"
1229 " that it is probably corrupted."),
1230 from_utf8(fn.absFileName())));
1231 return ReadDocumentFailure;
1234 d->file_fully_loaded = true;
1235 d->read_only = !d->filename.isWritable();
1236 params().compressed = theFormats().isZippedFile(d->filename);
1242 bool Buffer::isFullyLoaded() const
1244 return d->file_fully_loaded;
1248 void Buffer::setFullyLoaded(bool value)
1250 d->file_fully_loaded = value;
1254 bool Buffer::freshStartRequired() const
1256 return d->require_fresh_start_;
1259 void Buffer::requireFreshStart(bool const b) const
1261 d->require_fresh_start_ = b;
1265 PreviewLoader * Buffer::loader() const
1267 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1269 if (!d->preview_loader_)
1270 d->preview_loader_ = new PreviewLoader(*this);
1271 return d->preview_loader_;
1275 void Buffer::removePreviews() const
1277 delete d->preview_loader_;
1278 d->preview_loader_ = nullptr;
1282 void Buffer::updatePreviews() const
1284 PreviewLoader * ploader = loader();
1288 InsetIterator it = inset_iterator_begin(*d->inset);
1289 InsetIterator const end = inset_iterator_end(*d->inset);
1290 for (; it != end; ++it)
1291 it->addPreview(it, *ploader);
1293 ploader->startLoading();
1297 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1298 FileName const & fn, int & file_format) const
1300 if(!lex.checkFor("\\lyxformat")) {
1301 Alert::error(_("Document format failure"),
1302 bformat(_("%1$s is not a readable LyX document."),
1303 from_utf8(fn.absFileName())));
1304 return ReadNoLyXFormat;
1310 // LyX formats 217 and earlier were written as 2.17. This corresponds
1311 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1312 // these cases. See also: www.lyx.org/trac/changeset/1313.
1313 size_t dot = tmp_format.find_first_of(".,");
1314 if (dot != string::npos)
1315 tmp_format.erase(dot, 1);
1317 file_format = convert<int>(tmp_format);
1322 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1323 FileName & tmpfile, int from_format)
1325 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1326 tempfile.setAutoRemove(false);
1327 tmpfile = tempfile.name();
1328 if(tmpfile.empty()) {
1329 Alert::error(_("Conversion failed"),
1330 bformat(_("%1$s is from a different"
1331 " version of LyX, but a temporary"
1332 " file for converting it could"
1333 " not be created."),
1334 from_utf8(fn.absFileName())));
1335 return LyX2LyXNoTempFile;
1338 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1339 if (lyx2lyx.empty()) {
1340 Alert::error(_("Conversion script not found"),
1341 bformat(_("%1$s is from a different"
1342 " version of LyX, but the"
1343 " conversion script lyx2lyx"
1344 " could not be found."),
1345 from_utf8(fn.absFileName())));
1346 return LyX2LyXNotFound;
1350 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1351 ostringstream command;
1352 command << os::python()
1353 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1354 << " -t " << convert<string>(LYX_FORMAT)
1355 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1356 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1357 string const command_str = command.str();
1359 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1361 cmd_ret const ret = runCommand(command_str);
1362 if (ret.first != 0) {
1363 if (from_format < LYX_FORMAT) {
1364 Alert::error(_("Conversion script failed"),
1365 bformat(_("%1$s is from an older version"
1366 " of LyX and the lyx2lyx script"
1367 " failed to convert it."),
1368 from_utf8(fn.absFileName())));
1369 return LyX2LyXOlderFormat;
1371 Alert::error(_("Conversion script failed"),
1372 bformat(_("%1$s is from a newer version"
1373 " of LyX and the lyx2lyx script"
1374 " failed to convert it."),
1375 from_utf8(fn.absFileName())));
1376 return LyX2LyXNewerFormat;
1383 FileName Buffer::getBackupName() const {
1384 map<int, string> const file_formats = {
1401 FileName const & fn = fileName();
1402 string const fname = fn.onlyFileNameWithoutExt();
1403 string const fext = fn.extension() + "~";
1404 string const fpath = lyxrc.backupdir_path.empty() ?
1405 fn.onlyPath().absFileName() :
1406 lyxrc.backupdir_path;
1407 string backup_suffix;
1408 // If file format is from a stable series use version instead of file format
1409 auto const it = file_formats.find(d->file_format);
1410 if (it != file_formats.end())
1411 backup_suffix = "-lyx" + it->second;
1413 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1414 string const backname = fname + backup_suffix;
1415 FileName backup(addName(fpath, addExtension(backname, fext)));
1417 // limit recursion, just in case
1419 unsigned long orig_checksum = 0;
1420 while (backup.exists() && v < 100) {
1421 if (orig_checksum == 0)
1422 orig_checksum = fn.checksum();
1423 unsigned long new_checksum = backup.checksum();
1424 if (orig_checksum == new_checksum) {
1425 LYXERR(Debug::FILES, "Not backing up " << fn <<
1426 "since " << backup << "has the same checksum.");
1427 // a bit of a hack, but we have to check this anyway
1428 // below, and setting this is simpler than introducing
1429 // a special boolean for this purpose.
1433 string const newbackname = backname + "-" + convert<string>(v);
1434 backup.set(addName(fpath, addExtension(newbackname, fext)));
1437 return v < 100 ? backup : FileName();
1441 // Should probably be moved to somewhere else: BufferView? GuiView?
1442 bool Buffer::save() const
1444 docstring const file = makeDisplayPath(absFileName(), 20);
1445 d->filename.refresh();
1447 // check the read-only status before moving the file as a backup
1448 if (d->filename.exists()) {
1449 bool const read_only = !d->filename.isWritable();
1451 Alert::warning(_("File is read-only"),
1452 bformat(_("The file %1$s cannot be written because it "
1453 "is marked as read-only."), file));
1458 // ask if the disk file has been externally modified (use checksum method)
1459 if (fileName().exists() && isChecksumModified()) {
1461 bformat(_("Document %1$s has been externally modified. "
1462 "Are you sure you want to overwrite this file?"), file);
1463 int const ret = Alert::prompt(_("Overwrite modified file?"),
1464 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1469 // We don't need autosaves in the immediate future. (Asger)
1470 resetAutosaveTimers();
1472 // if the file does not yet exist, none of the backup activity
1473 // that follows is necessary
1474 if (!fileName().exists()) {
1475 if (!writeFile(fileName()))
1481 // we first write the file to a new name, then move it to its
1482 // proper location once that has been done successfully. that
1483 // way we preserve the original file if something goes wrong.
1484 string const justname = fileName().onlyFileNameWithoutExt();
1485 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1486 justname + "-XXXXXX.lyx");
1487 bool const symlink = fileName().isSymLink();
1489 tempfile->setAutoRemove(false);
1491 FileName savefile(tempfile->name());
1492 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1493 if (!savefile.clonePermissions(fileName()))
1494 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1496 if (!writeFile(savefile))
1499 // we will set this to false if we fail
1500 bool made_backup = true;
1502 FileName backupName;
1503 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1505 if (d->need_format_backup)
1506 backupName = getBackupName();
1508 // If we for some reason failed to find a backup name in case of
1509 // a format change, this will still set one. It's the best we can
1511 if (backupName.empty()) {
1512 backupName.set(fileName().absFileName() + "~");
1513 if (!lyxrc.backupdir_path.empty()) {
1514 string const mangledName =
1515 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1516 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1520 LYXERR(Debug::FILES, "Backing up original file to " <<
1521 backupName.absFileName());
1522 // Except file is symlink do not copy because of #6587.
1523 // Hard links have bad luck.
1524 made_backup = symlink ?
1525 fileName().copyTo(backupName):
1526 fileName().moveTo(backupName);
1529 Alert::error(_("Backup failure"),
1530 bformat(_("Cannot create backup file %1$s.\n"
1531 "Please check whether the directory exists and is writable."),
1532 from_utf8(backupName.absFileName())));
1533 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1534 } else if (d->need_format_backup) {
1535 // the original file has been backed up successfully, so we
1536 // will not need to do that again
1537 d->need_format_backup = false;
1541 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1542 // Only do this if tempfile is not in autoremove mode
1545 // If we have no symlink, we can simply rename the temp file.
1546 // Otherwise, we need to copy it so the symlink stays intact.
1547 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1548 savefile.moveTo(fileName()))
1550 // saveCheckSum() was already called by writeFile(), but the
1551 // time stamp is invalidated by copying/moving
1554 if (d->file_format != LYX_FORMAT)
1555 // the file associated with this buffer is now in the current format
1556 d->file_format = LYX_FORMAT;
1559 // else we saved the file, but failed to move it to the right location.
1561 if (needBackup && made_backup && !symlink) {
1562 // the original file was moved to some new location, so it will look
1563 // to the user as if it was deleted. (see bug #9234.) we could try
1564 // to restore it, but that would basically mean trying to do again
1565 // what we just failed to do. better to leave things as they are.
1566 Alert::error(_("Write failure"),
1567 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1568 "But LyX could not move it to:\n %2$s.\n"
1569 "Your original file has been backed up to:\n %3$s"),
1570 from_utf8(savefile.absFileName()),
1571 from_utf8(fileName().absFileName()),
1572 from_utf8(backupName.absFileName())));
1574 // either we did not try to make a backup, or else we tried and failed,
1575 // or else the original file was a symlink, in which case it was copied,
1576 // not moved. so the original file is intact.
1577 Alert::error(_("Write failure"),
1578 bformat(_("Cannot move saved file to:\n %1$s.\n"
1579 "But the file has successfully been saved as:\n %2$s."),
1580 from_utf8(fileName().absFileName()),
1581 from_utf8(savefile.absFileName())));
1587 bool Buffer::writeFile(FileName const & fname) const
1589 if (d->read_only && fname == d->filename)
1592 bool retval = false;
1594 docstring const str = bformat(_("Saving document %1$s..."),
1595 makeDisplayPath(fname.absFileName()));
1598 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1600 if (params().compressed) {
1601 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1602 retval = ofs && write(ofs);
1604 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1605 retval = ofs && write(ofs);
1609 message(str + _(" could not write file!"));
1614 // removeAutosaveFile();
1617 message(str + _(" done."));
1623 docstring Buffer::emergencyWrite()
1625 // No need to save if the buffer has not changed.
1629 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1631 docstring user_message = bformat(
1632 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1634 // We try to save three places:
1635 // 1) Same place as document. Unless it is an unnamed doc.
1637 string s = absFileName();
1640 if (writeFile(FileName(s))) {
1642 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1643 return user_message;
1645 user_message += " " + _("Save failed! Trying again...\n");
1649 // 2) In HOME directory.
1650 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1652 lyxerr << ' ' << s << endl;
1653 if (writeFile(FileName(s))) {
1655 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1656 return user_message;
1659 user_message += " " + _("Save failed! Trying yet again...\n");
1661 // 3) In "/tmp" directory.
1662 // MakeAbsPath to prepend the current
1663 // drive letter on OS/2
1664 s = addName(package().temp_dir().absFileName(), absFileName());
1666 lyxerr << ' ' << s << endl;
1667 if (writeFile(FileName(s))) {
1669 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1670 return user_message;
1673 user_message += " " + _("Save failed! Document is lost.");
1676 return user_message;
1680 bool Buffer::write(ostream & ofs) const
1683 // Use the standard "C" locale for file output.
1684 ofs.imbue(locale::classic());
1687 // The top of the file should not be written by params().
1689 // write out a comment in the top of the file
1690 // Important: Keep the version formatting in sync with lyx2lyx and
1691 // tex2lyx (bug 7951)
1692 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1693 << " created this file. For more info see https://www.lyx.org/\n"
1694 << "\\lyxformat " << LYX_FORMAT << "\n"
1695 << "\\begin_document\n";
1697 /// For each author, set 'used' to true if there is a change
1698 /// by this author in the document; otherwise set it to 'false'.
1699 for (Author const & a : params().authors())
1702 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1703 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1704 for ( ; it != end; ++it)
1705 it->checkAuthors(params().authors());
1707 // now write out the buffer parameters.
1708 ofs << "\\begin_header\n";
1709 params().writeFile(ofs, this);
1710 ofs << "\\end_header\n";
1713 ofs << "\n\\begin_body\n";
1715 ofs << "\n\\end_body\n";
1717 // Write marker that shows file is complete
1718 ofs << "\\end_document" << endl;
1720 // Shouldn't really be needed....
1723 // how to check if close went ok?
1724 // Following is an attempt... (BE 20001011)
1726 // good() returns false if any error occurred, including some
1727 // formatting error.
1728 // bad() returns true if something bad happened in the buffer,
1729 // which should include file system full errors.
1734 lyxerr << "File was not closed properly." << endl;
1741 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1742 string const & original_path,
1743 OutputParams const & runparams_in,
1744 OutputWhat output) const
1746 OutputParams runparams = runparams_in;
1748 string const encoding = runparams.encoding->iconvName();
1749 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1752 try { ofs.reset(encoding); }
1753 catch (iconv_codecvt_facet_exception const & e) {
1754 lyxerr << "Caught iconv exception: " << e.what() << endl;
1755 Alert::error(_("Iconv software exception Detected"),
1756 bformat(_("Please verify that the `iconv' support software is"
1757 " properly installed and supports the selected encoding"
1758 " (%1$s), or change the encoding in"
1759 " Document>Settings>Language."), from_ascii(encoding)));
1762 if (!openFileWrite(ofs, fname))
1765 ErrorList & errorList = d->errorLists["Export"];
1767 ExportStatus status = ExportSuccess;
1770 // make sure we are ready to export
1771 // this needs to be done before we validate
1772 // FIXME Do we need to do this all the time? I.e., in children
1773 // of a master we are exporting?
1775 updateMacroInstances(OutputUpdate);
1777 ExportStatus retval;
1779 retval = writeLaTeXSource(os, original_path, runparams, output);
1780 if (retval == ExportKilled)
1781 return ExportKilled;
1783 catch (EncodingException const & e) {
1784 docstring const failed(1, e.failed_char);
1786 oss << "0x" << hex << e.failed_char << dec;
1787 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1788 docstring msg = bformat(_("Uncodable character '%1$s'"
1789 " (code point %2$s)"),
1790 failed, from_utf8(oss.str()));
1791 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1792 "representable in specific verbatim contexts.\n"
1793 "Changing the document encoding to utf8 could help."),
1794 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1796 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1797 " (code point %2$s)"),
1798 failed, from_utf8(oss.str()));
1799 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1800 "representable in the chosen encoding.\n"
1801 "Changing the document encoding to utf8 could help."),
1802 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1804 status = ExportError;
1806 catch (iconv_codecvt_facet_exception const & e) {
1807 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1809 status = ExportError;
1811 catch (exception const & e) {
1812 errorList.push_back(ErrorItem(_("conversion failed"),
1814 lyxerr << e.what() << endl;
1815 status = ExportError;
1818 lyxerr << "Caught some really weird exception..." << endl;
1822 d->texrow = move(os.texrow());
1826 status = ExportError;
1827 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1830 if (runparams_in.silent)
1838 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1839 string const & original_path,
1840 OutputParams const & runparams_in,
1841 OutputWhat output) const
1843 // The child documents, if any, shall be already loaded at this point.
1845 OutputParams runparams = runparams_in;
1847 // Some macros rely on font encoding
1848 runparams.main_fontenc = params().main_font_encoding();
1850 // If we are compiling a file standalone, even if this is the
1851 // child of some other buffer, let's cut the link here, so the
1852 // file is really independent and no concurring settings from
1853 // the master (e.g. branch state) interfere (see #8100).
1854 if (!runparams.is_child)
1855 d->ignore_parent = true;
1857 // Classify the unicode characters appearing in math insets
1858 BufferEncodings::initUnicodeMath(*this);
1860 // validate the buffer.
1861 LYXERR(Debug::LATEX, " Validating buffer...");
1862 LaTeXFeatures features(*this, params(), runparams);
1864 // This is only set once per document (in master)
1865 if (!runparams.is_child) {
1866 runparams.use_polyglossia = features.usePolyglossia();
1867 runparams.use_hyperref = features.isRequired("hyperref");
1868 runparams.use_CJK = features.mustProvide("CJK");
1870 LYXERR(Debug::LATEX, " Buffer validation done.");
1872 bool const output_preamble =
1873 output == FullSource || output == OnlyPreamble;
1874 bool const output_body =
1875 output == FullSource || output == OnlyBody;
1877 // The starting paragraph of the coming rows is the
1878 // first paragraph of the document. (Asger)
1879 if (output_preamble && runparams.nice) {
1880 os << "%% LyX " << lyx_version << " created this file. "
1881 "For more info, see https://www.lyx.org/.\n"
1882 "%% Do not edit unless you really know what "
1885 LYXERR(Debug::INFO, "lyx document header finished");
1887 // There are a few differences between nice LaTeX and usual files:
1888 // usual files have \batchmode and special input@path to allow
1889 // inclusion of figures specified by an explicitly relative path
1890 // (i.e., a path starting with './' or '../') with either \input or
1891 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1892 // input@path is set when the actual parameter original_path is set.
1893 // This is done for usual tex-file, but not for nice-latex-file.
1894 // (Matthias 250696)
1895 // Note that input@path is only needed for something the user does
1896 // in the preamble, included .tex files or ERT, files included by
1897 // LyX work without it.
1898 if (output_preamble) {
1899 if (!runparams.nice) {
1900 // code for usual, NOT nice-latex-file
1901 os << "\\batchmode\n"; // changed from \nonstopmode
1903 if (!original_path.empty()) {
1905 // We don't know the encoding of inputpath
1906 docstring const inputpath = from_utf8(original_path);
1907 docstring uncodable_glyphs;
1908 Encoding const * const enc = runparams.encoding;
1910 for (size_t n = 0; n < inputpath.size(); ++n) {
1911 if (!enc->encodable(inputpath[n])) {
1912 docstring const glyph(1, inputpath[n]);
1913 LYXERR0("Uncodable character '"
1915 << "' in input path!");
1916 uncodable_glyphs += glyph;
1921 // warn user if we found uncodable glyphs.
1922 if (!uncodable_glyphs.empty()) {
1923 frontend::Alert::warning(
1924 _("Uncodable character in file path"),
1926 _("The path of your document\n"
1928 "contains glyphs that are unknown "
1929 "in the current document encoding "
1930 "(namely %2$s). This may result in "
1931 "incomplete output, unless "
1932 "TEXINPUTS contains the document "
1933 "directory and you don't use "
1934 "explicitly relative paths (i.e., "
1935 "paths starting with './' or "
1936 "'../') in the preamble or in ERT."
1937 "\n\nIn case of problems, choose "
1938 "an appropriate document encoding\n"
1939 "(such as utf8) or change the "
1941 inputpath, uncodable_glyphs));
1943 string docdir = os::latex_path(original_path);
1944 if (contains(docdir, '#')) {
1945 docdir = subst(docdir, "#", "\\#");
1946 os << "\\catcode`\\#=11"
1947 "\\def\\#{#}\\catcode`\\#=6\n";
1949 if (contains(docdir, '%')) {
1950 docdir = subst(docdir, "%", "\\%");
1951 os << "\\catcode`\\%=11"
1952 "\\def\\%{%}\\catcode`\\%=14\n";
1954 if (contains(docdir, '~'))
1955 docdir = subst(docdir, "~", "\\string~");
1956 bool const nonascii = !isAscii(from_utf8(docdir));
1957 // LaTeX 2019/10/01 handles non-ascii path without detokenize
1958 bool const utfpathlatex = features.isAvailable("LaTeX-2019/10/01");
1959 bool const detokenize = !utfpathlatex && nonascii;
1960 bool const quote = contains(docdir, ' ');
1961 if (utfpathlatex && nonascii)
1962 os << "\\UseRawInputEncoding\n";
1963 os << "\\makeatletter\n"
1964 << "\\def\\input@path{{";
1966 os << "\\detokenize{";
1975 << "\\makeatother\n";
1979 // get parent macros (if this buffer has a parent) which will be
1980 // written at the document begin further down.
1981 MacroSet parentMacros;
1982 listParentMacros(parentMacros, features);
1984 // Write the preamble
1985 runparams.use_babel = params().writeLaTeX(os, features,
1986 d->filename.onlyPath());
1988 // Active characters
1989 runparams.active_chars = features.getActiveChars();
1991 // Biblatex bibliographies are loaded here
1992 if (params().useBiblatex()) {
1993 vector<pair<docstring, string>> const bibfiles =
1994 prepareBibFilePaths(runparams, getBibfiles(), true);
1995 for (pair<docstring, string> const & file: bibfiles) {
1996 os << "\\addbibresource";
1997 if (!file.second.empty())
1998 os << "[bibencoding=" << file.second << "]";
1999 os << "{" << file.first << "}\n";
2003 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
2004 && !features.hasOnlyPolyglossiaLanguages()) {
2007 vector<string> bll = features.getBabelExclusiveLanguages();
2008 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
2011 for (string const & sit : bll) {
2016 blangs = bll.size() > 1 ?
2017 bformat(_("The languages %1$s are only supported by Babel."), langs)
2018 : bformat(_("The language %1$s is only supported by Babel."), langs);
2022 for (string const & pit : pll) {
2027 plangs = pll.size() > 1 ?
2028 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
2029 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
2030 if (!blangs.empty())
2034 frontend::Alert::warning(
2035 _("Incompatible Languages!"),
2037 _("You cannot use the following languages "
2038 "together in one LaTeX document because "
2039 "they require conflicting language packages:\n"
2044 // Japanese might be required only in some children of a document,
2045 // but once required, we must keep use_japanese true.
2046 runparams.use_japanese |= features.isRequired("japanese");
2049 // Restore the parenthood if needed
2050 if (!runparams.is_child)
2051 d->ignore_parent = false;
2052 return ExportSuccess;
2056 // mark the beginning of the body to separate it from InPreamble insets
2057 os.texrow().start(TexRow::beginDocument());
2058 os << "\\begin{document}\n";
2060 // mark the start of a new paragraph by simulating a newline,
2061 // so that os.afterParbreak() returns true at document start
2064 // output the parent macros
2065 for (auto const & mac : parentMacros) {
2066 int num_lines = mac->write(os.os(), true);
2067 os.texrow().newlines(num_lines);
2070 } // output_preamble
2072 LYXERR(Debug::INFO, "preamble finished, now the body.");
2076 latexParagraphs(*this, text(), os, runparams);
2078 catch (ConversionException const &) { return ExportKilled; }
2080 // Restore the parenthood if needed
2081 if (!runparams.is_child)
2082 d->ignore_parent = false;
2084 // add this just in case after all the paragraphs
2087 if (output_preamble) {
2088 os << "\\end{document}\n";
2089 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2091 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2093 runparams_in.encoding = runparams.encoding;
2095 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2096 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2097 return ExportSuccess;
2101 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2102 OutputParams const & runparams,
2103 OutputWhat output) const
2105 LYXERR(Debug::LATEX, "makeDocBookFile...");
2108 if (!openFileWrite(ofs, fname))
2111 // make sure we are ready to export
2112 // this needs to be done before we validate
2114 updateMacroInstances(OutputUpdate);
2116 ExportStatus const retval =
2117 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2118 if (retval == ExportKilled)
2119 return ExportKilled;
2123 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2124 return ExportSuccess;
2128 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os, string const & fname,
2129 OutputParams const & runparams,
2130 OutputWhat output) const
2132 LaTeXFeatures features(*this, params(), runparams);
2137 DocumentClass const & tclass = params().documentClass();
2138 string const & top_element = tclass.latexname();
2140 bool const output_preamble =
2141 output == FullSource || output == OnlyPreamble;
2142 bool const output_body =
2143 output == FullSource || output == OnlyBody;
2145 if (output_preamble) {
2146 if (runparams.flavor == OutputParams::XML)
2147 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2150 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2153 if (! tclass.class_header().empty())
2154 os << from_ascii(tclass.class_header());
2155 else if (runparams.flavor == OutputParams::XML)
2156 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2157 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2159 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2161 docstring preamble = params().preamble;
2162 if (runparams.flavor != OutputParams::XML ) {
2163 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2164 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2165 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2166 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2169 string const name = runparams.nice
2170 ? changeExtension(absFileName(), ".sgml") : fname;
2171 preamble += features.getIncludedFiles(name);
2172 preamble += features.getLyXSGMLEntities();
2174 if (!preamble.empty()) {
2175 os << "\n [ " << preamble << " ]";
2181 string top = top_element;
2183 if (runparams.flavor == OutputParams::XML)
2184 top += params().language->code();
2186 top += params().language->code().substr(0, 2);
2189 if (!params().options.empty()) {
2191 top += params().options;
2194 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2195 << " file was created by LyX " << lyx_version
2196 << "\n See https://www.lyx.org/ for more information -->\n";
2198 params().documentClass().counters().reset();
2200 sgml::openTag(os, top);
2203 docbookParagraphs(text(), *this, os, runparams);
2205 catch (ConversionException const &) { return ExportKilled; }
2206 sgml::closeTag(os, top_element);
2208 return ExportSuccess;
2212 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2213 OutputParams const & runparams) const
2215 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2218 if (!openFileWrite(ofs, fname))
2221 // make sure we are ready to export
2222 // this has to be done before we validate
2223 updateBuffer(UpdateMaster, OutputUpdate);
2224 updateMacroInstances(OutputUpdate);
2226 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2227 if (retval == ExportKilled)
2232 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2237 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2238 OutputParams const & runparams,
2239 OutputWhat output) const
2241 LaTeXFeatures features(*this, params(), runparams);
2243 d->bibinfo_.makeCitationLabels(*this);
2245 bool const output_preamble =
2246 output == FullSource || output == OnlyPreamble;
2247 bool const output_body =
2248 output == FullSource || output == OnlyBody || output == IncludedFile;
2250 if (output_preamble) {
2251 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2252 << "<!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"
2253 // FIXME Language should be set properly.
2254 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2256 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2257 // FIXME Presumably need to set this right
2258 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2260 docstring const & doctitle = features.htmlTitle();
2262 << (doctitle.empty() ?
2263 from_ascii("LyX Document") :
2264 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2267 docstring styles = features.getTClassHTMLPreamble();
2268 if (!styles.empty())
2269 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2271 // we will collect CSS information in a stream, and then output it
2272 // either here, as part of the header, or else in a separate file.
2273 odocstringstream css;
2274 styles = features.getCSSSnippets();
2275 if (!styles.empty())
2276 css << "/* LyX Provided Styles */\n" << styles << '\n';
2278 styles = features.getTClassHTMLStyles();
2279 if (!styles.empty())
2280 css << "/* Layout-provided Styles */\n" << styles << '\n';
2282 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2283 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2284 if (needfg || needbg) {
2285 css << "\nbody {\n";
2288 << from_ascii(X11hexname(params().fontcolor))
2291 css << " background-color: "
2292 << from_ascii(X11hexname(params().backgroundcolor))
2297 docstring const dstyles = css.str();
2298 if (!dstyles.empty()) {
2299 bool written = false;
2300 if (params().html_css_as_file) {
2301 // open a file for CSS info
2303 string const fcssname = addName(temppath(), "docstyle.css");
2304 FileName const fcssfile = FileName(fcssname);
2305 if (openFileWrite(ocss, fcssfile)) {
2309 // write link to header
2310 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2312 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2315 // we are here if the CSS is supposed to be written to the header
2316 // or if we failed to write it to an external file.
2318 os << "<style type='text/css'>\n"
2327 bool const output_body_tag = (output != IncludedFile);
2328 if (output_body_tag)
2329 os << "<body dir=\"auto\">\n";
2331 if (output != IncludedFile)
2332 // if we're an included file, the counters are in the master.
2333 params().documentClass().counters().reset();
2335 xhtmlParagraphs(text(), *this, xs, runparams);
2337 catch (ConversionException const &) { return ExportKilled; }
2338 if (output_body_tag)
2342 if (output_preamble)
2345 return ExportSuccess;
2349 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2350 // Other flags: -wall -v0 -x
2351 int Buffer::runChktex()
2355 // get LaTeX-Filename
2356 FileName const path(temppath());
2357 string const name = addName(path.absFileName(), latexName());
2358 string const org_path = filePath();
2360 PathChanger p(path); // path to LaTeX file
2361 message(_("Running chktex..."));
2363 // Generate the LaTeX file if neccessary
2364 OutputParams runparams(¶ms().encoding());
2365 runparams.flavor = OutputParams::LATEX;
2366 runparams.nice = false;
2367 runparams.linelen = lyxrc.plaintext_linelen;
2368 ExportStatus const retval =
2369 makeLaTeXFile(FileName(name), org_path, runparams);
2370 if (retval != ExportSuccess) {
2371 // error code on failure
2376 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2377 int const res = chktex.run(terr); // run chktex
2380 Alert::error(_("chktex failure"),
2381 _("Could not run chktex successfully."));
2383 ErrorList & errlist = d->errorLists["ChkTeX"];
2385 bufferErrors(terr, errlist);
2390 if (runparams.silent)
2391 d->errorLists["ChkTeX"].clear();
2399 void Buffer::validate(LaTeXFeatures & features) const
2401 // Validate the buffer params, but not for included
2402 // files, since they also use the parent buffer's
2404 if (!features.runparams().is_child)
2405 params().validate(features);
2410 for (Paragraph const & p : paragraphs())
2411 p.validate(features);
2413 if (lyxerr.debugging(Debug::LATEX)) {
2414 features.showStruct();
2419 void Buffer::getLabelList(vector<docstring> & list) const
2421 // If this is a child document, use the master's list instead.
2423 masterBuffer()->getLabelList(list);
2428 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2429 for (auto const & tocit : *toc) {
2430 if (tocit.depth() == 0)
2431 list.push_back(tocit.str());
2436 void Buffer::invalidateBibinfoCache() const
2438 d->bibinfo_cache_valid_ = false;
2439 d->cite_labels_valid_ = false;
2440 removeBiblioTempFiles();
2441 // also invalidate the cache for the parent buffer
2442 Buffer const * const pbuf = d->parent();
2444 pbuf->invalidateBibinfoCache();
2448 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2450 // FIXME This is probably unnecessary, given where we call this.
2451 // If this is a child document, use the master instead.
2452 Buffer const * const pbuf = masterBuffer();
2453 if (pbuf != this && scope != UpdateChildOnly)
2454 return pbuf->getBibfiles();
2456 // In 2.3.x, we have:
2457 //if (!d->bibfile_cache_valid_)
2458 // this->updateBibfilesCache(scope);
2459 // I think that is a leftover, but there have been so many back-
2460 // and-forths with this, due to Windows issues, that I am not sure.
2462 return d->bibfiles_cache_;
2466 BiblioInfo const & Buffer::masterBibInfo() const
2468 Buffer const * const tmp = masterBuffer();
2470 return tmp->masterBibInfo();
2475 BiblioInfo const & Buffer::bibInfo() const
2481 void Buffer::registerBibfiles(const docstring_list & bf) const
2483 // We register the bib files in the master buffer,
2484 // if there is one, but also in every single buffer,
2485 // in case a child is compiled alone.
2486 Buffer const * const tmp = masterBuffer();
2488 tmp->registerBibfiles(bf);
2490 for (auto const & p : bf) {
2491 docstring_list::const_iterator temp =
2492 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2493 if (temp == d->bibfiles_cache_.end())
2494 d->bibfiles_cache_.push_back(p);
2499 static map<docstring, FileName> bibfileCache;
2501 FileName Buffer::getBibfilePath(docstring const & bibid) const
2503 map<docstring, FileName>::const_iterator it =
2504 bibfileCache.find(bibid);
2505 if (it != bibfileCache.end()) {
2506 // i.e., return bibfileCache[bibid];
2510 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2511 string const texfile = changeExtension(to_utf8(bibid), "bib");
2512 // we need to check first if this file exists where it's said to be.
2513 // there's a weird bug that occurs otherwise: if the file is in the
2514 // Buffer's directory but has the same name as some file that would be
2515 // found by kpsewhich, then we find the latter, not the former.
2516 FileName const local_file = makeAbsPath(texfile, filePath());
2517 FileName file = local_file;
2518 if (!file.exists()) {
2519 // there's no need now to check whether the file can be found
2521 file = findtexfile(texfile, "bib", true);
2525 LYXERR(Debug::FILES, "Found at: " << file);
2527 bibfileCache[bibid] = file;
2528 return bibfileCache[bibid];
2532 void Buffer::checkIfBibInfoCacheIsValid() const
2534 // use the master's cache
2535 Buffer const * const tmp = masterBuffer();
2537 tmp->checkIfBibInfoCacheIsValid();
2541 // If we already know the cache is invalid, stop here.
2542 // This is important in the case when the bibliography
2543 // environment (rather than Bib[la]TeX) is used.
2544 // In that case, the timestamp check below gives no
2545 // sensible result. Rather than that, the cache will
2546 // be invalidated explicitly via invalidateBibInfoCache()
2547 // by the Bibitem inset.
2548 // Same applies for bib encoding changes, which trigger
2549 // invalidateBibInfoCache() by InsetBibtex.
2550 if (!d->bibinfo_cache_valid_)
2553 if (d->have_bibitems_) {
2554 // We have a bibliography environment.
2555 // Invalidate the bibinfo cache unconditionally.
2556 // Cite labels will get invalidated by the inset if needed.
2557 d->bibinfo_cache_valid_ = false;
2561 // OK. This is with Bib(la)tex. We'll assume the cache
2562 // is valid and change this if we find changes in the bibs.
2563 d->bibinfo_cache_valid_ = true;
2564 d->cite_labels_valid_ = true;
2566 // compare the cached timestamps with the actual ones.
2567 docstring_list const & bibfiles_cache = getBibfiles();
2568 for (auto const & bf : bibfiles_cache) {
2569 FileName const fn = getBibfilePath(bf);
2570 time_t lastw = fn.lastModified();
2571 time_t prevw = d->bibfile_status_[fn];
2572 if (lastw != prevw) {
2573 d->bibinfo_cache_valid_ = false;
2574 d->cite_labels_valid_ = false;
2575 d->bibfile_status_[fn] = lastw;
2581 void Buffer::clearBibFileCache() const
2583 bibfileCache.clear();
2587 void Buffer::reloadBibInfoCache(bool const force) const
2589 // we should not need to do this for internal buffers
2593 // use the master's cache
2594 Buffer const * const tmp = masterBuffer();
2596 tmp->reloadBibInfoCache(force);
2601 checkIfBibInfoCacheIsValid();
2602 if (d->bibinfo_cache_valid_)
2606 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2607 // re-read file locations when this info changes
2608 // FIXME Is this sufficient? Or should we also force that
2609 // in some other cases? If so, then it is easy enough to
2610 // add the following line in some other places.
2611 clearBibFileCache();
2612 d->bibinfo_.clear();
2613 FileNameList checkedFiles;
2614 d->have_bibitems_ = false;
2615 collectBibKeys(checkedFiles);
2616 d->bibinfo_cache_valid_ = true;
2620 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2625 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2626 it->collectBibKeys(it, checkedFiles);
2627 if (it->lyxCode() == BIBITEM_CODE) {
2628 if (parent() != nullptr)
2629 parent()->d->have_bibitems_ = true;
2631 d->have_bibitems_ = true;
2637 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2639 // We add the biblio info to the master buffer,
2640 // if there is one, but also to every single buffer,
2641 // in case a child is compiled alone.
2642 BiblioInfo & bi = d->bibinfo_;
2643 bi.mergeBiblioInfo(bin);
2645 if (parent() != nullptr) {
2646 BiblioInfo & masterbi = parent()->d->bibinfo_;
2647 masterbi.mergeBiblioInfo(bin);
2652 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2654 // We add the bibtex info to the master buffer,
2655 // if there is one, but also to every single buffer,
2656 // in case a child is compiled alone.
2657 BiblioInfo & bi = d->bibinfo_;
2660 if (parent() != nullptr) {
2661 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2662 masterbi[key] = bin;
2667 void Buffer::makeCitationLabels() const
2669 Buffer const * const master = masterBuffer();
2670 return d->bibinfo_.makeCitationLabels(*master);
2674 void Buffer::invalidateCiteLabels() const
2676 masterBuffer()->d->cite_labels_valid_ = false;
2679 bool Buffer::citeLabelsValid() const
2681 return masterBuffer()->d->cite_labels_valid_;
2685 void Buffer::removeBiblioTempFiles() const
2687 // We remove files that contain LaTeX commands specific to the
2688 // particular bibliographic style being used, in order to avoid
2689 // LaTeX errors when we switch style.
2690 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2691 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2692 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2693 aux_file.removeFile();
2694 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2695 bbl_file.removeFile();
2696 // Also for the parent buffer
2697 Buffer const * const pbuf = parent();
2699 pbuf->removeBiblioTempFiles();
2703 bool Buffer::isDepClean(string const & name) const
2705 DepClean::const_iterator const it = d->dep_clean.find(name);
2706 if (it == d->dep_clean.end())
2712 void Buffer::markDepClean(string const & name)
2714 d->dep_clean[name] = true;
2718 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2721 // FIXME? if there is an Buffer LFUN that can be dispatched even
2722 // if internal, put a switch '(cmd.action)' here.
2728 switch (cmd.action()) {
2730 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2731 flag.setOnOff(hasReadonlyFlag());
2734 // FIXME: There is need for a command-line import.
2735 //case LFUN_BUFFER_IMPORT:
2737 case LFUN_BUFFER_AUTO_SAVE:
2740 case LFUN_BUFFER_EXPORT_CUSTOM:
2741 // FIXME: Nothing to check here?
2744 case LFUN_BUFFER_EXPORT: {
2745 docstring const arg = cmd.argument();
2746 if (arg == "custom") {
2750 string format = (arg.empty() || arg == "default") ?
2751 params().getDefaultOutputFormat() : to_utf8(arg);
2752 size_t pos = format.find(' ');
2753 if (pos != string::npos)
2754 format = format.substr(0, pos);
2755 enable = params().isExportable(format, false);
2757 flag.message(bformat(
2758 _("Don't know how to export to format: %1$s"), arg));
2762 case LFUN_BUILD_PROGRAM:
2763 enable = params().isExportable("program", false);
2766 case LFUN_BRANCH_ACTIVATE:
2767 case LFUN_BRANCH_DEACTIVATE:
2768 case LFUN_BRANCH_MASTER_ACTIVATE:
2769 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2770 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2771 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2772 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2773 : params().branchlist();
2774 docstring const branchName = cmd.argument();
2775 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2779 case LFUN_BRANCH_ADD:
2780 case LFUN_BRANCHES_RENAME:
2781 // if no Buffer is present, then of course we won't be called!
2784 case LFUN_BUFFER_LANGUAGE:
2785 enable = !isReadonly();
2788 case LFUN_BUFFER_VIEW_CACHE:
2789 (d->preview_file_).refresh();
2790 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2793 case LFUN_CHANGES_TRACK:
2794 flag.setEnabled(true);
2795 flag.setOnOff(params().track_changes);
2798 case LFUN_CHANGES_OUTPUT:
2799 flag.setEnabled(true);
2800 flag.setOnOff(params().output_changes);
2803 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2804 flag.setOnOff(params().compressed);
2807 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2808 flag.setOnOff(params().output_sync);
2811 case LFUN_BUFFER_ANONYMIZE:
2817 flag.setEnabled(enable);
2822 void Buffer::dispatch(string const & command, DispatchResult & result)
2824 return dispatch(lyxaction.lookupFunc(command), result);
2828 // NOTE We can end up here even if we have no GUI, because we are called
2829 // by LyX::exec to handled command-line requests. So we may need to check
2830 // whether we have a GUI or not. The boolean use_gui holds this information.
2831 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2834 // FIXME? if there is an Buffer LFUN that can be dispatched even
2835 // if internal, put a switch '(cmd.action())' here.
2836 dr.dispatched(false);
2839 string const argument = to_utf8(func.argument());
2840 // We'll set this back to false if need be.
2841 bool dispatched = true;
2842 // This handles undo groups automagically
2843 UndoGroupHelper ugh(this);
2845 switch (func.action()) {
2846 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2847 if (lyxvc().inUse()) {
2848 string log = lyxvc().toggleReadOnly();
2853 setReadonly(!hasReadonlyFlag());
2856 case LFUN_BUFFER_EXPORT: {
2857 string const format = (argument.empty() || argument == "default") ?
2858 params().getDefaultOutputFormat() : argument;
2859 ExportStatus const status = doExport(format, false);
2860 dr.setError(status != ExportSuccess);
2861 if (status != ExportSuccess)
2862 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2863 from_utf8(format)));
2867 case LFUN_BUILD_PROGRAM: {
2868 ExportStatus const status = doExport("program", true);
2869 dr.setError(status != ExportSuccess);
2870 if (status != ExportSuccess)
2871 dr.setMessage(_("Error generating literate programming code."));
2875 case LFUN_BUFFER_EXPORT_CUSTOM: {
2877 string command = split(argument, format_name, ' ');
2878 Format const * format = theFormats().getFormat(format_name);
2880 lyxerr << "Format \"" << format_name
2881 << "\" not recognized!"
2886 // The name of the file created by the conversion process
2889 // Output to filename
2890 if (format->name() == "lyx") {
2891 string const latexname = latexName(false);
2892 filename = changeExtension(latexname,
2893 format->extension());
2894 filename = addName(temppath(), filename);
2896 if (!writeFile(FileName(filename)))
2900 doExport(format_name, true, filename);
2903 // Substitute $$FName for filename
2904 if (!contains(command, "$$FName"))
2905 command = "( " + command + " ) < $$FName";
2906 command = subst(command, "$$FName", filename);
2908 // Execute the command in the background
2910 call.startscript(Systemcall::DontWait, command,
2911 filePath(), layoutPos());
2915 // FIXME: There is need for a command-line import.
2917 case LFUN_BUFFER_IMPORT:
2922 case LFUN_BUFFER_AUTO_SAVE:
2924 resetAutosaveTimers();
2927 case LFUN_BRANCH_ACTIVATE:
2928 case LFUN_BRANCH_DEACTIVATE:
2929 case LFUN_BRANCH_MASTER_ACTIVATE:
2930 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2931 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2932 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2933 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2936 docstring const branch_name = func.argument();
2937 // the case without a branch name is handled elsewhere
2938 if (branch_name.empty()) {
2942 Branch * branch = buf->params().branchlist().find(branch_name);
2944 LYXERR0("Branch " << branch_name << " does not exist.");
2946 docstring const msg =
2947 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2951 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2952 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2953 if (branch->isSelected() != activate) {
2954 buf->undo().recordUndoBufferParams(CursorData());
2955 branch->setSelected(activate);
2957 dr.screenUpdate(Update::Force);
2958 dr.forceBufferUpdate();
2963 case LFUN_BRANCH_ADD: {
2964 docstring branchnames = func.argument();
2965 if (branchnames.empty()) {
2969 BranchList & branch_list = params().branchlist();
2970 vector<docstring> const branches =
2971 getVectorFromString(branchnames, branch_list.separator());
2973 for (docstring const & branch_name : branches) {
2974 Branch * branch = branch_list.find(branch_name);
2976 LYXERR0("Branch " << branch_name << " already exists.");
2980 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2982 undo().recordUndoBufferParams(CursorData());
2983 branch_list.add(branch_name);
2984 branch = branch_list.find(branch_name);
2985 string const x11hexname = X11hexname(branch->color());
2986 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2987 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2989 dr.screenUpdate(Update::Force);
2997 case LFUN_BRANCHES_RENAME: {
2998 if (func.argument().empty())
3001 docstring const oldname = from_utf8(func.getArg(0));
3002 docstring const newname = from_utf8(func.getArg(1));
3003 InsetIterator it = inset_iterator_begin(inset());
3004 InsetIterator const end = inset_iterator_end(inset());
3005 bool success = false;
3006 for (; it != end; ++it) {
3007 if (it->lyxCode() == BRANCH_CODE) {
3008 InsetBranch & ins = static_cast<InsetBranch &>(*it);
3009 if (ins.branch() == oldname) {
3010 undo().recordUndo(CursorData(it));
3011 ins.rename(newname);
3016 if (it->lyxCode() == INCLUDE_CODE) {
3017 // get buffer of external file
3018 InsetInclude const & ins =
3019 static_cast<InsetInclude const &>(*it);
3020 Buffer * child = ins.loadIfNeeded();
3023 child->dispatch(func, dr);
3028 dr.screenUpdate(Update::Force);
3029 dr.forceBufferUpdate();
3034 case LFUN_BUFFER_VIEW_CACHE:
3035 if (!theFormats().view(*this, d->preview_file_,
3036 d->preview_format_))
3037 dr.setMessage(_("Error viewing the output file."));
3040 case LFUN_CHANGES_TRACK:
3041 if (params().save_transient_properties)
3042 undo().recordUndoBufferParams(CursorData());
3043 params().track_changes = !params().track_changes;
3046 case LFUN_CHANGES_OUTPUT:
3047 if (params().save_transient_properties)
3048 undo().recordUndoBufferParams(CursorData());
3049 params().output_changes = !params().output_changes;
3050 if (params().output_changes) {
3051 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
3052 LaTeXFeatures::isAvailable("xcolor");
3055 Alert::warning(_("Changes not shown in LaTeX output"),
3056 _("Changes will not be highlighted in LaTeX output, "
3057 "because xcolor and ulem are not installed.\n"
3058 "Please install both packages or redefine "
3059 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3064 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3065 // turn compression on/off
3066 undo().recordUndoBufferParams(CursorData());
3067 params().compressed = !params().compressed;
3070 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3071 undo().recordUndoBufferParams(CursorData());
3072 params().output_sync = !params().output_sync;
3075 case LFUN_BUFFER_ANONYMIZE: {
3076 undo().recordUndoFullBuffer(CursorData());
3077 CursorData cur(doc_iterator_begin(this));
3078 for ( ; cur ; cur.forwardPar())
3079 cur.paragraph().anonymize();
3080 dr.forceBufferUpdate();
3081 dr.screenUpdate(Update::Force);
3089 dr.dispatched(dispatched);
3093 void Buffer::changeLanguage(Language const * from, Language const * to)
3095 LASSERT(from, return);
3096 LASSERT(to, return);
3098 ParIterator it = par_iterator_begin();
3099 ParIterator eit = par_iterator_end();
3100 for (; it != eit; ++it)
3101 it->changeLanguage(params(), from, to);
3105 bool Buffer::isMultiLingual() const
3107 ParConstIterator end = par_iterator_end();
3108 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3109 if (it->isMultiLingual(params()))
3116 std::set<Language const *> Buffer::getLanguages() const
3118 std::set<Language const *> langs;
3119 getLanguages(langs);
3124 void Buffer::getLanguages(std::set<Language const *> & langs) const
3126 ParConstIterator end = par_iterator_end();
3127 // add the buffer language, even if it's not actively used
3128 langs.insert(language());
3129 // iterate over the paragraphs
3130 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3131 it->getLanguages(langs);
3133 ListOfBuffers clist = getDescendants();
3134 for (auto const & cit : clist)
3135 cit->getLanguages(langs);
3139 DocIterator Buffer::getParFromID(int const id) const
3141 Buffer * buf = const_cast<Buffer *>(this);
3143 // This means non-existent
3144 return doc_iterator_end(buf);
3146 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3147 if (it.paragraph().id() == id)
3150 return doc_iterator_end(buf);
3154 bool Buffer::hasParWithID(int const id) const
3156 return !getParFromID(id).atEnd();
3160 ParIterator Buffer::par_iterator_begin()
3162 return ParIterator(doc_iterator_begin(this));
3166 ParIterator Buffer::par_iterator_end()
3168 return ParIterator(doc_iterator_end(this));
3172 ParConstIterator Buffer::par_iterator_begin() const
3174 return ParConstIterator(doc_iterator_begin(this));
3178 ParConstIterator Buffer::par_iterator_end() const
3180 return ParConstIterator(doc_iterator_end(this));
3184 Language const * Buffer::language() const
3186 return params().language;
3190 docstring Buffer::B_(string const & l10n) const
3192 return params().B_(l10n);
3196 bool Buffer::isClean() const
3198 return d->lyx_clean;
3202 bool Buffer::isChecksumModified() const
3204 LASSERT(d->filename.exists(), return false);
3205 return d->checksum_ != d->filename.checksum();
3209 void Buffer::saveCheckSum() const
3211 FileName const & file = d->filename;
3213 d->checksum_ = file.exists() ? file.checksum()
3214 : 0; // in the case of save to a new file.
3218 void Buffer::markClean() const
3220 if (!d->lyx_clean) {
3221 d->lyx_clean = true;
3224 // if the .lyx file has been saved, we don't need an
3226 d->bak_clean = true;
3227 d->undo_.markDirty();
3228 clearExternalModification();
3232 void Buffer::setUnnamed(bool flag)
3238 bool Buffer::isUnnamed() const
3245 /// Don't check unnamed, here: isInternal() is used in
3246 /// newBuffer(), where the unnamed flag has not been set by anyone
3247 /// yet. Also, for an internal buffer, there should be no need for
3248 /// retrieving fileName() nor for checking if it is unnamed or not.
3249 bool Buffer::isInternal() const
3251 return d->internal_buffer;
3255 void Buffer::setInternal(bool flag)
3257 d->internal_buffer = flag;
3261 void Buffer::markDirty()
3264 d->lyx_clean = false;
3267 d->bak_clean = false;
3269 for (auto & depit : d->dep_clean)
3270 depit.second = false;
3274 FileName Buffer::fileName() const
3280 string Buffer::absFileName() const
3282 return d->filename.absFileName();
3286 string Buffer::filePath() const
3288 string const abs = d->filename.onlyPath().absFileName();
3291 int last = abs.length() - 1;
3293 return abs[last] == '/' ? abs : abs + '/';
3297 DocFileName Buffer::getReferencedFileName(string const & fn) const
3300 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3301 result.set(fn, filePath());
3303 // filePath() ends with a path separator
3304 FileName const test(filePath() + fn);
3306 result.set(fn, filePath());
3308 result.set(fn, params().origin);
3315 string const Buffer::prepareFileNameForLaTeX(string const & name,
3316 string const & ext, bool nice) const
3318 string const fname = makeAbsPath(name, filePath()).absFileName();
3319 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3325 return to_utf8(makeRelPath(from_utf8(fname),
3326 from_utf8(masterBuffer()->filePath())));
3330 vector<pair<docstring, string>> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3331 docstring_list const & bibfilelist,
3332 bool const add_extension) const
3334 // If we are processing the LaTeX file in a temp directory then
3335 // copy the .bib databases to this temp directory, mangling their
3336 // names in the process. Store this mangled name in the list of
3338 // (We need to do all this because BibTeX *really*, *really*
3339 // can't handle "files with spaces" and Windows users tend to
3340 // use such filenames.)
3341 // Otherwise, store the (maybe absolute) path to the original,
3342 // unmangled database name.
3344 vector<pair<docstring, string>> res;
3346 // determine the export format
3347 string const tex_format = flavor2format(runparams.flavor);
3349 // check for spaces in paths
3350 bool found_space = false;
3352 for (auto const & bit : bibfilelist) {
3353 string utf8input = to_utf8(bit);
3355 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3356 FileName try_in_file =
3357 makeAbsPath(database + ".bib", filePath());
3358 bool not_from_texmf = try_in_file.isReadableFile();
3359 // If the file has not been found, try with the real file name
3360 // (it might come from a child in a sub-directory)
3361 if (!not_from_texmf) {
3362 try_in_file = getBibfilePath(bit);
3363 if (try_in_file.isReadableFile()) {
3364 // Check if the file is in texmf
3365 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3366 not_from_texmf = kpsefile.empty()
3367 || kpsefile.absFileName() != try_in_file.absFileName();
3369 // If this exists, make path relative to the master
3372 removeExtension(prepareFileNameForLaTeX(
3373 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3374 from_utf8(filePath()))),
3375 ".bib", runparams.nice));
3379 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3381 // mangledFileName() needs the extension
3382 DocFileName const in_file = DocFileName(try_in_file);
3383 database = removeExtension(in_file.mangledFileName());
3384 FileName const out_file = makeAbsPath(database + ".bib",
3385 masterBuffer()->temppath());
3386 bool const success = in_file.copyTo(out_file);
3388 LYXERR0("Failed to copy '" << in_file
3389 << "' to '" << out_file << "'");
3391 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3392 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3393 if (!isValidLaTeXFileName(database)) {
3394 frontend::Alert::warning(_("Invalid filename"),
3395 _("The following filename will cause troubles "
3396 "when running the exported file through LaTeX: ") +
3397 from_utf8(database));
3399 if (!isValidDVIFileName(database)) {
3400 frontend::Alert::warning(_("Problematic filename for DVI"),
3401 _("The following filename can cause troubles "
3402 "when running the exported file through LaTeX "
3403 "and opening the resulting DVI: ") +
3404 from_utf8(database), true);
3412 docstring const path = from_utf8(latex_path(database));
3414 if (contains(path, ' '))
3417 if (params().useBiblatex() && !params().bibFileEncoding(utf8input).empty())
3418 enc = params().bibFileEncoding(utf8input);
3420 bool recorded = false;
3421 for (auto const & pe : res) {
3422 if (pe.first == path) {
3429 res.push_back(make_pair(path, enc));
3432 // Check if there are spaces in the path and warn BibTeX users, if so.
3433 // (biber can cope with such paths)
3434 if (!prefixIs(runparams.bibtex_command, "biber")) {
3435 // Post this warning only once.
3436 static bool warned_about_spaces = false;
3437 if (!warned_about_spaces &&
3438 runparams.nice && found_space) {
3439 warned_about_spaces = true;
3440 Alert::warning(_("Export Warning!"),
3441 _("There are spaces in the paths to your BibTeX databases.\n"
3442 "BibTeX will be unable to find them."));
3451 string Buffer::layoutPos() const
3453 return d->layout_position;
3457 void Buffer::setLayoutPos(string const & path)
3460 d->layout_position.clear();
3464 LATTEST(FileName::isAbsolute(path));
3466 d->layout_position =
3467 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3469 if (d->layout_position.empty())
3470 d->layout_position = ".";
3474 bool Buffer::hasReadonlyFlag() const
3476 return d->read_only;
3480 bool Buffer::isReadonly() const
3482 return hasReadonlyFlag() || notifiesExternalModification();
3486 void Buffer::setParent(Buffer const * buffer)
3488 // We need to do some work here to avoid recursive parent structures.
3489 // This is the easy case.
3490 if (buffer == this) {
3491 LYXERR0("Ignoring attempt to set self as parent in\n" << fileName());
3494 // Now we check parents going upward, to make sure that IF we set the
3495 // parent as requested, we would not generate a recursive include.
3496 set<Buffer const *> sb;
3497 Buffer const * b = buffer;
3498 bool found_recursion = false;
3500 if (sb.find(b) != sb.end()) {
3501 found_recursion = true;
3508 if (found_recursion) {
3509 LYXERR0("Ignoring attempt to set parent of\n" <<
3512 buffer->fileName() <<
3513 "\nbecause that would create a recursive inclusion.");
3517 // We should be safe now.
3518 d->setParent(buffer);
3523 Buffer const * Buffer::parent() const
3529 ListOfBuffers Buffer::allRelatives() const
3531 ListOfBuffers lb = masterBuffer()->getDescendants();
3532 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3537 Buffer const * Buffer::masterBuffer() const
3539 Buffer const * const pbuf = d->parent();
3543 return pbuf->masterBuffer();
3547 bool Buffer::isChild(Buffer * child) const
3549 return d->children_positions.find(child) != d->children_positions.end();
3553 DocIterator Buffer::firstChildPosition(Buffer const * child)
3555 Impl::BufferPositionMap::iterator it;
3556 it = d->children_positions.find(child);
3557 if (it == d->children_positions.end())
3558 return DocIterator(this);
3563 bool Buffer::hasChildren() const
3565 return !d->children_positions.empty();
3569 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3571 // loop over children
3572 for (auto const & p : d->children_positions) {
3573 Buffer * child = const_cast<Buffer *>(p.first);
3575 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3576 if (bit != clist.end())
3578 clist.push_back(child);
3580 // there might be grandchildren
3581 child->collectChildren(clist, true);
3586 ListOfBuffers Buffer::getChildren() const
3589 collectChildren(v, false);
3590 // Make sure we have not included ourselves.
3591 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3592 if (bit != v.end()) {
3593 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3600 ListOfBuffers Buffer::getDescendants() const
3603 collectChildren(v, true);
3604 // Make sure we have not included ourselves.
3605 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3606 if (bit != v.end()) {
3607 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3614 template<typename M>
3615 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3620 typename M::const_iterator it = m.lower_bound(x);
3621 if (it == m.begin())
3629 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3630 DocIterator const & pos) const
3632 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3634 // if paragraphs have no macro context set, pos will be empty
3638 // we haven't found anything yet
3639 DocIterator bestPos = owner_->par_iterator_begin();
3640 MacroData const * bestData = nullptr;
3642 // find macro definitions for name
3643 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3644 if (nameIt != macros.end()) {
3645 // find last definition in front of pos or at pos itself
3646 PositionScopeMacroMap::const_iterator it
3647 = greatest_below(nameIt->second, pos);
3648 if (it != nameIt->second.end()) {
3650 // scope ends behind pos?
3651 if (pos < it->second.scope) {
3652 // Looks good, remember this. If there
3653 // is no external macro behind this,
3654 // we found the right one already.
3655 bestPos = it->first;
3656 bestData = &it->second.macro;
3660 // try previous macro if there is one
3661 if (it == nameIt->second.begin())
3668 // find macros in included files
3669 PositionScopeBufferMap::const_iterator it
3670 = greatest_below(position_to_children, pos);
3671 if (it == position_to_children.end())
3672 // no children before
3676 // do we know something better (i.e. later) already?
3677 if (it->first < bestPos )
3680 // scope ends behind pos?
3681 if (pos < it->second.scope
3682 && (cloned_buffer_ ||
3683 theBufferList().isLoaded(it->second.buffer))) {
3684 // look for macro in external file
3686 MacroData const * data
3687 = it->second.buffer->getMacro(name, false);
3690 bestPos = it->first;
3696 // try previous file if there is one
3697 if (it == position_to_children.begin())
3702 // return the best macro we have found
3707 MacroData const * Buffer::getMacro(docstring const & name,
3708 DocIterator const & pos, bool global) const
3713 // query buffer macros
3714 MacroData const * data = d->getBufferMacro(name, pos);
3715 if (data != nullptr)
3718 // If there is a master buffer, query that
3719 Buffer const * const pbuf = d->parent();
3721 d->macro_lock = true;
3722 MacroData const * macro = pbuf->getMacro(
3723 name, *this, false);
3724 d->macro_lock = false;
3730 data = MacroTable::globalMacros().get(name);
3731 if (data != nullptr)
3739 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3741 // set scope end behind the last paragraph
3742 DocIterator scope = par_iterator_begin();
3743 scope.pit() = scope.lastpit() + 1;
3745 return getMacro(name, scope, global);
3749 MacroData const * Buffer::getMacro(docstring const & name,
3750 Buffer const & child, bool global) const
3752 // look where the child buffer is included first
3753 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3754 if (it == d->children_positions.end())
3757 // check for macros at the inclusion position
3758 return getMacro(name, it->second, global);
3762 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3764 pit_type const lastpit = it.lastpit();
3766 // look for macros in each paragraph
3767 while (it.pit() <= lastpit) {
3768 Paragraph & par = it.paragraph();
3770 // FIXME Can this be done with the new-style iterators?
3771 // iterate over the insets of the current paragraph
3772 for (auto const & insit : par.insetList()) {
3773 it.pos() = insit.pos;
3775 // is it a nested text inset?
3776 if (insit.inset->asInsetText()) {
3777 // Inset needs its own scope?
3778 InsetText const * itext = insit.inset->asInsetText();
3779 bool newScope = itext->isMacroScope();
3781 // scope which ends just behind the inset
3782 DocIterator insetScope = it;
3785 // collect macros in inset
3786 it.push_back(CursorSlice(*insit.inset));
3787 updateMacros(it, newScope ? insetScope : scope);
3792 if (insit.inset->asInsetTabular()) {
3793 CursorSlice slice(*insit.inset);
3794 size_t const numcells = slice.nargs();
3795 for (; slice.idx() < numcells; slice.forwardIdx()) {
3796 it.push_back(slice);
3797 updateMacros(it, scope);
3803 // is it an external file?
3804 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3805 // get buffer of external file
3806 InsetInclude const & incinset =
3807 static_cast<InsetInclude const &>(*insit.inset);
3809 Buffer * child = incinset.loadIfNeeded();
3814 // register its position, but only when it is
3815 // included first in the buffer
3816 if (children_positions.find(child) ==
3817 children_positions.end())
3818 children_positions[child] = it;
3820 // register child with its scope
3821 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3825 InsetMath * im = insit.inset->asInsetMath();
3826 if (doing_export && im) {
3827 InsetMathHull * hull = im->asHullInset();
3829 hull->recordLocation(it);
3832 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3836 InsetMathMacroTemplate & macroTemplate =
3837 *insit.inset->asInsetMath()->asMacroTemplate();
3838 MacroContext mc(owner_, it);
3839 macroTemplate.updateToContext(mc);
3842 bool valid = macroTemplate.validMacro();
3843 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3844 // then the BufferView's cursor will be invalid in
3845 // some cases which leads to crashes.
3850 // FIXME (Abdel), I don't understand why we pass 'it' here
3851 // instead of 'macroTemplate' defined above... is this correct?
3852 macros[macroTemplate.name()][it] =
3853 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3863 void Buffer::updateMacros() const
3868 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3870 // start with empty table
3872 d->children_positions.clear();
3873 d->position_to_children.clear();
3875 // Iterate over buffer, starting with first paragraph
3876 // The scope must be bigger than any lookup DocIterator
3877 // later. For the global lookup, lastpit+1 is used, hence
3878 // we use lastpit+2 here.
3879 DocIterator it = par_iterator_begin();
3880 DocIterator outerScope = it;
3881 outerScope.pit() = outerScope.lastpit() + 2;
3882 d->updateMacros(it, outerScope);
3886 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3888 InsetIterator it = inset_iterator_begin(inset());
3889 InsetIterator const end = inset_iterator_end(inset());
3890 for (; it != end; ++it) {
3891 if (it->lyxCode() == BRANCH_CODE) {
3892 InsetBranch & br = static_cast<InsetBranch &>(*it);
3893 docstring const name = br.branch();
3894 if (!from_master && !params().branchlist().find(name))
3895 result.push_back(name);
3896 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3897 result.push_back(name);
3900 if (it->lyxCode() == INCLUDE_CODE) {
3901 // get buffer of external file
3902 InsetInclude const & ins =
3903 static_cast<InsetInclude const &>(*it);
3904 Buffer * child = ins.loadIfNeeded();
3907 child->getUsedBranches(result, true);
3910 // remove duplicates
3915 void Buffer::updateMacroInstances(UpdateType utype) const
3917 LYXERR(Debug::MACROS, "updateMacroInstances for "
3918 << d->filename.onlyFileName());
3919 DocIterator it = doc_iterator_begin(this);
3921 DocIterator const end = doc_iterator_end(this);
3922 for (; it != end; it.forwardInset()) {
3923 // look for MathData cells in InsetMathNest insets
3924 InsetMath * minset = it.nextInset()->asInsetMath();
3928 // update macro in all cells of the InsetMathNest
3929 DocIterator::idx_type n = minset->nargs();
3930 MacroContext mc = MacroContext(this, it);
3931 for (DocIterator::idx_type i = 0; i < n; ++i) {
3932 MathData & data = minset->cell(i);
3933 data.updateMacros(nullptr, mc, utype, 0);
3939 void Buffer::listMacroNames(MacroNameSet & macros) const
3944 d->macro_lock = true;
3946 // loop over macro names
3947 for (auto const & nameit : d->macros)
3948 macros.insert(nameit.first);
3950 // loop over children
3951 for (auto const & p : d->children_positions) {
3952 Buffer * child = const_cast<Buffer *>(p.first);
3953 // The buffer might have been closed (see #10766).
3954 if (theBufferList().isLoaded(child))
3955 child->listMacroNames(macros);
3959 Buffer const * const pbuf = d->parent();
3961 pbuf->listMacroNames(macros);
3963 d->macro_lock = false;
3967 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3969 Buffer const * const pbuf = d->parent();
3974 pbuf->listMacroNames(names);
3977 for (auto const & mit : names) {
3979 MacroData const * data = pbuf->getMacro(mit, *this, false);
3981 macros.insert(data);
3983 // we cannot access the original InsetMathMacroTemplate anymore
3984 // here to calls validate method. So we do its work here manually.
3985 // FIXME: somehow make the template accessible here.
3986 if (data->optionals() > 0)
3987 features.require("xargs");
3993 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3996 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3998 RefCache::iterator it = d->ref_cache_.find(label);
3999 if (it != d->ref_cache_.end())
4002 static References const dummy_refs = References();
4003 it = d->ref_cache_.insert(
4004 make_pair(label, dummy_refs)).first;
4009 Buffer::References const & Buffer::references(docstring const & label) const
4011 return const_cast<Buffer *>(this)->getReferenceCache(label);
4015 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
4017 References & refs = getReferenceCache(label);
4018 refs.push_back(make_pair(inset, it));
4022 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
4026 linfo.label = label;
4028 linfo.active = active;
4029 masterBuffer()->d->label_cache_.push_back(linfo);
4033 InsetLabel const * Buffer::insetLabel(docstring const & label,
4034 bool const active) const
4036 for (auto const & rc : masterBuffer()->d->label_cache_) {
4037 if (rc.label == label && (rc.active || !active))
4044 bool Buffer::activeLabel(docstring const & label) const
4046 if (!insetLabel(label, true))
4053 void Buffer::clearReferenceCache() const
4056 d->ref_cache_.clear();
4057 d->label_cache_.clear();
4062 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
4064 //FIXME: This does not work for child documents yet.
4065 reloadBibInfoCache();
4067 // Check if the label 'from' appears more than once
4068 vector<docstring> labels;
4069 for (auto const & bibit : masterBibInfo())
4070 labels.push_back(bibit.first);
4072 if (count(labels.begin(), labels.end(), from) > 1)
4075 string const paramName = "key";
4076 UndoGroupHelper ugh(this);
4077 InsetIterator it = inset_iterator_begin(inset());
4079 if (it->lyxCode() != CITE_CODE)
4081 InsetCommand * inset = it->asInsetCommand();
4082 docstring const oldValue = inset->getParam(paramName);
4083 if (oldValue == from) {
4084 undo().recordUndo(CursorData(it));
4085 inset->setParam(paramName, to);
4090 // returns NULL if id-to-row conversion is unsupported
4091 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4092 pit_type par_begin, pit_type par_end,
4093 OutputWhat output, bool master) const
4095 unique_ptr<TexRow> texrow;
4096 OutputParams runparams(¶ms().encoding());
4097 runparams.nice = true;
4098 runparams.flavor = params().getOutputFlavor(format);
4099 runparams.linelen = lyxrc.plaintext_linelen;
4100 // No side effect of file copying and image conversion
4101 runparams.dryrun = true;
4103 // Some macros rely on font encoding
4104 runparams.main_fontenc = params().main_font_encoding();
4106 if (output == CurrentParagraph) {
4107 runparams.par_begin = par_begin;
4108 runparams.par_end = par_end;
4109 if (par_begin + 1 == par_end) {
4111 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4115 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4116 convert<docstring>(par_begin),
4117 convert<docstring>(par_end - 1))
4120 // output paragraphs
4121 if (runparams.flavor == OutputParams::LYX) {
4122 Paragraph const & par = text().paragraphs()[par_begin];
4124 depth_type dt = par.getDepth();
4125 par.write(ods, params(), dt);
4126 os << from_utf8(ods.str());
4127 } else if (runparams.flavor == OutputParams::HTML) {
4129 setMathFlavor(runparams);
4130 xhtmlParagraphs(text(), *this, xs, runparams);
4131 } else if (runparams.flavor == OutputParams::TEXT) {
4133 // FIXME Handles only one paragraph, unlike the others.
4134 // Probably should have some routine with a signature like them.
4135 writePlaintextParagraph(*this,
4136 text().paragraphs()[par_begin], os, runparams, dummy);
4137 } else if (params().isDocBook()) {
4138 docbookParagraphs(text(), *this, os, runparams);
4140 // If we are previewing a paragraph, even if this is the
4141 // child of some other buffer, let's cut the link here,
4142 // so that no concurring settings from the master
4143 // (e.g. branch state) interfere (see #8101).
4145 d->ignore_parent = true;
4146 // We need to validate the Buffer params' features here
4147 // in order to know if we should output polyglossia
4148 // macros (instead of babel macros)
4149 LaTeXFeatures features(*this, params(), runparams);
4151 runparams.use_polyglossia = features.usePolyglossia();
4152 runparams.use_hyperref = features.isRequired("hyperref");
4153 // latex or literate
4156 ots.texrow().newlines(2);
4158 latexParagraphs(*this, text(), ots, runparams);
4159 texrow = ots.releaseTexRow();
4161 // Restore the parenthood
4163 d->ignore_parent = false;
4167 if (output == FullSource)
4168 os << _("Preview source code");
4169 else if (output == OnlyPreamble)
4170 os << _("Preview preamble");
4171 else if (output == OnlyBody)
4172 os << _("Preview body");
4174 if (runparams.flavor == OutputParams::LYX) {
4176 if (output == FullSource)
4178 else if (output == OnlyPreamble)
4179 params().writeFile(ods, this);
4180 else if (output == OnlyBody)
4182 os << from_utf8(ods.str());
4183 } else if (runparams.flavor == OutputParams::HTML) {
4184 writeLyXHTMLSource(os, runparams, output);
4185 } else if (runparams.flavor == OutputParams::TEXT) {
4186 if (output == OnlyPreamble) {
4187 os << "% "<< _("Plain text does not have a preamble.");
4189 writePlaintextFile(*this, os, runparams);
4190 } else if (params().isDocBook()) {
4191 writeDocBookSource(os, absFileName(), runparams, output);
4193 // latex or literate
4196 ots.texrow().newlines(2);
4198 runparams.is_child = true;
4200 writeLaTeXSource(ots, string(), runparams, output);
4201 texrow = ots.releaseTexRow();
4208 ErrorList & Buffer::errorList(string const & type) const
4210 return d->errorLists[type];
4214 void Buffer::updateTocItem(std::string const & type,
4215 DocIterator const & dit) const
4218 d->gui_->updateTocItem(type, dit);
4222 void Buffer::structureChanged() const
4225 d->gui_->structureChanged();
4229 void Buffer::errors(string const & err, bool from_master) const
4232 d->gui_->errors(err, from_master);
4236 void Buffer::message(docstring const & msg) const
4239 d->gui_->message(msg);
4243 void Buffer::setBusy(bool on) const
4246 d->gui_->setBusy(on);
4250 void Buffer::updateTitles() const
4253 d->wa_->updateTitles();
4257 void Buffer::resetAutosaveTimers() const
4260 d->gui_->resetAutosaveTimers();
4264 bool Buffer::hasGuiDelegate() const
4270 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4276 FileName Buffer::getEmergencyFileName() const
4278 return FileName(d->filename.absFileName() + ".emergency");
4282 FileName Buffer::getAutosaveFileName() const
4284 // if the document is unnamed try to save in the backup dir, else
4285 // in the default document path, and as a last try in the filePath,
4286 // which will most often be the temporary directory
4289 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4290 : lyxrc.backupdir_path;
4291 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4294 string const fname = "#" + d->filename.onlyFileName() + "#";
4296 return makeAbsPath(fname, fpath);
4300 void Buffer::removeAutosaveFile() const
4302 FileName const f = getAutosaveFileName();
4308 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4310 FileName const newauto = getAutosaveFileName();
4312 if (newauto != oldauto && oldauto.exists())
4313 if (!oldauto.moveTo(newauto))
4314 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4318 bool Buffer::autoSave() const
4320 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4321 if (buf->d->bak_clean || hasReadonlyFlag())
4324 message(_("Autosaving current document..."));
4325 buf->d->bak_clean = true;
4327 FileName const fname = getAutosaveFileName();
4328 LASSERT(d->cloned_buffer_, return false);
4330 // If this buffer is cloned, we assume that
4331 // we are running in a separate thread already.
4332 TempFile tempfile("lyxautoXXXXXX.lyx");
4333 tempfile.setAutoRemove(false);
4334 FileName const tmp_ret = tempfile.name();
4335 if (!tmp_ret.empty()) {
4337 // assume successful write of tmp_ret
4338 if (tmp_ret.moveTo(fname))
4341 // failed to write/rename tmp_ret so try writing direct
4342 return writeFile(fname);
4346 void Buffer::setExportStatus(bool e) const
4348 d->doing_export = e;
4349 ListOfBuffers clist = getDescendants();
4350 for (auto const & bit : clist)
4351 bit->d->doing_export = e;
4355 bool Buffer::isExporting() const
4357 return d->doing_export;
4361 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4365 return doExport(target, put_in_tempdir, result_file);
4368 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4369 string & result_file) const
4371 bool const update_unincluded =
4372 params().maintain_unincluded_children != BufferParams::CM_None
4373 && !params().getIncludedChildren().empty();
4375 // (1) export with all included children (omit \includeonly)
4376 if (update_unincluded) {
4377 ExportStatus const status =
4378 doExport(target, put_in_tempdir, true, result_file);
4379 if (status != ExportSuccess)
4382 // (2) export with included children only
4383 return doExport(target, put_in_tempdir, false, result_file);
4387 void Buffer::setMathFlavor(OutputParams & op) const
4389 switch (params().html_math_output) {
4390 case BufferParams::MathML:
4391 op.math_flavor = OutputParams::MathAsMathML;
4393 case BufferParams::HTML:
4394 op.math_flavor = OutputParams::MathAsHTML;
4396 case BufferParams::Images:
4397 op.math_flavor = OutputParams::MathAsImages;
4399 case BufferParams::LaTeX:
4400 op.math_flavor = OutputParams::MathAsLaTeX;
4406 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4407 bool includeall, string & result_file) const
4409 LYXERR(Debug::FILES, "target=" << target);
4410 OutputParams runparams(¶ms().encoding());
4411 string format = target;
4412 string dest_filename;
4413 size_t pos = target.find(' ');
4414 if (pos != string::npos) {
4415 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4416 format = target.substr(0, pos);
4417 if (format == "default")
4418 format = params().getDefaultOutputFormat();
4419 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4420 FileName(dest_filename).onlyPath().createPath();
4421 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4423 MarkAsExporting exporting(this);
4424 string backend_format;
4425 runparams.flavor = OutputParams::LATEX;
4426 runparams.linelen = lyxrc.plaintext_linelen;
4427 runparams.includeall = includeall;
4428 vector<string> backs = params().backends();
4429 Converters converters = theConverters();
4430 bool need_nice_file = false;
4431 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4432 // Get shortest path to format
4433 converters.buildGraph();
4434 Graph::EdgePath path;
4435 for (string const & sit : backs) {
4436 Graph::EdgePath p = converters.getPath(sit, format);
4437 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4438 backend_format = sit;
4443 if (!put_in_tempdir) {
4444 // Only show this alert if this is an export to a non-temporary
4445 // file (not for previewing).
4446 docstring s = bformat(_("No information for exporting the format %1$s."),
4447 theFormats().prettyName(format));
4448 if (format == "pdf4")
4450 + bformat(_("Hint: use non-TeX fonts or set input encoding "
4451 " to '%1$s'"), from_utf8(encodings.fromLyXName("ascii")->guiName()));
4452 Alert::error(_("Couldn't export file"), s);
4454 return ExportNoPathToFormat;
4456 runparams.flavor = converters.getFlavor(path, this);
4457 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4458 for (auto const & edge : path)
4459 if (theConverters().get(edge).nice()) {
4460 need_nice_file = true;
4465 backend_format = format;
4466 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4467 // FIXME: Don't hardcode format names here, but use a flag
4468 if (backend_format == "pdflatex")
4469 runparams.flavor = OutputParams::PDFLATEX;
4470 else if (backend_format == "luatex")
4471 runparams.flavor = OutputParams::LUATEX;
4472 else if (backend_format == "dviluatex")
4473 runparams.flavor = OutputParams::DVILUATEX;
4474 else if (backend_format == "xetex")
4475 runparams.flavor = OutputParams::XETEX;
4478 string filename = latexName(false);
4479 filename = addName(temppath(), filename);
4480 filename = changeExtension(filename,
4481 theFormats().extension(backend_format));
4482 LYXERR(Debug::FILES, "filename=" << filename);
4484 // Plain text backend
4485 if (backend_format == "text") {
4486 runparams.flavor = OutputParams::TEXT;
4488 writePlaintextFile(*this, FileName(filename), runparams);
4490 catch (ConversionException const &) { return ExportCancel; }
4493 else if (backend_format == "xhtml") {
4494 runparams.flavor = OutputParams::HTML;
4495 setMathFlavor(runparams);
4496 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4497 return ExportKilled;
4498 } else if (backend_format == "lyx")
4499 writeFile(FileName(filename));
4501 else if (params().isDocBook()) {
4502 runparams.nice = !put_in_tempdir;
4503 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4504 return ExportKilled;
4507 else if (backend_format == format || need_nice_file) {
4508 runparams.nice = true;
4509 ExportStatus const retval =
4510 makeLaTeXFile(FileName(filename), string(), runparams);
4511 if (retval == ExportKilled)
4512 return ExportKilled;
4513 if (d->cloned_buffer_)
4514 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4515 if (retval != ExportSuccess)
4517 } else if (!lyxrc.tex_allows_spaces
4518 && contains(filePath(), ' ')) {
4519 Alert::error(_("File name error"),
4520 bformat(_("The directory path to the document\n%1$s\n"
4521 "contains spaces, but your TeX installation does "
4522 "not allow them. You should save the file to a directory "
4523 "whose name does not contain spaces."), from_utf8(filePath())));
4524 return ExportTexPathHasSpaces;
4526 runparams.nice = false;
4527 ExportStatus const retval =
4528 makeLaTeXFile(FileName(filename), filePath(), runparams);
4529 if (retval == ExportKilled)
4530 return ExportKilled;
4531 if (d->cloned_buffer_)
4532 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4533 if (retval != ExportSuccess)
4537 string const error_type = (format == "program")
4538 ? "Build" : params().bufferFormat();
4539 ErrorList & error_list = d->errorLists[error_type];
4540 string const ext = theFormats().extension(format);
4541 FileName const tmp_result_file(changeExtension(filename, ext));
4542 Converters::RetVal const retval =
4543 converters.convert(this, FileName(filename), tmp_result_file,
4544 FileName(absFileName()), backend_format, format,
4545 error_list, Converters::none, includeall);
4546 if (retval == Converters::KILLED)
4547 return ExportCancel;
4548 bool success = (retval == Converters::SUCCESS);
4550 // Emit the signal to show the error list or copy it back to the
4551 // cloned Buffer so that it can be emitted afterwards.
4552 if (format != backend_format) {
4553 if (runparams.silent)
4555 else if (d->cloned_buffer_)
4556 d->cloned_buffer_->d->errorLists[error_type] =
4557 d->errorLists[error_type];
4560 // also to the children, in case of master-buffer-view
4561 ListOfBuffers clist = getDescendants();
4562 for (auto const & bit : clist) {
4563 if (runparams.silent)
4564 bit->d->errorLists[error_type].clear();
4565 else if (d->cloned_buffer_) {
4566 // Enable reverse search by copying back the
4567 // texrow object to the cloned buffer.
4568 // FIXME: this is not thread safe.
4569 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4570 bit->d->cloned_buffer_->d->errorLists[error_type] =
4571 bit->d->errorLists[error_type];
4573 bit->errors(error_type, true);
4577 if (d->cloned_buffer_) {
4578 // Enable reverse dvi or pdf to work by copying back the texrow
4579 // object to the cloned buffer.
4580 // FIXME: There is a possibility of concurrent access to texrow
4581 // here from the main GUI thread that should be securized.
4582 d->cloned_buffer_->d->texrow = d->texrow;
4583 string const err_type = params().bufferFormat();
4584 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4588 if (put_in_tempdir) {
4589 result_file = tmp_result_file.absFileName();
4590 return success ? ExportSuccess : ExportConverterError;
4593 if (dest_filename.empty())
4594 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4596 result_file = dest_filename;
4597 // We need to copy referenced files (e. g. included graphics
4598 // if format == "dvi") to the result dir.
4599 vector<ExportedFile> const extfiles =
4600 runparams.exportdata->externalFiles(format);
4601 string const dest = runparams.export_folder.empty() ?
4602 onlyPath(result_file) : runparams.export_folder;
4603 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4604 : force_overwrite == ALL_FILES;
4605 CopyStatus status = use_force ? FORCE : SUCCESS;
4607 for (ExportedFile const & exp : extfiles) {
4608 if (status == CANCEL) {
4609 message(_("Document export cancelled."));
4610 return ExportCancel;
4612 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4613 string fixedName = exp.exportName;
4614 if (!runparams.export_folder.empty()) {
4615 // Relative pathnames starting with ../ will be sanitized
4616 // if exporting to a different folder
4617 while (fixedName.substr(0, 3) == "../")
4618 fixedName = fixedName.substr(3, fixedName.length() - 3);
4620 FileName fixedFileName = makeAbsPath(fixedName, dest);
4621 fixedFileName.onlyPath().createPath();
4622 status = copyFile(fmt, exp.sourceName,
4624 exp.exportName, status == FORCE,
4625 runparams.export_folder.empty());
4629 if (tmp_result_file.exists()) {
4630 // Finally copy the main file
4631 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4632 : force_overwrite != NO_FILES;
4633 if (status == SUCCESS && use_force)
4635 status = copyFile(format, tmp_result_file,
4636 FileName(result_file), result_file,
4638 if (status == CANCEL) {
4639 message(_("Document export cancelled."));
4640 return ExportCancel;
4642 message(bformat(_("Document exported as %1$s "
4644 theFormats().prettyName(format),
4645 makeDisplayPath(result_file)));
4648 // This must be a dummy converter like fax (bug 1888)
4649 message(bformat(_("Document exported as %1$s"),
4650 theFormats().prettyName(format)));
4653 return success ? ExportSuccess : ExportConverterError;
4657 Buffer::ExportStatus Buffer::preview(string const & format) const
4659 bool const update_unincluded =
4660 params().maintain_unincluded_children != BufferParams::CM_None
4661 && !params().getIncludedChildren().empty();
4662 return preview(format, update_unincluded);
4666 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4668 MarkAsExporting exporting(this);
4670 // (1) export with all included children (omit \includeonly)
4672 ExportStatus const status = doExport(format, true, true, result_file);
4673 if (status != ExportSuccess)
4676 // (2) export with included children only
4677 ExportStatus const status = doExport(format, true, false, result_file);
4678 FileName const previewFile(result_file);
4680 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4681 theimpl->preview_file_ = previewFile;
4682 theimpl->preview_format_ = format;
4683 theimpl->require_fresh_start_ = (status != ExportSuccess);
4685 if (status != ExportSuccess)
4688 if (previewFile.exists())
4689 return theFormats().view(*this, previewFile, format) ?
4690 PreviewSuccess : PreviewError;
4692 // Successful export but no output file?
4693 // Probably a bug in error detection.
4694 LATTEST(status != ExportSuccess);
4699 Buffer::ReadStatus Buffer::extractFromVC()
4701 bool const found = LyXVC::file_not_found_hook(d->filename);
4703 return ReadFileNotFound;
4704 if (!d->filename.isReadableFile())
4710 Buffer::ReadStatus Buffer::loadEmergency()
4712 FileName const emergencyFile = getEmergencyFileName();
4713 if (!emergencyFile.exists()
4714 || emergencyFile.lastModified() <= d->filename.lastModified())
4715 return ReadFileNotFound;
4717 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4718 docstring const text = bformat(_("An emergency save of the document "
4719 "%1$s exists.\n\nRecover emergency save?"), file);
4721 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4722 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4728 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4729 bool const success = (ret_llf == ReadSuccess);
4731 if (hasReadonlyFlag()) {
4732 Alert::warning(_("File is read-only"),
4733 bformat(_("An emergency file is successfully loaded, "
4734 "but the original file %1$s is marked read-only. "
4735 "Please make sure to save the document as a different "
4736 "file."), from_utf8(d->filename.absFileName())));
4739 lyxvc().file_found_hook(d->filename);
4740 str = _("Document was successfully recovered.");
4742 str = _("Document was NOT successfully recovered.");
4743 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4744 makeDisplayPath(emergencyFile.absFileName()));
4746 int const del_emerg =
4747 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4748 _("&Remove"), _("&Keep"));
4749 if (del_emerg == 0) {
4750 emergencyFile.removeFile();
4752 Alert::warning(_("Emergency file deleted"),
4753 _("Do not forget to save your file now!"), true);
4755 return success ? ReadSuccess : ReadEmergencyFailure;
4758 int const del_emerg =
4759 Alert::prompt(_("Delete emergency file?"),
4760 _("Remove emergency file now?"), 1, 1,
4761 _("&Remove"), _("&Keep"));
4763 emergencyFile.removeFile();
4767 string const ename = emergencyFile.absFileName();
4769 // Surely we can find one in 100 tries?
4770 for (int i = 1; i < 100; ++i) {
4771 newname.set(ename + to_string(i) + ".lyx");
4772 if (!newname.exists()) {
4778 // renameTo returns true on success. So inverting that
4779 // will give us true if we fail.
4780 noname = !emergencyFile.renameTo(newname);
4783 Alert::warning(_("Can't rename emergency file!"),
4784 _("LyX was unable to rename the emergency file. "
4785 "You should do so manually. Otherwise, you will be "
4786 "asked about it again the next time you try to load "
4787 "this file, and may over-write your own work."));
4789 Alert::warning(_("Emergency File Renames"),
4790 bformat(_("Emergency file renamed as:\n %1$s"),
4791 from_utf8(newname.onlyFileName())));
4794 return ReadOriginal;
4804 Buffer::ReadStatus Buffer::loadAutosave()
4806 // Now check if autosave file is newer.
4807 FileName const autosaveFile = getAutosaveFileName();
4808 if (!autosaveFile.exists()
4809 || autosaveFile.lastModified() <= d->filename.lastModified())
4810 return ReadFileNotFound;
4812 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4813 docstring const text = bformat(_("The backup of the document %1$s "
4814 "is newer.\n\nLoad the backup instead?"), file);
4815 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4816 _("&Load backup"), _("Load &original"), _("&Cancel"));
4821 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4822 // the file is not saved if we load the autosave file.
4823 if (ret_llf == ReadSuccess) {
4824 if (hasReadonlyFlag()) {
4825 Alert::warning(_("File is read-only"),
4826 bformat(_("A backup file is successfully loaded, "
4827 "but the original file %1$s is marked read-only. "
4828 "Please make sure to save the document as a "
4830 from_utf8(d->filename.absFileName())));
4833 lyxvc().file_found_hook(d->filename);
4836 return ReadAutosaveFailure;
4839 // Here we delete the autosave
4840 autosaveFile.removeFile();
4841 return ReadOriginal;
4849 Buffer::ReadStatus Buffer::loadLyXFile()
4851 if (!d->filename.isReadableFile()) {
4852 ReadStatus const ret_rvc = extractFromVC();
4853 if (ret_rvc != ReadSuccess)
4857 ReadStatus const ret_re = loadEmergency();
4858 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4861 ReadStatus const ret_ra = loadAutosave();
4862 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4865 return loadThisLyXFile(d->filename);
4869 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4871 return readFile(fn);
4875 void Buffer::Impl::traverseErrors(TeXErrors::Errors::const_iterator err, TeXErrors::Errors::const_iterator end, ErrorList & errorList) const
4877 for (; err != end; ++err) {
4878 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4879 int errorRow = err->error_in_line;
4880 Buffer const * buf = nullptr;
4881 Impl const * p = this;
4882 if (err->child_name.empty())
4883 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4885 // The error occurred in a child
4886 for (Buffer const * child : owner_->getDescendants()) {
4887 string const child_name =
4888 DocFileName(changeExtension(child->absFileName(), "tex")).
4890 if (err->child_name != child_name)
4892 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4893 if (!TexRow::isNone(start)) {
4894 buf = this->cloned_buffer_
4895 ? child->d->cloned_buffer_->d->owner_
4902 errorList.push_back(ErrorItem(err->error_desc, err->error_text,
4908 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4910 TeXErrors::Errors::const_iterator err = terr.begin();
4911 TeXErrors::Errors::const_iterator end = terr.end();
4913 d->traverseErrors(err, end, errorList);
4917 void Buffer::bufferRefs(TeXErrors const & terr, ErrorList & errorList) const
4919 TeXErrors::Errors::const_iterator err = terr.begin_ref();
4920 TeXErrors::Errors::const_iterator end = terr.end_ref();
4922 d->traverseErrors(err, end, errorList);
4926 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4928 LBUFERR(!text().paragraphs().empty());
4930 // Use the master text class also for child documents
4931 Buffer const * const master = masterBuffer();
4932 DocumentClass const & textclass = master->params().documentClass();
4934 docstring_list old_bibfiles;
4935 // Do this only if we are the top-level Buffer. We also need to account
4936 // for the case of a previewed child with ignored parent here.
4937 if (master == this && !d->ignore_parent) {
4938 textclass.counters().reset(from_ascii("bibitem"));
4939 reloadBibInfoCache();
4940 // we will re-read this cache as we go through, but we need
4941 // to know whether it's changed to know whether we need to
4942 // update the bibinfo cache.
4943 old_bibfiles = d->bibfiles_cache_;
4944 d->bibfiles_cache_.clear();
4947 // keep the buffers to be children in this set. If the call from the
4948 // master comes back we can see which of them were actually seen (i.e.
4949 // via an InsetInclude). The remaining ones in the set need still be updated.
4950 static std::set<Buffer const *> bufToUpdate;
4951 if (scope == UpdateMaster) {
4952 // If this is a child document start with the master
4953 if (master != this) {
4954 bufToUpdate.insert(this);
4955 master->updateBuffer(UpdateMaster, utype);
4956 // If the master buffer has no gui associated with it, then the TocModel is
4957 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4958 // (bug 5699). The same happens if the master buffer is open in a different
4959 // window. This test catches both possibilities.
4960 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4961 // There remains a problem here: If there is another child open in yet a third
4962 // window, that TOC is not updated. So some more general solution is needed at
4964 if (master->d->gui_ != d->gui_)
4967 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4968 if (bufToUpdate.find(this) == bufToUpdate.end())
4972 // start over the counters in the master
4973 textclass.counters().reset();
4976 // update will be done below for this buffer
4977 bufToUpdate.erase(this);
4979 // update all caches
4980 clearReferenceCache();
4983 Buffer & cbuf = const_cast<Buffer &>(*this);
4984 // if we are reloading, then we could have a dangling TOC,
4985 // in effect. so we need to go ahead and reset, even though
4986 // we will do so again when we rebuild the TOC later.
4987 cbuf.tocBackend().reset();
4990 ParIterator parit = cbuf.par_iterator_begin();
4991 if (scope == UpdateMaster)
4993 updateBuffer(parit, utype);
4995 // If this document has siblings, then update the TocBackend later. The
4996 // reason is to ensure that later siblings are up to date when e.g. the
4997 // broken or not status of references is computed. The update is called
4998 // in InsetInclude::addToToc.
5002 // if the bibfiles changed, the cache of bibinfo is invalid
5003 docstring_list new_bibfiles = d->bibfiles_cache_;
5004 // this is a trick to determine whether the two vectors have
5005 // the same elements.
5006 sort(new_bibfiles.begin(), new_bibfiles.end());
5007 sort(old_bibfiles.begin(), old_bibfiles.end());
5008 if (old_bibfiles != new_bibfiles) {
5009 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
5010 invalidateBibinfoCache();
5011 reloadBibInfoCache();
5012 // We relied upon the bibinfo cache when recalculating labels. But that
5013 // cache was invalid, although we didn't find that out until now. So we
5014 // have to do it all again.
5015 // That said, the only thing we really need to do is update the citation
5016 // labels. Nothing else will have changed. So we could create a new
5017 // UpdateType that would signal that fact, if we needed to do so.
5018 parit = cbuf.par_iterator_begin();
5019 // we will be re-doing the counters and references and such.
5020 textclass.counters().reset();
5021 clearReferenceCache();
5022 // we should not need to do this again?
5024 updateBuffer(parit, utype);
5025 // this will already have been done by reloadBibInfoCache();
5026 // d->bibinfo_cache_valid_ = true;
5029 LYXERR(Debug::FILES, "Bibfiles unchanged.");
5030 // this is also set to true on the other path, by reloadBibInfoCache.
5031 d->bibinfo_cache_valid_ = true;
5033 d->cite_labels_valid_ = true;
5036 cbuf.tocBackend().update(true, utype);
5037 if (scope == UpdateMaster)
5038 cbuf.structureChanged();
5042 static depth_type getDepth(DocIterator const & it)
5044 depth_type depth = 0;
5045 for (size_t i = 0 ; i < it.depth() ; ++i)
5046 if (!it[i].inset().inMathed())
5047 depth += it[i].paragraph().getDepth() + 1;
5048 // remove 1 since the outer inset does not count
5049 // we should have at least one non-math inset, so
5050 // depth should nevery be 0. but maybe it is worth
5051 // marking this, just in case.
5053 // coverity[INTEGER_OVERFLOW]
5057 static depth_type getItemDepth(ParIterator const & it)
5059 Paragraph const & par = *it;
5060 LabelType const labeltype = par.layout().labeltype;
5062 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5065 // this will hold the lowest depth encountered up to now.
5066 depth_type min_depth = getDepth(it);
5067 ParIterator prev_it = it;
5070 --prev_it.top().pit();
5072 // start of nested inset: go to outer par
5074 if (prev_it.empty()) {
5075 // start of document: nothing to do
5080 // We search for the first paragraph with same label
5081 // that is not more deeply nested.
5082 Paragraph & prev_par = *prev_it;
5083 depth_type const prev_depth = getDepth(prev_it);
5084 if (labeltype == prev_par.layout().labeltype) {
5085 if (prev_depth < min_depth)
5086 return prev_par.itemdepth + 1;
5087 if (prev_depth == min_depth)
5088 return prev_par.itemdepth;
5090 min_depth = min(min_depth, prev_depth);
5091 // small optimization: if we are at depth 0, we won't
5092 // find anything else
5093 if (prev_depth == 0)
5099 static bool needEnumCounterReset(ParIterator const & it)
5101 Paragraph const & par = *it;
5102 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5103 depth_type const cur_depth = par.getDepth();
5104 ParIterator prev_it = it;
5105 while (prev_it.pit()) {
5106 --prev_it.top().pit();
5107 Paragraph const & prev_par = *prev_it;
5108 if (prev_par.getDepth() <= cur_depth)
5109 return prev_par.layout().name() != par.layout().name();
5111 // start of nested inset: reset
5116 // set the label of a paragraph. This includes the counters.
5117 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5119 BufferParams const & bp = owner_->masterBuffer()->params();
5120 DocumentClass const & textclass = bp.documentClass();
5121 Paragraph & par = it.paragraph();
5122 Layout const & layout = par.layout();
5123 Counters & counters = textclass.counters();
5125 if (par.params().startOfAppendix()) {
5126 // We want to reset the counter corresponding to toplevel sectioning
5127 Layout const & lay = textclass.getTOCLayout();
5128 docstring const cnt = lay.counter;
5130 counters.reset(cnt);
5131 counters.appendix(true);
5133 par.params().appendix(counters.appendix());
5135 // Compute the item depth of the paragraph
5136 par.itemdepth = getItemDepth(it);
5138 if (layout.margintype == MARGIN_MANUAL) {
5139 if (par.params().labelWidthString().empty())
5140 par.params().labelWidthString(par.expandLabel(layout, bp));
5141 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5142 // we do not need to do anything here, since the empty case is
5143 // handled during export.
5145 par.params().labelWidthString(docstring());
5148 switch(layout.labeltype) {
5149 case LABEL_ITEMIZE: {
5150 // At some point of time we should do something more
5151 // clever here, like:
5152 // par.params().labelString(
5153 // bp.user_defined_bullet(par.itemdepth).getText());
5154 // for now, use a simple hardcoded label
5155 docstring itemlabel;
5156 switch (par.itemdepth) {
5159 itemlabel = char_type(0x2022);
5163 itemlabel = char_type(0x2013);
5166 // ∗ U+2217 ASTERISK OPERATOR
5167 itemlabel = char_type(0x2217);
5170 // · U+00B7 MIDDLE DOT
5171 itemlabel = char_type(0x00b7);
5174 par.params().labelString(itemlabel);
5178 case LABEL_ENUMERATE: {
5179 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5181 switch (par.itemdepth) {
5192 enumcounter += "iv";
5195 // not a valid enumdepth...
5199 if (needEnumCounterReset(it)) {
5200 // Increase the master counter?
5201 if (layout.stepmastercounter)
5202 counters.stepMaster(enumcounter, utype);
5203 // Maybe we have to reset the enumeration counter.
5204 if (!layout.resumecounter)
5205 counters.reset(enumcounter);
5207 counters.step(enumcounter, utype);
5209 string const & lang = par.getParLanguage(bp)->code();
5210 par.params().labelString(counters.theCounter(enumcounter, lang));
5215 case LABEL_SENSITIVE: {
5216 string const & type = counters.current_float();
5217 docstring full_label;
5219 full_label = owner_->B_("Senseless!!! ");
5221 docstring name = owner_->B_(textclass.floats().getType(type).name());
5222 if (counters.hasCounter(from_utf8(type))) {
5223 string const & lang = par.getParLanguage(bp)->code();
5224 counters.step(from_utf8(type), utype);
5225 full_label = bformat(from_ascii("%1$s %2$s:"),
5227 counters.theCounter(from_utf8(type), lang));
5229 full_label = bformat(from_ascii("%1$s #:"), name);
5231 par.params().labelString(full_label);
5235 case LABEL_NO_LABEL:
5236 par.params().labelString(docstring());
5240 case LABEL_CENTERED:
5241 case LABEL_STATIC: {
5242 docstring const & lcounter = layout.counter;
5243 if (!lcounter.empty()) {
5244 if (layout.toclevel <= bp.secnumdepth
5245 && (layout.latextype != LATEX_ENVIRONMENT
5246 || it.text()->isFirstInSequence(it.pit()))) {
5247 if (counters.hasCounter(lcounter))
5248 counters.step(lcounter, utype);
5249 par.params().labelString(par.expandLabel(layout, bp));
5251 par.params().labelString(docstring());
5253 par.params().labelString(par.expandLabel(layout, bp));
5259 par.params().labelString(par.expandLabel(layout, bp));
5264 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype, bool const deleted) const
5266 pushIncludedBuffer(this);
5267 // LASSERT: Is it safe to continue here, or should we just return?
5268 LASSERT(parit.pit() == 0, /**/);
5270 // Set the position of the text in the buffer to be able
5271 // to resolve macros in it.
5272 parit.text()->setMacrocontextPosition(parit);
5274 // Reset bibitem counter in master (#8499)
5275 Buffer const * const master = masterBuffer();
5276 if (master == this && !d->ignore_parent)
5277 master->params().documentClass().counters().reset(from_ascii("bibitem"));
5279 depth_type maxdepth = 0;
5280 pit_type const lastpit = parit.lastpit();
5281 bool changed = false;
5282 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5283 // reduce depth if necessary
5284 if (parit->params().depth() > maxdepth) {
5285 /** FIXME: this function is const, but
5286 * nevertheless it modifies the buffer. To be
5287 * cleaner, one should modify the buffer in
5288 * another function, which is actually
5289 * non-const. This would however be costly in
5290 * terms of code duplication.
5292 CursorData(parit).recordUndo();
5293 parit->params().depth(maxdepth);
5295 maxdepth = parit->getMaxDepthAfter();
5297 if (utype == OutputUpdate) {
5298 // track the active counters
5299 // we have to do this for the master buffer, since the local
5300 // buffer isn't tracking anything.
5301 masterBuffer()->params().documentClass().counters().
5302 setActiveLayout(parit->layout());
5305 // set the counter for this paragraph
5306 d->setLabel(parit, utype);
5309 for (auto const & insit : parit->insetList()) {
5310 parit.pos() = insit.pos;
5311 insit.inset->updateBuffer(parit, utype, deleted || parit->isDeleted(insit.pos));
5312 changed |= insit.inset->isChanged();
5315 // are there changes in this paragraph?
5316 changed |= parit->isChanged();
5319 // set change indicator for the inset (or the cell that the iterator
5320 // points to, if applicable).
5321 parit.text()->inset().isChanged(changed);
5322 popIncludedBuffer();
5326 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5327 WordLangTuple & word_lang, docstring_list & suggestions) const
5331 suggestions.clear();
5332 word_lang = WordLangTuple();
5333 bool const to_end = to.empty();
5334 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5335 // OK, we start from here.
5336 for (; from != end; from.forwardPos()) {
5337 // This skips all insets with spell check disabled.
5338 while (!from.allowSpellCheck()) {
5342 // If from is at the end of the document (which is possible
5343 // when "from" was changed above) LyX will crash later otherwise.
5344 if (from.atEnd() || (!to_end && from >= end))
5347 from.paragraph().spellCheck();
5348 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5349 if (SpellChecker::misspelled(res)) {
5353 // Do not increase progress when from == to, otherwise the word
5354 // count will be wrong.
5364 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5366 bool inword = false;
5371 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5372 if (!dit.inTexted()) {
5377 Paragraph const & par = dit.paragraph();
5378 pos_type const pos = dit.pos();
5380 // Copied and adapted from isWordSeparator() in Paragraph
5381 if (pos == dit.lastpos()) {
5384 Inset const * ins = par.getInset(pos);
5385 if (ins && skipNoOutput && !ins->producesOutput()) {
5388 // stop if end of range was skipped
5389 if (!to.atEnd() && dit >= to)
5392 } else if (!par.isDeleted(pos)) {
5393 if (par.isWordSeparator(pos))
5399 if (ins && ins->isLetter())
5401 else if (ins && ins->isSpace())
5404 char_type const c = par.getChar(pos);
5405 if (isPrintableNonspace(c))
5407 else if (isSpace(c))
5417 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5419 d->updateStatistics(from, to, skipNoOutput);
5423 int Buffer::wordCount() const
5425 return d->wordCount();
5429 int Buffer::charCount(bool with_blanks) const
5431 return d->charCount(with_blanks);
5435 bool Buffer::areChangesPresent() const
5437 return inset().isChanged();
5441 Buffer::ReadStatus Buffer::reload()
5444 // c.f. bug https://www.lyx.org/trac/ticket/6587
5445 removeAutosaveFile();
5446 // e.g., read-only status could have changed due to version control
5447 d->filename.refresh();
5448 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5450 // clear parent. this will get reset if need be.
5451 d->setParent(nullptr);
5452 ReadStatus const status = loadLyXFile();
5453 if (status == ReadSuccess) {
5458 message(bformat(_("Document %1$s reloaded."), disp_fn));
5461 message(bformat(_("Could not reload document %1$s."), disp_fn));
5471 bool Buffer::saveAs(FileName const & fn)
5473 FileName const old_name = fileName();
5474 FileName const old_auto = getAutosaveFileName();
5475 bool const old_unnamed = isUnnamed();
5476 bool success = true;
5477 d->old_position = filePath();
5484 // bring the autosave file with us, just in case.
5485 moveAutosaveFile(old_auto);
5486 // validate version control data and
5487 // correct buffer title
5488 lyxvc().file_found_hook(fileName());
5490 // the file has now been saved to the new location.
5491 // we need to check that the locations of child buffers
5493 checkChildBuffers();
5494 checkMasterBuffer();
5497 // reset the old filename and unnamed state
5498 setFileName(old_name);
5499 setUnnamed(old_unnamed);
5503 d->old_position.clear();
5508 void Buffer::checkChildBuffers()
5510 for (auto const & bit : d->children_positions) {
5511 DocIterator dit = bit.second;
5512 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5513 if (!cbuf || !theBufferList().isLoaded(cbuf))
5515 Inset * inset = dit.nextInset();
5516 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5517 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5518 docstring const & incfile = inset_inc->getParam("filename");
5519 string oldloc = cbuf->absFileName();
5520 string newloc = makeAbsPath(to_utf8(incfile),
5521 onlyPath(absFileName())).absFileName();
5522 if (oldloc == newloc)
5524 // the location of the child file is incorrect.
5525 cbuf->setParent(nullptr);
5526 inset_inc->setChildBuffer(nullptr);
5528 // invalidate cache of children
5529 d->children_positions.clear();
5530 d->position_to_children.clear();
5534 // If a child has been saved under a different name/path, it might have been
5535 // orphaned. Therefore the master needs to be reset (bug 8161).
5536 void Buffer::checkMasterBuffer()
5538 Buffer const * const master = masterBuffer();
5542 // necessary to re-register the child (bug 5873)
5543 // FIXME: clean up updateMacros (here, only
5544 // child registering is needed).
5545 master->updateMacros();
5546 // (re)set master as master buffer, but only
5547 // if we are a real child
5548 if (master->isChild(this))
5555 string Buffer::includedFilePath(string const & name, string const & ext) const
5557 if (d->old_position.empty() ||
5558 equivalent(FileName(d->old_position), FileName(filePath())))
5561 bool isabsolute = FileName::isAbsolute(name);
5562 // both old_position and filePath() end with a path separator
5563 string absname = isabsolute ? name : d->old_position + name;
5565 // if old_position is set to origin, we need to do the equivalent of
5566 // getReferencedFileName() (see readDocument())
5567 if (!isabsolute && d->old_position == params().origin) {
5568 FileName const test(addExtension(filePath() + name, ext));
5570 absname = filePath() + name;
5573 if (!FileName(addExtension(absname, ext)).exists())
5577 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5579 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5580 from_utf8(filePath())));
5584 void Buffer::Impl::refreshFileMonitor()
5586 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5587 file_monitor_->refresh();
5591 // The previous file monitor is invalid
5592 // This also destroys the previous file monitor and all its connections
5593 file_monitor_ = FileSystemWatcher::monitor(filename);
5594 // file_monitor_ will be destroyed with *this, so it is not going to call a
5595 // destroyed object method.
5596 file_monitor_->connect([this](bool exists) {
5597 fileExternallyModified(exists);
5602 void Buffer::Impl::fileExternallyModified(bool const exists)
5604 // ignore notifications after our own saving operations
5605 if (checksum_ == filename.checksum()) {
5606 LYXERR(Debug::FILES, "External modification but "
5607 "checksum unchanged: " << filename);
5610 // If the file has been deleted, only mark the file as dirty since it is
5611 // pointless to prompt for reloading. If later a file is moved into this
5612 // location, then the externally modified warning will appear then.
5614 externally_modified_ = true;
5615 // Update external modification notification.
5616 // Dirty buffers must be visible at all times.
5617 if (wa_ && wa_->unhide(owner_))
5618 wa_->updateTitles();
5620 // Unable to unhide the buffer (e.g. no GUI or not current View)
5625 bool Buffer::notifiesExternalModification() const
5627 return d->externally_modified_;
5631 void Buffer::clearExternalModification() const
5633 d->externally_modified_ = false;
5635 d->wa_->updateTitles();
5639 void Buffer::pushIncludedBuffer(Buffer const * buf) const
5641 masterBuffer()->d->include_list_.push_back(buf);
5642 if (lyxerr.debugging(Debug::FILES)) {
5643 LYXERR0("Pushed. Stack now:");
5644 if (masterBuffer()->d->include_list_.empty())
5647 for (auto const & b : masterBuffer()->d->include_list_)
5648 LYXERR0(b->fileName());
5653 void Buffer::popIncludedBuffer() const
5655 masterBuffer()->d->include_list_.pop_back();
5656 if (lyxerr.debugging(Debug::FILES)) {
5657 LYXERR0("Popped. Stack now:");
5658 if (masterBuffer()->d->include_list_.empty())
5661 for (auto const & b : masterBuffer()->d->include_list_)
5662 LYXERR0(b->fileName());
5667 bool Buffer::isBufferIncluded(Buffer const * buf) const
5671 if (lyxerr.debugging(Debug::FILES)) {
5672 LYXERR0("Checking for " << buf->fileName() << ". Stack now:");
5673 if (masterBuffer()->d->include_list_.empty())
5676 for (auto const & b : masterBuffer()->d->include_list_)
5677 LYXERR0(b->fileName());
5679 list<Buffer const *> const & blist = masterBuffer()->d->include_list_;
5680 return find(blist.begin(), blist.end(), buf) != blist.end();
5684 void Buffer::clearIncludeList() const
5686 LYXERR(Debug::FILES, "Clearing include list for " << fileName());
5687 d->include_list_.clear();