3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
50 #include "output_latex.h"
51 #include "output_docbook.h"
52 #include "output_plaintext.h"
53 #include "output_xhtml.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
59 #include "SpellChecker.h"
61 #include "texstream.h"
64 #include "TextClass.h"
65 #include "TocBackend.h"
67 #include "VCBackend.h"
69 #include "WordLangTuple.h"
72 #include "insets/InsetBibtex.h"
73 #include "insets/InsetBranch.h"
74 #include "insets/InsetInclude.h"
75 #include "insets/InsetTabular.h"
76 #include "insets/InsetText.h"
78 #include "mathed/InsetMathHull.h"
79 #include "mathed/MacroTable.h"
80 #include "mathed/InsetMathMacroTemplate.h"
81 #include "mathed/MathSupport.h"
83 #include "graphics/GraphicsCache.h"
84 #include "graphics/PreviewLoader.h"
86 #include "frontends/Application.h"
87 #include "frontends/alert.h"
88 #include "frontends/Delegates.h"
89 #include "frontends/WorkAreaManager.h"
91 #include "support/lassert.h"
92 #include "support/convert.h"
93 #include "support/debug.h"
94 #include "support/docstring_list.h"
95 #include "support/ExceptionMessage.h"
96 #include "support/FileMonitor.h"
97 #include "support/FileName.h"
98 #include "support/FileNameList.h"
99 #include "support/filetools.h"
100 #include "support/ForkedCalls.h"
101 #include "support/gettext.h"
102 #include "support/gzstream.h"
103 #include "support/lstrings.h"
104 #include "support/lyxalgo.h"
105 #include "support/mutex.h"
106 #include "support/os.h"
107 #include "support/Package.h"
108 #include "support/PathChanger.h"
109 #include "support/Systemcall.h"
110 #include "support/TempFile.h"
111 #include "support/textutils.h"
112 #include "support/types.h"
124 using namespace lyx::support;
125 using namespace lyx::graphics;
129 namespace Alert = frontend::Alert;
130 namespace os = support::os;
134 int const LYX_FORMAT = LYX_FORMAT_LYX;
136 typedef map<string, bool> DepClean;
138 // Information about labels and their associated refs
143 InsetLabel const * inset;
144 /// associated references cache
145 Buffer::References references;
146 /// whether this label is active (i.e., not deleted)
150 typedef vector<LabelInfo> LabelCache;
152 typedef map<docstring, Buffer::References> RefCache;
154 // A storehouse for the cloned buffers.
155 typedef list<CloneList_ptr> CloneStore;
156 CloneStore cloned_buffers;
165 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
169 delete preview_loader_;
177 /// search for macro in local (buffer) table or in children
178 MacroData const * getBufferMacro(docstring const & name,
179 DocIterator const & pos) const;
181 /// Update macro table starting with position of it \param it in some
183 void updateMacros(DocIterator & it, DocIterator & scope);
185 void setLabel(ParIterator & it, UpdateType utype) const;
187 /** If we have branches that use the file suffix
188 feature, return the file name with suffix appended.
190 FileName exportFileName() const;
197 mutable TexRow texrow;
199 /// need to regenerate .tex?
202 /// name of the file the buffer is associated with.
206 mutable TocBackend toc_backend;
211 ScopeMacro(DocIterator const & s, MacroData const & m)
212 : scope(s), macro(m) {}
216 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
217 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
218 /// map from the macro name to the position map,
219 /// which maps the macro definition position to the scope and the MacroData.
220 NamePositionScopeMacroMap macros;
222 /// positions of child buffers in the buffer
223 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
225 ScopeBuffer() : buffer(nullptr) {}
226 ScopeBuffer(DocIterator const & s, Buffer const * b)
227 : scope(s), buffer(b) {}
229 Buffer const * buffer;
231 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
232 /// position of children buffers in this buffer
233 BufferPositionMap children_positions;
234 /// map from children inclusion positions to their scope and their buffer
235 PositionScopeBufferMap position_to_children;
237 /// Contains the old buffer filePath() while saving-as, or the
238 /// directory where the document was last saved while loading.
241 /** Keeps track of the path of local layout files.
242 * If possible, it is always relative to the buffer path.
243 * Empty for layouts in system or user directory.
245 string layout_position;
247 /// Container for all sort of Buffer dependant errors.
248 map<string, ErrorList> errorLists;
250 /// checksum used to test if the file has been externally modified. Used to
251 /// double check whether the file had been externally modified when saving.
252 unsigned long checksum_;
255 frontend::WorkAreaManager * wa_;
257 frontend::GuiBufferDelegate * gui_;
262 /// A cache for the bibfiles (including bibfiles of loaded child
263 /// documents), needed for appropriate update of natbib labels.
264 mutable docstring_list bibfiles_cache_;
266 // FIXME The caching mechanism could be improved. At present, we have a
267 // cache for each Buffer, that caches all the bibliography info for that
268 // Buffer. A more efficient solution would be to have a global cache per
269 // file, and then to construct the Buffer's bibinfo from that.
270 /// A cache for bibliography info
271 mutable BiblioInfo bibinfo_;
272 /// Cache of timestamps of .bib files
273 map<FileName, time_t> bibfile_status_;
275 /// These two hold the file name and format, written to by
276 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
277 FileName preview_file_;
278 string preview_format_;
280 /// Cache the references associated to a label and their positions
282 mutable RefCache ref_cache_;
283 /// Cache the label insets and their activity status.
284 mutable LabelCache label_cache_;
286 /// our Text that should be wrapped in an InsetText
290 PreviewLoader * preview_loader_;
292 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
293 /// This one is useful for preview detached in a thread.
294 Buffer const * cloned_buffer_;
296 CloneList_ptr clone_list_;
299 std::list<Buffer const *> include_list_;
301 /// So we can force access via the accessors.
302 mutable Buffer const * parent_buffer;
304 FileMonitorPtr file_monitor_;
306 /// ints and bools are all listed last so as to avoid alignment issues
308 /// original format of loaded file
311 /// are we in the process of exporting this buffer?
312 mutable bool doing_export;
314 /// If there was an error when previewing, on the next preview we do
315 /// a fresh compile (e.g. in case the user installed a package that
317 bool require_fresh_start_;
319 /// Indicates whether the bibinfo has changed since the last time
320 /// we ran updateBuffer(), i.e., whether citation labels may need
322 mutable bool cite_labels_valid_;
323 /// Do we have a bibliography environment?
324 mutable bool have_bibitems_;
327 mutable bool lyx_clean;
329 /// is autosave needed?
330 mutable bool bak_clean;
332 /// is this an unnamed file (New...)?
335 /// is this an internal bufffer?
336 bool internal_buffer;
341 /** Set to true only when the file is fully loaded.
342 * Used to prevent the premature generation of previews
343 * and by the citation inset.
345 bool file_fully_loaded;
347 /// if the file was originally loaded from an older format, do
348 /// we need to back it up still?
349 bool need_format_backup;
351 /// Ignore the parent (e.g. when exporting a child standalone)?
354 /// This seem to change the way Buffer::getMacro() works
355 mutable bool macro_lock;
357 /// has been externally modified? Can be reset by the user.
358 mutable bool externally_modified_;
360 /// whether the bibinfo cache is valid
361 mutable bool bibinfo_cache_valid_;
369 /// This is here to force the test to be done whenever parent_buffer
371 Buffer const * parent() const
373 // ignore_parent temporarily "orphans" a buffer
374 // (e.g. if a child is compiled standalone)
377 // if parent_buffer is not loaded, then it has been unloaded,
378 // which means that parent_buffer is an invalid pointer. So we
379 // set it to null in that case.
380 // however, the BufferList doesn't know about cloned buffers, so
381 // they will always be regarded as unloaded. in that case, we hope
383 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
384 parent_buffer = nullptr;
385 return parent_buffer;
389 void setParent(Buffer const * pb)
391 if (parent_buffer == pb)
394 if (!cloned_buffer_ && parent_buffer && pb)
395 LYXERR0("Warning: a buffer should not have two parents!");
397 if (!cloned_buffer_ && parent_buffer)
398 parent_buffer->invalidateBibinfoCache();
401 /// compute statistics
402 /// \p from initial position
403 /// \p to points to the end position
404 void updateStatistics(DocIterator & from, DocIterator & to,
405 bool skipNoOutput = true);
406 /// statistics accessor functions
407 int wordCount() const
411 int charCount(bool with_blanks) const
414 + (with_blanks ? blank_count_ : 0);
417 // Make sure the file monitor monitors the good file.
418 void refreshFileMonitor();
420 /// Notify or clear of external modification
421 void fileExternallyModified(bool exists);
423 ///Binding LaTeX lines with buffer positions.
424 //Common routine for LaTeX and Reference errors listing.
425 void traverseErrors(TeXErrors::Errors::const_iterator err,
426 TeXErrors::Errors::const_iterator end,
427 ErrorList & errorList) const;
431 /// Creates the per buffer temporary directory
432 static FileName createBufferTmpDir()
434 // FIXME This would be the ideal application for a TempDir class (like
435 // TempFile but for directories)
440 Mutex::Locker locker(&mutex);
441 counter = convert<string>(count++);
443 // We are in our own directory. Why bother to mangle name?
444 // In fact I wrote this code to circumvent a problematic behaviour
445 // (bug?) of EMX mkstemp().
446 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
449 if (!tmpfl.createDirectory(0777)) {
450 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
451 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
452 from_utf8(tmpfl.absFileName())));
458 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
459 Buffer const * cloned_buffer)
460 : owner_(owner), filename(file), toc_backend(owner), checksum_(0),
461 wa_(nullptr), gui_(nullptr), undo_(*owner), inset(nullptr),
462 preview_loader_(nullptr), cloned_buffer_(cloned_buffer),
463 clone_list_(nullptr), parent_buffer(nullptr), file_format(LYX_FORMAT),
464 doing_export(false), require_fresh_start_(false), cite_labels_valid_(false),
465 have_bibitems_(false), lyx_clean(true), bak_clean(true), unnamed(false),
466 internal_buffer(false), read_only(readonly_), file_fully_loaded(false),
467 need_format_backup(false), ignore_parent(false), macro_lock(false),
468 externally_modified_(false), bibinfo_cache_valid_(false),
469 word_count_(0), char_count_(0), blank_count_(0)
471 refreshFileMonitor();
472 if (!cloned_buffer_) {
473 temppath = createBufferTmpDir();
474 lyxvc.setBuffer(owner_);
475 Language const * inplang = theApp() ?
476 languages.getFromCode(theApp()->inputLanguageCode())
479 params.language = inplang;
481 wa_ = new frontend::WorkAreaManager;
484 temppath = cloned_buffer_->d->temppath;
485 file_fully_loaded = true;
486 params = cloned_buffer_->d->params;
487 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
488 bibinfo_ = cloned_buffer_->d->bibinfo_;
489 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
490 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
491 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
492 have_bibitems_ = cloned_buffer_->d->have_bibitems_;
493 unnamed = cloned_buffer_->d->unnamed;
494 internal_buffer = cloned_buffer_->d->internal_buffer;
495 layout_position = cloned_buffer_->d->layout_position;
496 preview_file_ = cloned_buffer_->d->preview_file_;
497 preview_format_ = cloned_buffer_->d->preview_format_;
498 require_fresh_start_ = cloned_buffer_->d->require_fresh_start_;
502 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
503 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
505 LYXERR(Debug::INFO, "Buffer::Buffer()");
507 d->inset = new InsetText(*cloned_buffer->d->inset);
508 d->inset->setBuffer(*this);
509 // FIXME: optimize this loop somewhat, maybe by creating a new
510 // general recursive Inset::setId().
511 DocIterator it = doc_iterator_begin(this);
512 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
513 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
514 it.paragraph().setId(cloned_it.paragraph().id());
516 d->inset = new InsetText(this);
517 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
523 LYXERR(Debug::INFO, "Buffer::~Buffer()");
524 // here the buffer should take care that it is
525 // saved properly, before it goes into the void.
527 // GuiView already destroyed
531 // No need to do additional cleanups for internal buffer.
537 // this is in case of recursive includes: we won't try to delete
538 // ourselves as a child.
539 d->clone_list_->erase(this);
540 // loop over children
541 for (auto const & p : d->children_positions) {
542 Buffer * child = const_cast<Buffer *>(p.first);
543 if (d->clone_list_->erase(child))
546 // if we're the master buffer, then we should get rid of the list
549 // If this is not empty, we have leaked something. Worse, one of the
550 // children still has a reference to this list. But we will try to
551 // continue, rather than shut down.
552 LATTEST(d->clone_list_->empty());
553 // The clone list itself is empty, but it's still referenced in our list
554 // of clones. So let's find it and remove it.
555 CloneStore::iterator it =
556 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
557 if (it == cloned_buffers.end()) {
558 // We will leak in this case, but it is safe to continue.
561 cloned_buffers.erase(it);
563 // FIXME Do we really need to do this right before we delete d?
564 // clear references to children in macro tables
565 d->children_positions.clear();
566 d->position_to_children.clear();
568 // loop over children
569 for (auto const & p : d->children_positions) {
570 Buffer * child = const_cast<Buffer *>(p.first);
571 if (theBufferList().isLoaded(child)) {
572 if (theBufferList().isOthersChild(this, child))
573 child->setParent(nullptr);
575 theBufferList().release(child);
580 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
582 msg += emergencyWrite();
584 msg += " " + _("Save failed! Document is lost.");
586 Alert::warning(_("Attempting to close changed document!"), msg);
589 // FIXME Do we really need to do this right before we delete d?
590 // clear references to children in macro tables
591 d->children_positions.clear();
592 d->position_to_children.clear();
594 if (!d->temppath.destroyDirectory()) {
595 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
596 from_utf8(d->temppath.absFileName())));
605 Buffer * Buffer::cloneWithChildren() const
608 cloned_buffers.emplace_back(new CloneList);
609 CloneList_ptr clones = cloned_buffers.back();
611 cloneWithChildren(bufmap, clones);
613 // make sure we got cloned
614 BufferMap::const_iterator bit = bufmap.find(this);
615 LASSERT(bit != bufmap.end(), return nullptr);
616 Buffer * cloned_buffer = bit->second;
618 return cloned_buffer;
622 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList_ptr clones) const
624 // have we already been cloned?
625 if (bufmap.find(this) != bufmap.end())
628 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
630 // The clone needs its own DocumentClass, since running updateBuffer() will
631 // modify it, and we would otherwise be sharing it with the original Buffer.
632 buffer_clone->params().makeDocumentClass(true);
634 cap::switchBetweenClasses(
635 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
636 static_cast<InsetText &>(buffer_clone->inset()), el);
638 bufmap[this] = buffer_clone;
639 clones->insert(buffer_clone);
640 buffer_clone->d->clone_list_ = clones;
641 buffer_clone->d->macro_lock = true;
642 buffer_clone->d->children_positions.clear();
644 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
645 // math macro caches need to be rethought and simplified.
646 // I am not sure wether we should handle Buffer cloning here or in BufferList.
647 // Right now BufferList knows nothing about buffer clones.
648 for (auto const & p : d->position_to_children) {
649 DocIterator dit = p.first.clone(buffer_clone);
650 dit.setBuffer(buffer_clone);
651 Buffer * child = const_cast<Buffer *>(p.second.buffer);
653 child->cloneWithChildren(bufmap, clones);
654 BufferMap::iterator const bit = bufmap.find(child);
655 LASSERT(bit != bufmap.end(), continue);
656 Buffer * child_clone = bit->second;
658 Inset * inset = dit.nextInset();
659 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
660 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
661 inset_inc->setChildBuffer(child_clone);
662 child_clone->d->setParent(buffer_clone);
663 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
664 buffer_clone->setChild(dit, child_clone);
666 buffer_clone->d->macro_lock = false;
671 Buffer * Buffer::cloneBufferOnly() const {
672 cloned_buffers.emplace_back(new CloneList);
673 CloneList_ptr clones = cloned_buffers.back();
674 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
676 // The clone needs its own DocumentClass, since running updateBuffer() will
677 // modify it, and we would otherwise be sharing it with the original Buffer.
678 buffer_clone->params().makeDocumentClass(true);
680 cap::switchBetweenClasses(
681 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
682 static_cast<InsetText &>(buffer_clone->inset()), el);
684 clones->insert(buffer_clone);
685 buffer_clone->d->clone_list_ = clones;
687 // we won't be cloning the children
688 buffer_clone->d->children_positions.clear();
693 bool Buffer::isClone() const
695 return d->cloned_buffer_;
699 void Buffer::changed(bool update_metrics) const
702 d->wa_->redrawAll(update_metrics);
706 frontend::WorkAreaManager & Buffer::workAreaManager() const
713 Text & Buffer::text() const
715 return d->inset->text();
719 Inset & Buffer::inset() const
725 BufferParams & Buffer::params()
731 BufferParams const & Buffer::params() const
737 BufferParams const & Buffer::masterParams() const
739 if (masterBuffer() == this)
742 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
743 // Copy child authors to the params. We need those pointers.
744 for (Author const & a : params().authors())
745 mparams.authors().record(a);
750 double Buffer::fontScalingFactor() const
752 return isExporting() ? 75.0 * params().html_math_img_scale
753 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
757 ParagraphList & Buffer::paragraphs()
759 return text().paragraphs();
763 ParagraphList const & Buffer::paragraphs() const
765 return text().paragraphs();
769 LyXVC & Buffer::lyxvc()
775 LyXVC const & Buffer::lyxvc() const
781 string const Buffer::temppath() const
783 return d->temppath.absFileName();
787 TexRow & Buffer::texrow()
793 TexRow const & Buffer::texrow() const
799 TocBackend & Buffer::tocBackend() const
801 return d->toc_backend;
805 Undo & Buffer::undo()
811 void Buffer::setChild(DocIterator const & dit, Buffer * child)
813 d->children_positions[child] = dit;
817 string Buffer::latexName(bool const no_path) const
819 FileName latex_name =
820 makeLatexName(d->exportFileName());
821 return no_path ? latex_name.onlyFileName()
822 : latex_name.absFileName();
826 FileName Buffer::Impl::exportFileName() const
828 docstring const branch_suffix =
829 params.branchlist().getFileNameSuffix();
830 if (branch_suffix.empty())
833 string const name = addExtension(filename.onlyFileNameWithoutExt()
834 + to_utf8(branch_suffix), filename.extension());
835 FileName res(filename.onlyPath().absFileName() + "/" + name);
841 string Buffer::logName(LogType * type) const
843 string const filename = latexName(false);
845 if (filename.empty()) {
851 string const path = temppath();
853 FileName const fname(addName(temppath(),
854 onlyFileName(changeExtension(filename,
857 // FIXME: how do we know this is the name of the build log?
858 FileName const bname(
859 addName(path, onlyFileName(
860 changeExtension(filename,
861 theFormats().extension(params().bufferFormat()) + ".out"))));
863 // Also consider the master buffer log file
864 FileName masterfname = fname;
865 LogType mtype = latexlog;
866 if (masterBuffer() != this) {
867 string const mlogfile = masterBuffer()->logName(&mtype);
868 masterfname = FileName(mlogfile);
871 // If no Latex log or Build log is newer, show Build log
872 if (bname.exists() &&
873 ((!fname.exists() && !masterfname.exists())
874 || (fname.lastModified() < bname.lastModified()
875 && masterfname.lastModified() < bname.lastModified()))) {
876 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
879 return bname.absFileName();
880 // If we have a newer master file log or only a master log, show this
881 } else if (fname != masterfname
882 && (!fname.exists() && (masterfname.exists()
883 || fname.lastModified() < masterfname.lastModified()))) {
884 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
887 return masterfname.absFileName();
889 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
892 return fname.absFileName();
896 void Buffer::setReadonly(bool const flag)
898 if (d->read_only != flag) {
905 void Buffer::setFileName(FileName const & fname)
907 bool const changed = fname != d->filename;
909 d->refreshFileMonitor();
911 lyxvc().file_found_hook(fname);
912 setReadonly(d->filename.isReadOnly());
918 int Buffer::readHeader(Lexer & lex)
920 int unknown_tokens = 0;
922 int begin_header_line = -1;
924 // Initialize parameters that may be/go lacking in header:
925 params().branchlist().clear();
926 params().preamble.erase();
927 params().options.erase();
928 params().master.erase();
929 params().float_placement.erase();
930 params().float_alignment.erase();
931 params().paperwidth.erase();
932 params().paperheight.erase();
933 params().leftmargin.erase();
934 params().rightmargin.erase();
935 params().topmargin.erase();
936 params().bottommargin.erase();
937 params().headheight.erase();
938 params().headsep.erase();
939 params().footskip.erase();
940 params().columnsep.erase();
941 params().font_roman_opts.erase();
942 params().font_sans_opts.erase();
943 params().font_typewriter_opts.erase();
944 params().fonts_cjk.erase();
945 params().listings_params.clear();
946 params().clearLayoutModules();
947 params().clearRemovedModules();
948 params().clearIncludedChildren();
949 params().pdfoptions().clear();
950 params().indiceslist().clear();
951 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
952 params().isbackgroundcolor = false;
953 params().fontcolor = RGBColor(0, 0, 0);
954 params().isfontcolor = false;
955 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
956 params().boxbgcolor = RGBColor(0xFF, 0, 0);
957 params().html_latex_start.clear();
958 params().html_latex_end.clear();
959 params().html_math_img_scale = 1.0;
960 params().output_sync_macro.erase();
961 params().setLocalLayout(docstring(), false);
962 params().setLocalLayout(docstring(), true);
963 params().biblio_opts.erase();
964 params().biblatex_bibstyle.erase();
965 params().biblatex_citestyle.erase();
966 params().multibib.erase();
967 params().lineno_opts.clear();
969 for (int i = 0; i < 4; ++i) {
970 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
971 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
974 ErrorList & errorList = d->errorLists["Parse"];
983 if (token == "\\end_header")
987 if (token == "\\begin_header") {
988 begin_header_line = line;
992 LYXERR(Debug::PARSER, "Handling document header token: `"
995 string const result =
996 params().readToken(lex, token, d->filename.onlyPath());
997 if (!result.empty()) {
998 if (token == "\\textclass") {
999 d->layout_position = result;
1002 docstring const s = bformat(_("Unknown token: "
1005 lex.getDocString());
1006 errorList.push_back(ErrorItem(_("Document header error"), s));
1010 if (begin_header_line) {
1011 docstring const s = _("\\begin_header is missing");
1012 errorList.push_back(ErrorItem(_("Document header error"), s));
1015 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
1017 params().makeDocumentClass();
1019 return unknown_tokens;
1024 // changed to be public and have one parameter
1025 // Returns true if "\end_document" is not read (Asger)
1026 bool Buffer::readDocument(Lexer & lex)
1028 ErrorList & errorList = d->errorLists["Parse"];
1031 // remove dummy empty par
1032 paragraphs().clear();
1034 if (!lex.checkFor("\\begin_document")) {
1035 docstring const s = _("\\begin_document is missing");
1036 errorList.push_back(ErrorItem(_("Document header error"), s));
1041 if (params().output_changes) {
1042 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1043 LaTeXFeatures::isAvailable("xcolor");
1046 Alert::warning(_("Changes not shown in LaTeX output"),
1047 _("Changes will not be highlighted in LaTeX output, "
1048 "because xcolor and ulem are not installed.\n"
1049 "Please install both packages or redefine "
1050 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1054 if (!parent() && !params().master.empty()) {
1055 FileName const master_file = makeAbsPath(params().master,
1056 onlyPath(absFileName()));
1057 if (isLyXFileName(master_file.absFileName())) {
1059 checkAndLoadLyXFile(master_file, true);
1061 // necessary e.g. after a reload
1062 // to re-register the child (bug 5873)
1063 // FIXME: clean up updateMacros (here, only
1064 // child registering is needed).
1065 master->updateMacros();
1066 // set master as master buffer, but only
1067 // if we are a real child
1068 if (master->isChild(this))
1070 // if the master is not fully loaded
1071 // it is probably just loading this
1072 // child. No warning needed then.
1073 else if (master->isFullyLoaded())
1074 LYXERR0("The master '"
1076 << "' assigned to this document ("
1078 << ") does not include "
1079 "this document. Ignoring the master assignment.");
1080 // If the master has just been created, un-hide it (#11162)
1081 if (!master->fileName().exists())
1082 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1083 master->absFileName()));
1088 // assure we have a default index
1089 params().indiceslist().addDefault(B_("Index"));
1092 if (FileName::isAbsolute(params().origin))
1093 d->old_position = params().origin;
1095 d->old_position = filePath();
1100 bool const res = text().read(lex, errorList, d->inset);
1101 d->old_position.clear();
1103 // inform parent buffer about local macros
1105 Buffer const * pbuf = parent();
1106 for (auto const & m : usermacros)
1107 pbuf->usermacros.insert(m);
1111 updateMacroInstances(InternalUpdate);
1116 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1118 Format const * fmt = theFormats().getFormat(format);
1121 // It is important to use the correct extension here, since some
1122 // converters create a wrong output file otherwise (e.g. html2latex)
1123 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1124 ofdocstream os(name.toFilesystemEncoding().c_str());
1125 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1126 bool const success = !(os << contents).fail();
1129 bool converted = false;
1131 params().compressed = false;
1133 // remove dummy empty par
1134 paragraphs().clear();
1136 converted = importFile(format, name, errorList);
1139 removeTempFile(name);
1144 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1146 if (!theConverters().isReachable(format, "lyx"))
1149 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1150 Converters::RetVal const retval =
1151 theConverters().convert(nullptr, name, lyx, name, format, "lyx", errorList);
1152 if (retval == Converters::SUCCESS) {
1153 bool const success = readFile(lyx) == ReadSuccess;
1154 removeTempFile(lyx);
1162 bool Buffer::readString(string const & s)
1164 params().compressed = false;
1167 istringstream is(s);
1169 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1170 FileName const fn = tempfile.name();
1173 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1175 if (success && file_format != LYX_FORMAT) {
1176 // We need to call lyx2lyx, so write the input to a file
1177 ofstream os(fn.toFilesystemEncoding().c_str());
1180 // lyxvc in readFile
1181 if (readFile(fn) != ReadSuccess)
1185 if (readDocument(lex))
1191 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1195 if (!lex.setFile(fname)) {
1196 Alert::error(_("File Not Found"),
1197 bformat(_("Unable to open file `%1$s'."),
1198 from_utf8(fn.absFileName())));
1199 return ReadFileNotFound;
1203 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1204 if (ret_plf != ReadSuccess)
1207 if (file_format != LYX_FORMAT) {
1209 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1210 if (ret_clf != ReadSuccess)
1212 ret_clf = readFile(tmpFile);
1213 if (ret_clf == ReadSuccess) {
1214 d->file_format = file_format;
1215 d->need_format_backup = true;
1220 // FIXME: InsetInfo needs to know whether the file is under VCS
1221 // during the parse process, so this has to be done before.
1222 lyxvc().file_found_hook(d->filename);
1224 if (readDocument(lex)) {
1225 Alert::error(_("Document format failure"),
1226 bformat(_("%1$s ended unexpectedly, which means"
1227 " that it is probably corrupted."),
1228 from_utf8(fn.absFileName())));
1229 return ReadDocumentFailure;
1232 d->file_fully_loaded = true;
1233 d->read_only = !d->filename.isWritable();
1234 params().compressed = theFormats().isZippedFile(d->filename);
1240 bool Buffer::isFullyLoaded() const
1242 return d->file_fully_loaded;
1246 void Buffer::setFullyLoaded(bool value)
1248 d->file_fully_loaded = value;
1252 bool Buffer::freshStartRequired() const
1254 return d->require_fresh_start_;
1257 void Buffer::requireFreshStart(bool const b) const
1259 d->require_fresh_start_ = b;
1263 PreviewLoader * Buffer::loader() const
1265 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1267 if (!d->preview_loader_)
1268 d->preview_loader_ = new PreviewLoader(*this);
1269 return d->preview_loader_;
1273 void Buffer::removePreviews() const
1275 delete d->preview_loader_;
1276 d->preview_loader_ = nullptr;
1280 void Buffer::updatePreviews() const
1282 PreviewLoader * ploader = loader();
1286 InsetIterator it = inset_iterator_begin(*d->inset);
1287 InsetIterator const end = inset_iterator_end(*d->inset);
1288 for (; it != end; ++it)
1289 it->addPreview(it, *ploader);
1291 ploader->startLoading();
1295 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1296 FileName const & fn, int & file_format) const
1298 if(!lex.checkFor("\\lyxformat")) {
1299 Alert::error(_("Document format failure"),
1300 bformat(_("%1$s is not a readable LyX document."),
1301 from_utf8(fn.absFileName())));
1302 return ReadNoLyXFormat;
1308 // LyX formats 217 and earlier were written as 2.17. This corresponds
1309 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1310 // these cases. See also: www.lyx.org/trac/changeset/1313.
1311 size_t dot = tmp_format.find_first_of(".,");
1312 if (dot != string::npos)
1313 tmp_format.erase(dot, 1);
1315 file_format = convert<int>(tmp_format);
1320 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1321 FileName & tmpfile, int from_format)
1323 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1324 tempfile.setAutoRemove(false);
1325 tmpfile = tempfile.name();
1326 if(tmpfile.empty()) {
1327 Alert::error(_("Conversion failed"),
1328 bformat(_("%1$s is from a different"
1329 " version of LyX, but a temporary"
1330 " file for converting it could"
1331 " not be created."),
1332 from_utf8(fn.absFileName())));
1333 return LyX2LyXNoTempFile;
1336 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1337 if (lyx2lyx.empty()) {
1338 Alert::error(_("Conversion script not found"),
1339 bformat(_("%1$s is from a different"
1340 " version of LyX, but the"
1341 " conversion script lyx2lyx"
1342 " could not be found."),
1343 from_utf8(fn.absFileName())));
1344 return LyX2LyXNotFound;
1348 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1349 ostringstream command;
1350 command << os::python()
1351 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1352 << " -t " << convert<string>(LYX_FORMAT)
1353 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1354 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1355 string const command_str = command.str();
1357 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1359 cmd_ret const ret = runCommand(command_str);
1361 if (from_format < LYX_FORMAT) {
1362 Alert::error(_("Conversion script failed"),
1363 bformat(_("%1$s is from an older version"
1364 " of LyX and the lyx2lyx script"
1365 " failed to convert it."),
1366 from_utf8(fn.absFileName())));
1367 return LyX2LyXOlderFormat;
1369 Alert::error(_("Conversion script failed"),
1370 bformat(_("%1$s is from a newer version"
1371 " of LyX and the lyx2lyx script"
1372 " failed to convert it."),
1373 from_utf8(fn.absFileName())));
1374 return LyX2LyXNewerFormat;
1381 FileName Buffer::getBackupName() const {
1382 map<int, string> const file_formats = {
1399 FileName const & fn = fileName();
1400 string const fname = fn.onlyFileNameWithoutExt();
1401 string const fext = fn.extension() + "~";
1402 string const fpath = lyxrc.backupdir_path.empty() ?
1403 fn.onlyPath().absFileName() :
1404 lyxrc.backupdir_path;
1405 string backup_suffix;
1406 // If file format is from a stable series use version instead of file format
1407 auto const it = file_formats.find(d->file_format);
1408 if (it != file_formats.end())
1409 backup_suffix = "-lyx" + it->second;
1411 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1412 string const backname = fname + backup_suffix;
1413 FileName backup(addName(fpath, addExtension(backname, fext)));
1415 // limit recursion, just in case
1417 unsigned long orig_checksum = 0;
1418 while (backup.exists() && v < 100) {
1419 if (orig_checksum == 0)
1420 orig_checksum = fn.checksum();
1421 unsigned long new_checksum = backup.checksum();
1422 if (orig_checksum == new_checksum) {
1423 LYXERR(Debug::FILES, "Not backing up " << fn <<
1424 "since " << backup << "has the same checksum.");
1425 // a bit of a hack, but we have to check this anyway
1426 // below, and setting this is simpler than introducing
1427 // a special boolean for this purpose.
1431 string const newbackname = backname + "-" + convert<string>(v);
1432 backup.set(addName(fpath, addExtension(newbackname, fext)));
1435 return v < 100 ? backup : FileName();
1439 // Should probably be moved to somewhere else: BufferView? GuiView?
1440 bool Buffer::save() const
1442 docstring const file = makeDisplayPath(absFileName(), 20);
1443 d->filename.refresh();
1445 // check the read-only status before moving the file as a backup
1446 if (d->filename.exists()) {
1447 bool const read_only = !d->filename.isWritable();
1449 Alert::warning(_("File is read-only"),
1450 bformat(_("The file %1$s cannot be written because it "
1451 "is marked as read-only."), file));
1456 // ask if the disk file has been externally modified (use checksum method)
1457 if (fileName().exists() && isChecksumModified()) {
1459 bformat(_("Document %1$s has been externally modified. "
1460 "Are you sure you want to overwrite this file?"), file);
1461 int const ret = Alert::prompt(_("Overwrite modified file?"),
1462 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1467 // We don't need autosaves in the immediate future. (Asger)
1468 resetAutosaveTimers();
1470 // if the file does not yet exist, none of the backup activity
1471 // that follows is necessary
1472 if (!fileName().exists()) {
1473 if (!writeFile(fileName()))
1479 // we first write the file to a new name, then move it to its
1480 // proper location once that has been done successfully. that
1481 // way we preserve the original file if something goes wrong.
1482 string const justname = fileName().onlyFileNameWithoutExt();
1483 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1484 justname + "-XXXXXX.lyx");
1485 bool const symlink = fileName().isSymLink();
1487 tempfile->setAutoRemove(false);
1489 FileName savefile(tempfile->name());
1490 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1491 if (!savefile.clonePermissions(fileName()))
1492 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1494 if (!writeFile(savefile))
1497 // we will set this to false if we fail
1498 bool made_backup = true;
1500 FileName backupName;
1501 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1503 if (d->need_format_backup)
1504 backupName = getBackupName();
1506 // If we for some reason failed to find a backup name in case of
1507 // a format change, this will still set one. It's the best we can
1509 if (backupName.empty()) {
1510 backupName.set(fileName().absFileName() + "~");
1511 if (!lyxrc.backupdir_path.empty()) {
1512 string const mangledName =
1513 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1514 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1518 LYXERR(Debug::FILES, "Backing up original file to " <<
1519 backupName.absFileName());
1520 // Except file is symlink do not copy because of #6587.
1521 // Hard links have bad luck.
1522 made_backup = symlink ?
1523 fileName().copyTo(backupName):
1524 fileName().moveTo(backupName);
1527 Alert::error(_("Backup failure"),
1528 bformat(_("Cannot create backup file %1$s.\n"
1529 "Please check whether the directory exists and is writable."),
1530 from_utf8(backupName.absFileName())));
1531 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1532 } else if (d->need_format_backup) {
1533 // the original file has been backed up successfully, so we
1534 // will not need to do that again
1535 d->need_format_backup = false;
1539 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1540 // Only do this if tempfile is not in autoremove mode
1543 // If we have no symlink, we can simply rename the temp file.
1544 // Otherwise, we need to copy it so the symlink stays intact.
1545 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1546 savefile.moveTo(fileName()))
1548 // saveCheckSum() was already called by writeFile(), but the
1549 // time stamp is invalidated by copying/moving
1552 // the file associated with this buffer is now in the current format
1553 d->file_format = LYX_FORMAT;
1556 // else we saved the file, but failed to move it to the right location.
1558 if (needBackup && made_backup && !symlink) {
1559 // the original file was moved to some new location, so it will look
1560 // to the user as if it was deleted. (see bug #9234.) we could try
1561 // to restore it, but that would basically mean trying to do again
1562 // what we just failed to do. better to leave things as they are.
1563 Alert::error(_("Write failure"),
1564 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1565 "But LyX could not move it to:\n %2$s.\n"
1566 "Your original file has been backed up to:\n %3$s"),
1567 from_utf8(savefile.absFileName()),
1568 from_utf8(fileName().absFileName()),
1569 from_utf8(backupName.absFileName())));
1571 // either we did not try to make a backup, or else we tried and failed,
1572 // or else the original file was a symlink, in which case it was copied,
1573 // not moved. so the original file is intact.
1574 Alert::error(_("Write failure"),
1575 bformat(_("Cannot move saved file to:\n %1$s.\n"
1576 "But the file has successfully been saved as:\n %2$s."),
1577 from_utf8(fileName().absFileName()),
1578 from_utf8(savefile.absFileName())));
1584 bool Buffer::writeFile(FileName const & fname) const
1586 if (d->read_only && fname == d->filename)
1589 bool retval = false;
1591 docstring const str = bformat(_("Saving document %1$s..."),
1592 makeDisplayPath(fname.absFileName()));
1595 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1597 if (params().compressed) {
1598 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1599 retval = ofs && write(ofs);
1601 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1602 retval = ofs && write(ofs);
1606 message(str + _(" could not write file!"));
1611 // removeAutosaveFile();
1614 message(str + _(" done."));
1620 docstring Buffer::emergencyWrite()
1622 // No need to save if the buffer has not changed.
1626 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1628 docstring user_message = bformat(
1629 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1631 // We try to save three places:
1632 // 1) Same place as document. Unless it is an unnamed doc.
1634 string s = absFileName();
1637 if (writeFile(FileName(s))) {
1639 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1640 return user_message;
1642 user_message += " " + _("Save failed! Trying again...\n");
1646 // 2) In HOME directory.
1647 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1649 lyxerr << ' ' << s << endl;
1650 if (writeFile(FileName(s))) {
1652 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1653 return user_message;
1656 user_message += " " + _("Save failed! Trying yet again...\n");
1658 // 3) In "/tmp" directory.
1659 // MakeAbsPath to prepend the current
1660 // drive letter on OS/2
1661 s = addName(package().temp_dir().absFileName(), absFileName());
1663 lyxerr << ' ' << s << endl;
1664 if (writeFile(FileName(s))) {
1666 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1667 return user_message;
1670 user_message += " " + _("Save failed! Document is lost.");
1673 return user_message;
1677 bool Buffer::write(ostream & ofs) const
1680 // Use the standard "C" locale for file output.
1681 ofs.imbue(locale::classic());
1684 // The top of the file should not be written by params().
1686 // write out a comment in the top of the file
1687 // Important: Keep the version formatting in sync with lyx2lyx and
1688 // tex2lyx (bug 7951)
1689 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1690 << " created this file. For more info see https://www.lyx.org/\n"
1691 << "\\lyxformat " << LYX_FORMAT << "\n"
1692 << "\\begin_document\n";
1694 /// For each author, set 'used' to true if there is a change
1695 /// by this author in the document; otherwise set it to 'false'.
1696 for (Author const & a : params().authors())
1699 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1700 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1701 for ( ; it != end; ++it)
1702 it->checkAuthors(params().authors());
1704 // now write out the buffer parameters.
1705 ofs << "\\begin_header\n";
1706 params().writeFile(ofs, this);
1707 ofs << "\\end_header\n";
1710 ofs << "\n\\begin_body\n";
1712 ofs << "\n\\end_body\n";
1714 // Write marker that shows file is complete
1715 ofs << "\\end_document" << endl;
1717 // Shouldn't really be needed....
1720 // how to check if close went ok?
1721 // Following is an attempt... (BE 20001011)
1723 // good() returns false if any error occurred, including some
1724 // formatting error.
1725 // bad() returns true if something bad happened in the buffer,
1726 // which should include file system full errors.
1731 lyxerr << "File was not closed properly." << endl;
1738 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1739 string const & original_path,
1740 OutputParams const & runparams_in,
1741 OutputWhat output) const
1743 OutputParams runparams = runparams_in;
1745 string const encoding = runparams.encoding->iconvName();
1746 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1749 try { ofs.reset(encoding); }
1750 catch (iconv_codecvt_facet_exception const & e) {
1751 lyxerr << "Caught iconv exception: " << e.what() << endl;
1752 Alert::error(_("Iconv software exception Detected"),
1753 bformat(_("Please verify that the `iconv' support software is"
1754 " properly installed and supports the selected encoding"
1755 " (%1$s), or change the encoding in"
1756 " Document>Settings>Language."), from_ascii(encoding)));
1759 if (!openFileWrite(ofs, fname))
1762 ErrorList & errorList = d->errorLists["Export"];
1764 ExportStatus status = ExportSuccess;
1767 // make sure we are ready to export
1768 // this needs to be done before we validate
1769 // FIXME Do we need to do this all the time? I.e., in children
1770 // of a master we are exporting?
1772 updateMacroInstances(OutputUpdate);
1774 ExportStatus retval;
1776 retval = writeLaTeXSource(os, original_path, runparams, output);
1777 if (retval == ExportKilled)
1778 return ExportKilled;
1780 catch (EncodingException const & e) {
1781 docstring const failed(1, e.failed_char);
1783 oss << "0x" << hex << e.failed_char << dec;
1784 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1785 docstring msg = bformat(_("Uncodable character '%1$s'"
1786 " (code point %2$s)"),
1787 failed, from_utf8(oss.str()));
1788 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1789 "representable in specific verbatim contexts.\n"
1790 "Changing the document encoding to utf8 could help."),
1791 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1793 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1794 " (code point %2$s)"),
1795 failed, from_utf8(oss.str()));
1796 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1797 "representable in the chosen encoding.\n"
1798 "Changing the document encoding to utf8 could help."),
1799 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1801 status = ExportError;
1803 catch (iconv_codecvt_facet_exception const & e) {
1804 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1806 status = ExportError;
1808 catch (exception const & e) {
1809 errorList.push_back(ErrorItem(_("conversion failed"),
1811 lyxerr << e.what() << endl;
1812 status = ExportError;
1815 lyxerr << "Caught some really weird exception..." << endl;
1819 d->texrow = move(os.texrow());
1823 status = ExportError;
1824 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1827 if (runparams_in.silent)
1835 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1836 string const & original_path,
1837 OutputParams const & runparams_in,
1838 OutputWhat output) const
1840 // The child documents, if any, shall be already loaded at this point.
1842 OutputParams runparams = runparams_in;
1844 // Some macros rely on font encoding
1845 runparams.main_fontenc = params().main_font_encoding();
1847 // If we are compiling a file standalone, even if this is the
1848 // child of some other buffer, let's cut the link here, so the
1849 // file is really independent and no concurring settings from
1850 // the master (e.g. branch state) interfere (see #8100).
1851 if (!runparams.is_child)
1852 d->ignore_parent = true;
1854 // Classify the unicode characters appearing in math insets
1855 BufferEncodings::initUnicodeMath(*this);
1857 // validate the buffer.
1858 LYXERR(Debug::LATEX, " Validating buffer...");
1859 LaTeXFeatures features(*this, params(), runparams);
1861 // This is only set once per document (in master)
1862 if (!runparams.is_child) {
1863 runparams.use_polyglossia = features.usePolyglossia();
1864 runparams.use_hyperref = features.isRequired("hyperref");
1865 runparams.use_CJK = features.mustProvide("CJK");
1867 LYXERR(Debug::LATEX, " Buffer validation done.");
1869 bool const output_preamble =
1870 output == FullSource || output == OnlyPreamble;
1871 bool const output_body =
1872 output == FullSource || output == OnlyBody;
1874 // The starting paragraph of the coming rows is the
1875 // first paragraph of the document. (Asger)
1876 if (output_preamble && runparams.nice) {
1877 os << "%% LyX " << lyx_version << " created this file. "
1878 "For more info, see https://www.lyx.org/.\n"
1879 "%% Do not edit unless you really know what "
1882 LYXERR(Debug::INFO, "lyx document header finished");
1884 // There are a few differences between nice LaTeX and usual files:
1885 // usual files have \batchmode and special input@path to allow
1886 // inclusion of figures specified by an explicitly relative path
1887 // (i.e., a path starting with './' or '../') with either \input or
1888 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1889 // input@path is set when the actual parameter original_path is set.
1890 // This is done for usual tex-file, but not for nice-latex-file.
1891 // (Matthias 250696)
1892 // Note that input@path is only needed for something the user does
1893 // in the preamble, included .tex files or ERT, files included by
1894 // LyX work without it.
1895 if (output_preamble) {
1896 if (!runparams.nice) {
1897 // code for usual, NOT nice-latex-file
1898 os << "\\batchmode\n"; // changed from \nonstopmode
1900 if (!original_path.empty()) {
1902 // We don't know the encoding of inputpath
1903 docstring const inputpath = from_utf8(original_path);
1904 docstring uncodable_glyphs;
1905 Encoding const * const enc = runparams.encoding;
1907 for (size_t n = 0; n < inputpath.size(); ++n) {
1908 if (!enc->encodable(inputpath[n])) {
1909 docstring const glyph(1, inputpath[n]);
1910 LYXERR0("Uncodable character '"
1912 << "' in input path!");
1913 uncodable_glyphs += glyph;
1918 // warn user if we found uncodable glyphs.
1919 if (!uncodable_glyphs.empty()) {
1920 frontend::Alert::warning(
1921 _("Uncodable character in file path"),
1923 _("The path of your document\n"
1925 "contains glyphs that are unknown "
1926 "in the current document encoding "
1927 "(namely %2$s). This may result in "
1928 "incomplete output, unless "
1929 "TEXINPUTS contains the document "
1930 "directory and you don't use "
1931 "explicitly relative paths (i.e., "
1932 "paths starting with './' or "
1933 "'../') in the preamble or in ERT."
1934 "\n\nIn case of problems, choose "
1935 "an appropriate document encoding\n"
1936 "(such as utf8) or change the "
1938 inputpath, uncodable_glyphs));
1940 string docdir = os::latex_path(original_path);
1941 if (contains(docdir, '#')) {
1942 docdir = subst(docdir, "#", "\\#");
1943 os << "\\catcode`\\#=11"
1944 "\\def\\#{#}\\catcode`\\#=6\n";
1946 if (contains(docdir, '%')) {
1947 docdir = subst(docdir, "%", "\\%");
1948 os << "\\catcode`\\%=11"
1949 "\\def\\%{%}\\catcode`\\%=14\n";
1951 if (contains(docdir, '~'))
1952 docdir = subst(docdir, "~", "\\string~");
1953 bool const nonascii = !isAscii(from_utf8(docdir));
1954 // LaTeX 2019/10/01 handles non-ascii path without detokenize
1955 bool const utfpathlatex = features.isAvailable("LaTeX-2019/10/01");
1956 bool const detokenize = !utfpathlatex && nonascii;
1957 bool const quote = contains(docdir, ' ');
1958 if (utfpathlatex && nonascii)
1959 os << "\\UseRawInputEncoding\n";
1960 os << "\\makeatletter\n"
1961 << "\\def\\input@path{{";
1963 os << "\\detokenize{";
1972 << "\\makeatother\n";
1976 // get parent macros (if this buffer has a parent) which will be
1977 // written at the document begin further down.
1978 MacroSet parentMacros;
1979 listParentMacros(parentMacros, features);
1981 // Write the preamble
1982 runparams.use_babel = params().writeLaTeX(os, features,
1983 d->filename.onlyPath());
1985 // Active characters
1986 runparams.active_chars = features.getActiveChars();
1988 // Biblatex bibliographies are loaded here
1989 if (params().useBiblatex()) {
1990 vector<pair<docstring, string>> const bibfiles =
1991 prepareBibFilePaths(runparams, getBibfiles(), true);
1992 for (pair<docstring, string> const & file: bibfiles) {
1993 os << "\\addbibresource";
1994 if (!file.second.empty())
1995 os << "[bibencoding=" << file.second << "]";
1996 os << "{" << file.first << "}\n";
2000 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
2001 && !features.hasOnlyPolyglossiaLanguages()) {
2004 vector<string> bll = features.getBabelExclusiveLanguages();
2005 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
2008 for (string const & sit : bll) {
2013 blangs = bll.size() > 1 ?
2014 bformat(_("The languages %1$s are only supported by Babel."), langs)
2015 : bformat(_("The language %1$s is only supported by Babel."), langs);
2019 for (string const & pit : pll) {
2024 plangs = pll.size() > 1 ?
2025 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
2026 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
2027 if (!blangs.empty())
2031 frontend::Alert::warning(
2032 _("Incompatible Languages!"),
2034 _("You cannot use the following languages "
2035 "together in one LaTeX document because "
2036 "they require conflicting language packages:\n"
2041 // Japanese might be required only in some children of a document,
2042 // but once required, we must keep use_japanese true.
2043 runparams.use_japanese |= features.isRequired("japanese");
2046 // Restore the parenthood if needed
2047 if (!runparams.is_child)
2048 d->ignore_parent = false;
2049 return ExportSuccess;
2053 // mark the beginning of the body to separate it from InPreamble insets
2054 os.texrow().start(TexRow::beginDocument());
2055 os << "\\begin{document}\n";
2057 // mark the start of a new paragraph by simulating a newline,
2058 // so that os.afterParbreak() returns true at document start
2061 // output the parent macros
2062 for (auto const & mac : parentMacros) {
2063 int num_lines = mac->write(os.os(), true);
2064 os.texrow().newlines(num_lines);
2067 } // output_preamble
2069 LYXERR(Debug::INFO, "preamble finished, now the body.");
2073 latexParagraphs(*this, text(), os, runparams);
2075 catch (ConversionException const &) { return ExportKilled; }
2077 // Restore the parenthood if needed
2078 if (!runparams.is_child)
2079 d->ignore_parent = false;
2081 // add this just in case after all the paragraphs
2084 if (output_preamble) {
2085 os << "\\end{document}\n";
2086 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2088 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2090 runparams_in.encoding = runparams.encoding;
2092 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2093 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2094 return ExportSuccess;
2098 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2099 OutputParams const & runparams,
2100 OutputWhat output) const
2102 LYXERR(Debug::LATEX, "makeDocBookFile...");
2105 if (!openFileWrite(ofs, fname))
2108 // make sure we are ready to export
2109 // this needs to be done before we validate
2111 updateMacroInstances(OutputUpdate);
2113 ExportStatus const retval =
2114 writeDocBookSource(ofs, runparams, output);
2115 if (retval == ExportKilled)
2116 return ExportKilled;
2120 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2121 return ExportSuccess;
2125 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os,
2126 OutputParams const & runparams,
2127 OutputWhat output) const
2129 LaTeXFeatures features(*this, params(), runparams);
2131 d->bibinfo_.makeCitationLabels(*this);
2135 DocumentClass const & tclass = params().documentClass();
2137 bool const output_preamble =
2138 output == FullSource || output == OnlyPreamble;
2139 bool const output_body =
2140 output == FullSource || output == OnlyBody;
2142 if (output_preamble) {
2143 // XML preamble, no doctype needed.
2144 // Not using XMLStream for this, as the root tag would be in the tag stack and make troubles with the error
2145 // detection mechanisms (these are called before the end tag is output, and thus interact with the canary
2146 // parsep in output_docbook.cpp).
2147 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2148 << "<!-- This DocBook file was created by LyX " << lyx_version
2149 << "\n See http://www.lyx.org/ for more information -->\n";
2151 // Directly output the root tag, based on the current type of document.
2152 string languageCode = params().language->code();
2153 string params = "xml:lang=\"" + languageCode + '"'
2154 + " xmlns=\"http://docbook.org/ns/docbook\""
2155 + " xmlns:xlink=\"http://www.w3.org/1999/xlink\""
2156 + " xmlns:m=\"http://www.w3.org/1998/Math/MathML\""
2157 + " xmlns:xi=\"http://www.w3.org/2001/XInclude\""
2158 + " version=\"5.2\"";
2160 os << "<" << from_ascii(tclass.docbookroot()) << " " << from_ascii(params) << ">\n";
2164 // Start to output the document.
2166 docbookParagraphs(text(), *this, xs, runparams);
2169 if (output_preamble) {
2170 // Close the root element. No need for a line break, as free text is never allowed
2171 // in a root element, it must always be wrapped in some container.
2172 os << "</" << from_ascii(tclass.docbookroot()) << ">";
2175 return ExportSuccess;
2179 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2180 OutputParams const & runparams) const
2182 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2185 if (!openFileWrite(ofs, fname))
2188 // make sure we are ready to export
2189 // this has to be done before we validate
2190 updateBuffer(UpdateMaster, OutputUpdate);
2191 updateMacroInstances(OutputUpdate);
2193 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2194 if (retval == ExportKilled)
2199 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2204 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2205 OutputParams const & runparams,
2206 OutputWhat output) const
2208 LaTeXFeatures features(*this, params(), runparams);
2210 d->bibinfo_.makeCitationLabels(*this);
2212 bool const output_preamble =
2213 output == FullSource || output == OnlyPreamble;
2214 bool const output_body =
2215 output == FullSource || output == OnlyBody || output == IncludedFile;
2217 if (output_preamble) {
2218 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2219 << "<!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"
2220 // FIXME Language should be set properly.
2221 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2223 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2224 // FIXME Presumably need to set this right
2225 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2227 docstring const & doctitle = features.htmlTitle();
2229 << (doctitle.empty() ?
2230 from_ascii("LyX Document") :
2231 xml::escapeString(doctitle, XMLStream::ESCAPE_ALL))
2234 docstring styles = features.getTClassHTMLPreamble();
2235 if (!styles.empty())
2236 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2238 // we will collect CSS information in a stream, and then output it
2239 // either here, as part of the header, or else in a separate file.
2240 odocstringstream css;
2241 styles = features.getCSSSnippets();
2242 if (!styles.empty())
2243 css << "/* LyX Provided Styles */\n" << styles << '\n';
2245 styles = features.getTClassHTMLStyles();
2246 if (!styles.empty())
2247 css << "/* Layout-provided Styles */\n" << styles << '\n';
2249 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2250 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2251 if (needfg || needbg) {
2252 css << "\nbody {\n";
2255 << from_ascii(X11hexname(params().fontcolor))
2258 css << " background-color: "
2259 << from_ascii(X11hexname(params().backgroundcolor))
2264 docstring const dstyles = css.str();
2265 if (!dstyles.empty()) {
2266 bool written = false;
2267 if (params().html_css_as_file) {
2268 // open a file for CSS info
2270 string const fcssname = addName(temppath(), "docstyle.css");
2271 FileName const fcssfile = FileName(fcssname);
2272 if (openFileWrite(ocss, fcssfile)) {
2276 // write link to header
2277 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2279 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2282 // we are here if the CSS is supposed to be written to the header
2283 // or if we failed to write it to an external file.
2285 os << "<style type='text/css'>\n"
2294 bool const output_body_tag = (output != IncludedFile);
2295 if (output_body_tag)
2296 os << "<body dir=\"auto\">\n";
2298 if (output != IncludedFile)
2299 // if we're an included file, the counters are in the master.
2300 params().documentClass().counters().reset();
2302 xhtmlParagraphs(text(), *this, xs, runparams);
2304 catch (ConversionException const &) { return ExportKilled; }
2305 if (output_body_tag)
2309 if (output_preamble)
2312 return ExportSuccess;
2316 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2317 // Other flags: -wall -v0 -x
2318 int Buffer::runChktex()
2322 // get LaTeX-Filename
2323 FileName const path(temppath());
2324 string const name = addName(path.absFileName(), latexName());
2325 string const org_path = filePath();
2327 PathChanger p(path); // path to LaTeX file
2328 message(_("Running chktex..."));
2330 // Generate the LaTeX file if neccessary
2331 OutputParams runparams(¶ms().encoding());
2332 runparams.flavor = OutputParams::LATEX;
2333 runparams.nice = false;
2334 runparams.linelen = lyxrc.plaintext_linelen;
2335 ExportStatus const retval =
2336 makeLaTeXFile(FileName(name), org_path, runparams);
2337 if (retval != ExportSuccess) {
2338 // error code on failure
2343 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2344 int const res = chktex.run(terr); // run chktex
2347 Alert::error(_("chktex failure"),
2348 _("Could not run chktex successfully."));
2350 ErrorList & errlist = d->errorLists["ChkTeX"];
2352 bufferErrors(terr, errlist);
2357 if (runparams.silent)
2358 d->errorLists["ChkTeX"].clear();
2366 void Buffer::validate(LaTeXFeatures & features) const
2368 // Validate the buffer params, but not for included
2369 // files, since they also use the parent buffer's
2371 if (!features.runparams().is_child)
2372 params().validate(features);
2377 for (Paragraph const & p : paragraphs())
2378 p.validate(features);
2380 if (lyxerr.debugging(Debug::LATEX)) {
2381 features.showStruct();
2386 void Buffer::getLabelList(vector<docstring> & list) const
2388 // If this is a child document, use the master's list instead.
2390 masterBuffer()->getLabelList(list);
2395 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2396 for (auto const & tocit : *toc) {
2397 if (tocit.depth() == 0)
2398 list.push_back(tocit.str());
2403 void Buffer::invalidateBibinfoCache() const
2405 d->bibinfo_cache_valid_ = false;
2406 d->cite_labels_valid_ = false;
2407 removeBiblioTempFiles();
2408 // also invalidate the cache for the parent buffer
2409 Buffer const * const pbuf = d->parent();
2411 pbuf->invalidateBibinfoCache();
2415 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2417 // FIXME This is probably unnecessary, given where we call this.
2418 // If this is a child document, use the master instead.
2419 Buffer const * const pbuf = masterBuffer();
2420 if (pbuf != this && scope != UpdateChildOnly)
2421 return pbuf->getBibfiles();
2423 // In 2.3.x, we have:
2424 //if (!d->bibfile_cache_valid_)
2425 // this->updateBibfilesCache(scope);
2426 // I think that is a leftover, but there have been so many back-
2427 // and-forths with this, due to Windows issues, that I am not sure.
2429 return d->bibfiles_cache_;
2433 BiblioInfo const & Buffer::masterBibInfo() const
2435 Buffer const * const tmp = masterBuffer();
2437 return tmp->masterBibInfo();
2442 BiblioInfo const & Buffer::bibInfo() const
2448 void Buffer::registerBibfiles(const docstring_list & bf) const
2450 // We register the bib files in the master buffer,
2451 // if there is one, but also in every single buffer,
2452 // in case a child is compiled alone.
2453 Buffer const * const tmp = masterBuffer();
2455 tmp->registerBibfiles(bf);
2457 for (auto const & p : bf) {
2458 docstring_list::const_iterator temp =
2459 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2460 if (temp == d->bibfiles_cache_.end())
2461 d->bibfiles_cache_.push_back(p);
2466 static map<docstring, FileName> bibfileCache;
2468 FileName Buffer::getBibfilePath(docstring const & bibid) const
2470 map<docstring, FileName>::const_iterator it =
2471 bibfileCache.find(bibid);
2472 if (it != bibfileCache.end()) {
2473 // i.e., return bibfileCache[bibid];
2477 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2478 string const texfile = changeExtension(to_utf8(bibid), "bib");
2479 // we need to check first if this file exists where it's said to be.
2480 // there's a weird bug that occurs otherwise: if the file is in the
2481 // Buffer's directory but has the same name as some file that would be
2482 // found by kpsewhich, then we find the latter, not the former.
2483 FileName const local_file = makeAbsPath(texfile, filePath());
2484 FileName file = local_file;
2485 if (!file.exists()) {
2486 // there's no need now to check whether the file can be found
2488 file = findtexfile(texfile, "bib", true);
2492 LYXERR(Debug::FILES, "Found at: " << file);
2494 bibfileCache[bibid] = file;
2495 return bibfileCache[bibid];
2499 void Buffer::checkIfBibInfoCacheIsValid() const
2501 // use the master's cache
2502 Buffer const * const tmp = masterBuffer();
2504 tmp->checkIfBibInfoCacheIsValid();
2508 // If we already know the cache is invalid, stop here.
2509 // This is important in the case when the bibliography
2510 // environment (rather than Bib[la]TeX) is used.
2511 // In that case, the timestamp check below gives no
2512 // sensible result. Rather than that, the cache will
2513 // be invalidated explicitly via invalidateBibInfoCache()
2514 // by the Bibitem inset.
2515 // Same applies for bib encoding changes, which trigger
2516 // invalidateBibInfoCache() by InsetBibtex.
2517 if (!d->bibinfo_cache_valid_)
2520 if (d->have_bibitems_) {
2521 // We have a bibliography environment.
2522 // Invalidate the bibinfo cache unconditionally.
2523 // Cite labels will get invalidated by the inset if needed.
2524 d->bibinfo_cache_valid_ = false;
2528 // OK. This is with Bib(la)tex. We'll assume the cache
2529 // is valid and change this if we find changes in the bibs.
2530 d->bibinfo_cache_valid_ = true;
2531 d->cite_labels_valid_ = true;
2533 // compare the cached timestamps with the actual ones.
2534 docstring_list const & bibfiles_cache = getBibfiles();
2535 for (auto const & bf : bibfiles_cache) {
2536 FileName const fn = getBibfilePath(bf);
2537 time_t lastw = fn.lastModified();
2538 time_t prevw = d->bibfile_status_[fn];
2539 if (lastw != prevw) {
2540 d->bibinfo_cache_valid_ = false;
2541 d->cite_labels_valid_ = false;
2542 d->bibfile_status_[fn] = lastw;
2548 void Buffer::clearBibFileCache() const
2550 bibfileCache.clear();
2554 void Buffer::reloadBibInfoCache(bool const force) const
2556 // we should not need to do this for internal buffers
2560 // use the master's cache
2561 Buffer const * const tmp = masterBuffer();
2563 tmp->reloadBibInfoCache(force);
2568 checkIfBibInfoCacheIsValid();
2569 if (d->bibinfo_cache_valid_)
2573 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2574 // re-read file locations when this info changes
2575 // FIXME Is this sufficient? Or should we also force that
2576 // in some other cases? If so, then it is easy enough to
2577 // add the following line in some other places.
2578 clearBibFileCache();
2579 d->bibinfo_.clear();
2580 FileNameList checkedFiles;
2581 d->have_bibitems_ = false;
2582 collectBibKeys(checkedFiles);
2583 d->bibinfo_cache_valid_ = true;
2587 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2592 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2593 it->collectBibKeys(it, checkedFiles);
2594 if (it->lyxCode() == BIBITEM_CODE) {
2595 if (parent() != nullptr)
2596 parent()->d->have_bibitems_ = true;
2598 d->have_bibitems_ = true;
2604 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2606 // We add the biblio info to the master buffer,
2607 // if there is one, but also to every single buffer,
2608 // in case a child is compiled alone.
2609 BiblioInfo & bi = d->bibinfo_;
2610 bi.mergeBiblioInfo(bin);
2612 if (parent() != nullptr) {
2613 BiblioInfo & masterbi = parent()->d->bibinfo_;
2614 masterbi.mergeBiblioInfo(bin);
2619 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2621 // We add the bibtex info to the master buffer,
2622 // if there is one, but also to every single buffer,
2623 // in case a child is compiled alone.
2624 BiblioInfo & bi = d->bibinfo_;
2627 if (parent() != nullptr) {
2628 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2629 masterbi[key] = bin;
2634 void Buffer::makeCitationLabels() const
2636 Buffer const * const master = masterBuffer();
2637 return d->bibinfo_.makeCitationLabels(*master);
2641 void Buffer::invalidateCiteLabels() const
2643 masterBuffer()->d->cite_labels_valid_ = false;
2646 bool Buffer::citeLabelsValid() const
2648 return masterBuffer()->d->cite_labels_valid_;
2652 void Buffer::removeBiblioTempFiles() const
2654 // We remove files that contain LaTeX commands specific to the
2655 // particular bibliographic style being used, in order to avoid
2656 // LaTeX errors when we switch style.
2657 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2658 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2659 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2660 aux_file.removeFile();
2661 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2662 bbl_file.removeFile();
2663 // Also for the parent buffer
2664 Buffer const * const pbuf = parent();
2666 pbuf->removeBiblioTempFiles();
2670 bool Buffer::isDepClean(string const & name) const
2672 DepClean::const_iterator const it = d->dep_clean.find(name);
2673 if (it == d->dep_clean.end())
2679 void Buffer::markDepClean(string const & name)
2681 d->dep_clean[name] = true;
2685 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2688 // FIXME? if there is an Buffer LFUN that can be dispatched even
2689 // if internal, put a switch '(cmd.action)' here.
2695 switch (cmd.action()) {
2697 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2698 flag.setOnOff(hasReadonlyFlag());
2701 // FIXME: There is need for a command-line import.
2702 //case LFUN_BUFFER_IMPORT:
2704 case LFUN_BUFFER_AUTO_SAVE:
2707 case LFUN_BUFFER_EXPORT_CUSTOM:
2708 // FIXME: Nothing to check here?
2711 case LFUN_BUFFER_EXPORT: {
2712 docstring const arg = cmd.argument();
2713 if (arg == "custom") {
2717 string format = (arg.empty() || arg == "default") ?
2718 params().getDefaultOutputFormat() : to_utf8(arg);
2719 size_t pos = format.find(' ');
2720 if (pos != string::npos)
2721 format = format.substr(0, pos);
2722 enable = params().isExportable(format, false);
2724 flag.message(bformat(
2725 _("Don't know how to export to format: %1$s"), arg));
2729 case LFUN_BUILD_PROGRAM:
2730 enable = params().isExportable("program", false);
2733 case LFUN_BRANCH_ACTIVATE:
2734 case LFUN_BRANCH_DEACTIVATE:
2735 case LFUN_BRANCH_MASTER_ACTIVATE:
2736 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2737 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2738 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2739 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2740 : params().branchlist();
2741 docstring const branchName = cmd.argument();
2742 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2746 case LFUN_BRANCH_ADD:
2747 case LFUN_BRANCHES_RENAME:
2748 // if no Buffer is present, then of course we won't be called!
2751 case LFUN_BUFFER_LANGUAGE:
2752 enable = !isReadonly();
2755 case LFUN_BUFFER_VIEW_CACHE:
2756 (d->preview_file_).refresh();
2757 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2760 case LFUN_CHANGES_TRACK:
2761 flag.setEnabled(true);
2762 flag.setOnOff(params().track_changes);
2765 case LFUN_CHANGES_OUTPUT:
2766 flag.setEnabled(true);
2767 flag.setOnOff(params().output_changes);
2770 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2771 flag.setOnOff(params().compressed);
2774 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2775 flag.setOnOff(params().output_sync);
2778 case LFUN_BUFFER_ANONYMIZE:
2784 flag.setEnabled(enable);
2789 void Buffer::dispatch(string const & command, DispatchResult & result)
2791 return dispatch(lyxaction.lookupFunc(command), result);
2795 // NOTE We can end up here even if we have no GUI, because we are called
2796 // by LyX::exec to handled command-line requests. So we may need to check
2797 // whether we have a GUI or not. The boolean use_gui holds this information.
2798 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2801 // FIXME? if there is an Buffer LFUN that can be dispatched even
2802 // if internal, put a switch '(cmd.action())' here.
2803 dr.dispatched(false);
2806 string const argument = to_utf8(func.argument());
2807 // We'll set this back to false if need be.
2808 bool dispatched = true;
2809 // This handles undo groups automagically
2810 UndoGroupHelper ugh(this);
2812 switch (func.action()) {
2813 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2814 if (lyxvc().inUse()) {
2815 string log = lyxvc().toggleReadOnly();
2820 setReadonly(!hasReadonlyFlag());
2823 case LFUN_BUFFER_EXPORT: {
2824 string const format = (argument.empty() || argument == "default") ?
2825 params().getDefaultOutputFormat() : argument;
2826 ExportStatus const status = doExport(format, false);
2827 dr.setError(status != ExportSuccess);
2828 if (status != ExportSuccess)
2829 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2830 from_utf8(format)));
2834 case LFUN_BUILD_PROGRAM: {
2835 ExportStatus const status = doExport("program", true);
2836 dr.setError(status != ExportSuccess);
2837 if (status != ExportSuccess)
2838 dr.setMessage(_("Error generating literate programming code."));
2842 case LFUN_BUFFER_EXPORT_CUSTOM: {
2844 string command = split(argument, format_name, ' ');
2845 Format const * format = theFormats().getFormat(format_name);
2847 lyxerr << "Format \"" << format_name
2848 << "\" not recognized!"
2853 // The name of the file created by the conversion process
2856 // Output to filename
2857 if (format->name() == "lyx") {
2858 string const latexname = latexName(false);
2859 filename = changeExtension(latexname,
2860 format->extension());
2861 filename = addName(temppath(), filename);
2863 if (!writeFile(FileName(filename)))
2867 doExport(format_name, true, filename);
2870 // Substitute $$FName for filename
2871 if (!contains(command, "$$FName"))
2872 command = "( " + command + " ) < $$FName";
2873 command = subst(command, "$$FName", filename);
2875 // Execute the command in the background
2877 call.startscript(Systemcall::DontWait, command,
2878 filePath(), layoutPos());
2882 // FIXME: There is need for a command-line import.
2884 case LFUN_BUFFER_IMPORT:
2889 case LFUN_BUFFER_AUTO_SAVE:
2891 resetAutosaveTimers();
2894 case LFUN_BRANCH_ACTIVATE:
2895 case LFUN_BRANCH_DEACTIVATE:
2896 case LFUN_BRANCH_MASTER_ACTIVATE:
2897 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2898 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2899 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2900 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2903 docstring const branch_name = func.argument();
2904 // the case without a branch name is handled elsewhere
2905 if (branch_name.empty()) {
2909 Branch * branch = buf->params().branchlist().find(branch_name);
2911 LYXERR0("Branch " << branch_name << " does not exist.");
2913 docstring const msg =
2914 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2918 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2919 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2920 if (branch->isSelected() != activate) {
2921 buf->undo().recordUndoBufferParams(CursorData());
2922 branch->setSelected(activate);
2924 dr.screenUpdate(Update::Force);
2925 dr.forceBufferUpdate();
2930 case LFUN_BRANCH_ADD: {
2931 docstring branchnames = func.argument();
2932 if (branchnames.empty()) {
2936 BranchList & branch_list = params().branchlist();
2937 vector<docstring> const branches =
2938 getVectorFromString(branchnames, branch_list.separator());
2940 for (docstring const & branch_name : branches) {
2941 Branch * branch = branch_list.find(branch_name);
2943 LYXERR0("Branch " << branch_name << " already exists.");
2947 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2949 undo().recordUndoBufferParams(CursorData());
2950 branch_list.add(branch_name);
2951 branch = branch_list.find(branch_name);
2952 string const x11hexname = X11hexname(branch->color());
2953 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2954 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2956 dr.screenUpdate(Update::Force);
2964 case LFUN_BRANCHES_RENAME: {
2965 if (func.argument().empty())
2968 docstring const oldname = from_utf8(func.getArg(0));
2969 docstring const newname = from_utf8(func.getArg(1));
2970 InsetIterator it = inset_iterator_begin(inset());
2971 InsetIterator const end = inset_iterator_end(inset());
2972 bool success = false;
2973 for (; it != end; ++it) {
2974 if (it->lyxCode() == BRANCH_CODE) {
2975 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2976 if (ins.branch() == oldname) {
2977 undo().recordUndo(CursorData(it));
2978 ins.rename(newname);
2983 if (it->lyxCode() == INCLUDE_CODE) {
2984 // get buffer of external file
2985 InsetInclude const & ins =
2986 static_cast<InsetInclude const &>(*it);
2987 Buffer * child = ins.loadIfNeeded();
2990 child->dispatch(func, dr);
2995 dr.screenUpdate(Update::Force);
2996 dr.forceBufferUpdate();
3001 case LFUN_BUFFER_VIEW_CACHE:
3002 if (!theFormats().view(*this, d->preview_file_,
3003 d->preview_format_))
3004 dr.setMessage(_("Error viewing the output file."));
3007 case LFUN_CHANGES_TRACK:
3008 if (params().save_transient_properties)
3009 undo().recordUndoBufferParams(CursorData());
3010 params().track_changes = !params().track_changes;
3013 case LFUN_CHANGES_OUTPUT:
3014 if (params().save_transient_properties)
3015 undo().recordUndoBufferParams(CursorData());
3016 params().output_changes = !params().output_changes;
3017 if (params().output_changes) {
3018 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
3019 LaTeXFeatures::isAvailable("xcolor");
3022 Alert::warning(_("Changes not shown in LaTeX output"),
3023 _("Changes will not be highlighted in LaTeX output, "
3024 "because xcolor and ulem are not installed.\n"
3025 "Please install both packages or redefine "
3026 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3031 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3032 // turn compression on/off
3033 undo().recordUndoBufferParams(CursorData());
3034 params().compressed = !params().compressed;
3037 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3038 undo().recordUndoBufferParams(CursorData());
3039 params().output_sync = !params().output_sync;
3042 case LFUN_BUFFER_ANONYMIZE: {
3043 undo().recordUndoFullBuffer(CursorData());
3044 CursorData cur(doc_iterator_begin(this));
3045 for ( ; cur ; cur.forwardPar())
3046 cur.paragraph().anonymize();
3047 dr.forceBufferUpdate();
3048 dr.screenUpdate(Update::Force);
3056 dr.dispatched(dispatched);
3060 void Buffer::changeLanguage(Language const * from, Language const * to)
3062 LASSERT(from, return);
3063 LASSERT(to, return);
3065 ParIterator it = par_iterator_begin();
3066 ParIterator eit = par_iterator_end();
3067 for (; it != eit; ++it)
3068 it->changeLanguage(params(), from, to);
3072 bool Buffer::isMultiLingual() const
3074 ParConstIterator end = par_iterator_end();
3075 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3076 if (it->isMultiLingual(params()))
3083 std::set<Language const *> Buffer::getLanguages() const
3085 std::set<Language const *> langs;
3086 getLanguages(langs);
3091 void Buffer::getLanguages(std::set<Language const *> & langs) const
3093 ParConstIterator end = par_iterator_end();
3094 // add the buffer language, even if it's not actively used
3095 langs.insert(language());
3096 // iterate over the paragraphs
3097 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3098 it->getLanguages(langs);
3100 ListOfBuffers clist = getDescendants();
3101 for (auto const & cit : clist)
3102 cit->getLanguages(langs);
3106 DocIterator Buffer::getParFromID(int const id) const
3108 Buffer * buf = const_cast<Buffer *>(this);
3110 // This means non-existent
3111 return doc_iterator_end(buf);
3113 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3114 if (it.paragraph().id() == id)
3117 return doc_iterator_end(buf);
3121 bool Buffer::hasParWithID(int const id) const
3123 return !getParFromID(id).atEnd();
3127 ParIterator Buffer::par_iterator_begin()
3129 return ParIterator(doc_iterator_begin(this));
3133 ParIterator Buffer::par_iterator_end()
3135 return ParIterator(doc_iterator_end(this));
3139 ParConstIterator Buffer::par_iterator_begin() const
3141 return ParConstIterator(doc_iterator_begin(this));
3145 ParConstIterator Buffer::par_iterator_end() const
3147 return ParConstIterator(doc_iterator_end(this));
3151 Language const * Buffer::language() const
3153 return params().language;
3157 docstring Buffer::B_(string const & l10n) const
3159 return params().B_(l10n);
3163 bool Buffer::isClean() const
3165 return d->lyx_clean;
3169 bool Buffer::isChecksumModified() const
3171 LASSERT(d->filename.exists(), return false);
3172 return d->checksum_ != d->filename.checksum();
3176 void Buffer::saveCheckSum() const
3178 FileName const & file = d->filename;
3180 d->checksum_ = file.exists() ? file.checksum()
3181 : 0; // in the case of save to a new file.
3185 void Buffer::markClean() const
3187 if (!d->lyx_clean) {
3188 d->lyx_clean = true;
3191 // if the .lyx file has been saved, we don't need an
3193 d->bak_clean = true;
3194 d->undo_.markDirty();
3195 clearExternalModification();
3199 void Buffer::setUnnamed(bool flag)
3205 bool Buffer::isUnnamed() const
3212 /// Don't check unnamed, here: isInternal() is used in
3213 /// newBuffer(), where the unnamed flag has not been set by anyone
3214 /// yet. Also, for an internal buffer, there should be no need for
3215 /// retrieving fileName() nor for checking if it is unnamed or not.
3216 bool Buffer::isInternal() const
3218 return d->internal_buffer;
3222 void Buffer::setInternal(bool flag)
3224 d->internal_buffer = flag;
3228 void Buffer::markDirty()
3231 d->lyx_clean = false;
3234 d->bak_clean = false;
3236 for (auto & depit : d->dep_clean)
3237 depit.second = false;
3241 FileName Buffer::fileName() const
3247 string Buffer::absFileName() const
3249 return d->filename.absFileName();
3253 string Buffer::filePath() const
3255 string const abs = d->filename.onlyPath().absFileName();
3258 int last = abs.length() - 1;
3260 return abs[last] == '/' ? abs : abs + '/';
3264 DocFileName Buffer::getReferencedFileName(string const & fn) const
3267 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3268 result.set(fn, filePath());
3270 // filePath() ends with a path separator
3271 FileName const test(filePath() + fn);
3273 result.set(fn, filePath());
3275 result.set(fn, params().origin);
3282 string const Buffer::prepareFileNameForLaTeX(string const & name,
3283 string const & ext, bool nice) const
3285 string const fname = makeAbsPath(name, filePath()).absFileName();
3286 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3292 return to_utf8(makeRelPath(from_utf8(fname),
3293 from_utf8(masterBuffer()->filePath())));
3297 vector<pair<docstring, string>> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3298 docstring_list const & bibfilelist,
3299 bool const add_extension) const
3301 // If we are processing the LaTeX file in a temp directory then
3302 // copy the .bib databases to this temp directory, mangling their
3303 // names in the process. Store this mangled name in the list of
3305 // (We need to do all this because BibTeX *really*, *really*
3306 // can't handle "files with spaces" and Windows users tend to
3307 // use such filenames.)
3308 // Otherwise, store the (maybe absolute) path to the original,
3309 // unmangled database name.
3311 vector<pair<docstring, string>> res;
3313 // determine the export format
3314 string const tex_format = flavor2format(runparams.flavor);
3316 // check for spaces in paths
3317 bool found_space = false;
3319 for (auto const & bit : bibfilelist) {
3320 string utf8input = to_utf8(bit);
3322 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3323 FileName try_in_file =
3324 makeAbsPath(database + ".bib", filePath());
3325 bool not_from_texmf = try_in_file.isReadableFile();
3326 // If the file has not been found, try with the real file name
3327 // (it might come from a child in a sub-directory)
3328 if (!not_from_texmf) {
3329 try_in_file = getBibfilePath(bit);
3330 if (try_in_file.isReadableFile()) {
3331 // Check if the file is in texmf
3332 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3333 not_from_texmf = kpsefile.empty()
3334 || kpsefile.absFileName() != try_in_file.absFileName();
3336 // If this exists, make path relative to the master
3339 removeExtension(prepareFileNameForLaTeX(
3340 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3341 from_utf8(filePath()))),
3342 ".bib", runparams.nice));
3346 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3348 // mangledFileName() needs the extension
3349 DocFileName const in_file = DocFileName(try_in_file);
3350 database = removeExtension(in_file.mangledFileName());
3351 FileName const out_file = makeAbsPath(database + ".bib",
3352 masterBuffer()->temppath());
3353 bool const success = in_file.copyTo(out_file);
3355 LYXERR0("Failed to copy '" << in_file
3356 << "' to '" << out_file << "'");
3358 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3359 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3360 if (!isValidLaTeXFileName(database)) {
3361 frontend::Alert::warning(_("Invalid filename"),
3362 _("The following filename will cause troubles "
3363 "when running the exported file through LaTeX: ") +
3364 from_utf8(database));
3366 if (!isValidDVIFileName(database)) {
3367 frontend::Alert::warning(_("Problematic filename for DVI"),
3368 _("The following filename can cause troubles "
3369 "when running the exported file through LaTeX "
3370 "and opening the resulting DVI: ") +
3371 from_utf8(database), true);
3379 docstring const path = from_utf8(latex_path(database));
3381 if (contains(path, ' '))
3384 if (params().useBiblatex() && !params().bibFileEncoding(utf8input).empty())
3385 enc = params().bibFileEncoding(utf8input);
3387 bool recorded = false;
3388 for (auto const & pe : res) {
3389 if (pe.first == path) {
3396 res.push_back(make_pair(path, enc));
3399 // Check if there are spaces in the path and warn BibTeX users, if so.
3400 // (biber can cope with such paths)
3401 if (!prefixIs(runparams.bibtex_command, "biber")) {
3402 // Post this warning only once.
3403 static bool warned_about_spaces = false;
3404 if (!warned_about_spaces &&
3405 runparams.nice && found_space) {
3406 warned_about_spaces = true;
3407 Alert::warning(_("Export Warning!"),
3408 _("There are spaces in the paths to your BibTeX databases.\n"
3409 "BibTeX will be unable to find them."));
3418 string Buffer::layoutPos() const
3420 return d->layout_position;
3424 void Buffer::setLayoutPos(string const & path)
3427 d->layout_position.clear();
3431 LATTEST(FileName::isAbsolute(path));
3433 d->layout_position =
3434 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3436 if (d->layout_position.empty())
3437 d->layout_position = ".";
3441 bool Buffer::hasReadonlyFlag() const
3443 return d->read_only;
3447 bool Buffer::isReadonly() const
3449 return hasReadonlyFlag() || notifiesExternalModification();
3453 void Buffer::setParent(Buffer const * buffer)
3455 // We need to do some work here to avoid recursive parent structures.
3456 // This is the easy case.
3457 if (buffer == this) {
3458 LYXERR0("Ignoring attempt to set self as parent in\n" << fileName());
3461 // Now we check parents going upward, to make sure that IF we set the
3462 // parent as requested, we would not generate a recursive include.
3463 set<Buffer const *> sb;
3464 Buffer const * b = buffer;
3465 bool found_recursion = false;
3467 if (sb.find(b) != sb.end()) {
3468 found_recursion = true;
3475 if (found_recursion) {
3476 LYXERR0("Ignoring attempt to set parent of\n" <<
3479 buffer->fileName() <<
3480 "\nbecause that would create a recursive inclusion.");
3484 // We should be safe now.
3485 d->setParent(buffer);
3490 Buffer const * Buffer::parent() const
3496 ListOfBuffers Buffer::allRelatives() const
3498 ListOfBuffers lb = masterBuffer()->getDescendants();
3499 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3504 Buffer const * Buffer::masterBuffer() const
3506 Buffer const * const pbuf = d->parent();
3510 return pbuf->masterBuffer();
3514 bool Buffer::isChild(Buffer * child) const
3516 return d->children_positions.find(child) != d->children_positions.end();
3520 DocIterator Buffer::firstChildPosition(Buffer const * child)
3522 Impl::BufferPositionMap::iterator it;
3523 it = d->children_positions.find(child);
3524 if (it == d->children_positions.end())
3525 return DocIterator(this);
3530 bool Buffer::hasChildren() const
3532 return !d->children_positions.empty();
3536 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3538 // loop over children
3539 for (auto const & p : d->children_positions) {
3540 Buffer * child = const_cast<Buffer *>(p.first);
3542 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3543 if (bit != clist.end())
3545 clist.push_back(child);
3547 // there might be grandchildren
3548 child->collectChildren(clist, true);
3553 ListOfBuffers Buffer::getChildren() const
3556 collectChildren(v, false);
3557 // Make sure we have not included ourselves.
3558 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3559 if (bit != v.end()) {
3560 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3567 ListOfBuffers Buffer::getDescendants() const
3570 collectChildren(v, true);
3571 // Make sure we have not included ourselves.
3572 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3573 if (bit != v.end()) {
3574 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3581 template<typename M>
3582 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3587 typename M::const_iterator it = m.lower_bound(x);
3588 if (it == m.begin())
3596 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3597 DocIterator const & pos) const
3599 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3601 // if paragraphs have no macro context set, pos will be empty
3605 // we haven't found anything yet
3606 DocIterator bestPos = owner_->par_iterator_begin();
3607 MacroData const * bestData = nullptr;
3609 // find macro definitions for name
3610 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3611 if (nameIt != macros.end()) {
3612 // find last definition in front of pos or at pos itself
3613 PositionScopeMacroMap::const_iterator it
3614 = greatest_below(nameIt->second, pos);
3615 if (it != nameIt->second.end()) {
3617 // scope ends behind pos?
3618 if (pos < it->second.scope) {
3619 // Looks good, remember this. If there
3620 // is no external macro behind this,
3621 // we found the right one already.
3622 bestPos = it->first;
3623 bestData = &it->second.macro;
3627 // try previous macro if there is one
3628 if (it == nameIt->second.begin())
3635 // find macros in included files
3636 PositionScopeBufferMap::const_iterator it
3637 = greatest_below(position_to_children, pos);
3638 if (it == position_to_children.end())
3639 // no children before
3643 // do we know something better (i.e. later) already?
3644 if (it->first < bestPos )
3647 // scope ends behind pos?
3648 if (pos < it->second.scope
3649 && (cloned_buffer_ ||
3650 theBufferList().isLoaded(it->second.buffer))) {
3651 // look for macro in external file
3653 MacroData const * data
3654 = it->second.buffer->getMacro(name, false);
3657 bestPos = it->first;
3663 // try previous file if there is one
3664 if (it == position_to_children.begin())
3669 // return the best macro we have found
3674 MacroData const * Buffer::getMacro(docstring const & name,
3675 DocIterator const & pos, bool global) const
3680 // query buffer macros
3681 MacroData const * data = d->getBufferMacro(name, pos);
3682 if (data != nullptr)
3685 // If there is a master buffer, query that
3686 Buffer const * const pbuf = d->parent();
3688 d->macro_lock = true;
3689 MacroData const * macro = pbuf->getMacro(
3690 name, *this, false);
3691 d->macro_lock = false;
3697 data = MacroTable::globalMacros().get(name);
3698 if (data != nullptr)
3706 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3708 // set scope end behind the last paragraph
3709 DocIterator scope = par_iterator_begin();
3710 scope.pit() = scope.lastpit() + 1;
3712 return getMacro(name, scope, global);
3716 MacroData const * Buffer::getMacro(docstring const & name,
3717 Buffer const & child, bool global) const
3719 // look where the child buffer is included first
3720 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3721 if (it == d->children_positions.end())
3724 // check for macros at the inclusion position
3725 return getMacro(name, it->second, global);
3729 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3731 pit_type const lastpit = it.lastpit();
3733 // look for macros in each paragraph
3734 while (it.pit() <= lastpit) {
3735 Paragraph & par = it.paragraph();
3737 // FIXME Can this be done with the new-style iterators?
3738 // iterate over the insets of the current paragraph
3739 for (auto const & insit : par.insetList()) {
3740 it.pos() = insit.pos;
3742 // is it a nested text inset?
3743 if (insit.inset->asInsetText()) {
3744 // Inset needs its own scope?
3745 InsetText const * itext = insit.inset->asInsetText();
3746 bool newScope = itext->isMacroScope();
3748 // scope which ends just behind the inset
3749 DocIterator insetScope = it;
3752 // collect macros in inset
3753 it.push_back(CursorSlice(*insit.inset));
3754 updateMacros(it, newScope ? insetScope : scope);
3759 if (insit.inset->asInsetTabular()) {
3760 CursorSlice slice(*insit.inset);
3761 size_t const numcells = slice.nargs();
3762 for (; slice.idx() < numcells; slice.forwardIdx()) {
3763 it.push_back(slice);
3764 updateMacros(it, scope);
3770 // is it an external file?
3771 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3772 // get buffer of external file
3773 InsetInclude const & incinset =
3774 static_cast<InsetInclude const &>(*insit.inset);
3776 Buffer * child = incinset.loadIfNeeded();
3781 // register its position, but only when it is
3782 // included first in the buffer
3783 if (children_positions.find(child) ==
3784 children_positions.end())
3785 children_positions[child] = it;
3787 // register child with its scope
3788 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3792 InsetMath * im = insit.inset->asInsetMath();
3793 if (doing_export && im) {
3794 InsetMathHull * hull = im->asHullInset();
3796 hull->recordLocation(it);
3799 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3803 InsetMathMacroTemplate & macroTemplate =
3804 *insit.inset->asInsetMath()->asMacroTemplate();
3805 MacroContext mc(owner_, it);
3806 macroTemplate.updateToContext(mc);
3809 bool valid = macroTemplate.validMacro();
3810 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3811 // then the BufferView's cursor will be invalid in
3812 // some cases which leads to crashes.
3817 // FIXME (Abdel), I don't understand why we pass 'it' here
3818 // instead of 'macroTemplate' defined above... is this correct?
3819 macros[macroTemplate.name()][it] =
3820 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3830 void Buffer::updateMacros() const
3835 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3837 // start with empty table
3839 d->children_positions.clear();
3840 d->position_to_children.clear();
3842 // Iterate over buffer, starting with first paragraph
3843 // The scope must be bigger than any lookup DocIterator
3844 // later. For the global lookup, lastpit+1 is used, hence
3845 // we use lastpit+2 here.
3846 DocIterator it = par_iterator_begin();
3847 DocIterator outerScope = it;
3848 outerScope.pit() = outerScope.lastpit() + 2;
3849 d->updateMacros(it, outerScope);
3853 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3855 InsetIterator it = inset_iterator_begin(inset());
3856 InsetIterator const end = inset_iterator_end(inset());
3857 for (; it != end; ++it) {
3858 if (it->lyxCode() == BRANCH_CODE) {
3859 InsetBranch & br = static_cast<InsetBranch &>(*it);
3860 docstring const name = br.branch();
3861 if (!from_master && !params().branchlist().find(name))
3862 result.push_back(name);
3863 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3864 result.push_back(name);
3867 if (it->lyxCode() == INCLUDE_CODE) {
3868 // get buffer of external file
3869 InsetInclude const & ins =
3870 static_cast<InsetInclude const &>(*it);
3871 Buffer * child = ins.loadIfNeeded();
3874 child->getUsedBranches(result, true);
3877 // remove duplicates
3882 void Buffer::updateMacroInstances(UpdateType utype) const
3884 LYXERR(Debug::MACROS, "updateMacroInstances for "
3885 << d->filename.onlyFileName());
3886 DocIterator it = doc_iterator_begin(this);
3888 DocIterator const end = doc_iterator_end(this);
3889 for (; it != end; it.forwardInset()) {
3890 // look for MathData cells in InsetMathNest insets
3891 InsetMath * minset = it.nextInset()->asInsetMath();
3895 // update macro in all cells of the InsetMathNest
3896 DocIterator::idx_type n = minset->nargs();
3897 MacroContext mc = MacroContext(this, it);
3898 for (DocIterator::idx_type i = 0; i < n; ++i) {
3899 MathData & data = minset->cell(i);
3900 data.updateMacros(nullptr, mc, utype, 0);
3906 void Buffer::listMacroNames(MacroNameSet & macros) const
3911 d->macro_lock = true;
3913 // loop over macro names
3914 for (auto const & nameit : d->macros)
3915 macros.insert(nameit.first);
3917 // loop over children
3918 for (auto const & p : d->children_positions) {
3919 Buffer * child = const_cast<Buffer *>(p.first);
3920 // The buffer might have been closed (see #10766).
3921 if (theBufferList().isLoaded(child))
3922 child->listMacroNames(macros);
3926 Buffer const * const pbuf = d->parent();
3928 pbuf->listMacroNames(macros);
3930 d->macro_lock = false;
3934 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3936 Buffer const * const pbuf = d->parent();
3941 pbuf->listMacroNames(names);
3944 for (auto const & mit : names) {
3946 MacroData const * data = pbuf->getMacro(mit, *this, false);
3948 macros.insert(data);
3950 // we cannot access the original InsetMathMacroTemplate anymore
3951 // here to calls validate method. So we do its work here manually.
3952 // FIXME: somehow make the template accessible here.
3953 if (data->optionals() > 0)
3954 features.require("xargs");
3960 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3963 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3965 RefCache::iterator it = d->ref_cache_.find(label);
3966 if (it != d->ref_cache_.end())
3969 static References const dummy_refs = References();
3970 it = d->ref_cache_.insert(
3971 make_pair(label, dummy_refs)).first;
3976 Buffer::References const & Buffer::references(docstring const & label) const
3978 return const_cast<Buffer *>(this)->getReferenceCache(label);
3982 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3984 References & refs = getReferenceCache(label);
3985 refs.push_back(make_pair(inset, it));
3989 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3993 linfo.label = label;
3995 linfo.active = active;
3996 masterBuffer()->d->label_cache_.push_back(linfo);
4000 InsetLabel const * Buffer::insetLabel(docstring const & label,
4001 bool const active) const
4003 for (auto const & rc : masterBuffer()->d->label_cache_) {
4004 if (rc.label == label && (rc.active || !active))
4011 bool Buffer::activeLabel(docstring const & label) const
4013 if (!insetLabel(label, true))
4020 void Buffer::clearReferenceCache() const
4023 d->ref_cache_.clear();
4024 d->label_cache_.clear();
4029 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
4031 //FIXME: This does not work for child documents yet.
4032 reloadBibInfoCache();
4034 // Check if the label 'from' appears more than once
4035 vector<docstring> labels;
4036 for (auto const & bibit : masterBibInfo())
4037 labels.push_back(bibit.first);
4039 if (count(labels.begin(), labels.end(), from) > 1)
4042 string const paramName = "key";
4043 UndoGroupHelper ugh(this);
4044 InsetIterator it = inset_iterator_begin(inset());
4046 if (it->lyxCode() != CITE_CODE)
4048 InsetCommand * inset = it->asInsetCommand();
4049 docstring const oldValue = inset->getParam(paramName);
4050 if (oldValue == from) {
4051 undo().recordUndo(CursorData(it));
4052 inset->setParam(paramName, to);
4057 // returns NULL if id-to-row conversion is unsupported
4058 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4059 pit_type par_begin, pit_type par_end,
4060 OutputWhat output, bool master) const
4062 unique_ptr<TexRow> texrow;
4063 OutputParams runparams(¶ms().encoding());
4064 runparams.nice = true;
4065 runparams.flavor = params().getOutputFlavor(format);
4066 runparams.linelen = lyxrc.plaintext_linelen;
4067 // No side effect of file copying and image conversion
4068 runparams.dryrun = true;
4070 // Some macros rely on font encoding
4071 runparams.main_fontenc = params().main_font_encoding();
4073 if (output == CurrentParagraph) {
4074 runparams.par_begin = par_begin;
4075 runparams.par_end = par_end;
4076 if (par_begin + 1 == par_end) {
4078 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4082 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4083 convert<docstring>(par_begin),
4084 convert<docstring>(par_end - 1))
4087 // output paragraphs
4088 if (runparams.flavor == OutputParams::LYX) {
4089 Paragraph const & par = text().paragraphs()[par_begin];
4091 depth_type dt = par.getDepth();
4092 par.write(ods, params(), dt);
4093 os << from_utf8(ods.str());
4094 } else if (runparams.flavor == OutputParams::HTML) {
4096 setMathFlavor(runparams);
4097 xhtmlParagraphs(text(), *this, xs, runparams);
4098 } else if (runparams.flavor == OutputParams::TEXT) {
4100 // FIXME Handles only one paragraph, unlike the others.
4101 // Probably should have some routine with a signature like them.
4102 writePlaintextParagraph(*this,
4103 text().paragraphs()[par_begin], os, runparams, dummy);
4104 } else if (runparams.flavor == OutputParams::DOCBOOK5) {
4106 docbookParagraphs(text(), *this, xs, runparams);
4108 // If we are previewing a paragraph, even if this is the
4109 // child of some other buffer, let's cut the link here,
4110 // so that no concurring settings from the master
4111 // (e.g. branch state) interfere (see #8101).
4113 d->ignore_parent = true;
4114 // We need to validate the Buffer params' features here
4115 // in order to know if we should output polyglossia
4116 // macros (instead of babel macros)
4117 LaTeXFeatures features(*this, params(), runparams);
4119 runparams.use_polyglossia = features.usePolyglossia();
4120 runparams.use_hyperref = features.isRequired("hyperref");
4121 // latex or literate
4124 ots.texrow().newlines(2);
4126 latexParagraphs(*this, text(), ots, runparams);
4127 texrow = ots.releaseTexRow();
4129 // Restore the parenthood
4131 d->ignore_parent = false;
4135 if (output == FullSource)
4136 os << _("Preview source code");
4137 else if (output == OnlyPreamble)
4138 os << _("Preview preamble");
4139 else if (output == OnlyBody)
4140 os << _("Preview body");
4142 if (runparams.flavor == OutputParams::LYX) {
4144 if (output == FullSource)
4146 else if (output == OnlyPreamble)
4147 params().writeFile(ods, this);
4148 else if (output == OnlyBody)
4150 os << from_utf8(ods.str());
4151 } else if (runparams.flavor == OutputParams::HTML) {
4152 writeLyXHTMLSource(os, runparams, output);
4153 } else if (runparams.flavor == OutputParams::TEXT) {
4154 if (output == OnlyPreamble) {
4155 os << "% "<< _("Plain text does not have a preamble.");
4157 writePlaintextFile(*this, os, runparams);
4158 } else if (runparams.flavor == OutputParams::DOCBOOK5) {
4159 writeDocBookSource(os, runparams, output);
4161 // latex or literate
4164 ots.texrow().newlines(2);
4166 runparams.is_child = true;
4168 writeLaTeXSource(ots, string(), runparams, output);
4169 texrow = ots.releaseTexRow();
4176 ErrorList & Buffer::errorList(string const & type) const
4178 return d->errorLists[type];
4182 void Buffer::updateTocItem(std::string const & type,
4183 DocIterator const & dit) const
4186 d->gui_->updateTocItem(type, dit);
4190 void Buffer::structureChanged() const
4193 d->gui_->structureChanged();
4197 void Buffer::errors(string const & err, bool from_master) const
4200 d->gui_->errors(err, from_master);
4204 void Buffer::message(docstring const & msg) const
4207 d->gui_->message(msg);
4211 void Buffer::setBusy(bool on) const
4214 d->gui_->setBusy(on);
4218 void Buffer::updateTitles() const
4221 d->wa_->updateTitles();
4225 void Buffer::resetAutosaveTimers() const
4228 d->gui_->resetAutosaveTimers();
4232 bool Buffer::hasGuiDelegate() const
4238 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4244 FileName Buffer::getEmergencyFileName() const
4246 return FileName(d->filename.absFileName() + ".emergency");
4250 FileName Buffer::getAutosaveFileName() const
4252 // if the document is unnamed try to save in the backup dir, else
4253 // in the default document path, and as a last try in the filePath,
4254 // which will most often be the temporary directory
4257 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4258 : lyxrc.backupdir_path;
4259 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4262 string const fname = "#" + d->filename.onlyFileName() + "#";
4264 return makeAbsPath(fname, fpath);
4268 void Buffer::removeAutosaveFile() const
4270 FileName const f = getAutosaveFileName();
4276 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4278 FileName const newauto = getAutosaveFileName();
4280 if (newauto != oldauto && oldauto.exists())
4281 if (!oldauto.moveTo(newauto))
4282 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4286 bool Buffer::autoSave() const
4288 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4289 if (buf->d->bak_clean || hasReadonlyFlag())
4292 message(_("Autosaving current document..."));
4293 buf->d->bak_clean = true;
4295 FileName const fname = getAutosaveFileName();
4296 LASSERT(d->cloned_buffer_, return false);
4298 // If this buffer is cloned, we assume that
4299 // we are running in a separate thread already.
4300 TempFile tempfile("lyxautoXXXXXX.lyx");
4301 tempfile.setAutoRemove(false);
4302 FileName const tmp_ret = tempfile.name();
4303 if (!tmp_ret.empty()) {
4305 // assume successful write of tmp_ret
4306 if (tmp_ret.moveTo(fname))
4309 // failed to write/rename tmp_ret so try writing direct
4310 return writeFile(fname);
4314 void Buffer::setExportStatus(bool e) const
4316 d->doing_export = e;
4317 ListOfBuffers clist = getDescendants();
4318 for (auto const & bit : clist)
4319 bit->d->doing_export = e;
4323 bool Buffer::isExporting() const
4325 return d->doing_export;
4329 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4333 return doExport(target, put_in_tempdir, result_file);
4336 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4337 string & result_file) const
4339 bool const update_unincluded =
4340 params().maintain_unincluded_children != BufferParams::CM_None
4341 && !params().getIncludedChildren().empty();
4343 // (1) export with all included children (omit \includeonly)
4344 if (update_unincluded) {
4345 ExportStatus const status =
4346 doExport(target, put_in_tempdir, true, result_file);
4347 if (status != ExportSuccess)
4350 // (2) export with included children only
4351 return doExport(target, put_in_tempdir, false, result_file);
4355 void Buffer::setMathFlavor(OutputParams & op) const
4357 switch (params().html_math_output) {
4358 case BufferParams::MathML:
4359 op.math_flavor = OutputParams::MathAsMathML;
4361 case BufferParams::HTML:
4362 op.math_flavor = OutputParams::MathAsHTML;
4364 case BufferParams::Images:
4365 op.math_flavor = OutputParams::MathAsImages;
4367 case BufferParams::LaTeX:
4368 op.math_flavor = OutputParams::MathAsLaTeX;
4374 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4375 bool includeall, string & result_file) const
4377 LYXERR(Debug::FILES, "target=" << target);
4378 OutputParams runparams(¶ms().encoding());
4379 string format = target;
4380 string dest_filename;
4381 size_t pos = target.find(' ');
4382 if (pos != string::npos) {
4383 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4384 format = target.substr(0, pos);
4385 if (format == "default")
4386 format = params().getDefaultOutputFormat();
4387 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4388 FileName(dest_filename).onlyPath().createPath();
4389 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4391 MarkAsExporting exporting(this);
4392 string backend_format;
4393 runparams.flavor = OutputParams::LATEX;
4394 runparams.linelen = lyxrc.plaintext_linelen;
4395 runparams.includeall = includeall;
4396 vector<string> backs = params().backends();
4397 Converters converters = theConverters();
4398 bool need_nice_file = false;
4399 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4400 // Get shortest path to format
4401 converters.buildGraph();
4402 Graph::EdgePath path;
4403 for (string const & sit : backs) {
4404 Graph::EdgePath p = converters.getPath(sit, format);
4405 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4406 backend_format = sit;
4411 if (!put_in_tempdir) {
4412 // Only show this alert if this is an export to a non-temporary
4413 // file (not for previewing).
4414 docstring s = bformat(_("No information for exporting the format %1$s."),
4415 translateIfPossible(theFormats().prettyName(format)));
4416 if (format == "pdf4")
4418 + bformat(_("Hint: use non-TeX fonts or set input encoding "
4419 " to '%1$s'"), from_utf8(encodings.fromLyXName("ascii")->guiName()));
4420 Alert::error(_("Couldn't export file"), s);
4422 return ExportNoPathToFormat;
4424 runparams.flavor = converters.getFlavor(path, this);
4425 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4426 for (auto const & edge : path)
4427 if (theConverters().get(edge).nice()) {
4428 need_nice_file = true;
4433 backend_format = format;
4434 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4435 // FIXME: Don't hardcode format names here, but use a flag
4436 if (backend_format == "pdflatex")
4437 runparams.flavor = OutputParams::PDFLATEX;
4438 else if (backend_format == "luatex")
4439 runparams.flavor = OutputParams::LUATEX;
4440 else if (backend_format == "dviluatex")
4441 runparams.flavor = OutputParams::DVILUATEX;
4442 else if (backend_format == "xetex")
4443 runparams.flavor = OutputParams::XETEX;
4446 string filename = latexName(false);
4447 filename = addName(temppath(), filename);
4448 filename = changeExtension(filename,
4449 theFormats().extension(backend_format));
4450 LYXERR(Debug::FILES, "filename=" << filename);
4452 // Plain text backend
4453 if (backend_format == "text") {
4454 runparams.flavor = OutputParams::TEXT;
4456 writePlaintextFile(*this, FileName(filename), runparams);
4458 catch (ConversionException const &) { return ExportCancel; }
4461 else if (backend_format == "xhtml") {
4462 runparams.flavor = OutputParams::HTML;
4463 setMathFlavor(runparams);
4464 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4465 return ExportKilled;
4466 } else if (backend_format == "lyx")
4467 writeFile(FileName(filename));
4469 else if (backend_format == "docbook5") {
4470 runparams.flavor = OutputParams::DOCBOOK5;
4471 runparams.nice = false;
4472 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4473 return ExportKilled;
4476 else if (backend_format == format || need_nice_file) {
4477 runparams.nice = true;
4478 ExportStatus const retval =
4479 makeLaTeXFile(FileName(filename), string(), runparams);
4480 if (retval == ExportKilled)
4481 return ExportKilled;
4482 if (d->cloned_buffer_)
4483 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4484 if (retval != ExportSuccess)
4486 } else if (!lyxrc.tex_allows_spaces
4487 && contains(filePath(), ' ')) {
4488 Alert::error(_("File name error"),
4489 bformat(_("The directory path to the document\n%1$s\n"
4490 "contains spaces, but your TeX installation does "
4491 "not allow them. You should save the file to a directory "
4492 "whose name does not contain spaces."), from_utf8(filePath())));
4493 return ExportTexPathHasSpaces;
4495 runparams.nice = false;
4496 ExportStatus const retval =
4497 makeLaTeXFile(FileName(filename), filePath(), runparams);
4498 if (retval == ExportKilled)
4499 return ExportKilled;
4500 if (d->cloned_buffer_)
4501 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4502 if (retval != ExportSuccess)
4506 string const error_type = (format == "program")
4507 ? "Build" : params().bufferFormat();
4508 ErrorList & error_list = d->errorLists[error_type];
4509 string const ext = theFormats().extension(format);
4510 FileName const tmp_result_file(changeExtension(filename, ext));
4511 Converters::RetVal const retval =
4512 converters.convert(this, FileName(filename), tmp_result_file,
4513 FileName(absFileName()), backend_format, format,
4514 error_list, Converters::none, includeall);
4515 if (retval == Converters::KILLED)
4516 return ExportCancel;
4517 bool success = (retval == Converters::SUCCESS);
4519 // Emit the signal to show the error list or copy it back to the
4520 // cloned Buffer so that it can be emitted afterwards.
4521 if (format != backend_format) {
4522 if (runparams.silent)
4524 else if (d->cloned_buffer_)
4525 d->cloned_buffer_->d->errorLists[error_type] =
4526 d->errorLists[error_type];
4529 // also to the children, in case of master-buffer-view
4530 ListOfBuffers clist = getDescendants();
4531 for (auto const & bit : clist) {
4532 if (runparams.silent)
4533 bit->d->errorLists[error_type].clear();
4534 else if (d->cloned_buffer_) {
4535 // Enable reverse search by copying back the
4536 // texrow object to the cloned buffer.
4537 // FIXME: this is not thread safe.
4538 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4539 bit->d->cloned_buffer_->d->errorLists[error_type] =
4540 bit->d->errorLists[error_type];
4542 bit->errors(error_type, true);
4546 if (d->cloned_buffer_) {
4547 // Enable reverse dvi or pdf to work by copying back the texrow
4548 // object to the cloned buffer.
4549 // FIXME: There is a possibility of concurrent access to texrow
4550 // here from the main GUI thread that should be securized.
4551 d->cloned_buffer_->d->texrow = d->texrow;
4552 string const err_type = params().bufferFormat();
4553 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4557 if (put_in_tempdir) {
4558 result_file = tmp_result_file.absFileName();
4559 return success ? ExportSuccess : ExportConverterError;
4562 if (dest_filename.empty())
4563 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4565 result_file = dest_filename;
4566 // We need to copy referenced files (e. g. included graphics
4567 // if format == "dvi") to the result dir.
4568 vector<ExportedFile> const extfiles =
4569 runparams.exportdata->externalFiles(format);
4570 string const dest = runparams.export_folder.empty() ?
4571 onlyPath(result_file) : runparams.export_folder;
4572 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4573 : force_overwrite == ALL_FILES;
4574 CopyStatus status = use_force ? FORCE : SUCCESS;
4576 for (ExportedFile const & exp : extfiles) {
4577 if (status == CANCEL) {
4578 message(_("Document export cancelled."));
4579 return ExportCancel;
4581 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4582 string fixedName = exp.exportName;
4583 if (!runparams.export_folder.empty()) {
4584 // Relative pathnames starting with ../ will be sanitized
4585 // if exporting to a different folder
4586 while (fixedName.substr(0, 3) == "../")
4587 fixedName = fixedName.substr(3, fixedName.length() - 3);
4589 FileName fixedFileName = makeAbsPath(fixedName, dest);
4590 fixedFileName.onlyPath().createPath();
4591 status = copyFile(fmt, exp.sourceName,
4593 exp.exportName, status == FORCE,
4594 runparams.export_folder.empty());
4598 if (tmp_result_file.exists()) {
4599 // Finally copy the main file
4600 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4601 : force_overwrite != NO_FILES;
4602 if (status == SUCCESS && use_force)
4604 status = copyFile(format, tmp_result_file,
4605 FileName(result_file), result_file,
4607 if (status == CANCEL) {
4608 message(_("Document export cancelled."));
4609 return ExportCancel;
4611 message(bformat(_("Document exported as %1$s "
4613 translateIfPossible(theFormats().prettyName(format)),
4614 makeDisplayPath(result_file)));
4617 // This must be a dummy converter like fax (bug 1888)
4618 message(bformat(_("Document exported as %1$s"),
4619 translateIfPossible(theFormats().prettyName(format))));
4622 return success ? ExportSuccess : ExportConverterError;
4626 Buffer::ExportStatus Buffer::preview(string const & format) const
4628 bool const update_unincluded =
4629 params().maintain_unincluded_children != BufferParams::CM_None
4630 && !params().getIncludedChildren().empty();
4631 return preview(format, update_unincluded);
4635 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4637 MarkAsExporting exporting(this);
4639 // (1) export with all included children (omit \includeonly)
4641 ExportStatus const status = doExport(format, true, true, result_file);
4642 if (status != ExportSuccess)
4645 // (2) export with included children only
4646 ExportStatus const status = doExport(format, true, false, result_file);
4647 FileName const previewFile(result_file);
4649 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4650 theimpl->preview_file_ = previewFile;
4651 theimpl->preview_format_ = format;
4652 theimpl->require_fresh_start_ = (status != ExportSuccess);
4654 if (status != ExportSuccess)
4657 if (previewFile.exists())
4658 return theFormats().view(*this, previewFile, format) ?
4659 PreviewSuccess : PreviewError;
4661 // Successful export but no output file?
4662 // Probably a bug in error detection.
4663 LATTEST(status != ExportSuccess);
4668 Buffer::ReadStatus Buffer::extractFromVC()
4670 bool const found = LyXVC::file_not_found_hook(d->filename);
4672 return ReadFileNotFound;
4673 if (!d->filename.isReadableFile())
4679 Buffer::ReadStatus Buffer::loadEmergency()
4681 FileName const emergencyFile = getEmergencyFileName();
4682 if (!emergencyFile.exists()
4683 || emergencyFile.lastModified() <= d->filename.lastModified())
4684 return ReadFileNotFound;
4686 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4687 docstring const text = bformat(_("An emergency save of the document "
4688 "%1$s exists.\n\nRecover emergency save?"), file);
4690 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4691 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4697 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4698 bool const success = (ret_llf == ReadSuccess);
4700 if (hasReadonlyFlag()) {
4701 Alert::warning(_("File is read-only"),
4702 bformat(_("An emergency file is successfully loaded, "
4703 "but the original file %1$s is marked read-only. "
4704 "Please make sure to save the document as a different "
4705 "file."), from_utf8(d->filename.absFileName())));
4708 lyxvc().file_found_hook(d->filename);
4709 str = _("Document was successfully recovered.");
4711 str = _("Document was NOT successfully recovered.");
4712 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4713 makeDisplayPath(emergencyFile.absFileName()));
4715 int const del_emerg =
4716 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4717 _("&Remove"), _("&Keep"));
4718 if (del_emerg == 0) {
4719 emergencyFile.removeFile();
4721 Alert::warning(_("Emergency file deleted"),
4722 _("Do not forget to save your file now!"), true);
4724 return success ? ReadSuccess : ReadEmergencyFailure;
4727 int const del_emerg =
4728 Alert::prompt(_("Delete emergency file?"),
4729 _("Remove emergency file now?"), 1, 1,
4730 _("&Remove"), _("&Keep"));
4732 emergencyFile.removeFile();
4736 string const ename = emergencyFile.absFileName();
4738 // Surely we can find one in 100 tries?
4739 for (int i = 1; i < 100; ++i) {
4740 newname.set(ename + to_string(i) + ".lyx");
4741 if (!newname.exists()) {
4747 // renameTo returns true on success. So inverting that
4748 // will give us true if we fail.
4749 noname = !emergencyFile.renameTo(newname);
4752 Alert::warning(_("Can't rename emergency file!"),
4753 _("LyX was unable to rename the emergency file. "
4754 "You should do so manually. Otherwise, you will be "
4755 "asked about it again the next time you try to load "
4756 "this file, and may over-write your own work."));
4758 Alert::warning(_("Emergency File Renames"),
4759 bformat(_("Emergency file renamed as:\n %1$s"),
4760 from_utf8(newname.onlyFileName())));
4763 return ReadOriginal;
4773 Buffer::ReadStatus Buffer::loadAutosave()
4775 // Now check if autosave file is newer.
4776 FileName const autosaveFile = getAutosaveFileName();
4777 if (!autosaveFile.exists()
4778 || autosaveFile.lastModified() <= d->filename.lastModified())
4779 return ReadFileNotFound;
4781 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4782 docstring const text = bformat(_("The backup of the document %1$s "
4783 "is newer.\n\nLoad the backup instead?"), file);
4784 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4785 _("&Load backup"), _("Load &original"), _("&Cancel"));
4790 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4791 // the file is not saved if we load the autosave file.
4792 if (ret_llf == ReadSuccess) {
4793 if (hasReadonlyFlag()) {
4794 Alert::warning(_("File is read-only"),
4795 bformat(_("A backup file is successfully loaded, "
4796 "but the original file %1$s is marked read-only. "
4797 "Please make sure to save the document as a "
4799 from_utf8(d->filename.absFileName())));
4802 lyxvc().file_found_hook(d->filename);
4805 return ReadAutosaveFailure;
4808 // Here we delete the autosave
4809 autosaveFile.removeFile();
4810 return ReadOriginal;
4818 Buffer::ReadStatus Buffer::loadLyXFile()
4820 if (!d->filename.isReadableFile()) {
4821 ReadStatus const ret_rvc = extractFromVC();
4822 if (ret_rvc != ReadSuccess)
4826 ReadStatus const ret_re = loadEmergency();
4827 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4830 ReadStatus const ret_ra = loadAutosave();
4831 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4834 return loadThisLyXFile(d->filename);
4838 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4840 return readFile(fn);
4844 void Buffer::Impl::traverseErrors(TeXErrors::Errors::const_iterator err, TeXErrors::Errors::const_iterator end, ErrorList & errorList) const
4846 for (; err != end; ++err) {
4847 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4848 int errorRow = err->error_in_line;
4849 Buffer const * buf = nullptr;
4850 Impl const * p = this;
4851 if (err->child_name.empty())
4852 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4854 // The error occurred in a child
4855 for (Buffer const * child : owner_->getDescendants()) {
4856 string const child_name =
4857 DocFileName(changeExtension(child->absFileName(), "tex")).
4859 if (err->child_name != child_name)
4861 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4862 if (!TexRow::isNone(start)) {
4863 buf = this->cloned_buffer_
4864 ? child->d->cloned_buffer_->d->owner_
4871 errorList.push_back(ErrorItem(err->error_desc, err->error_text,
4877 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4879 TeXErrors::Errors::const_iterator err = terr.begin();
4880 TeXErrors::Errors::const_iterator end = terr.end();
4882 d->traverseErrors(err, end, errorList);
4886 void Buffer::bufferRefs(TeXErrors const & terr, ErrorList & errorList) const
4888 TeXErrors::Errors::const_iterator err = terr.begin_ref();
4889 TeXErrors::Errors::const_iterator end = terr.end_ref();
4891 d->traverseErrors(err, end, errorList);
4895 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4897 LBUFERR(!text().paragraphs().empty());
4899 // Use the master text class also for child documents
4900 Buffer const * const master = masterBuffer();
4901 DocumentClass const & textclass = master->params().documentClass();
4903 docstring_list old_bibfiles;
4904 // Do this only if we are the top-level Buffer. We also need to account
4905 // for the case of a previewed child with ignored parent here.
4906 if (master == this && !d->ignore_parent) {
4907 textclass.counters().reset(from_ascii("bibitem"));
4908 reloadBibInfoCache();
4909 // we will re-read this cache as we go through, but we need
4910 // to know whether it's changed to know whether we need to
4911 // update the bibinfo cache.
4912 old_bibfiles = d->bibfiles_cache_;
4913 d->bibfiles_cache_.clear();
4916 // keep the buffers to be children in this set. If the call from the
4917 // master comes back we can see which of them were actually seen (i.e.
4918 // via an InsetInclude). The remaining ones in the set need still be updated.
4919 static std::set<Buffer const *> bufToUpdate;
4920 if (scope == UpdateMaster) {
4921 // If this is a child document start with the master
4922 if (master != this) {
4923 bufToUpdate.insert(this);
4924 master->updateBuffer(UpdateMaster, utype);
4925 // If the master buffer has no gui associated with it, then the TocModel is
4926 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4927 // (bug 5699). The same happens if the master buffer is open in a different
4928 // window. This test catches both possibilities.
4929 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4930 // There remains a problem here: If there is another child open in yet a third
4931 // window, that TOC is not updated. So some more general solution is needed at
4933 if (master->d->gui_ != d->gui_)
4936 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4937 if (bufToUpdate.find(this) == bufToUpdate.end())
4941 // start over the counters in the master
4942 textclass.counters().reset();
4945 // update will be done below for this buffer
4946 bufToUpdate.erase(this);
4948 // update all caches
4949 clearReferenceCache();
4952 Buffer & cbuf = const_cast<Buffer &>(*this);
4953 // if we are reloading, then we could have a dangling TOC,
4954 // in effect. so we need to go ahead and reset, even though
4955 // we will do so again when we rebuild the TOC later.
4956 cbuf.tocBackend().reset();
4959 ParIterator parit = cbuf.par_iterator_begin();
4960 if (scope == UpdateMaster)
4962 updateBuffer(parit, utype);
4964 // If this document has siblings, then update the TocBackend later. The
4965 // reason is to ensure that later siblings are up to date when e.g. the
4966 // broken or not status of references is computed. The update is called
4967 // in InsetInclude::addToToc.
4971 // if the bibfiles changed, the cache of bibinfo is invalid
4972 docstring_list new_bibfiles = d->bibfiles_cache_;
4973 // this is a trick to determine whether the two vectors have
4974 // the same elements.
4975 sort(new_bibfiles.begin(), new_bibfiles.end());
4976 sort(old_bibfiles.begin(), old_bibfiles.end());
4977 if (old_bibfiles != new_bibfiles) {
4978 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4979 invalidateBibinfoCache();
4980 reloadBibInfoCache();
4981 // We relied upon the bibinfo cache when recalculating labels. But that
4982 // cache was invalid, although we didn't find that out until now. So we
4983 // have to do it all again.
4984 // That said, the only thing we really need to do is update the citation
4985 // labels. Nothing else will have changed. So we could create a new
4986 // UpdateType that would signal that fact, if we needed to do so.
4987 parit = cbuf.par_iterator_begin();
4988 // we will be re-doing the counters and references and such.
4989 textclass.counters().reset();
4990 clearReferenceCache();
4991 // we should not need to do this again?
4993 updateBuffer(parit, utype);
4994 // this will already have been done by reloadBibInfoCache();
4995 // d->bibinfo_cache_valid_ = true;
4998 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4999 // this is also set to true on the other path, by reloadBibInfoCache.
5000 d->bibinfo_cache_valid_ = true;
5002 d->cite_labels_valid_ = true;
5005 cbuf.tocBackend().update(true, utype);
5006 if (scope == UpdateMaster)
5007 cbuf.structureChanged();
5011 static depth_type getDepth(DocIterator const & it)
5013 depth_type depth = 0;
5014 for (size_t i = 0 ; i < it.depth() ; ++i)
5015 if (!it[i].inset().inMathed())
5016 depth += it[i].paragraph().getDepth() + 1;
5017 // remove 1 since the outer inset does not count
5018 // we should have at least one non-math inset, so
5019 // depth should nevery be 0. but maybe it is worth
5020 // marking this, just in case.
5022 // coverity[INTEGER_OVERFLOW]
5026 static depth_type getItemDepth(ParIterator const & it)
5028 Paragraph const & par = *it;
5029 LabelType const labeltype = par.layout().labeltype;
5031 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5034 // this will hold the lowest depth encountered up to now.
5035 depth_type min_depth = getDepth(it);
5036 ParIterator prev_it = it;
5039 --prev_it.top().pit();
5041 // start of nested inset: go to outer par
5043 if (prev_it.empty()) {
5044 // start of document: nothing to do
5049 // We search for the first paragraph with same label
5050 // that is not more deeply nested.
5051 Paragraph & prev_par = *prev_it;
5052 depth_type const prev_depth = getDepth(prev_it);
5053 if (labeltype == prev_par.layout().labeltype) {
5054 if (prev_depth < min_depth)
5055 return prev_par.itemdepth + 1;
5056 if (prev_depth == min_depth)
5057 return prev_par.itemdepth;
5059 min_depth = min(min_depth, prev_depth);
5060 // small optimization: if we are at depth 0, we won't
5061 // find anything else
5062 if (prev_depth == 0)
5068 static bool needEnumCounterReset(ParIterator const & it)
5070 Paragraph const & par = *it;
5071 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5072 depth_type const cur_depth = par.getDepth();
5073 ParIterator prev_it = it;
5074 while (prev_it.pit()) {
5075 --prev_it.top().pit();
5076 Paragraph const & prev_par = *prev_it;
5077 if (prev_par.getDepth() <= cur_depth)
5078 return prev_par.layout().name() != par.layout().name();
5080 // start of nested inset: reset
5085 // set the label of a paragraph. This includes the counters.
5086 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5088 BufferParams const & bp = owner_->masterBuffer()->params();
5089 DocumentClass const & textclass = bp.documentClass();
5090 Paragraph & par = it.paragraph();
5091 Layout const & layout = par.layout();
5092 Counters & counters = textclass.counters();
5094 if (par.params().startOfAppendix()) {
5095 // We want to reset the counter corresponding to toplevel sectioning
5096 Layout const & lay = textclass.getTOCLayout();
5097 docstring const cnt = lay.counter;
5099 counters.reset(cnt);
5100 counters.appendix(true);
5102 par.params().appendix(counters.appendix());
5104 // Compute the item depth of the paragraph
5105 par.itemdepth = getItemDepth(it);
5107 if (layout.margintype == MARGIN_MANUAL) {
5108 if (par.params().labelWidthString().empty())
5109 par.params().labelWidthString(par.expandLabel(layout, bp));
5110 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5111 // we do not need to do anything here, since the empty case is
5112 // handled during export.
5114 par.params().labelWidthString(docstring());
5117 switch(layout.labeltype) {
5118 case LABEL_ITEMIZE: {
5119 // At some point of time we should do something more
5120 // clever here, like:
5121 // par.params().labelString(
5122 // bp.user_defined_bullet(par.itemdepth).getText());
5123 // for now, use a simple hardcoded label
5124 docstring itemlabel;
5125 switch (par.itemdepth) {
5128 itemlabel = char_type(0x2022);
5132 itemlabel = char_type(0x2013);
5135 // ∗ U+2217 ASTERISK OPERATOR
5136 itemlabel = char_type(0x2217);
5139 // · U+00B7 MIDDLE DOT
5140 itemlabel = char_type(0x00b7);
5143 par.params().labelString(itemlabel);
5147 case LABEL_ENUMERATE: {
5148 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5150 switch (par.itemdepth) {
5161 enumcounter += "iv";
5164 // not a valid enumdepth...
5168 if (needEnumCounterReset(it)) {
5169 // Increase the master counter?
5170 if (layout.stepmastercounter)
5171 counters.stepMaster(enumcounter, utype);
5172 // Maybe we have to reset the enumeration counter.
5173 if (!layout.resumecounter)
5174 counters.reset(enumcounter);
5176 counters.step(enumcounter, utype);
5178 string const & lang = par.getParLanguage(bp)->code();
5179 par.params().labelString(counters.theCounter(enumcounter, lang));
5184 case LABEL_SENSITIVE: {
5185 string const & type = counters.current_float();
5186 docstring full_label;
5188 full_label = owner_->B_("Senseless!!! ");
5190 docstring name = owner_->B_(textclass.floats().getType(type).name());
5191 if (counters.hasCounter(from_utf8(type))) {
5192 string const & lang = par.getParLanguage(bp)->code();
5193 counters.step(from_utf8(type), utype);
5194 full_label = bformat(from_ascii("%1$s %2$s:"),
5196 counters.theCounter(from_utf8(type), lang));
5198 full_label = bformat(from_ascii("%1$s #:"), name);
5200 par.params().labelString(full_label);
5204 case LABEL_NO_LABEL:
5205 par.params().labelString(docstring());
5209 case LABEL_CENTERED:
5210 case LABEL_STATIC: {
5211 docstring const & lcounter = layout.counter;
5212 if (!lcounter.empty()) {
5213 if (layout.toclevel <= bp.secnumdepth
5214 && (layout.latextype != LATEX_ENVIRONMENT
5215 || it.text()->isFirstInSequence(it.pit()))) {
5216 if (counters.hasCounter(lcounter))
5217 counters.step(lcounter, utype);
5218 par.params().labelString(par.expandLabel(layout, bp));
5220 par.params().labelString(docstring());
5222 par.params().labelString(par.expandLabel(layout, bp));
5228 par.params().labelString(par.expandLabel(layout, bp));
5233 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype, bool const deleted) const
5235 pushIncludedBuffer(this);
5236 // LASSERT: Is it safe to continue here, or should we just return?
5237 LASSERT(parit.pit() == 0, /**/);
5239 // Set the position of the text in the buffer to be able
5240 // to resolve macros in it.
5241 parit.text()->setMacrocontextPosition(parit);
5243 depth_type maxdepth = 0;
5244 pit_type const lastpit = parit.lastpit();
5245 bool changed = false;
5246 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5247 // reduce depth if necessary
5248 if (parit->params().depth() > maxdepth) {
5249 /** FIXME: this function is const, but
5250 * nevertheless it modifies the buffer. To be
5251 * cleaner, one should modify the buffer in
5252 * another function, which is actually
5253 * non-const. This would however be costly in
5254 * terms of code duplication.
5256 CursorData(parit).recordUndo();
5257 parit->params().depth(maxdepth);
5259 maxdepth = parit->getMaxDepthAfter();
5261 if (utype == OutputUpdate) {
5262 // track the active counters
5263 // we have to do this for the master buffer, since the local
5264 // buffer isn't tracking anything.
5265 masterBuffer()->params().documentClass().counters().
5266 setActiveLayout(parit->layout());
5269 // set the counter for this paragraph
5270 d->setLabel(parit, utype);
5273 for (auto const & insit : parit->insetList()) {
5274 parit.pos() = insit.pos;
5275 insit.inset->updateBuffer(parit, utype, deleted || parit->isDeleted(insit.pos));
5276 changed |= insit.inset->isChanged();
5279 // are there changes in this paragraph?
5280 changed |= parit->isChanged();
5283 // set change indicator for the inset (or the cell that the iterator
5284 // points to, if applicable).
5285 parit.text()->inset().isChanged(changed);
5286 popIncludedBuffer();
5290 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5291 WordLangTuple & word_lang, docstring_list & suggestions) const
5295 suggestions.clear();
5296 word_lang = WordLangTuple();
5297 bool const to_end = to.empty();
5298 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5299 // OK, we start from here.
5300 for (; from != end; from.forwardPos()) {
5301 // This skips all insets with spell check disabled.
5302 while (!from.allowSpellCheck()) {
5306 // If from is at the end of the document (which is possible
5307 // when "from" was changed above) LyX will crash later otherwise.
5308 if (from.atEnd() || (!to_end && from >= end))
5311 from.paragraph().spellCheck();
5312 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5313 if (SpellChecker::misspelled(res)) {
5317 // Do not increase progress when from == to, otherwise the word
5318 // count will be wrong.
5328 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5330 bool inword = false;
5335 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5336 if (!dit.inTexted()) {
5341 Paragraph const & par = dit.paragraph();
5342 pos_type const pos = dit.pos();
5344 // Copied and adapted from isWordSeparator() in Paragraph
5345 if (pos == dit.lastpos()) {
5348 Inset const * ins = par.getInset(pos);
5349 if (ins && skipNoOutput && !ins->producesOutput()) {
5352 // stop if end of range was skipped
5353 if (!to.atEnd() && dit >= to)
5356 } else if (!par.isDeleted(pos)) {
5357 if (par.isWordSeparator(pos))
5363 if (ins && ins->isLetter()) {
5364 odocstringstream os;
5366 char_count_ += os.str().length();
5368 else if (ins && ins->isSpace())
5371 char_type const c = par.getChar(pos);
5372 if (isPrintableNonspace(c))
5374 else if (isSpace(c))
5384 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5386 d->updateStatistics(from, to, skipNoOutput);
5390 int Buffer::wordCount() const
5392 return d->wordCount();
5396 int Buffer::charCount(bool with_blanks) const
5398 return d->charCount(with_blanks);
5402 bool Buffer::areChangesPresent() const
5404 return inset().isChanged();
5408 Buffer::ReadStatus Buffer::reload()
5411 // c.f. bug https://www.lyx.org/trac/ticket/6587
5412 removeAutosaveFile();
5413 // e.g., read-only status could have changed due to version control
5414 d->filename.refresh();
5415 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5417 // clear parent. this will get reset if need be.
5418 d->setParent(nullptr);
5419 ReadStatus const status = loadLyXFile();
5420 if (status == ReadSuccess) {
5425 message(bformat(_("Document %1$s reloaded."), disp_fn));
5428 message(bformat(_("Could not reload document %1$s."), disp_fn));
5438 bool Buffer::saveAs(FileName const & fn)
5440 FileName const old_name = fileName();
5441 FileName const old_auto = getAutosaveFileName();
5442 bool const old_unnamed = isUnnamed();
5443 bool success = true;
5444 d->old_position = filePath();
5451 // bring the autosave file with us, just in case.
5452 moveAutosaveFile(old_auto);
5453 // validate version control data and
5454 // correct buffer title
5455 lyxvc().file_found_hook(fileName());
5457 // the file has now been saved to the new location.
5458 // we need to check that the locations of child buffers
5460 checkChildBuffers();
5461 checkMasterBuffer();
5464 // reset the old filename and unnamed state
5465 setFileName(old_name);
5466 setUnnamed(old_unnamed);
5470 d->old_position.clear();
5475 void Buffer::checkChildBuffers()
5477 for (auto const & bit : d->children_positions) {
5478 DocIterator dit = bit.second;
5479 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5480 if (!cbuf || !theBufferList().isLoaded(cbuf))
5482 Inset * inset = dit.nextInset();
5483 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5484 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5485 docstring const & incfile = inset_inc->getParam("filename");
5486 string oldloc = cbuf->absFileName();
5487 string newloc = makeAbsPath(to_utf8(incfile),
5488 onlyPath(absFileName())).absFileName();
5489 if (oldloc == newloc)
5491 // the location of the child file is incorrect.
5492 cbuf->setParent(nullptr);
5493 inset_inc->setChildBuffer(nullptr);
5495 // invalidate cache of children
5496 d->children_positions.clear();
5497 d->position_to_children.clear();
5501 // If a child has been saved under a different name/path, it might have been
5502 // orphaned. Therefore the master needs to be reset (bug 8161).
5503 void Buffer::checkMasterBuffer()
5505 Buffer const * const master = masterBuffer();
5509 // necessary to re-register the child (bug 5873)
5510 // FIXME: clean up updateMacros (here, only
5511 // child registering is needed).
5512 master->updateMacros();
5513 // (re)set master as master buffer, but only
5514 // if we are a real child
5515 if (master->isChild(this))
5522 string Buffer::includedFilePath(string const & name, string const & ext) const
5524 if (d->old_position.empty() ||
5525 equivalent(FileName(d->old_position), FileName(filePath())))
5528 bool isabsolute = FileName::isAbsolute(name);
5529 // both old_position and filePath() end with a path separator
5530 string absname = isabsolute ? name : d->old_position + name;
5532 // if old_position is set to origin, we need to do the equivalent of
5533 // getReferencedFileName() (see readDocument())
5534 if (!isabsolute && d->old_position == params().origin) {
5535 FileName const test(addExtension(filePath() + name, ext));
5537 absname = filePath() + name;
5540 if (!FileName(addExtension(absname, ext)).exists())
5544 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5546 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5547 from_utf8(filePath())));
5551 void Buffer::Impl::refreshFileMonitor()
5553 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5554 file_monitor_->refresh();
5558 // The previous file monitor is invalid
5559 // This also destroys the previous file monitor and all its connections
5560 file_monitor_ = FileSystemWatcher::monitor(filename);
5561 // file_monitor_ will be destroyed with *this, so it is not going to call a
5562 // destroyed object method.
5563 file_monitor_->connect([this](bool exists) {
5564 fileExternallyModified(exists);
5569 void Buffer::Impl::fileExternallyModified(bool const exists)
5571 // ignore notifications after our own saving operations
5572 if (checksum_ == filename.checksum()) {
5573 LYXERR(Debug::FILES, "External modification but "
5574 "checksum unchanged: " << filename);
5577 // If the file has been deleted, only mark the file as dirty since it is
5578 // pointless to prompt for reloading. If later a file is moved into this
5579 // location, then the externally modified warning will appear then.
5581 externally_modified_ = true;
5582 // Update external modification notification.
5583 // Dirty buffers must be visible at all times.
5584 if (wa_ && wa_->unhide(owner_))
5585 wa_->updateTitles();
5587 // Unable to unhide the buffer (e.g. no GUI or not current View)
5592 bool Buffer::notifiesExternalModification() const
5594 return d->externally_modified_;
5598 void Buffer::clearExternalModification() const
5600 d->externally_modified_ = false;
5602 d->wa_->updateTitles();
5606 void Buffer::pushIncludedBuffer(Buffer const * buf) const
5608 masterBuffer()->d->include_list_.push_back(buf);
5609 if (lyxerr.debugging(Debug::FILES)) {
5610 LYXERR0("Pushed. Stack now:");
5611 if (masterBuffer()->d->include_list_.empty())
5614 for (auto const & b : masterBuffer()->d->include_list_)
5615 LYXERR0(b->fileName());
5620 void Buffer::popIncludedBuffer() const
5622 masterBuffer()->d->include_list_.pop_back();
5623 if (lyxerr.debugging(Debug::FILES)) {
5624 LYXERR0("Popped. Stack now:");
5625 if (masterBuffer()->d->include_list_.empty())
5628 for (auto const & b : masterBuffer()->d->include_list_)
5629 LYXERR0(b->fileName());
5634 bool Buffer::isBufferIncluded(Buffer const * buf) const
5638 if (lyxerr.debugging(Debug::FILES)) {
5639 LYXERR0("Checking for " << buf->fileName() << ". Stack now:");
5640 if (masterBuffer()->d->include_list_.empty())
5643 for (auto const & b : masterBuffer()->d->include_list_)
5644 LYXERR0(b->fileName());
5646 list<Buffer const *> const & blist = masterBuffer()->d->include_list_;
5647 return find(blist.begin(), blist.end(), buf) != blist.end();
5651 void Buffer::clearIncludeList() const
5653 LYXERR(Debug::FILES, "Clearing include list for " << fileName());
5654 d->include_list_.clear();