3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
59 #include "SpellChecker.h"
61 #include "texstream.h"
64 #include "TextClass.h"
65 #include "TocBackend.h"
67 #include "VCBackend.h"
69 #include "WordLangTuple.h"
72 #include "insets/InsetBibtex.h"
73 #include "insets/InsetBranch.h"
74 #include "insets/InsetInclude.h"
75 #include "insets/InsetTabular.h"
76 #include "insets/InsetText.h"
78 #include "mathed/InsetMathHull.h"
79 #include "mathed/MacroTable.h"
80 #include "mathed/InsetMathMacroTemplate.h"
81 #include "mathed/MathSupport.h"
83 #include "graphics/GraphicsCache.h"
84 #include "graphics/PreviewLoader.h"
86 #include "frontends/Application.h"
87 #include "frontends/alert.h"
88 #include "frontends/Delegates.h"
89 #include "frontends/WorkAreaManager.h"
91 #include "support/lassert.h"
92 #include "support/convert.h"
93 #include "support/debug.h"
94 #include "support/docstring_list.h"
95 #include "support/ExceptionMessage.h"
96 #include "support/FileMonitor.h"
97 #include "support/FileName.h"
98 #include "support/FileNameList.h"
99 #include "support/filetools.h"
100 #include "support/ForkedCalls.h"
101 #include "support/gettext.h"
102 #include "support/gzstream.h"
103 #include "support/lstrings.h"
104 #include "support/lyxalgo.h"
105 #include "support/mutex.h"
106 #include "support/os.h"
107 #include "support/Package.h"
108 #include "support/PathChanger.h"
109 #include "support/Systemcall.h"
110 #include "support/TempFile.h"
111 #include "support/textutils.h"
112 #include "support/types.h"
114 #include "support/bind.h"
126 using namespace lyx::support;
127 using namespace lyx::graphics;
131 namespace Alert = frontend::Alert;
132 namespace os = support::os;
136 int const LYX_FORMAT = LYX_FORMAT_LYX;
138 typedef map<string, bool> DepClean;
140 // Information about labels and their associated refs
145 InsetLabel const * inset;
146 /// associated references cache
147 Buffer::References references;
148 /// whether this label is active (i.e., not deleted)
152 typedef vector<LabelInfo> LabelCache;
154 typedef map<docstring, Buffer::References> RefCache;
156 // A storehouse for the cloned buffers.
157 typedef list<CloneList_ptr> CloneStore;
158 CloneStore cloned_buffers;
167 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
171 delete preview_loader_;
179 /// search for macro in local (buffer) table or in children
180 MacroData const * getBufferMacro(docstring const & name,
181 DocIterator const & pos) const;
183 /// Update macro table starting with position of it \param it in some
185 void updateMacros(DocIterator & it, DocIterator & scope);
187 void setLabel(ParIterator & it, UpdateType utype) const;
189 /** If we have branches that use the file suffix
190 feature, return the file name with suffix appended.
192 FileName exportFileName() const;
199 mutable TexRow texrow;
201 /// need to regenerate .tex?
205 mutable bool lyx_clean;
207 /// is autosave needed?
208 mutable bool bak_clean;
210 /// is this an unnamed file (New...)?
213 /// is this an internal bufffer?
214 bool internal_buffer;
219 /// name of the file the buffer is associated with.
222 /** Set to true only when the file is fully loaded.
223 * Used to prevent the premature generation of previews
224 * and by the citation inset.
226 bool file_fully_loaded;
228 /// original format of loaded file
231 /// if the file was originally loaded from an older format, do
232 /// we need to back it up still?
233 bool need_format_backup;
235 /// Ignore the parent (e.g. when exporting a child standalone)?
239 mutable TocBackend toc_backend;
244 ScopeMacro(DocIterator const & s, MacroData const & m)
245 : scope(s), macro(m) {}
249 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
250 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
251 /// map from the macro name to the position map,
252 /// which maps the macro definition position to the scope and the MacroData.
253 NamePositionScopeMacroMap macros;
254 /// This seem to change the way Buffer::getMacro() works
255 mutable bool macro_lock;
257 /// positions of child buffers in the buffer
258 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
260 ScopeBuffer() : buffer(nullptr) {}
261 ScopeBuffer(DocIterator const & s, Buffer const * b)
262 : scope(s), buffer(b) {}
264 Buffer const * buffer;
266 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
267 /// position of children buffers in this buffer
268 BufferPositionMap children_positions;
269 /// map from children inclusion positions to their scope and their buffer
270 PositionScopeBufferMap position_to_children;
272 /// Contains the old buffer filePath() while saving-as, or the
273 /// directory where the document was last saved while loading.
276 /** Keeps track of the path of local layout files.
277 * If possible, it is always relative to the buffer path.
278 * Empty for layouts in system or user directory.
280 string layout_position;
282 /// Container for all sort of Buffer dependant errors.
283 map<string, ErrorList> errorLists;
285 /// checksum used to test if the file has been externally modified. Used to
286 /// double check whether the file had been externally modified when saving.
287 unsigned long checksum_;
290 frontend::WorkAreaManager * wa_;
292 frontend::GuiBufferDelegate * gui_;
297 /// A cache for the bibfiles (including bibfiles of loaded child
298 /// documents), needed for appropriate update of natbib labels.
299 mutable docstring_list bibfiles_cache_;
301 // FIXME The caching mechanism could be improved. At present, we have a
302 // cache for each Buffer, that caches all the bibliography info for that
303 // Buffer. A more efficient solution would be to have a global cache per
304 // file, and then to construct the Buffer's bibinfo from that.
305 /// A cache for bibliography info
306 mutable BiblioInfo bibinfo_;
307 /// whether the bibinfo cache is valid
308 mutable bool bibinfo_cache_valid_;
309 /// Cache of timestamps of .bib files
310 map<FileName, time_t> bibfile_status_;
311 /// Indicates whether the bibinfo has changed since the last time
312 /// we ran updateBuffer(), i.e., whether citation labels may need
314 mutable bool cite_labels_valid_;
315 /// Do we have a bibliography environment?
316 mutable bool have_bibitems_;
318 /// These two hold the file name and format, written to by
319 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
320 FileName preview_file_;
321 string preview_format_;
322 /// If there was an error when previewing, on the next preview we do
323 /// a fresh compile (e.g. in case the user installed a package that
325 bool require_fresh_start_;
327 /// Cache the references associated to a label and their positions
329 mutable RefCache ref_cache_;
330 /// Cache the label insets and their activity status.
331 mutable LabelCache label_cache_;
333 /// our Text that should be wrapped in an InsetText
337 PreviewLoader * preview_loader_;
339 /// This is here to force the test to be done whenever parent_buffer
341 Buffer const * parent() const
343 // ignore_parent temporarily "orphans" a buffer
344 // (e.g. if a child is compiled standalone)
347 // if parent_buffer is not loaded, then it has been unloaded,
348 // which means that parent_buffer is an invalid pointer. So we
349 // set it to null in that case.
350 // however, the BufferList doesn't know about cloned buffers, so
351 // they will always be regarded as unloaded. in that case, we hope
353 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
354 parent_buffer = nullptr;
355 return parent_buffer;
359 void setParent(Buffer const * pb)
361 if (parent_buffer == pb)
364 if (!cloned_buffer_ && parent_buffer && pb)
365 LYXERR0("Warning: a buffer should not have two parents!");
367 if (!cloned_buffer_ && parent_buffer)
368 parent_buffer->invalidateBibinfoCache();
371 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
372 /// This one is useful for preview detached in a thread.
373 Buffer const * cloned_buffer_;
375 CloneList_ptr clone_list_;
376 /// are we in the process of exporting this buffer?
377 mutable bool doing_export;
379 /// compute statistics
380 /// \p from initial position
381 /// \p to points to the end position
382 void updateStatistics(DocIterator & from, DocIterator & to,
383 bool skipNoOutput = true);
384 /// statistics accessor functions
385 int wordCount() const
389 int charCount(bool with_blanks) const
392 + (with_blanks ? blank_count_ : 0);
395 // Make sure the file monitor monitors the good file.
396 void refreshFileMonitor();
398 /// Notify or clear of external modification
399 void fileExternallyModified(bool exists);
401 /// has been externally modified? Can be reset by the user.
402 mutable bool externally_modified_;
404 ///Binding LaTeX lines with buffer positions.
405 //Common routine for LaTeX and Reference errors listing.
406 void traverseErrors(TeXErrors::Errors::const_iterator err,
407 TeXErrors::Errors::const_iterator end,
408 ErrorList & errorList) const;
411 /// So we can force access via the accessors.
412 mutable Buffer const * parent_buffer;
418 FileMonitorPtr file_monitor_;
422 /// Creates the per buffer temporary directory
423 static FileName createBufferTmpDir()
425 // FIXME This would be the ideal application for a TempDir class (like
426 // TempFile but for directories)
431 Mutex::Locker locker(&mutex);
432 counter = convert<string>(count++);
434 // We are in our own directory. Why bother to mangle name?
435 // In fact I wrote this code to circumvent a problematic behaviour
436 // (bug?) of EMX mkstemp().
437 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
440 if (!tmpfl.createDirectory(0777)) {
441 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
442 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
443 from_utf8(tmpfl.absFileName())));
449 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
450 Buffer const * cloned_buffer)
451 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
452 internal_buffer(false), read_only(readonly_), filename(file),
453 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
454 ignore_parent(false), toc_backend(owner), macro_lock(false),
455 checksum_(0), wa_(nullptr), gui_(nullptr), undo_(*owner), bibinfo_cache_valid_(false),
456 cite_labels_valid_(false), have_bibitems_(false), require_fresh_start_(false),
457 inset(nullptr), preview_loader_(nullptr), cloned_buffer_(cloned_buffer),
458 clone_list_(nullptr), doing_export(false),
459 externally_modified_(false), parent_buffer(nullptr),
460 word_count_(0), char_count_(0), blank_count_(0)
462 refreshFileMonitor();
463 if (!cloned_buffer_) {
464 temppath = createBufferTmpDir();
465 lyxvc.setBuffer(owner_);
466 Language const * inplang = theApp() ?
467 languages.getFromCode(theApp()->inputLanguageCode())
470 params.language = inplang;
472 wa_ = new frontend::WorkAreaManager;
475 temppath = cloned_buffer_->d->temppath;
476 file_fully_loaded = true;
477 params = cloned_buffer_->d->params;
478 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
479 bibinfo_ = cloned_buffer_->d->bibinfo_;
480 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
481 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
482 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
483 have_bibitems_ = cloned_buffer_->d->have_bibitems_;
484 unnamed = cloned_buffer_->d->unnamed;
485 internal_buffer = cloned_buffer_->d->internal_buffer;
486 layout_position = cloned_buffer_->d->layout_position;
487 preview_file_ = cloned_buffer_->d->preview_file_;
488 preview_format_ = cloned_buffer_->d->preview_format_;
489 require_fresh_start_ = cloned_buffer_->d->require_fresh_start_;
493 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
494 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
496 LYXERR(Debug::INFO, "Buffer::Buffer()");
498 d->inset = new InsetText(*cloned_buffer->d->inset);
499 d->inset->setBuffer(*this);
500 // FIXME: optimize this loop somewhat, maybe by creating a new
501 // general recursive Inset::setId().
502 DocIterator it = doc_iterator_begin(this);
503 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
504 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
505 it.paragraph().setId(cloned_it.paragraph().id());
507 d->inset = new InsetText(this);
508 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
514 LYXERR(Debug::INFO, "Buffer::~Buffer()");
515 // here the buffer should take care that it is
516 // saved properly, before it goes into the void.
518 // GuiView already destroyed
522 // No need to do additional cleanups for internal buffer.
528 // this is in case of recursive includes: we won't try to delete
529 // ourselves as a child.
530 d->clone_list_->erase(this);
531 // loop over children
532 for (auto const & p : d->children_positions) {
533 Buffer * child = const_cast<Buffer *>(p.first);
534 if (d->clone_list_->erase(child))
537 // if we're the master buffer, then we should get rid of the list
540 // If this is not empty, we have leaked something. Worse, one of the
541 // children still has a reference to this list. But we will try to
542 // continue, rather than shut down.
543 LATTEST(d->clone_list_->empty());
544 // The clone list itself is empty, but it's still referenced in our list
545 // of clones. So let's find it and remove it.
546 CloneStore::iterator it =
547 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
548 if (it == cloned_buffers.end()) {
549 // We will leak in this case, but it is safe to continue.
552 cloned_buffers.erase(it);
554 // FIXME Do we really need to do this right before we delete d?
555 // clear references to children in macro tables
556 d->children_positions.clear();
557 d->position_to_children.clear();
559 // loop over children
560 for (auto const & p : d->children_positions) {
561 Buffer * child = const_cast<Buffer *>(p.first);
562 if (theBufferList().isLoaded(child)) {
563 if (theBufferList().isOthersChild(this, child))
564 child->setParent(nullptr);
566 theBufferList().release(child);
571 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
573 msg += emergencyWrite();
575 msg += " " + _("Save failed! Document is lost.");
577 Alert::warning(_("Attempting to close changed document!"), msg);
580 // FIXME Do we really need to do this right before we delete d?
581 // clear references to children in macro tables
582 d->children_positions.clear();
583 d->position_to_children.clear();
585 if (!d->temppath.destroyDirectory()) {
586 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
587 from_utf8(d->temppath.absFileName())));
596 Buffer * Buffer::cloneWithChildren() const
599 cloned_buffers.emplace_back(new CloneList);
600 CloneList_ptr clones = cloned_buffers.back();
602 cloneWithChildren(bufmap, clones);
604 // make sure we got cloned
605 BufferMap::const_iterator bit = bufmap.find(this);
606 LASSERT(bit != bufmap.end(), return nullptr);
607 Buffer * cloned_buffer = bit->second;
609 return cloned_buffer;
613 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList_ptr clones) const
615 // have we already been cloned?
616 if (bufmap.find(this) != bufmap.end())
619 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
621 // The clone needs its own DocumentClass, since running updateBuffer() will
622 // modify it, and we would otherwise be sharing it with the original Buffer.
623 buffer_clone->params().makeDocumentClass(true);
625 cap::switchBetweenClasses(
626 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
627 static_cast<InsetText &>(buffer_clone->inset()), el);
629 bufmap[this] = buffer_clone;
630 clones->insert(buffer_clone);
631 buffer_clone->d->clone_list_ = clones;
632 buffer_clone->d->macro_lock = true;
633 buffer_clone->d->children_positions.clear();
635 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
636 // math macro caches need to be rethought and simplified.
637 // I am not sure wether we should handle Buffer cloning here or in BufferList.
638 // Right now BufferList knows nothing about buffer clones.
639 for (auto const & p : d->position_to_children) {
640 DocIterator dit = p.first.clone(buffer_clone);
641 dit.setBuffer(buffer_clone);
642 Buffer * child = const_cast<Buffer *>(p.second.buffer);
644 child->cloneWithChildren(bufmap, clones);
645 BufferMap::iterator const bit = bufmap.find(child);
646 LASSERT(bit != bufmap.end(), continue);
647 Buffer * child_clone = bit->second;
649 Inset * inset = dit.nextInset();
650 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
651 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
652 inset_inc->setChildBuffer(child_clone);
653 child_clone->d->setParent(buffer_clone);
654 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
655 buffer_clone->setChild(dit, child_clone);
657 buffer_clone->d->macro_lock = false;
662 Buffer * Buffer::cloneBufferOnly() const {
663 cloned_buffers.emplace_back(new CloneList);
664 CloneList_ptr clones = cloned_buffers.back();
665 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
667 // The clone needs its own DocumentClass, since running updateBuffer() will
668 // modify it, and we would otherwise be sharing it with the original Buffer.
669 buffer_clone->params().makeDocumentClass(true);
671 cap::switchBetweenClasses(
672 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
673 static_cast<InsetText &>(buffer_clone->inset()), el);
675 clones->insert(buffer_clone);
676 buffer_clone->d->clone_list_ = clones;
678 // we won't be cloning the children
679 buffer_clone->d->children_positions.clear();
684 bool Buffer::isClone() const
686 return d->cloned_buffer_;
690 void Buffer::changed(bool update_metrics) const
693 d->wa_->redrawAll(update_metrics);
697 frontend::WorkAreaManager & Buffer::workAreaManager() const
704 Text & Buffer::text() const
706 return d->inset->text();
710 Inset & Buffer::inset() const
716 BufferParams & Buffer::params()
722 BufferParams const & Buffer::params() const
728 BufferParams const & Buffer::masterParams() const
730 if (masterBuffer() == this)
733 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
734 // Copy child authors to the params. We need those pointers.
735 for (Author const & a : params().authors())
736 mparams.authors().record(a);
741 double Buffer::fontScalingFactor() const
743 return isExporting() ? 75.0 * params().html_math_img_scale
744 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
748 ParagraphList & Buffer::paragraphs()
750 return text().paragraphs();
754 ParagraphList const & Buffer::paragraphs() const
756 return text().paragraphs();
760 LyXVC & Buffer::lyxvc()
766 LyXVC const & Buffer::lyxvc() const
772 string const Buffer::temppath() const
774 return d->temppath.absFileName();
778 TexRow & Buffer::texrow()
784 TexRow const & Buffer::texrow() const
790 TocBackend & Buffer::tocBackend() const
792 return d->toc_backend;
796 Undo & Buffer::undo()
802 void Buffer::setChild(DocIterator const & dit, Buffer * child)
804 d->children_positions[child] = dit;
808 string Buffer::latexName(bool const no_path) const
810 FileName latex_name =
811 makeLatexName(d->exportFileName());
812 return no_path ? latex_name.onlyFileName()
813 : latex_name.absFileName();
817 FileName Buffer::Impl::exportFileName() const
819 docstring const branch_suffix =
820 params.branchlist().getFileNameSuffix();
821 if (branch_suffix.empty())
824 string const name = addExtension(filename.onlyFileNameWithoutExt()
825 + to_utf8(branch_suffix), filename.extension());
826 FileName res(filename.onlyPath().absFileName() + "/" + name);
832 string Buffer::logName(LogType * type) const
834 string const filename = latexName(false);
836 if (filename.empty()) {
842 string const path = temppath();
844 FileName const fname(addName(temppath(),
845 onlyFileName(changeExtension(filename,
848 // FIXME: how do we know this is the name of the build log?
849 FileName const bname(
850 addName(path, onlyFileName(
851 changeExtension(filename,
852 theFormats().extension(params().bufferFormat()) + ".out"))));
854 // Also consider the master buffer log file
855 FileName masterfname = fname;
856 LogType mtype = latexlog;
857 if (masterBuffer() != this) {
858 string const mlogfile = masterBuffer()->logName(&mtype);
859 masterfname = FileName(mlogfile);
862 // If no Latex log or Build log is newer, show Build log
863 if (bname.exists() &&
864 ((!fname.exists() && !masterfname.exists())
865 || (fname.lastModified() < bname.lastModified()
866 && masterfname.lastModified() < bname.lastModified()))) {
867 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
870 return bname.absFileName();
871 // If we have a newer master file log or only a master log, show this
872 } else if (fname != masterfname
873 && (!fname.exists() && (masterfname.exists()
874 || fname.lastModified() < masterfname.lastModified()))) {
875 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
878 return masterfname.absFileName();
880 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
883 return fname.absFileName();
887 void Buffer::setReadonly(bool const flag)
889 if (d->read_only != flag) {
896 void Buffer::setFileName(FileName const & fname)
898 bool const changed = fname != d->filename;
900 d->refreshFileMonitor();
902 lyxvc().file_found_hook(fname);
903 setReadonly(d->filename.isReadOnly());
909 int Buffer::readHeader(Lexer & lex)
911 int unknown_tokens = 0;
913 int begin_header_line = -1;
915 // Initialize parameters that may be/go lacking in header:
916 params().branchlist().clear();
917 params().preamble.erase();
918 params().options.erase();
919 params().master.erase();
920 params().float_placement.erase();
921 params().float_alignment.erase();
922 params().paperwidth.erase();
923 params().paperheight.erase();
924 params().leftmargin.erase();
925 params().rightmargin.erase();
926 params().topmargin.erase();
927 params().bottommargin.erase();
928 params().headheight.erase();
929 params().headsep.erase();
930 params().footskip.erase();
931 params().columnsep.erase();
932 params().font_roman_opts.erase();
933 params().font_sans_opts.erase();
934 params().font_typewriter_opts.erase();
935 params().fonts_cjk.erase();
936 params().listings_params.clear();
937 params().clearLayoutModules();
938 params().clearRemovedModules();
939 params().clearIncludedChildren();
940 params().pdfoptions().clear();
941 params().indiceslist().clear();
942 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
943 params().isbackgroundcolor = false;
944 params().fontcolor = RGBColor(0, 0, 0);
945 params().isfontcolor = false;
946 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
947 params().boxbgcolor = RGBColor(0xFF, 0, 0);
948 params().html_latex_start.clear();
949 params().html_latex_end.clear();
950 params().html_math_img_scale = 1.0;
951 params().output_sync_macro.erase();
952 params().setLocalLayout(docstring(), false);
953 params().setLocalLayout(docstring(), true);
954 params().biblio_opts.erase();
955 params().biblatex_bibstyle.erase();
956 params().biblatex_citestyle.erase();
957 params().multibib.erase();
958 params().lineno_opts.clear();
960 for (int i = 0; i < 4; ++i) {
961 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
962 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
965 ErrorList & errorList = d->errorLists["Parse"];
974 if (token == "\\end_header")
978 if (token == "\\begin_header") {
979 begin_header_line = line;
983 LYXERR(Debug::PARSER, "Handling document header token: `"
986 string const result =
987 params().readToken(lex, token, d->filename.onlyPath());
988 if (!result.empty()) {
989 if (token == "\\textclass") {
990 d->layout_position = result;
993 docstring const s = bformat(_("Unknown token: "
997 errorList.push_back(ErrorItem(_("Document header error"), s));
1001 if (begin_header_line) {
1002 docstring const s = _("\\begin_header is missing");
1003 errorList.push_back(ErrorItem(_("Document header error"), s));
1006 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
1008 params().makeDocumentClass();
1010 return unknown_tokens;
1015 // changed to be public and have one parameter
1016 // Returns true if "\end_document" is not read (Asger)
1017 bool Buffer::readDocument(Lexer & lex)
1019 ErrorList & errorList = d->errorLists["Parse"];
1022 // remove dummy empty par
1023 paragraphs().clear();
1025 if (!lex.checkFor("\\begin_document")) {
1026 docstring const s = _("\\begin_document is missing");
1027 errorList.push_back(ErrorItem(_("Document header error"), s));
1032 if (params().output_changes) {
1033 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1034 LaTeXFeatures::isAvailable("xcolor");
1037 Alert::warning(_("Changes not shown in LaTeX output"),
1038 _("Changes will not be highlighted in LaTeX output, "
1039 "because xcolor and ulem are not installed.\n"
1040 "Please install both packages or redefine "
1041 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1045 if (!parent() && !params().master.empty()) {
1046 FileName const master_file = makeAbsPath(params().master,
1047 onlyPath(absFileName()));
1048 if (isLyXFileName(master_file.absFileName())) {
1050 checkAndLoadLyXFile(master_file, true);
1052 // necessary e.g. after a reload
1053 // to re-register the child (bug 5873)
1054 // FIXME: clean up updateMacros (here, only
1055 // child registering is needed).
1056 master->updateMacros();
1057 // set master as master buffer, but only
1058 // if we are a real child
1059 if (master->isChild(this))
1061 // if the master is not fully loaded
1062 // it is probably just loading this
1063 // child. No warning needed then.
1064 else if (master->isFullyLoaded())
1065 LYXERR0("The master '"
1067 << "' assigned to this document ("
1069 << ") does not include "
1070 "this document. Ignoring the master assignment.");
1071 // If the master has just been created, un-hide it (#11162)
1072 if (!master->fileName().exists())
1073 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1074 master->absFileName()));
1079 // assure we have a default index
1080 params().indiceslist().addDefault(B_("Index"));
1083 if (FileName::isAbsolute(params().origin))
1084 d->old_position = params().origin;
1086 d->old_position = filePath();
1087 bool const res = text().read(lex, errorList, d->inset);
1088 d->old_position.clear();
1090 // inform parent buffer about local macros
1092 Buffer const * pbuf = parent();
1093 for (auto const & m : usermacros)
1094 pbuf->usermacros.insert(m);
1098 updateMacroInstances(InternalUpdate);
1103 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1105 Format const * fmt = theFormats().getFormat(format);
1108 // It is important to use the correct extension here, since some
1109 // converters create a wrong output file otherwise (e.g. html2latex)
1110 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1111 ofdocstream os(name.toFilesystemEncoding().c_str());
1112 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1113 bool const success = !(os << contents).fail();
1116 bool converted = false;
1118 params().compressed = false;
1120 // remove dummy empty par
1121 paragraphs().clear();
1123 converted = importFile(format, name, errorList);
1126 removeTempFile(name);
1131 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1133 if (!theConverters().isReachable(format, "lyx"))
1136 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1137 Converters::RetVal const retval =
1138 theConverters().convert(nullptr, name, lyx, name, format, "lyx", errorList);
1139 if (retval == Converters::SUCCESS) {
1140 bool const success = readFile(lyx) == ReadSuccess;
1141 removeTempFile(lyx);
1149 bool Buffer::readString(string const & s)
1151 params().compressed = false;
1154 istringstream is(s);
1156 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1157 FileName const fn = tempfile.name();
1160 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1162 if (success && file_format != LYX_FORMAT) {
1163 // We need to call lyx2lyx, so write the input to a file
1164 ofstream os(fn.toFilesystemEncoding().c_str());
1167 // lyxvc in readFile
1168 if (readFile(fn) != ReadSuccess)
1172 if (readDocument(lex))
1178 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1182 if (!lex.setFile(fname)) {
1183 Alert::error(_("File Not Found"),
1184 bformat(_("Unable to open file `%1$s'."),
1185 from_utf8(fn.absFileName())));
1186 return ReadFileNotFound;
1190 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1191 if (ret_plf != ReadSuccess)
1194 if (file_format != LYX_FORMAT) {
1196 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1197 if (ret_clf != ReadSuccess)
1199 ret_clf = readFile(tmpFile);
1200 if (ret_clf == ReadSuccess) {
1201 d->file_format = file_format;
1202 d->need_format_backup = true;
1207 // FIXME: InsetInfo needs to know whether the file is under VCS
1208 // during the parse process, so this has to be done before.
1209 lyxvc().file_found_hook(d->filename);
1211 if (readDocument(lex)) {
1212 Alert::error(_("Document format failure"),
1213 bformat(_("%1$s ended unexpectedly, which means"
1214 " that it is probably corrupted."),
1215 from_utf8(fn.absFileName())));
1216 return ReadDocumentFailure;
1219 d->file_fully_loaded = true;
1220 d->read_only = !d->filename.isWritable();
1221 params().compressed = theFormats().isZippedFile(d->filename);
1227 bool Buffer::isFullyLoaded() const
1229 return d->file_fully_loaded;
1233 void Buffer::setFullyLoaded(bool value)
1235 d->file_fully_loaded = value;
1239 bool Buffer::freshStartRequired() const
1241 return d->require_fresh_start_;
1244 void Buffer::requireFreshStart(bool const b) const
1246 d->require_fresh_start_ = b;
1250 PreviewLoader * Buffer::loader() const
1252 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1254 if (!d->preview_loader_)
1255 d->preview_loader_ = new PreviewLoader(*this);
1256 return d->preview_loader_;
1260 void Buffer::removePreviews() const
1262 delete d->preview_loader_;
1263 d->preview_loader_ = nullptr;
1267 void Buffer::updatePreviews() const
1269 PreviewLoader * ploader = loader();
1273 InsetIterator it = inset_iterator_begin(*d->inset);
1274 InsetIterator const end = inset_iterator_end(*d->inset);
1275 for (; it != end; ++it)
1276 it->addPreview(it, *ploader);
1278 ploader->startLoading();
1282 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1283 FileName const & fn, int & file_format) const
1285 if(!lex.checkFor("\\lyxformat")) {
1286 Alert::error(_("Document format failure"),
1287 bformat(_("%1$s is not a readable LyX document."),
1288 from_utf8(fn.absFileName())));
1289 return ReadNoLyXFormat;
1295 // LyX formats 217 and earlier were written as 2.17. This corresponds
1296 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1297 // these cases. See also: www.lyx.org/trac/changeset/1313.
1298 size_t dot = tmp_format.find_first_of(".,");
1299 if (dot != string::npos)
1300 tmp_format.erase(dot, 1);
1302 file_format = convert<int>(tmp_format);
1307 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1308 FileName & tmpfile, int from_format)
1310 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1311 tempfile.setAutoRemove(false);
1312 tmpfile = tempfile.name();
1313 if(tmpfile.empty()) {
1314 Alert::error(_("Conversion failed"),
1315 bformat(_("%1$s is from a different"
1316 " version of LyX, but a temporary"
1317 " file for converting it could"
1318 " not be created."),
1319 from_utf8(fn.absFileName())));
1320 return LyX2LyXNoTempFile;
1323 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1324 if (lyx2lyx.empty()) {
1325 Alert::error(_("Conversion script not found"),
1326 bformat(_("%1$s is from a different"
1327 " version of LyX, but the"
1328 " conversion script lyx2lyx"
1329 " could not be found."),
1330 from_utf8(fn.absFileName())));
1331 return LyX2LyXNotFound;
1335 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1336 ostringstream command;
1337 command << os::python()
1338 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1339 << " -t " << convert<string>(LYX_FORMAT)
1340 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1341 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1342 string const command_str = command.str();
1344 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1346 cmd_ret const ret = runCommand(command_str);
1347 if (ret.first != 0) {
1348 if (from_format < LYX_FORMAT) {
1349 Alert::error(_("Conversion script failed"),
1350 bformat(_("%1$s is from an older version"
1351 " of LyX and the lyx2lyx script"
1352 " failed to convert it."),
1353 from_utf8(fn.absFileName())));
1354 return LyX2LyXOlderFormat;
1356 Alert::error(_("Conversion script failed"),
1357 bformat(_("%1$s is from a newer version"
1358 " of LyX and the lyx2lyx script"
1359 " failed to convert it."),
1360 from_utf8(fn.absFileName())));
1361 return LyX2LyXNewerFormat;
1368 FileName Buffer::getBackupName() const {
1369 map<int, string> const file_formats = {
1386 FileName const & fn = fileName();
1387 string const fname = fn.onlyFileNameWithoutExt();
1388 string const fext = fn.extension() + "~";
1389 string const fpath = lyxrc.backupdir_path.empty() ?
1390 fn.onlyPath().absFileName() :
1391 lyxrc.backupdir_path;
1392 string backup_suffix;
1393 // If file format is from a stable series use version instead of file format
1394 auto const it = file_formats.find(d->file_format);
1395 if (it != file_formats.end())
1396 backup_suffix = "-lyx" + it->second;
1398 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1399 string const backname = fname + backup_suffix;
1400 FileName backup(addName(fpath, addExtension(backname, fext)));
1402 // limit recursion, just in case
1404 unsigned long orig_checksum = 0;
1405 while (backup.exists() && v < 100) {
1406 if (orig_checksum == 0)
1407 orig_checksum = fn.checksum();
1408 unsigned long new_checksum = backup.checksum();
1409 if (orig_checksum == new_checksum) {
1410 LYXERR(Debug::FILES, "Not backing up " << fn <<
1411 "since " << backup << "has the same checksum.");
1412 // a bit of a hack, but we have to check this anyway
1413 // below, and setting this is simpler than introducing
1414 // a special boolean for this purpose.
1418 string const newbackname = backname + "-" + convert<string>(v);
1419 backup.set(addName(fpath, addExtension(newbackname, fext)));
1422 return v < 100 ? backup : FileName();
1426 // Should probably be moved to somewhere else: BufferView? GuiView?
1427 bool Buffer::save() const
1429 docstring const file = makeDisplayPath(absFileName(), 20);
1430 d->filename.refresh();
1432 // check the read-only status before moving the file as a backup
1433 if (d->filename.exists()) {
1434 bool const read_only = !d->filename.isWritable();
1436 Alert::warning(_("File is read-only"),
1437 bformat(_("The file %1$s cannot be written because it "
1438 "is marked as read-only."), file));
1443 // ask if the disk file has been externally modified (use checksum method)
1444 if (fileName().exists() && isChecksumModified()) {
1446 bformat(_("Document %1$s has been externally modified. "
1447 "Are you sure you want to overwrite this file?"), file);
1448 int const ret = Alert::prompt(_("Overwrite modified file?"),
1449 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1454 // We don't need autosaves in the immediate future. (Asger)
1455 resetAutosaveTimers();
1457 // if the file does not yet exist, none of the backup activity
1458 // that follows is necessary
1459 if (!fileName().exists()) {
1460 if (!writeFile(fileName()))
1466 // we first write the file to a new name, then move it to its
1467 // proper location once that has been done successfully. that
1468 // way we preserve the original file if something goes wrong.
1469 string const justname = fileName().onlyFileNameWithoutExt();
1470 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1471 justname + "-XXXXXX.lyx");
1472 bool const symlink = fileName().isSymLink();
1474 tempfile->setAutoRemove(false);
1476 FileName savefile(tempfile->name());
1477 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1478 if (!savefile.clonePermissions(fileName()))
1479 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1481 if (!writeFile(savefile))
1484 // we will set this to false if we fail
1485 bool made_backup = true;
1487 FileName backupName;
1488 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1490 if (d->need_format_backup)
1491 backupName = getBackupName();
1493 // If we for some reason failed to find a backup name in case of
1494 // a format change, this will still set one. It's the best we can
1496 if (backupName.empty()) {
1497 backupName.set(fileName().absFileName() + "~");
1498 if (!lyxrc.backupdir_path.empty()) {
1499 string const mangledName =
1500 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1501 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1505 LYXERR(Debug::FILES, "Backing up original file to " <<
1506 backupName.absFileName());
1507 // Except file is symlink do not copy because of #6587.
1508 // Hard links have bad luck.
1509 made_backup = symlink ?
1510 fileName().copyTo(backupName):
1511 fileName().moveTo(backupName);
1514 Alert::error(_("Backup failure"),
1515 bformat(_("Cannot create backup file %1$s.\n"
1516 "Please check whether the directory exists and is writable."),
1517 from_utf8(backupName.absFileName())));
1518 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1519 } else if (d->need_format_backup) {
1520 // the original file has been backed up successfully, so we
1521 // will not need to do that again
1522 d->need_format_backup = false;
1526 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1527 // Only do this if tempfile is not in autoremove mode
1530 // If we have no symlink, we can simply rename the temp file.
1531 // Otherwise, we need to copy it so the symlink stays intact.
1532 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1533 savefile.moveTo(fileName()))
1535 // saveCheckSum() was already called by writeFile(), but the
1536 // time stamp is invalidated by copying/moving
1539 if (d->file_format != LYX_FORMAT)
1540 // the file associated with this buffer is now in the current format
1541 d->file_format = LYX_FORMAT;
1544 // else we saved the file, but failed to move it to the right location.
1546 if (needBackup && made_backup && !symlink) {
1547 // the original file was moved to some new location, so it will look
1548 // to the user as if it was deleted. (see bug #9234.) we could try
1549 // to restore it, but that would basically mean trying to do again
1550 // what we just failed to do. better to leave things as they are.
1551 Alert::error(_("Write failure"),
1552 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1553 "But LyX could not move it to:\n %2$s.\n"
1554 "Your original file has been backed up to:\n %3$s"),
1555 from_utf8(savefile.absFileName()),
1556 from_utf8(fileName().absFileName()),
1557 from_utf8(backupName.absFileName())));
1559 // either we did not try to make a backup, or else we tried and failed,
1560 // or else the original file was a symlink, in which case it was copied,
1561 // not moved. so the original file is intact.
1562 Alert::error(_("Write failure"),
1563 bformat(_("Cannot move saved file to:\n %1$s.\n"
1564 "But the file has successfully been saved as:\n %2$s."),
1565 from_utf8(fileName().absFileName()),
1566 from_utf8(savefile.absFileName())));
1572 bool Buffer::writeFile(FileName const & fname) const
1574 if (d->read_only && fname == d->filename)
1577 bool retval = false;
1579 docstring const str = bformat(_("Saving document %1$s..."),
1580 makeDisplayPath(fname.absFileName()));
1583 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1585 if (params().compressed) {
1586 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1587 retval = ofs && write(ofs);
1589 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1590 retval = ofs && write(ofs);
1594 message(str + _(" could not write file!"));
1599 // removeAutosaveFile();
1602 message(str + _(" done."));
1608 docstring Buffer::emergencyWrite()
1610 // No need to save if the buffer has not changed.
1614 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1616 docstring user_message = bformat(
1617 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1619 // We try to save three places:
1620 // 1) Same place as document. Unless it is an unnamed doc.
1622 string s = absFileName();
1625 if (writeFile(FileName(s))) {
1627 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1628 return user_message;
1630 user_message += " " + _("Save failed! Trying again...\n");
1634 // 2) In HOME directory.
1635 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1637 lyxerr << ' ' << s << endl;
1638 if (writeFile(FileName(s))) {
1640 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1641 return user_message;
1644 user_message += " " + _("Save failed! Trying yet again...\n");
1646 // 3) In "/tmp" directory.
1647 // MakeAbsPath to prepend the current
1648 // drive letter on OS/2
1649 s = addName(package().temp_dir().absFileName(), absFileName());
1651 lyxerr << ' ' << s << endl;
1652 if (writeFile(FileName(s))) {
1654 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1655 return user_message;
1658 user_message += " " + _("Save failed! Document is lost.");
1661 return user_message;
1665 bool Buffer::write(ostream & ofs) const
1668 // Use the standard "C" locale for file output.
1669 ofs.imbue(locale::classic());
1672 // The top of the file should not be written by params().
1674 // write out a comment in the top of the file
1675 // Important: Keep the version formatting in sync with lyx2lyx and
1676 // tex2lyx (bug 7951)
1677 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1678 << " created this file. For more info see https://www.lyx.org/\n"
1679 << "\\lyxformat " << LYX_FORMAT << "\n"
1680 << "\\begin_document\n";
1682 /// For each author, set 'used' to true if there is a change
1683 /// by this author in the document; otherwise set it to 'false'.
1684 for (Author const & a : params().authors())
1687 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1688 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1689 for ( ; it != end; ++it)
1690 it->checkAuthors(params().authors());
1692 // now write out the buffer parameters.
1693 ofs << "\\begin_header\n";
1694 params().writeFile(ofs, this);
1695 ofs << "\\end_header\n";
1698 ofs << "\n\\begin_body\n";
1700 ofs << "\n\\end_body\n";
1702 // Write marker that shows file is complete
1703 ofs << "\\end_document" << endl;
1705 // Shouldn't really be needed....
1708 // how to check if close went ok?
1709 // Following is an attempt... (BE 20001011)
1711 // good() returns false if any error occurred, including some
1712 // formatting error.
1713 // bad() returns true if something bad happened in the buffer,
1714 // which should include file system full errors.
1719 lyxerr << "File was not closed properly." << endl;
1726 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1727 string const & original_path,
1728 OutputParams const & runparams_in,
1729 OutputWhat output) const
1731 OutputParams runparams = runparams_in;
1733 string const encoding = runparams.encoding->iconvName();
1734 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1737 try { ofs.reset(encoding); }
1738 catch (iconv_codecvt_facet_exception const & e) {
1739 lyxerr << "Caught iconv exception: " << e.what() << endl;
1740 Alert::error(_("Iconv software exception Detected"),
1741 bformat(_("Please verify that the `iconv' support software is"
1742 " properly installed and supports the selected encoding"
1743 " (%1$s), or change the encoding in"
1744 " Document>Settings>Language."), from_ascii(encoding)));
1747 if (!openFileWrite(ofs, fname))
1750 ErrorList & errorList = d->errorLists["Export"];
1752 ExportStatus status = ExportSuccess;
1755 // make sure we are ready to export
1756 // this needs to be done before we validate
1757 // FIXME Do we need to do this all the time? I.e., in children
1758 // of a master we are exporting?
1760 updateMacroInstances(OutputUpdate);
1762 ExportStatus retval;
1764 retval = writeLaTeXSource(os, original_path, runparams, output);
1765 if (retval == ExportKilled)
1766 return ExportKilled;
1768 catch (EncodingException const & e) {
1769 docstring const failed(1, e.failed_char);
1771 oss << "0x" << hex << e.failed_char << dec;
1772 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1773 docstring msg = bformat(_("Uncodable character '%1$s'"
1774 " (code point %2$s)"),
1775 failed, from_utf8(oss.str()));
1776 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1777 "representable in specific verbatim contexts.\n"
1778 "Changing the document encoding to utf8 could help."),
1779 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1781 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1782 " (code point %2$s)"),
1783 failed, from_utf8(oss.str()));
1784 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1785 "representable in the chosen encoding.\n"
1786 "Changing the document encoding to utf8 could help."),
1787 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1789 status = ExportError;
1791 catch (iconv_codecvt_facet_exception const & e) {
1792 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1794 status = ExportError;
1796 catch (exception const & e) {
1797 errorList.push_back(ErrorItem(_("conversion failed"),
1799 lyxerr << e.what() << endl;
1800 status = ExportError;
1803 lyxerr << "Caught some really weird exception..." << endl;
1807 d->texrow = move(os.texrow());
1811 status = ExportError;
1812 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1815 if (runparams_in.silent)
1823 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1824 string const & original_path,
1825 OutputParams const & runparams_in,
1826 OutputWhat output) const
1828 // The child documents, if any, shall be already loaded at this point.
1830 OutputParams runparams = runparams_in;
1832 // Some macros rely on font encoding
1833 runparams.main_fontenc = params().main_font_encoding();
1835 // If we are compiling a file standalone, even if this is the
1836 // child of some other buffer, let's cut the link here, so the
1837 // file is really independent and no concurring settings from
1838 // the master (e.g. branch state) interfere (see #8100).
1839 if (!runparams.is_child)
1840 d->ignore_parent = true;
1842 // Classify the unicode characters appearing in math insets
1843 BufferEncodings::initUnicodeMath(*this);
1845 // validate the buffer.
1846 LYXERR(Debug::LATEX, " Validating buffer...");
1847 LaTeXFeatures features(*this, params(), runparams);
1849 // This is only set once per document (in master)
1850 if (!runparams.is_child) {
1851 runparams.use_polyglossia = features.usePolyglossia();
1852 runparams.use_CJK = features.mustProvide("CJK");
1854 LYXERR(Debug::LATEX, " Buffer validation done.");
1856 bool const output_preamble =
1857 output == FullSource || output == OnlyPreamble;
1858 bool const output_body =
1859 output == FullSource || output == OnlyBody;
1861 // The starting paragraph of the coming rows is the
1862 // first paragraph of the document. (Asger)
1863 if (output_preamble && runparams.nice) {
1864 os << "%% LyX " << lyx_version << " created this file. "
1865 "For more info, see https://www.lyx.org/.\n"
1866 "%% Do not edit unless you really know what "
1869 LYXERR(Debug::INFO, "lyx document header finished");
1871 // There are a few differences between nice LaTeX and usual files:
1872 // usual files have \batchmode and special input@path to allow
1873 // inclusion of figures specified by an explicitly relative path
1874 // (i.e., a path starting with './' or '../') with either \input or
1875 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1876 // input@path is set when the actual parameter original_path is set.
1877 // This is done for usual tex-file, but not for nice-latex-file.
1878 // (Matthias 250696)
1879 // Note that input@path is only needed for something the user does
1880 // in the preamble, included .tex files or ERT, files included by
1881 // LyX work without it.
1882 if (output_preamble) {
1883 if (!runparams.nice) {
1884 // code for usual, NOT nice-latex-file
1885 os << "\\batchmode\n"; // changed from \nonstopmode
1887 if (!original_path.empty()) {
1889 // We don't know the encoding of inputpath
1890 docstring const inputpath = from_utf8(original_path);
1891 docstring uncodable_glyphs;
1892 Encoding const * const enc = runparams.encoding;
1894 for (size_t n = 0; n < inputpath.size(); ++n) {
1895 if (!enc->encodable(inputpath[n])) {
1896 docstring const glyph(1, inputpath[n]);
1897 LYXERR0("Uncodable character '"
1899 << "' in input path!");
1900 uncodable_glyphs += glyph;
1905 // warn user if we found uncodable glyphs.
1906 if (!uncodable_glyphs.empty()) {
1907 frontend::Alert::warning(
1908 _("Uncodable character in file path"),
1910 _("The path of your document\n"
1912 "contains glyphs that are unknown "
1913 "in the current document encoding "
1914 "(namely %2$s). This may result in "
1915 "incomplete output, unless "
1916 "TEXINPUTS contains the document "
1917 "directory and you don't use "
1918 "explicitly relative paths (i.e., "
1919 "paths starting with './' or "
1920 "'../') in the preamble or in ERT."
1921 "\n\nIn case of problems, choose "
1922 "an appropriate document encoding\n"
1923 "(such as utf8) or change the "
1925 inputpath, uncodable_glyphs));
1927 string docdir = os::latex_path(original_path);
1928 if (contains(docdir, '#')) {
1929 docdir = subst(docdir, "#", "\\#");
1930 os << "\\catcode`\\#=11"
1931 "\\def\\#{#}\\catcode`\\#=6\n";
1933 if (contains(docdir, '%')) {
1934 docdir = subst(docdir, "%", "\\%");
1935 os << "\\catcode`\\%=11"
1936 "\\def\\%{%}\\catcode`\\%=14\n";
1938 if (contains(docdir, '~'))
1939 docdir = subst(docdir, "~", "\\string~");
1940 bool const nonascii = !isAscii(from_utf8(docdir));
1941 // LaTeX 2019/10/01 handles non-ascii path without detokenize
1942 bool const utfpathlatex = features.isAvailable("LaTeX-2019/10/01");
1943 bool const detokenize = !utfpathlatex && nonascii;
1944 bool const quote = contains(docdir, ' ');
1945 if (utfpathlatex && nonascii)
1946 os << "\\UseRawInputEncoding\n";
1947 os << "\\makeatletter\n"
1948 << "\\def\\input@path{{";
1950 os << "\\detokenize{";
1959 << "\\makeatother\n";
1963 // get parent macros (if this buffer has a parent) which will be
1964 // written at the document begin further down.
1965 MacroSet parentMacros;
1966 listParentMacros(parentMacros, features);
1968 // Write the preamble
1969 runparams.use_babel = params().writeLaTeX(os, features,
1970 d->filename.onlyPath());
1972 // Active characters
1973 runparams.active_chars = features.getActiveChars();
1975 // Biblatex bibliographies are loaded here
1976 if (params().useBiblatex()) {
1977 vector<pair<docstring, string>> const bibfiles =
1978 prepareBibFilePaths(runparams, getBibfiles(), true);
1979 for (pair<docstring, string> const & file: bibfiles) {
1980 os << "\\addbibresource";
1981 if (!file.second.empty())
1982 os << "[bibencoding=" << file.second << "]";
1983 os << "{" << file.first << "}\n";
1987 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1988 && !features.hasOnlyPolyglossiaLanguages()) {
1991 vector<string> bll = features.getBabelExclusiveLanguages();
1992 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1995 for (string const & sit : bll) {
2000 blangs = bll.size() > 1 ?
2001 bformat(_("The languages %1$s are only supported by Babel."), langs)
2002 : bformat(_("The language %1$s is only supported by Babel."), langs);
2006 for (string const & pit : pll) {
2011 plangs = pll.size() > 1 ?
2012 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
2013 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
2014 if (!blangs.empty())
2018 frontend::Alert::warning(
2019 _("Incompatible Languages!"),
2021 _("You cannot use the following languages "
2022 "together in one LaTeX document because "
2023 "they require conflicting language packages:\n"
2028 // Japanese might be required only in some children of a document,
2029 // but once required, we must keep use_japanese true.
2030 runparams.use_japanese |= features.isRequired("japanese");
2033 // Restore the parenthood if needed
2034 if (!runparams.is_child)
2035 d->ignore_parent = false;
2036 return ExportSuccess;
2040 // mark the beginning of the body to separate it from InPreamble insets
2041 os.texrow().start(TexRow::beginDocument());
2042 os << "\\begin{document}\n";
2044 // mark the start of a new paragraph by simulating a newline,
2045 // so that os.afterParbreak() returns true at document start
2048 // output the parent macros
2049 for (auto const & mac : parentMacros) {
2050 int num_lines = mac->write(os.os(), true);
2051 os.texrow().newlines(num_lines);
2054 } // output_preamble
2056 LYXERR(Debug::INFO, "preamble finished, now the body.");
2060 latexParagraphs(*this, text(), os, runparams);
2062 catch (ConversionException const &) { return ExportKilled; }
2064 // Restore the parenthood if needed
2065 if (!runparams.is_child)
2066 d->ignore_parent = false;
2068 // add this just in case after all the paragraphs
2071 if (output_preamble) {
2072 os << "\\end{document}\n";
2073 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2075 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2077 runparams_in.encoding = runparams.encoding;
2079 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2080 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2081 return ExportSuccess;
2085 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2086 OutputParams const & runparams,
2087 OutputWhat output) const
2089 LYXERR(Debug::LATEX, "makeDocBookFile...");
2092 if (!openFileWrite(ofs, fname))
2095 // make sure we are ready to export
2096 // this needs to be done before we validate
2098 updateMacroInstances(OutputUpdate);
2100 ExportStatus const retval =
2101 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2102 if (retval == ExportKilled)
2103 return ExportKilled;
2107 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2108 return ExportSuccess;
2112 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os, string const & fname,
2113 OutputParams const & runparams,
2114 OutputWhat output) const
2116 LaTeXFeatures features(*this, params(), runparams);
2121 DocumentClass const & tclass = params().documentClass();
2122 string const & top_element = tclass.latexname();
2124 bool const output_preamble =
2125 output == FullSource || output == OnlyPreamble;
2126 bool const output_body =
2127 output == FullSource || output == OnlyBody;
2129 if (output_preamble) {
2130 if (runparams.flavor == OutputParams::XML)
2131 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2134 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2137 if (! tclass.class_header().empty())
2138 os << from_ascii(tclass.class_header());
2139 else if (runparams.flavor == OutputParams::XML)
2140 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2141 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2143 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2145 docstring preamble = params().preamble;
2146 if (runparams.flavor != OutputParams::XML ) {
2147 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2148 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2149 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2150 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2153 string const name = runparams.nice
2154 ? changeExtension(absFileName(), ".sgml") : fname;
2155 preamble += features.getIncludedFiles(name);
2156 preamble += features.getLyXSGMLEntities();
2158 if (!preamble.empty()) {
2159 os << "\n [ " << preamble << " ]";
2165 string top = top_element;
2167 if (runparams.flavor == OutputParams::XML)
2168 top += params().language->code();
2170 top += params().language->code().substr(0, 2);
2173 if (!params().options.empty()) {
2175 top += params().options;
2178 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2179 << " file was created by LyX " << lyx_version
2180 << "\n See https://www.lyx.org/ for more information -->\n";
2182 params().documentClass().counters().reset();
2184 sgml::openTag(os, top);
2187 docbookParagraphs(text(), *this, os, runparams);
2189 catch (ConversionException const &) { return ExportKilled; }
2190 sgml::closeTag(os, top_element);
2192 return ExportSuccess;
2196 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2197 OutputParams const & runparams) const
2199 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2202 if (!openFileWrite(ofs, fname))
2205 // make sure we are ready to export
2206 // this has to be done before we validate
2207 updateBuffer(UpdateMaster, OutputUpdate);
2208 updateMacroInstances(OutputUpdate);
2210 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2211 if (retval == ExportKilled)
2216 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2221 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2222 OutputParams const & runparams,
2223 OutputWhat output) const
2225 LaTeXFeatures features(*this, params(), runparams);
2227 d->bibinfo_.makeCitationLabels(*this);
2229 bool const output_preamble =
2230 output == FullSource || output == OnlyPreamble;
2231 bool const output_body =
2232 output == FullSource || output == OnlyBody || output == IncludedFile;
2234 if (output_preamble) {
2235 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2236 << "<!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"
2237 // FIXME Language should be set properly.
2238 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2240 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2241 // FIXME Presumably need to set this right
2242 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2244 docstring const & doctitle = features.htmlTitle();
2246 << (doctitle.empty() ?
2247 from_ascii("LyX Document") :
2248 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2251 docstring styles = features.getTClassHTMLPreamble();
2252 if (!styles.empty())
2253 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2255 styles = features.getPreambleSnippets().str;
2256 if (!styles.empty())
2257 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2259 // we will collect CSS information in a stream, and then output it
2260 // either here, as part of the header, or else in a separate file.
2261 odocstringstream css;
2262 styles = features.getCSSSnippets();
2263 if (!styles.empty())
2264 css << "/* LyX Provided Styles */\n" << styles << '\n';
2266 styles = features.getTClassHTMLStyles();
2267 if (!styles.empty())
2268 css << "/* Layout-provided Styles */\n" << styles << '\n';
2270 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2271 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2272 if (needfg || needbg) {
2273 css << "\nbody {\n";
2276 << from_ascii(X11hexname(params().fontcolor))
2279 css << " background-color: "
2280 << from_ascii(X11hexname(params().backgroundcolor))
2285 docstring const dstyles = css.str();
2286 if (!dstyles.empty()) {
2287 bool written = false;
2288 if (params().html_css_as_file) {
2289 // open a file for CSS info
2291 string const fcssname = addName(temppath(), "docstyle.css");
2292 FileName const fcssfile = FileName(fcssname);
2293 if (openFileWrite(ocss, fcssfile)) {
2297 // write link to header
2298 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2300 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2303 // we are here if the CSS is supposed to be written to the header
2304 // or if we failed to write it to an external file.
2306 os << "<style type='text/css'>\n"
2315 bool const output_body_tag = (output != IncludedFile);
2316 if (output_body_tag)
2317 os << "<body dir=\"auto\">\n";
2319 if (output != IncludedFile)
2320 // if we're an included file, the counters are in the master.
2321 params().documentClass().counters().reset();
2323 xhtmlParagraphs(text(), *this, xs, runparams);
2325 catch (ConversionException const &) { return ExportKilled; }
2326 if (output_body_tag)
2330 if (output_preamble)
2333 return ExportSuccess;
2337 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2338 // Other flags: -wall -v0 -x
2339 int Buffer::runChktex()
2343 // get LaTeX-Filename
2344 FileName const path(temppath());
2345 string const name = addName(path.absFileName(), latexName());
2346 string const org_path = filePath();
2348 PathChanger p(path); // path to LaTeX file
2349 message(_("Running chktex..."));
2351 // Generate the LaTeX file if neccessary
2352 OutputParams runparams(¶ms().encoding());
2353 runparams.flavor = OutputParams::LATEX;
2354 runparams.nice = false;
2355 runparams.linelen = lyxrc.plaintext_linelen;
2356 ExportStatus const retval =
2357 makeLaTeXFile(FileName(name), org_path, runparams);
2358 if (retval != ExportSuccess) {
2359 // error code on failure
2364 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2365 int const res = chktex.run(terr); // run chktex
2368 Alert::error(_("chktex failure"),
2369 _("Could not run chktex successfully."));
2371 ErrorList & errlist = d->errorLists["ChkTeX"];
2373 bufferErrors(terr, errlist);
2378 if (runparams.silent)
2379 d->errorLists["ChkTeX"].clear();
2387 void Buffer::validate(LaTeXFeatures & features) const
2389 // Validate the buffer params, but not for included
2390 // files, since they also use the parent buffer's
2392 if (!features.runparams().is_child)
2393 params().validate(features);
2395 for (Paragraph const & p : paragraphs())
2396 p.validate(features);
2398 if (lyxerr.debugging(Debug::LATEX)) {
2399 features.showStruct();
2404 void Buffer::getLabelList(vector<docstring> & list) const
2406 // If this is a child document, use the master's list instead.
2408 masterBuffer()->getLabelList(list);
2413 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2414 for (auto const & tocit : *toc) {
2415 if (tocit.depth() == 0)
2416 list.push_back(tocit.str());
2421 void Buffer::invalidateBibinfoCache() const
2423 d->bibinfo_cache_valid_ = false;
2424 d->cite_labels_valid_ = false;
2425 removeBiblioTempFiles();
2426 // also invalidate the cache for the parent buffer
2427 Buffer const * const pbuf = d->parent();
2429 pbuf->invalidateBibinfoCache();
2433 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2435 // FIXME This is probably unnecessary, given where we call this.
2436 // If this is a child document, use the master instead.
2437 Buffer const * const pbuf = masterBuffer();
2438 if (pbuf != this && scope != UpdateChildOnly)
2439 return pbuf->getBibfiles();
2441 // In 2.3.x, we have:
2442 //if (!d->bibfile_cache_valid_)
2443 // this->updateBibfilesCache(scope);
2444 // I think that is a leftover, but there have been so many back-
2445 // and-forths with this, due to Windows issues, that I am not sure.
2447 return d->bibfiles_cache_;
2451 BiblioInfo const & Buffer::masterBibInfo() const
2453 Buffer const * const tmp = masterBuffer();
2455 return tmp->masterBibInfo();
2460 BiblioInfo const & Buffer::bibInfo() const
2466 void Buffer::registerBibfiles(const docstring_list & bf) const
2468 // We register the bib files in the master buffer,
2469 // if there is one, but also in every single buffer,
2470 // in case a child is compiled alone.
2471 Buffer const * const tmp = masterBuffer();
2473 tmp->registerBibfiles(bf);
2475 for (auto const & p : bf) {
2476 docstring_list::const_iterator temp =
2477 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2478 if (temp == d->bibfiles_cache_.end())
2479 d->bibfiles_cache_.push_back(p);
2484 static map<docstring, FileName> bibfileCache;
2486 FileName Buffer::getBibfilePath(docstring const & bibid) const
2488 map<docstring, FileName>::const_iterator it =
2489 bibfileCache.find(bibid);
2490 if (it != bibfileCache.end()) {
2491 // i.e., return bibfileCache[bibid];
2495 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2496 string const texfile = changeExtension(to_utf8(bibid), "bib");
2497 // we need to check first if this file exists where it's said to be.
2498 // there's a weird bug that occurs otherwise: if the file is in the
2499 // Buffer's directory but has the same name as some file that would be
2500 // found by kpsewhich, then we find the latter, not the former.
2501 FileName const local_file = makeAbsPath(texfile, filePath());
2502 FileName file = local_file;
2503 if (!file.exists()) {
2504 // there's no need now to check whether the file can be found
2506 file = findtexfile(texfile, "bib", true);
2510 LYXERR(Debug::FILES, "Found at: " << file);
2512 bibfileCache[bibid] = file;
2513 return bibfileCache[bibid];
2517 void Buffer::checkIfBibInfoCacheIsValid() const
2519 // use the master's cache
2520 Buffer const * const tmp = masterBuffer();
2522 tmp->checkIfBibInfoCacheIsValid();
2526 // If we already know the cache is invalid, stop here.
2527 // This is important in the case when the bibliography
2528 // environment (rather than Bib[la]TeX) is used.
2529 // In that case, the timestamp check below gives no
2530 // sensible result. Rather than that, the cache will
2531 // be invalidated explicitly via invalidateBibInfoCache()
2532 // by the Bibitem inset.
2533 // Same applies for bib encoding changes, which trigger
2534 // invalidateBibInfoCache() by InsetBibtex.
2535 if (!d->bibinfo_cache_valid_)
2538 if (d->have_bibitems_) {
2539 // We have a bibliography environment.
2540 // Invalidate the bibinfo cache unconditionally.
2541 // Cite labels will get invalidated by the inset if needed.
2542 d->bibinfo_cache_valid_ = false;
2546 // OK. This is with Bib(la)tex. We'll assume the cache
2547 // is valid and change this if we find changes in the bibs.
2548 d->bibinfo_cache_valid_ = true;
2549 d->cite_labels_valid_ = true;
2551 // compare the cached timestamps with the actual ones.
2552 docstring_list const & bibfiles_cache = getBibfiles();
2553 for (auto const & bf : bibfiles_cache) {
2554 FileName const fn = getBibfilePath(bf);
2555 time_t lastw = fn.lastModified();
2556 time_t prevw = d->bibfile_status_[fn];
2557 if (lastw != prevw) {
2558 d->bibinfo_cache_valid_ = false;
2559 d->cite_labels_valid_ = false;
2560 d->bibfile_status_[fn] = lastw;
2566 void Buffer::clearBibFileCache() const
2568 bibfileCache.clear();
2572 void Buffer::reloadBibInfoCache(bool const force) const
2574 // we should not need to do this for internal buffers
2578 // use the master's cache
2579 Buffer const * const tmp = masterBuffer();
2581 tmp->reloadBibInfoCache(force);
2586 checkIfBibInfoCacheIsValid();
2587 if (d->bibinfo_cache_valid_)
2591 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2592 // re-read file locations when this info changes
2593 // FIXME Is this sufficient? Or should we also force that
2594 // in some other cases? If so, then it is easy enough to
2595 // add the following line in some other places.
2596 clearBibFileCache();
2597 d->bibinfo_.clear();
2598 FileNameList checkedFiles;
2599 d->have_bibitems_ = false;
2600 collectBibKeys(checkedFiles);
2601 d->bibinfo_cache_valid_ = true;
2605 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2607 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2608 it->collectBibKeys(it, checkedFiles);
2609 if (it->lyxCode() == BIBITEM_CODE) {
2610 if (parent() != nullptr)
2611 parent()->d->have_bibitems_ = true;
2613 d->have_bibitems_ = true;
2619 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2621 // We add the biblio 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_;
2625 bi.mergeBiblioInfo(bin);
2627 if (parent() != nullptr) {
2628 BiblioInfo & masterbi = parent()->d->bibinfo_;
2629 masterbi.mergeBiblioInfo(bin);
2634 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2636 // We add the bibtex info to the master buffer,
2637 // if there is one, but also to every single buffer,
2638 // in case a child is compiled alone.
2639 BiblioInfo & bi = d->bibinfo_;
2642 if (parent() != nullptr) {
2643 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2644 masterbi[key] = bin;
2649 void Buffer::makeCitationLabels() const
2651 Buffer const * const master = masterBuffer();
2652 return d->bibinfo_.makeCitationLabels(*master);
2656 void Buffer::invalidateCiteLabels() const
2658 masterBuffer()->d->cite_labels_valid_ = false;
2661 bool Buffer::citeLabelsValid() const
2663 return masterBuffer()->d->cite_labels_valid_;
2667 void Buffer::removeBiblioTempFiles() const
2669 // We remove files that contain LaTeX commands specific to the
2670 // particular bibliographic style being used, in order to avoid
2671 // LaTeX errors when we switch style.
2672 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2673 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2674 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2675 aux_file.removeFile();
2676 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2677 bbl_file.removeFile();
2678 // Also for the parent buffer
2679 Buffer const * const pbuf = parent();
2681 pbuf->removeBiblioTempFiles();
2685 bool Buffer::isDepClean(string const & name) const
2687 DepClean::const_iterator const it = d->dep_clean.find(name);
2688 if (it == d->dep_clean.end())
2694 void Buffer::markDepClean(string const & name)
2696 d->dep_clean[name] = true;
2700 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2703 // FIXME? if there is an Buffer LFUN that can be dispatched even
2704 // if internal, put a switch '(cmd.action)' here.
2710 switch (cmd.action()) {
2712 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2713 flag.setOnOff(hasReadonlyFlag());
2716 // FIXME: There is need for a command-line import.
2717 //case LFUN_BUFFER_IMPORT:
2719 case LFUN_BUFFER_AUTO_SAVE:
2722 case LFUN_BUFFER_EXPORT_CUSTOM:
2723 // FIXME: Nothing to check here?
2726 case LFUN_BUFFER_EXPORT: {
2727 docstring const arg = cmd.argument();
2728 if (arg == "custom") {
2732 string format = (arg.empty() || arg == "default") ?
2733 params().getDefaultOutputFormat() : to_utf8(arg);
2734 size_t pos = format.find(' ');
2735 if (pos != string::npos)
2736 format = format.substr(0, pos);
2737 enable = params().isExportable(format, false);
2739 flag.message(bformat(
2740 _("Don't know how to export to format: %1$s"), arg));
2744 case LFUN_BUILD_PROGRAM:
2745 enable = params().isExportable("program", false);
2748 case LFUN_BRANCH_ACTIVATE:
2749 case LFUN_BRANCH_DEACTIVATE:
2750 case LFUN_BRANCH_MASTER_ACTIVATE:
2751 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2752 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2753 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2754 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2755 : params().branchlist();
2756 docstring const branchName = cmd.argument();
2757 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2761 case LFUN_BRANCH_ADD:
2762 case LFUN_BRANCHES_RENAME:
2763 // if no Buffer is present, then of course we won't be called!
2766 case LFUN_BUFFER_LANGUAGE:
2767 enable = !isReadonly();
2770 case LFUN_BUFFER_VIEW_CACHE:
2771 (d->preview_file_).refresh();
2772 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2775 case LFUN_CHANGES_TRACK:
2776 flag.setEnabled(true);
2777 flag.setOnOff(params().track_changes);
2780 case LFUN_CHANGES_OUTPUT:
2781 flag.setEnabled(true);
2782 flag.setOnOff(params().output_changes);
2785 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2786 flag.setOnOff(params().compressed);
2789 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2790 flag.setOnOff(params().output_sync);
2793 case LFUN_BUFFER_ANONYMIZE:
2799 flag.setEnabled(enable);
2804 void Buffer::dispatch(string const & command, DispatchResult & result)
2806 return dispatch(lyxaction.lookupFunc(command), result);
2810 // NOTE We can end up here even if we have no GUI, because we are called
2811 // by LyX::exec to handled command-line requests. So we may need to check
2812 // whether we have a GUI or not. The boolean use_gui holds this information.
2813 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2816 // FIXME? if there is an Buffer LFUN that can be dispatched even
2817 // if internal, put a switch '(cmd.action())' here.
2818 dr.dispatched(false);
2821 string const argument = to_utf8(func.argument());
2822 // We'll set this back to false if need be.
2823 bool dispatched = true;
2824 // This handles undo groups automagically
2825 UndoGroupHelper ugh(this);
2827 switch (func.action()) {
2828 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2829 if (lyxvc().inUse()) {
2830 string log = lyxvc().toggleReadOnly();
2835 setReadonly(!hasReadonlyFlag());
2838 case LFUN_BUFFER_EXPORT: {
2839 string const format = (argument.empty() || argument == "default") ?
2840 params().getDefaultOutputFormat() : argument;
2841 ExportStatus const status = doExport(format, false);
2842 dr.setError(status != ExportSuccess);
2843 if (status != ExportSuccess)
2844 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2845 from_utf8(format)));
2849 case LFUN_BUILD_PROGRAM: {
2850 ExportStatus const status = doExport("program", true);
2851 dr.setError(status != ExportSuccess);
2852 if (status != ExportSuccess)
2853 dr.setMessage(_("Error generating literate programming code."));
2857 case LFUN_BUFFER_EXPORT_CUSTOM: {
2859 string command = split(argument, format_name, ' ');
2860 Format const * format = theFormats().getFormat(format_name);
2862 lyxerr << "Format \"" << format_name
2863 << "\" not recognized!"
2868 // The name of the file created by the conversion process
2871 // Output to filename
2872 if (format->name() == "lyx") {
2873 string const latexname = latexName(false);
2874 filename = changeExtension(latexname,
2875 format->extension());
2876 filename = addName(temppath(), filename);
2878 if (!writeFile(FileName(filename)))
2882 doExport(format_name, true, filename);
2885 // Substitute $$FName for filename
2886 if (!contains(command, "$$FName"))
2887 command = "( " + command + " ) < $$FName";
2888 command = subst(command, "$$FName", filename);
2890 // Execute the command in the background
2892 call.startscript(Systemcall::DontWait, command,
2893 filePath(), layoutPos());
2897 // FIXME: There is need for a command-line import.
2899 case LFUN_BUFFER_IMPORT:
2904 case LFUN_BUFFER_AUTO_SAVE:
2906 resetAutosaveTimers();
2909 case LFUN_BRANCH_ACTIVATE:
2910 case LFUN_BRANCH_DEACTIVATE:
2911 case LFUN_BRANCH_MASTER_ACTIVATE:
2912 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2913 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2914 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2915 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2918 docstring const branch_name = func.argument();
2919 // the case without a branch name is handled elsewhere
2920 if (branch_name.empty()) {
2924 Branch * branch = buf->params().branchlist().find(branch_name);
2926 LYXERR0("Branch " << branch_name << " does not exist.");
2928 docstring const msg =
2929 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2933 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2934 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2935 if (branch->isSelected() != activate) {
2936 buf->undo().recordUndoBufferParams(CursorData());
2937 branch->setSelected(activate);
2939 dr.screenUpdate(Update::Force);
2940 dr.forceBufferUpdate();
2945 case LFUN_BRANCH_ADD: {
2946 docstring branchnames = func.argument();
2947 if (branchnames.empty()) {
2951 BranchList & branch_list = params().branchlist();
2952 vector<docstring> const branches =
2953 getVectorFromString(branchnames, branch_list.separator());
2955 for (docstring const & branch_name : branches) {
2956 Branch * branch = branch_list.find(branch_name);
2958 LYXERR0("Branch " << branch_name << " already exists.");
2962 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2964 undo().recordUndoBufferParams(CursorData());
2965 branch_list.add(branch_name);
2966 branch = branch_list.find(branch_name);
2967 string const x11hexname = X11hexname(branch->color());
2968 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2969 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2971 dr.screenUpdate(Update::Force);
2979 case LFUN_BRANCHES_RENAME: {
2980 if (func.argument().empty())
2983 docstring const oldname = from_utf8(func.getArg(0));
2984 docstring const newname = from_utf8(func.getArg(1));
2985 InsetIterator it = inset_iterator_begin(inset());
2986 InsetIterator const end = inset_iterator_end(inset());
2987 bool success = false;
2988 for (; it != end; ++it) {
2989 if (it->lyxCode() == BRANCH_CODE) {
2990 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2991 if (ins.branch() == oldname) {
2992 undo().recordUndo(CursorData(it));
2993 ins.rename(newname);
2998 if (it->lyxCode() == INCLUDE_CODE) {
2999 // get buffer of external file
3000 InsetInclude const & ins =
3001 static_cast<InsetInclude const &>(*it);
3002 Buffer * child = ins.getChildBuffer();
3005 child->dispatch(func, dr);
3010 dr.screenUpdate(Update::Force);
3011 dr.forceBufferUpdate();
3016 case LFUN_BUFFER_VIEW_CACHE:
3017 if (!theFormats().view(*this, d->preview_file_,
3018 d->preview_format_))
3019 dr.setMessage(_("Error viewing the output file."));
3022 case LFUN_CHANGES_TRACK:
3023 if (params().save_transient_properties)
3024 undo().recordUndoBufferParams(CursorData());
3025 params().track_changes = !params().track_changes;
3028 case LFUN_CHANGES_OUTPUT:
3029 if (params().save_transient_properties)
3030 undo().recordUndoBufferParams(CursorData());
3031 params().output_changes = !params().output_changes;
3032 if (params().output_changes) {
3033 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
3034 LaTeXFeatures::isAvailable("xcolor");
3037 Alert::warning(_("Changes not shown in LaTeX output"),
3038 _("Changes will not be highlighted in LaTeX output, "
3039 "because xcolor and ulem are not installed.\n"
3040 "Please install both packages or redefine "
3041 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3046 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3047 // turn compression on/off
3048 undo().recordUndoBufferParams(CursorData());
3049 params().compressed = !params().compressed;
3052 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3053 undo().recordUndoBufferParams(CursorData());
3054 params().output_sync = !params().output_sync;
3057 case LFUN_BUFFER_ANONYMIZE: {
3058 undo().recordUndoFullBuffer(CursorData());
3059 CursorData cur(doc_iterator_begin(this));
3060 for ( ; cur ; cur.forwardPar())
3061 cur.paragraph().anonymize();
3062 dr.forceBufferUpdate();
3063 dr.screenUpdate(Update::Force);
3071 dr.dispatched(dispatched);
3075 void Buffer::changeLanguage(Language const * from, Language const * to)
3077 LASSERT(from, return);
3078 LASSERT(to, return);
3080 for_each(par_iterator_begin(),
3082 bind(&Paragraph::changeLanguage, _1, params(), from, to));
3086 bool Buffer::isMultiLingual() const
3088 ParConstIterator end = par_iterator_end();
3089 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3090 if (it->isMultiLingual(params()))
3097 std::set<Language const *> Buffer::getLanguages() const
3099 std::set<Language const *> langs;
3100 getLanguages(langs);
3105 void Buffer::getLanguages(std::set<Language const *> & langs) const
3107 ParConstIterator end = par_iterator_end();
3108 // add the buffer language, even if it's not actively used
3109 langs.insert(language());
3110 // iterate over the paragraphs
3111 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3112 it->getLanguages(langs);
3114 ListOfBuffers clist = getDescendants();
3115 for (auto const & cit : clist)
3116 cit->getLanguages(langs);
3120 DocIterator Buffer::getParFromID(int const id) const
3122 Buffer * buf = const_cast<Buffer *>(this);
3124 // This means non-existent
3125 return doc_iterator_end(buf);
3127 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3128 if (it.paragraph().id() == id)
3131 return doc_iterator_end(buf);
3135 bool Buffer::hasParWithID(int const id) const
3137 return !getParFromID(id).atEnd();
3141 ParIterator Buffer::par_iterator_begin()
3143 return ParIterator(doc_iterator_begin(this));
3147 ParIterator Buffer::par_iterator_end()
3149 return ParIterator(doc_iterator_end(this));
3153 ParConstIterator Buffer::par_iterator_begin() const
3155 return ParConstIterator(doc_iterator_begin(this));
3159 ParConstIterator Buffer::par_iterator_end() const
3161 return ParConstIterator(doc_iterator_end(this));
3165 Language const * Buffer::language() const
3167 return params().language;
3171 docstring const Buffer::B_(string const & l10n) const
3173 return params().B_(l10n);
3177 bool Buffer::isClean() const
3179 return d->lyx_clean;
3183 bool Buffer::isChecksumModified() const
3185 LASSERT(d->filename.exists(), return false);
3186 return d->checksum_ != d->filename.checksum();
3190 void Buffer::saveCheckSum() const
3192 FileName const & file = d->filename;
3194 d->checksum_ = file.exists() ? file.checksum()
3195 : 0; // in the case of save to a new file.
3199 void Buffer::markClean() const
3201 if (!d->lyx_clean) {
3202 d->lyx_clean = true;
3205 // if the .lyx file has been saved, we don't need an
3207 d->bak_clean = true;
3208 d->undo_.markDirty();
3209 clearExternalModification();
3213 void Buffer::setUnnamed(bool flag)
3219 bool Buffer::isUnnamed() const
3226 /// Don't check unnamed, here: isInternal() is used in
3227 /// newBuffer(), where the unnamed flag has not been set by anyone
3228 /// yet. Also, for an internal buffer, there should be no need for
3229 /// retrieving fileName() nor for checking if it is unnamed or not.
3230 bool Buffer::isInternal() const
3232 return d->internal_buffer;
3236 void Buffer::setInternal(bool flag)
3238 d->internal_buffer = flag;
3242 void Buffer::markDirty()
3245 d->lyx_clean = false;
3248 d->bak_clean = false;
3250 for (auto & depit : d->dep_clean)
3251 depit.second = false;
3255 FileName Buffer::fileName() const
3261 string Buffer::absFileName() const
3263 return d->filename.absFileName();
3267 string Buffer::filePath() const
3269 string const abs = d->filename.onlyPath().absFileName();
3272 int last = abs.length() - 1;
3274 return abs[last] == '/' ? abs : abs + '/';
3278 DocFileName Buffer::getReferencedFileName(string const & fn) const
3281 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3282 result.set(fn, filePath());
3284 // filePath() ends with a path separator
3285 FileName const test(filePath() + fn);
3287 result.set(fn, filePath());
3289 result.set(fn, params().origin);
3296 string const Buffer::prepareFileNameForLaTeX(string const & name,
3297 string const & ext, bool nice) const
3299 string const fname = makeAbsPath(name, filePath()).absFileName();
3300 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3306 return to_utf8(makeRelPath(from_utf8(fname),
3307 from_utf8(masterBuffer()->filePath())));
3311 vector<pair<docstring, string>> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3312 docstring_list const & bibfilelist,
3313 bool const add_extension) const
3315 // If we are processing the LaTeX file in a temp directory then
3316 // copy the .bib databases to this temp directory, mangling their
3317 // names in the process. Store this mangled name in the list of
3319 // (We need to do all this because BibTeX *really*, *really*
3320 // can't handle "files with spaces" and Windows users tend to
3321 // use such filenames.)
3322 // Otherwise, store the (maybe absolute) path to the original,
3323 // unmangled database name.
3325 vector<pair<docstring, string>> res;
3327 // determine the export format
3328 string const tex_format = flavor2format(runparams.flavor);
3330 // check for spaces in paths
3331 bool found_space = false;
3333 for (auto const & bit : bibfilelist) {
3334 string utf8input = to_utf8(bit);
3336 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3337 FileName try_in_file =
3338 makeAbsPath(database + ".bib", filePath());
3339 bool not_from_texmf = try_in_file.isReadableFile();
3340 // If the file has not been found, try with the real file name
3341 // (it might come from a child in a sub-directory)
3342 if (!not_from_texmf) {
3343 try_in_file = getBibfilePath(bit);
3344 if (try_in_file.isReadableFile()) {
3345 // Check if the file is in texmf
3346 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3347 not_from_texmf = kpsefile.empty()
3348 || kpsefile.absFileName() != try_in_file.absFileName();
3350 // If this exists, make path relative to the master
3353 removeExtension(prepareFileNameForLaTeX(
3354 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3355 from_utf8(filePath()))),
3356 ".bib", runparams.nice));
3360 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3362 // mangledFileName() needs the extension
3363 DocFileName const in_file = DocFileName(try_in_file);
3364 database = removeExtension(in_file.mangledFileName());
3365 FileName const out_file = makeAbsPath(database + ".bib",
3366 masterBuffer()->temppath());
3367 bool const success = in_file.copyTo(out_file);
3369 LYXERR0("Failed to copy '" << in_file
3370 << "' to '" << out_file << "'");
3372 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3373 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3374 if (!isValidLaTeXFileName(database)) {
3375 frontend::Alert::warning(_("Invalid filename"),
3376 _("The following filename will cause troubles "
3377 "when running the exported file through LaTeX: ") +
3378 from_utf8(database));
3380 if (!isValidDVIFileName(database)) {
3381 frontend::Alert::warning(_("Problematic filename for DVI"),
3382 _("The following filename can cause troubles "
3383 "when running the exported file through LaTeX "
3384 "and opening the resulting DVI: ") +
3385 from_utf8(database), true);
3393 docstring const path = from_utf8(latex_path(database));
3395 if (contains(path, ' '))
3398 if (params().useBiblatex() && !params().bibFileEncoding(utf8input).empty())
3399 enc = params().bibFileEncoding(utf8input);
3401 bool recorded = false;
3402 for (pair<docstring, string> pe : res) {
3403 if (pe.first == path) {
3410 res.push_back(make_pair(path, enc));
3413 // Check if there are spaces in the path and warn BibTeX users, if so.
3414 // (biber can cope with such paths)
3415 if (!prefixIs(runparams.bibtex_command, "biber")) {
3416 // Post this warning only once.
3417 static bool warned_about_spaces = false;
3418 if (!warned_about_spaces &&
3419 runparams.nice && found_space) {
3420 warned_about_spaces = true;
3421 Alert::warning(_("Export Warning!"),
3422 _("There are spaces in the paths to your BibTeX databases.\n"
3423 "BibTeX will be unable to find them."));
3432 string Buffer::layoutPos() const
3434 return d->layout_position;
3438 void Buffer::setLayoutPos(string const & path)
3441 d->layout_position.clear();
3445 LATTEST(FileName::isAbsolute(path));
3447 d->layout_position =
3448 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3450 if (d->layout_position.empty())
3451 d->layout_position = ".";
3455 bool Buffer::hasReadonlyFlag() const
3457 return d->read_only;
3461 bool Buffer::isReadonly() const
3463 return hasReadonlyFlag() || notifiesExternalModification();
3467 void Buffer::setParent(Buffer const * buffer)
3469 // Avoids recursive include.
3470 d->setParent(buffer == this ? nullptr : buffer);
3475 Buffer const * Buffer::parent() const
3481 ListOfBuffers Buffer::allRelatives() const
3483 ListOfBuffers lb = masterBuffer()->getDescendants();
3484 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3489 Buffer const * Buffer::masterBuffer() const
3491 // FIXME Should be make sure we are not in some kind
3492 // of recursive include? A -> B -> A will crash this.
3493 Buffer const * const pbuf = d->parent();
3497 return pbuf->masterBuffer();
3501 bool Buffer::isChild(Buffer * child) const
3503 return d->children_positions.find(child) != d->children_positions.end();
3507 DocIterator Buffer::firstChildPosition(Buffer const * child)
3509 Impl::BufferPositionMap::iterator it;
3510 it = d->children_positions.find(child);
3511 if (it == d->children_positions.end())
3512 return DocIterator(this);
3517 bool Buffer::hasChildren() const
3519 return !d->children_positions.empty();
3523 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3525 // loop over children
3526 for (auto const & p : d->children_positions) {
3527 Buffer * child = const_cast<Buffer *>(p.first);
3529 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3530 if (bit != clist.end())
3532 clist.push_back(child);
3534 // there might be grandchildren
3535 child->collectChildren(clist, true);
3540 ListOfBuffers Buffer::getChildren() const
3543 collectChildren(v, false);
3544 // Make sure we have not included ourselves.
3545 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3546 if (bit != v.end()) {
3547 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3554 ListOfBuffers Buffer::getDescendants() const
3557 collectChildren(v, true);
3558 // Make sure we have not included ourselves.
3559 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3560 if (bit != v.end()) {
3561 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3568 template<typename M>
3569 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3574 typename M::const_iterator it = m.lower_bound(x);
3575 if (it == m.begin())
3583 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3584 DocIterator const & pos) const
3586 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3588 // if paragraphs have no macro context set, pos will be empty
3592 // we haven't found anything yet
3593 DocIterator bestPos = owner_->par_iterator_begin();
3594 MacroData const * bestData = nullptr;
3596 // find macro definitions for name
3597 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3598 if (nameIt != macros.end()) {
3599 // find last definition in front of pos or at pos itself
3600 PositionScopeMacroMap::const_iterator it
3601 = greatest_below(nameIt->second, pos);
3602 if (it != nameIt->second.end()) {
3604 // scope ends behind pos?
3605 if (pos < it->second.scope) {
3606 // Looks good, remember this. If there
3607 // is no external macro behind this,
3608 // we found the right one already.
3609 bestPos = it->first;
3610 bestData = &it->second.macro;
3614 // try previous macro if there is one
3615 if (it == nameIt->second.begin())
3622 // find macros in included files
3623 PositionScopeBufferMap::const_iterator it
3624 = greatest_below(position_to_children, pos);
3625 if (it == position_to_children.end())
3626 // no children before
3630 // do we know something better (i.e. later) already?
3631 if (it->first < bestPos )
3634 // scope ends behind pos?
3635 if (pos < it->second.scope
3636 && (cloned_buffer_ ||
3637 theBufferList().isLoaded(it->second.buffer))) {
3638 // look for macro in external file
3640 MacroData const * data
3641 = it->second.buffer->getMacro(name, false);
3644 bestPos = it->first;
3650 // try previous file if there is one
3651 if (it == position_to_children.begin())
3656 // return the best macro we have found
3661 MacroData const * Buffer::getMacro(docstring const & name,
3662 DocIterator const & pos, bool global) const
3667 // query buffer macros
3668 MacroData const * data = d->getBufferMacro(name, pos);
3669 if (data != nullptr)
3672 // If there is a master buffer, query that
3673 Buffer const * const pbuf = d->parent();
3675 d->macro_lock = true;
3676 MacroData const * macro = pbuf->getMacro(
3677 name, *this, false);
3678 d->macro_lock = false;
3684 data = MacroTable::globalMacros().get(name);
3685 if (data != nullptr)
3693 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3695 // set scope end behind the last paragraph
3696 DocIterator scope = par_iterator_begin();
3697 scope.pit() = scope.lastpit() + 1;
3699 return getMacro(name, scope, global);
3703 MacroData const * Buffer::getMacro(docstring const & name,
3704 Buffer const & child, bool global) const
3706 // look where the child buffer is included first
3707 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3708 if (it == d->children_positions.end())
3711 // check for macros at the inclusion position
3712 return getMacro(name, it->second, global);
3716 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3718 pit_type const lastpit = it.lastpit();
3720 // look for macros in each paragraph
3721 while (it.pit() <= lastpit) {
3722 Paragraph & par = it.paragraph();
3724 // FIXME Can this be done with the new-style iterators?
3725 // iterate over the insets of the current paragraph
3726 for (auto const & insit : par.insetList()) {
3727 it.pos() = insit.pos;
3729 // is it a nested text inset?
3730 if (insit.inset->asInsetText()) {
3731 // Inset needs its own scope?
3732 InsetText const * itext = insit.inset->asInsetText();
3733 bool newScope = itext->isMacroScope();
3735 // scope which ends just behind the inset
3736 DocIterator insetScope = it;
3739 // collect macros in inset
3740 it.push_back(CursorSlice(*insit.inset));
3741 updateMacros(it, newScope ? insetScope : scope);
3746 if (insit.inset->asInsetTabular()) {
3747 CursorSlice slice(*insit.inset);
3748 size_t const numcells = slice.nargs();
3749 for (; slice.idx() < numcells; slice.forwardIdx()) {
3750 it.push_back(slice);
3751 updateMacros(it, scope);
3757 // is it an external file?
3758 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3759 // get buffer of external file
3760 InsetInclude const & incinset =
3761 static_cast<InsetInclude const &>(*insit.inset);
3763 Buffer * child = incinset.getChildBuffer();
3768 // register its position, but only when it is
3769 // included first in the buffer
3770 if (children_positions.find(child) ==
3771 children_positions.end())
3772 children_positions[child] = it;
3774 // register child with its scope
3775 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3779 InsetMath * im = insit.inset->asInsetMath();
3780 if (doing_export && im) {
3781 InsetMathHull * hull = im->asHullInset();
3783 hull->recordLocation(it);
3786 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3790 InsetMathMacroTemplate & macroTemplate =
3791 *insit.inset->asInsetMath()->asMacroTemplate();
3792 MacroContext mc(owner_, it);
3793 macroTemplate.updateToContext(mc);
3796 bool valid = macroTemplate.validMacro();
3797 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3798 // then the BufferView's cursor will be invalid in
3799 // some cases which leads to crashes.
3804 // FIXME (Abdel), I don't understand why we pass 'it' here
3805 // instead of 'macroTemplate' defined above... is this correct?
3806 macros[macroTemplate.name()][it] =
3807 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3817 void Buffer::updateMacros() const
3822 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3824 // start with empty table
3826 d->children_positions.clear();
3827 d->position_to_children.clear();
3829 // Iterate over buffer, starting with first paragraph
3830 // The scope must be bigger than any lookup DocIterator
3831 // later. For the global lookup, lastpit+1 is used, hence
3832 // we use lastpit+2 here.
3833 DocIterator it = par_iterator_begin();
3834 DocIterator outerScope = it;
3835 outerScope.pit() = outerScope.lastpit() + 2;
3836 d->updateMacros(it, outerScope);
3840 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3842 InsetIterator it = inset_iterator_begin(inset());
3843 InsetIterator const end = inset_iterator_end(inset());
3844 for (; it != end; ++it) {
3845 if (it->lyxCode() == BRANCH_CODE) {
3846 InsetBranch & br = static_cast<InsetBranch &>(*it);
3847 docstring const name = br.branch();
3848 if (!from_master && !params().branchlist().find(name))
3849 result.push_back(name);
3850 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3851 result.push_back(name);
3854 if (it->lyxCode() == INCLUDE_CODE) {
3855 // get buffer of external file
3856 InsetInclude const & ins =
3857 static_cast<InsetInclude const &>(*it);
3858 Buffer * child = ins.getChildBuffer();
3861 child->getUsedBranches(result, true);
3864 // remove duplicates
3869 void Buffer::updateMacroInstances(UpdateType utype) const
3871 LYXERR(Debug::MACROS, "updateMacroInstances for "
3872 << d->filename.onlyFileName());
3873 DocIterator it = doc_iterator_begin(this);
3875 DocIterator const end = doc_iterator_end(this);
3876 for (; it != end; it.forwardInset()) {
3877 // look for MathData cells in InsetMathNest insets
3878 InsetMath * minset = it.nextInset()->asInsetMath();
3882 // update macro in all cells of the InsetMathNest
3883 DocIterator::idx_type n = minset->nargs();
3884 MacroContext mc = MacroContext(this, it);
3885 for (DocIterator::idx_type i = 0; i < n; ++i) {
3886 MathData & data = minset->cell(i);
3887 data.updateMacros(nullptr, mc, utype, 0);
3893 void Buffer::listMacroNames(MacroNameSet & macros) const
3898 d->macro_lock = true;
3900 // loop over macro names
3901 for (auto const & nameit : d->macros)
3902 macros.insert(nameit.first);
3904 // loop over children
3905 for (auto const & p : d->children_positions) {
3906 Buffer * child = const_cast<Buffer *>(p.first);
3907 // The buffer might have been closed (see #10766).
3908 if (theBufferList().isLoaded(child))
3909 child->listMacroNames(macros);
3913 Buffer const * const pbuf = d->parent();
3915 pbuf->listMacroNames(macros);
3917 d->macro_lock = false;
3921 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3923 Buffer const * const pbuf = d->parent();
3928 pbuf->listMacroNames(names);
3931 for (auto const & mit : names) {
3933 MacroData const * data = pbuf->getMacro(mit, *this, false);
3935 macros.insert(data);
3937 // we cannot access the original InsetMathMacroTemplate anymore
3938 // here to calls validate method. So we do its work here manually.
3939 // FIXME: somehow make the template accessible here.
3940 if (data->optionals() > 0)
3941 features.require("xargs");
3947 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3950 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3952 RefCache::iterator it = d->ref_cache_.find(label);
3953 if (it != d->ref_cache_.end())
3956 static References const dummy_refs = References();
3957 it = d->ref_cache_.insert(
3958 make_pair(label, dummy_refs)).first;
3963 Buffer::References const & Buffer::references(docstring const & label) const
3965 return const_cast<Buffer *>(this)->getReferenceCache(label);
3969 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3971 References & refs = getReferenceCache(label);
3972 refs.push_back(make_pair(inset, it));
3976 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3980 linfo.label = label;
3982 linfo.active = active;
3983 masterBuffer()->d->label_cache_.push_back(linfo);
3987 InsetLabel const * Buffer::insetLabel(docstring const & label,
3988 bool const active) const
3990 for (auto & rc : masterBuffer()->d->label_cache_) {
3991 if (rc.label == label && (rc.active || !active))
3998 bool Buffer::activeLabel(docstring const & label) const
4000 if (!insetLabel(label, true))
4007 void Buffer::clearReferenceCache() const
4010 d->ref_cache_.clear();
4011 d->label_cache_.clear();
4016 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
4018 //FIXME: This does not work for child documents yet.
4019 reloadBibInfoCache();
4021 // Check if the label 'from' appears more than once
4022 vector<docstring> labels;
4023 for (auto const & bibit : masterBibInfo())
4024 labels.push_back(bibit.first);
4026 if (count(labels.begin(), labels.end(), from) > 1)
4029 string const paramName = "key";
4030 UndoGroupHelper ugh(this);
4031 InsetIterator it = inset_iterator_begin(inset());
4033 if (it->lyxCode() != CITE_CODE)
4035 InsetCommand * inset = it->asInsetCommand();
4036 docstring const oldValue = inset->getParam(paramName);
4037 if (oldValue == from) {
4038 undo().recordUndo(CursorData(it));
4039 inset->setParam(paramName, to);
4044 // returns NULL if id-to-row conversion is unsupported
4045 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4046 pit_type par_begin, pit_type par_end,
4047 OutputWhat output, bool master) const
4049 unique_ptr<TexRow> texrow;
4050 OutputParams runparams(¶ms().encoding());
4051 runparams.nice = true;
4052 runparams.flavor = params().getOutputFlavor(format);
4053 runparams.linelen = lyxrc.plaintext_linelen;
4054 // No side effect of file copying and image conversion
4055 runparams.dryrun = true;
4057 // Some macros rely on font encoding
4058 runparams.main_fontenc = params().main_font_encoding();
4060 if (output == CurrentParagraph) {
4061 runparams.par_begin = par_begin;
4062 runparams.par_end = par_end;
4063 if (par_begin + 1 == par_end) {
4065 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4069 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4070 convert<docstring>(par_begin),
4071 convert<docstring>(par_end - 1))
4074 // output paragraphs
4075 if (runparams.flavor == OutputParams::LYX) {
4076 Paragraph const & par = text().paragraphs()[par_begin];
4078 depth_type dt = par.getDepth();
4079 par.write(ods, params(), dt);
4080 os << from_utf8(ods.str());
4081 } else if (runparams.flavor == OutputParams::HTML) {
4083 setMathFlavor(runparams);
4084 xhtmlParagraphs(text(), *this, xs, runparams);
4085 } else if (runparams.flavor == OutputParams::TEXT) {
4087 // FIXME Handles only one paragraph, unlike the others.
4088 // Probably should have some routine with a signature like them.
4089 writePlaintextParagraph(*this,
4090 text().paragraphs()[par_begin], os, runparams, dummy);
4091 } else if (params().isDocBook()) {
4092 docbookParagraphs(text(), *this, os, runparams);
4094 // If we are previewing a paragraph, even if this is the
4095 // child of some other buffer, let's cut the link here,
4096 // so that no concurring settings from the master
4097 // (e.g. branch state) interfere (see #8101).
4099 d->ignore_parent = true;
4100 // We need to validate the Buffer params' features here
4101 // in order to know if we should output polyglossia
4102 // macros (instead of babel macros)
4103 LaTeXFeatures features(*this, params(), runparams);
4105 runparams.use_polyglossia = features.usePolyglossia();
4106 // latex or literate
4109 ots.texrow().newlines(2);
4111 latexParagraphs(*this, text(), ots, runparams);
4112 texrow = ots.releaseTexRow();
4114 // Restore the parenthood
4116 d->ignore_parent = false;
4120 if (output == FullSource)
4121 os << _("Preview source code");
4122 else if (output == OnlyPreamble)
4123 os << _("Preview preamble");
4124 else if (output == OnlyBody)
4125 os << _("Preview body");
4127 if (runparams.flavor == OutputParams::LYX) {
4129 if (output == FullSource)
4131 else if (output == OnlyPreamble)
4132 params().writeFile(ods, this);
4133 else if (output == OnlyBody)
4135 os << from_utf8(ods.str());
4136 } else if (runparams.flavor == OutputParams::HTML) {
4137 writeLyXHTMLSource(os, runparams, output);
4138 } else if (runparams.flavor == OutputParams::TEXT) {
4139 if (output == OnlyPreamble) {
4140 os << "% "<< _("Plain text does not have a preamble.");
4142 writePlaintextFile(*this, os, runparams);
4143 } else if (params().isDocBook()) {
4144 writeDocBookSource(os, absFileName(), runparams, output);
4146 // latex or literate
4149 ots.texrow().newlines(2);
4151 runparams.is_child = true;
4153 writeLaTeXSource(ots, string(), runparams, output);
4154 texrow = ots.releaseTexRow();
4161 ErrorList & Buffer::errorList(string const & type) const
4163 return d->errorLists[type];
4167 void Buffer::updateTocItem(std::string const & type,
4168 DocIterator const & dit) const
4171 d->gui_->updateTocItem(type, dit);
4175 void Buffer::structureChanged() const
4178 d->gui_->structureChanged();
4182 void Buffer::errors(string const & err, bool from_master) const
4185 d->gui_->errors(err, from_master);
4189 void Buffer::message(docstring const & msg) const
4192 d->gui_->message(msg);
4196 void Buffer::setBusy(bool on) const
4199 d->gui_->setBusy(on);
4203 void Buffer::updateTitles() const
4206 d->wa_->updateTitles();
4210 void Buffer::resetAutosaveTimers() const
4213 d->gui_->resetAutosaveTimers();
4217 bool Buffer::hasGuiDelegate() const
4223 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4232 class AutoSaveBuffer : public ForkedProcess {
4235 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4236 : buffer_(buffer), fname_(fname) {}
4238 virtual shared_ptr<ForkedProcess> clone() const
4240 return make_shared<AutoSaveBuffer>(*this);
4245 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4246 from_utf8(fname_.absFileName())));
4247 return run(DontWait);
4251 virtual int generateChild();
4253 Buffer const & buffer_;
4258 int AutoSaveBuffer::generateChild()
4260 #if defined(__APPLE__)
4261 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4262 * We should use something else like threads.
4264 * Since I do not know how to determine at run time what is the OS X
4265 * version, I just disable forking altogether for now (JMarc)
4267 pid_t const pid = -1;
4269 // tmp_ret will be located (usually) in /tmp
4270 // will that be a problem?
4271 // Note that this calls ForkedCalls::fork(), so it's
4272 // ok cross-platform.
4273 pid_t const pid = fork();
4274 // If you want to debug the autosave
4275 // you should set pid to -1, and comment out the fork.
4276 if (pid != 0 && pid != -1)
4280 // pid = -1 signifies that lyx was unable
4281 // to fork. But we will do the save
4283 bool failed = false;
4284 TempFile tempfile("lyxautoXXXXXX.lyx");
4285 tempfile.setAutoRemove(false);
4286 FileName const tmp_ret = tempfile.name();
4287 if (!tmp_ret.empty()) {
4288 if (!buffer_.writeFile(tmp_ret))
4290 else if (!tmp_ret.moveTo(fname_))
4296 // failed to write/rename tmp_ret so try writing direct
4297 if (!buffer_.writeFile(fname_)) {
4298 // It is dangerous to do this in the child,
4299 // but safe in the parent, so...
4300 if (pid == -1) // emit message signal.
4301 buffer_.message(_("Autosave failed!"));
4305 if (pid == 0) // we are the child so...
4314 FileName Buffer::getEmergencyFileName() const
4316 return FileName(d->filename.absFileName() + ".emergency");
4320 FileName Buffer::getAutosaveFileName() const
4322 // if the document is unnamed try to save in the backup dir, else
4323 // in the default document path, and as a last try in the filePath,
4324 // which will most often be the temporary directory
4327 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4328 : lyxrc.backupdir_path;
4329 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4332 string const fname = "#" + d->filename.onlyFileName() + "#";
4334 return makeAbsPath(fname, fpath);
4338 void Buffer::removeAutosaveFile() const
4340 FileName const f = getAutosaveFileName();
4346 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4348 FileName const newauto = getAutosaveFileName();
4350 if (newauto != oldauto && oldauto.exists())
4351 if (!oldauto.moveTo(newauto))
4352 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4356 bool Buffer::autoSave() const
4358 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4359 if (buf->d->bak_clean || hasReadonlyFlag())
4362 message(_("Autosaving current document..."));
4363 buf->d->bak_clean = true;
4365 FileName const fname = getAutosaveFileName();
4366 LASSERT(d->cloned_buffer_, return false);
4368 // If this buffer is cloned, we assume that
4369 // we are running in a separate thread already.
4370 TempFile tempfile("lyxautoXXXXXX.lyx");
4371 tempfile.setAutoRemove(false);
4372 FileName const tmp_ret = tempfile.name();
4373 if (!tmp_ret.empty()) {
4375 // assume successful write of tmp_ret
4376 if (tmp_ret.moveTo(fname))
4379 // failed to write/rename tmp_ret so try writing direct
4380 return writeFile(fname);
4384 void Buffer::setExportStatus(bool e) const
4386 d->doing_export = e;
4387 ListOfBuffers clist = getDescendants();
4388 for (auto const & bit : clist)
4389 bit->d->doing_export = e;
4393 bool Buffer::isExporting() const
4395 return d->doing_export;
4399 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4403 return doExport(target, put_in_tempdir, result_file);
4406 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4407 string & result_file) const
4409 bool const update_unincluded =
4410 params().maintain_unincluded_children
4411 && !params().getIncludedChildren().empty();
4413 // (1) export with all included children (omit \includeonly)
4414 if (update_unincluded) {
4415 ExportStatus const status =
4416 doExport(target, put_in_tempdir, true, result_file);
4417 if (status != ExportSuccess)
4420 // (2) export with included children only
4421 return doExport(target, put_in_tempdir, false, result_file);
4425 void Buffer::setMathFlavor(OutputParams & op) const
4427 switch (params().html_math_output) {
4428 case BufferParams::MathML:
4429 op.math_flavor = OutputParams::MathAsMathML;
4431 case BufferParams::HTML:
4432 op.math_flavor = OutputParams::MathAsHTML;
4434 case BufferParams::Images:
4435 op.math_flavor = OutputParams::MathAsImages;
4437 case BufferParams::LaTeX:
4438 op.math_flavor = OutputParams::MathAsLaTeX;
4444 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4445 bool includeall, string & result_file) const
4447 LYXERR(Debug::FILES, "target=" << target);
4448 OutputParams runparams(¶ms().encoding());
4449 string format = target;
4450 string dest_filename;
4451 size_t pos = target.find(' ');
4452 if (pos != string::npos) {
4453 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4454 format = target.substr(0, pos);
4455 if (format == "default")
4456 format = params().getDefaultOutputFormat();
4457 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4458 FileName(dest_filename).onlyPath().createPath();
4459 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4461 MarkAsExporting exporting(this);
4462 string backend_format;
4463 runparams.flavor = OutputParams::LATEX;
4464 runparams.linelen = lyxrc.plaintext_linelen;
4465 runparams.includeall = includeall;
4466 vector<string> backs = params().backends();
4467 Converters converters = theConverters();
4468 bool need_nice_file = false;
4469 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4470 // Get shortest path to format
4471 converters.buildGraph();
4472 Graph::EdgePath path;
4473 for (string const & sit : backs) {
4474 Graph::EdgePath p = converters.getPath(sit, format);
4475 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4476 backend_format = sit;
4481 if (!put_in_tempdir) {
4482 // Only show this alert if this is an export to a non-temporary
4483 // file (not for previewing).
4484 docstring s = bformat(_("No information for exporting the format %1$s."),
4485 theFormats().prettyName(format));
4486 if (format == "pdf4")
4488 + bformat(_("Hint: use non-TeX fonts or set input encoding "
4489 " to '%1$s'"), from_utf8(encodings.fromLyXName("ascii")->guiName()));
4490 Alert::error(_("Couldn't export file"), s);
4492 return ExportNoPathToFormat;
4494 runparams.flavor = converters.getFlavor(path, this);
4495 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4496 for (auto const & edge : path)
4497 if (theConverters().get(edge).nice()) {
4498 need_nice_file = true;
4503 backend_format = format;
4504 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4505 // FIXME: Don't hardcode format names here, but use a flag
4506 if (backend_format == "pdflatex")
4507 runparams.flavor = OutputParams::PDFLATEX;
4508 else if (backend_format == "luatex")
4509 runparams.flavor = OutputParams::LUATEX;
4510 else if (backend_format == "dviluatex")
4511 runparams.flavor = OutputParams::DVILUATEX;
4512 else if (backend_format == "xetex")
4513 runparams.flavor = OutputParams::XETEX;
4516 string filename = latexName(false);
4517 filename = addName(temppath(), filename);
4518 filename = changeExtension(filename,
4519 theFormats().extension(backend_format));
4520 LYXERR(Debug::FILES, "filename=" << filename);
4522 // Plain text backend
4523 if (backend_format == "text") {
4524 runparams.flavor = OutputParams::TEXT;
4526 writePlaintextFile(*this, FileName(filename), runparams);
4528 catch (ConversionException const &) { return ExportCancel; }
4531 else if (backend_format == "xhtml") {
4532 runparams.flavor = OutputParams::HTML;
4533 setMathFlavor(runparams);
4534 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4535 return ExportKilled;
4536 } else if (backend_format == "lyx")
4537 writeFile(FileName(filename));
4539 else if (params().isDocBook()) {
4540 runparams.nice = !put_in_tempdir;
4541 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4542 return ExportKilled;
4545 else if (backend_format == format || need_nice_file) {
4546 runparams.nice = true;
4547 ExportStatus const retval =
4548 makeLaTeXFile(FileName(filename), string(), runparams);
4549 if (retval == ExportKilled)
4550 return ExportKilled;
4551 if (d->cloned_buffer_)
4552 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4553 if (retval != ExportSuccess)
4555 } else if (!lyxrc.tex_allows_spaces
4556 && contains(filePath(), ' ')) {
4557 Alert::error(_("File name error"),
4558 bformat(_("The directory path to the document\n%1$s\n"
4559 "contains spaces, but your TeX installation does "
4560 "not allow them. You should save the file to a directory "
4561 "whose name does not contain spaces."), from_utf8(filePath())));
4562 return ExportTexPathHasSpaces;
4564 runparams.nice = false;
4565 ExportStatus const retval =
4566 makeLaTeXFile(FileName(filename), filePath(), runparams);
4567 if (retval == ExportKilled)
4568 return ExportKilled;
4569 if (d->cloned_buffer_)
4570 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4571 if (retval != ExportSuccess)
4575 string const error_type = (format == "program")
4576 ? "Build" : params().bufferFormat();
4577 ErrorList & error_list = d->errorLists[error_type];
4578 string const ext = theFormats().extension(format);
4579 FileName const tmp_result_file(changeExtension(filename, ext));
4580 Converters::RetVal const retval =
4581 converters.convert(this, FileName(filename), tmp_result_file,
4582 FileName(absFileName()), backend_format, format, error_list);
4583 if (retval == Converters::KILLED)
4584 return ExportCancel;
4585 bool success = (retval == Converters::SUCCESS);
4587 // Emit the signal to show the error list or copy it back to the
4588 // cloned Buffer so that it can be emitted afterwards.
4589 if (format != backend_format) {
4590 if (runparams.silent)
4592 else if (d->cloned_buffer_)
4593 d->cloned_buffer_->d->errorLists[error_type] =
4594 d->errorLists[error_type];
4597 // also to the children, in case of master-buffer-view
4598 ListOfBuffers clist = getDescendants();
4599 for (auto const & bit : clist) {
4600 if (runparams.silent)
4601 bit->d->errorLists[error_type].clear();
4602 else if (d->cloned_buffer_) {
4603 // Enable reverse search by copying back the
4604 // texrow object to the cloned buffer.
4605 // FIXME: this is not thread safe.
4606 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4607 bit->d->cloned_buffer_->d->errorLists[error_type] =
4608 bit->d->errorLists[error_type];
4610 bit->errors(error_type, true);
4614 if (d->cloned_buffer_) {
4615 // Enable reverse dvi or pdf to work by copying back the texrow
4616 // object to the cloned buffer.
4617 // FIXME: There is a possibility of concurrent access to texrow
4618 // here from the main GUI thread that should be securized.
4619 d->cloned_buffer_->d->texrow = d->texrow;
4620 string const err_type = params().bufferFormat();
4621 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4625 if (put_in_tempdir) {
4626 result_file = tmp_result_file.absFileName();
4627 return success ? ExportSuccess : ExportConverterError;
4630 if (dest_filename.empty())
4631 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4633 result_file = dest_filename;
4634 // We need to copy referenced files (e. g. included graphics
4635 // if format == "dvi") to the result dir.
4636 vector<ExportedFile> const extfiles =
4637 runparams.exportdata->externalFiles(format);
4638 string const dest = runparams.export_folder.empty() ?
4639 onlyPath(result_file) : runparams.export_folder;
4640 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4641 : force_overwrite == ALL_FILES;
4642 CopyStatus status = use_force ? FORCE : SUCCESS;
4644 for (ExportedFile const & exp : extfiles) {
4645 if (status == CANCEL) {
4646 message(_("Document export cancelled."));
4647 return ExportCancel;
4649 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4650 string fixedName = exp.exportName;
4651 if (!runparams.export_folder.empty()) {
4652 // Relative pathnames starting with ../ will be sanitized
4653 // if exporting to a different folder
4654 while (fixedName.substr(0, 3) == "../")
4655 fixedName = fixedName.substr(3, fixedName.length() - 3);
4657 FileName fixedFileName = makeAbsPath(fixedName, dest);
4658 fixedFileName.onlyPath().createPath();
4659 status = copyFile(fmt, exp.sourceName,
4661 exp.exportName, status == FORCE,
4662 runparams.export_folder.empty());
4666 if (tmp_result_file.exists()) {
4667 // Finally copy the main file
4668 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4669 : force_overwrite != NO_FILES;
4670 if (status == SUCCESS && use_force)
4672 status = copyFile(format, tmp_result_file,
4673 FileName(result_file), result_file,
4675 if (status == CANCEL) {
4676 message(_("Document export cancelled."));
4677 return ExportCancel;
4679 message(bformat(_("Document exported as %1$s "
4681 theFormats().prettyName(format),
4682 makeDisplayPath(result_file)));
4685 // This must be a dummy converter like fax (bug 1888)
4686 message(bformat(_("Document exported as %1$s"),
4687 theFormats().prettyName(format)));
4690 return success ? ExportSuccess : ExportConverterError;
4694 Buffer::ExportStatus Buffer::preview(string const & format) const
4696 bool const update_unincluded =
4697 params().maintain_unincluded_children
4698 && !params().getIncludedChildren().empty();
4699 return preview(format, update_unincluded);
4703 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4705 MarkAsExporting exporting(this);
4707 // (1) export with all included children (omit \includeonly)
4709 ExportStatus const status = doExport(format, true, true, result_file);
4710 if (status != ExportSuccess)
4713 // (2) export with included children only
4714 ExportStatus const status = doExport(format, true, false, result_file);
4715 FileName const previewFile(result_file);
4717 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4718 theimpl->preview_file_ = previewFile;
4719 theimpl->preview_format_ = format;
4720 theimpl->require_fresh_start_ = (status != ExportSuccess);
4722 if (status != ExportSuccess)
4725 if (previewFile.exists())
4726 return theFormats().view(*this, previewFile, format) ?
4727 PreviewSuccess : PreviewError;
4729 // Successful export but no output file?
4730 // Probably a bug in error detection.
4731 LATTEST(status != ExportSuccess);
4736 Buffer::ReadStatus Buffer::extractFromVC()
4738 bool const found = LyXVC::file_not_found_hook(d->filename);
4740 return ReadFileNotFound;
4741 if (!d->filename.isReadableFile())
4747 Buffer::ReadStatus Buffer::loadEmergency()
4749 FileName const emergencyFile = getEmergencyFileName();
4750 if (!emergencyFile.exists()
4751 || emergencyFile.lastModified() <= d->filename.lastModified())
4752 return ReadFileNotFound;
4754 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4755 docstring const text = bformat(_("An emergency save of the document "
4756 "%1$s exists.\n\nRecover emergency save?"), file);
4758 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4759 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4765 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4766 bool const success = (ret_llf == ReadSuccess);
4768 if (hasReadonlyFlag()) {
4769 Alert::warning(_("File is read-only"),
4770 bformat(_("An emergency file is successfully loaded, "
4771 "but the original file %1$s is marked read-only. "
4772 "Please make sure to save the document as a different "
4773 "file."), from_utf8(d->filename.absFileName())));
4776 lyxvc().file_found_hook(d->filename);
4777 str = _("Document was successfully recovered.");
4779 str = _("Document was NOT successfully recovered.");
4780 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4781 makeDisplayPath(emergencyFile.absFileName()));
4783 int const del_emerg =
4784 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4785 _("&Remove"), _("&Keep"));
4786 if (del_emerg == 0) {
4787 emergencyFile.removeFile();
4789 Alert::warning(_("Emergency file deleted"),
4790 _("Do not forget to save your file now!"), true);
4792 return success ? ReadSuccess : ReadEmergencyFailure;
4795 int const del_emerg =
4796 Alert::prompt(_("Delete emergency file?"),
4797 _("Remove emergency file now?"), 1, 1,
4798 _("&Remove"), _("&Keep"));
4800 emergencyFile.removeFile();
4804 string const ename = emergencyFile.absFileName();
4806 // Surely we can find one in 100 tries?
4807 for (int i = 1; i < 100; ++i) {
4808 newname.set(ename + to_string(i) + ".lyx");
4809 if (!newname.exists()) {
4815 // renameTo returns true on success. So inverting that
4816 // will give us true if we fail.
4817 noname = !emergencyFile.renameTo(newname);
4820 Alert::warning(_("Can't rename emergency file!"),
4821 _("LyX was unable to rename the emergency file. "
4822 "You should do so manually. Otherwise, you will be "
4823 "asked about it again the next time you try to load "
4824 "this file, and may over-write your own work."));
4826 Alert::warning(_("Emergency File Renames"),
4827 bformat(_("Emergency file renamed as:\n %1$s"),
4828 from_utf8(newname.onlyFileName())));
4831 return ReadOriginal;
4841 Buffer::ReadStatus Buffer::loadAutosave()
4843 // Now check if autosave file is newer.
4844 FileName const autosaveFile = getAutosaveFileName();
4845 if (!autosaveFile.exists()
4846 || autosaveFile.lastModified() <= d->filename.lastModified())
4847 return ReadFileNotFound;
4849 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4850 docstring const text = bformat(_("The backup of the document %1$s "
4851 "is newer.\n\nLoad the backup instead?"), file);
4852 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4853 _("&Load backup"), _("Load &original"), _("&Cancel"));
4858 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4859 // the file is not saved if we load the autosave file.
4860 if (ret_llf == ReadSuccess) {
4861 if (hasReadonlyFlag()) {
4862 Alert::warning(_("File is read-only"),
4863 bformat(_("A backup file is successfully loaded, "
4864 "but the original file %1$s is marked read-only. "
4865 "Please make sure to save the document as a "
4867 from_utf8(d->filename.absFileName())));
4870 lyxvc().file_found_hook(d->filename);
4873 return ReadAutosaveFailure;
4876 // Here we delete the autosave
4877 autosaveFile.removeFile();
4878 return ReadOriginal;
4886 Buffer::ReadStatus Buffer::loadLyXFile()
4888 if (!d->filename.isReadableFile()) {
4889 ReadStatus const ret_rvc = extractFromVC();
4890 if (ret_rvc != ReadSuccess)
4894 ReadStatus const ret_re = loadEmergency();
4895 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4898 ReadStatus const ret_ra = loadAutosave();
4899 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4902 return loadThisLyXFile(d->filename);
4906 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4908 return readFile(fn);
4912 void Buffer::Impl::traverseErrors(TeXErrors::Errors::const_iterator err, TeXErrors::Errors::const_iterator end, ErrorList & errorList) const
4914 for (; err != end; ++err) {
4915 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4916 int errorRow = err->error_in_line;
4917 Buffer const * buf = nullptr;
4918 Impl const * p = this;
4919 if (err->child_name.empty())
4920 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4922 // The error occurred in a child
4923 for (Buffer const * child : owner_->getDescendants()) {
4924 string const child_name =
4925 DocFileName(changeExtension(child->absFileName(), "tex")).
4927 if (err->child_name != child_name)
4929 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4930 if (!TexRow::isNone(start)) {
4931 buf = this->cloned_buffer_
4932 ? child->d->cloned_buffer_->d->owner_
4939 errorList.push_back(ErrorItem(err->error_desc, err->error_text,
4945 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4947 TeXErrors::Errors::const_iterator err = terr.begin();
4948 TeXErrors::Errors::const_iterator end = terr.end();
4950 d->traverseErrors(err, end, errorList);
4954 void Buffer::bufferRefs(TeXErrors const & terr, ErrorList & errorList) const
4956 TeXErrors::Errors::const_iterator err = terr.begin_ref();
4957 TeXErrors::Errors::const_iterator end = terr.end_ref();
4959 d->traverseErrors(err, end, errorList);
4963 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4965 LBUFERR(!text().paragraphs().empty());
4967 // Use the master text class also for child documents
4968 Buffer const * const master = masterBuffer();
4969 DocumentClass const & textclass = master->params().documentClass();
4971 docstring_list old_bibfiles;
4972 // Do this only if we are the top-level Buffer. We also need to account
4973 // for the case of a previewed child with ignored parent here.
4974 if (master == this && !d->ignore_parent) {
4975 textclass.counters().reset(from_ascii("bibitem"));
4976 reloadBibInfoCache();
4977 // we will re-read this cache as we go through, but we need
4978 // to know whether it's changed to know whether we need to
4979 // update the bibinfo cache.
4980 old_bibfiles = d->bibfiles_cache_;
4981 d->bibfiles_cache_.clear();
4984 // keep the buffers to be children in this set. If the call from the
4985 // master comes back we can see which of them were actually seen (i.e.
4986 // via an InsetInclude). The remaining ones in the set need still be updated.
4987 static std::set<Buffer const *> bufToUpdate;
4988 if (scope == UpdateMaster) {
4989 // If this is a child document start with the master
4990 if (master != this) {
4991 bufToUpdate.insert(this);
4992 master->updateBuffer(UpdateMaster, utype);
4993 // If the master buffer has no gui associated with it, then the TocModel is
4994 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4995 // (bug 5699). The same happens if the master buffer is open in a different
4996 // window. This test catches both possibilities.
4997 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4998 // There remains a problem here: If there is another child open in yet a third
4999 // window, that TOC is not updated. So some more general solution is needed at
5001 if (master->d->gui_ != d->gui_)
5004 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
5005 if (bufToUpdate.find(this) == bufToUpdate.end())
5009 // start over the counters in the master
5010 textclass.counters().reset();
5013 // update will be done below for this buffer
5014 bufToUpdate.erase(this);
5016 // update all caches
5017 clearReferenceCache();
5020 Buffer & cbuf = const_cast<Buffer &>(*this);
5021 // if we are reloading, then we could have a dangling TOC,
5022 // in effect. so we need to go ahead and reset, even though
5023 // we will do so again when we rebuild the TOC later.
5024 cbuf.tocBackend().reset();
5027 ParIterator parit = cbuf.par_iterator_begin();
5028 updateBuffer(parit, utype);
5030 // If this document has siblings, then update the TocBackend later. The
5031 // reason is to ensure that later siblings are up to date when e.g. the
5032 // broken or not status of references is computed. The update is called
5033 // in InsetInclude::addToToc.
5037 // if the bibfiles changed, the cache of bibinfo is invalid
5038 docstring_list new_bibfiles = d->bibfiles_cache_;
5039 // this is a trick to determine whether the two vectors have
5040 // the same elements.
5041 sort(new_bibfiles.begin(), new_bibfiles.end());
5042 sort(old_bibfiles.begin(), old_bibfiles.end());
5043 if (old_bibfiles != new_bibfiles) {
5044 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
5045 invalidateBibinfoCache();
5046 reloadBibInfoCache();
5047 // We relied upon the bibinfo cache when recalculating labels. But that
5048 // cache was invalid, although we didn't find that out until now. So we
5049 // have to do it all again.
5050 // That said, the only thing we really need to do is update the citation
5051 // labels. Nothing else will have changed. So we could create a new
5052 // UpdateType that would signal that fact, if we needed to do so.
5053 parit = cbuf.par_iterator_begin();
5054 // we will be re-doing the counters and references and such.
5055 textclass.counters().reset();
5056 clearReferenceCache();
5057 // we should not need to do this again?
5059 updateBuffer(parit, utype);
5060 // this will already have been done by reloadBibInfoCache();
5061 // d->bibinfo_cache_valid_ = true;
5064 LYXERR(Debug::FILES, "Bibfiles unchanged.");
5065 // this is also set to true on the other path, by reloadBibInfoCache.
5066 d->bibinfo_cache_valid_ = true;
5068 d->cite_labels_valid_ = true;
5070 cbuf.tocBackend().update(true, utype);
5071 if (scope == UpdateMaster)
5072 cbuf.structureChanged();
5076 static depth_type getDepth(DocIterator const & it)
5078 depth_type depth = 0;
5079 for (size_t i = 0 ; i < it.depth() ; ++i)
5080 if (!it[i].inset().inMathed())
5081 depth += it[i].paragraph().getDepth() + 1;
5082 // remove 1 since the outer inset does not count
5083 // we should have at least one non-math inset, so
5084 // depth should nevery be 0. but maybe it is worth
5085 // marking this, just in case.
5087 // coverity[INTEGER_OVERFLOW]
5091 static depth_type getItemDepth(ParIterator const & it)
5093 Paragraph const & par = *it;
5094 LabelType const labeltype = par.layout().labeltype;
5096 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5099 // this will hold the lowest depth encountered up to now.
5100 depth_type min_depth = getDepth(it);
5101 ParIterator prev_it = it;
5104 --prev_it.top().pit();
5106 // start of nested inset: go to outer par
5108 if (prev_it.empty()) {
5109 // start of document: nothing to do
5114 // We search for the first paragraph with same label
5115 // that is not more deeply nested.
5116 Paragraph & prev_par = *prev_it;
5117 depth_type const prev_depth = getDepth(prev_it);
5118 if (labeltype == prev_par.layout().labeltype) {
5119 if (prev_depth < min_depth)
5120 return prev_par.itemdepth + 1;
5121 if (prev_depth == min_depth)
5122 return prev_par.itemdepth;
5124 min_depth = min(min_depth, prev_depth);
5125 // small optimization: if we are at depth 0, we won't
5126 // find anything else
5127 if (prev_depth == 0)
5133 static bool needEnumCounterReset(ParIterator const & it)
5135 Paragraph const & par = *it;
5136 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5137 depth_type const cur_depth = par.getDepth();
5138 ParIterator prev_it = it;
5139 while (prev_it.pit()) {
5140 --prev_it.top().pit();
5141 Paragraph const & prev_par = *prev_it;
5142 if (prev_par.getDepth() <= cur_depth)
5143 return prev_par.layout().name() != par.layout().name();
5145 // start of nested inset: reset
5150 // set the label of a paragraph. This includes the counters.
5151 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5153 BufferParams const & bp = owner_->masterBuffer()->params();
5154 DocumentClass const & textclass = bp.documentClass();
5155 Paragraph & par = it.paragraph();
5156 Layout const & layout = par.layout();
5157 Counters & counters = textclass.counters();
5159 if (par.params().startOfAppendix()) {
5160 // We want to reset the counter corresponding to toplevel sectioning
5161 Layout const & lay = textclass.getTOCLayout();
5162 docstring const cnt = lay.counter;
5164 counters.reset(cnt);
5165 counters.appendix(true);
5167 par.params().appendix(counters.appendix());
5169 // Compute the item depth of the paragraph
5170 par.itemdepth = getItemDepth(it);
5172 if (layout.margintype == MARGIN_MANUAL) {
5173 if (par.params().labelWidthString().empty())
5174 par.params().labelWidthString(par.expandLabel(layout, bp));
5175 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5176 // we do not need to do anything here, since the empty case is
5177 // handled during export.
5179 par.params().labelWidthString(docstring());
5182 switch(layout.labeltype) {
5183 case LABEL_ITEMIZE: {
5184 // At some point of time we should do something more
5185 // clever here, like:
5186 // par.params().labelString(
5187 // bp.user_defined_bullet(par.itemdepth).getText());
5188 // for now, use a simple hardcoded label
5189 docstring itemlabel;
5190 switch (par.itemdepth) {
5193 itemlabel = char_type(0x2022);
5197 itemlabel = char_type(0x2013);
5200 // ∗ U+2217 ASTERISK OPERATOR
5201 itemlabel = char_type(0x2217);
5204 // · U+00B7 MIDDLE DOT
5205 itemlabel = char_type(0x00b7);
5208 par.params().labelString(itemlabel);
5212 case LABEL_ENUMERATE: {
5213 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5215 switch (par.itemdepth) {
5226 enumcounter += "iv";
5229 // not a valid enumdepth...
5233 if (needEnumCounterReset(it)) {
5234 // Increase the master counter?
5235 if (layout.stepmastercounter)
5236 counters.stepMaster(enumcounter, utype);
5237 // Maybe we have to reset the enumeration counter.
5238 if (!layout.resumecounter)
5239 counters.reset(enumcounter);
5241 counters.step(enumcounter, utype);
5243 string const & lang = par.getParLanguage(bp)->code();
5244 par.params().labelString(counters.theCounter(enumcounter, lang));
5249 case LABEL_SENSITIVE: {
5250 string const & type = counters.current_float();
5251 docstring full_label;
5253 full_label = owner_->B_("Senseless!!! ");
5255 docstring name = owner_->B_(textclass.floats().getType(type).name());
5256 if (counters.hasCounter(from_utf8(type))) {
5257 string const & lang = par.getParLanguage(bp)->code();
5258 counters.step(from_utf8(type), utype);
5259 full_label = bformat(from_ascii("%1$s %2$s:"),
5261 counters.theCounter(from_utf8(type), lang));
5263 full_label = bformat(from_ascii("%1$s #:"), name);
5265 par.params().labelString(full_label);
5269 case LABEL_NO_LABEL:
5270 par.params().labelString(docstring());
5274 case LABEL_CENTERED:
5275 case LABEL_STATIC: {
5276 docstring const & lcounter = layout.counter;
5277 if (!lcounter.empty()) {
5278 if (layout.toclevel <= bp.secnumdepth
5279 && (layout.latextype != LATEX_ENVIRONMENT
5280 || it.text()->isFirstInSequence(it.pit()))) {
5281 if (counters.hasCounter(lcounter))
5282 counters.step(lcounter, utype);
5283 par.params().labelString(par.expandLabel(layout, bp));
5285 par.params().labelString(docstring());
5287 par.params().labelString(par.expandLabel(layout, bp));
5293 par.params().labelString(par.expandLabel(layout, bp));
5298 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5300 // LASSERT: Is it safe to continue here, or should we just return?
5301 LASSERT(parit.pit() == 0, /**/);
5303 // Set the position of the text in the buffer to be able
5304 // to resolve macros in it.
5305 parit.text()->setMacrocontextPosition(parit);
5307 // Reset bibitem counter in master (#8499)
5308 Buffer const * const master = masterBuffer();
5309 if (master == this && !d->ignore_parent)
5310 master->params().documentClass().counters().reset(from_ascii("bibitem"));
5312 depth_type maxdepth = 0;
5313 pit_type const lastpit = parit.lastpit();
5314 bool changed = false;
5315 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5316 // reduce depth if necessary
5317 if (parit->params().depth() > maxdepth) {
5318 /** FIXME: this function is const, but
5319 * nevertheless it modifies the buffer. To be
5320 * cleaner, one should modify the buffer in
5321 * another function, which is actually
5322 * non-const. This would however be costly in
5323 * terms of code duplication.
5325 CursorData(parit).recordUndo();
5326 parit->params().depth(maxdepth);
5328 maxdepth = parit->getMaxDepthAfter();
5330 if (utype == OutputUpdate) {
5331 // track the active counters
5332 // we have to do this for the master buffer, since the local
5333 // buffer isn't tracking anything.
5334 masterBuffer()->params().documentClass().counters().
5335 setActiveLayout(parit->layout());
5338 // set the counter for this paragraph
5339 d->setLabel(parit, utype);
5342 for (auto const & insit : parit->insetList()) {
5343 parit.pos() = insit.pos;
5344 insit.inset->updateBuffer(parit, utype);
5345 changed |= insit.inset->isChanged();
5348 // are there changes in this paragraph?
5349 changed |= parit->isChanged();
5352 // set change indicator for the inset (or the cell that the iterator
5353 // points to, if applicable).
5354 parit.text()->inset().isChanged(changed);
5358 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5359 WordLangTuple & word_lang, docstring_list & suggestions) const
5363 suggestions.clear();
5364 word_lang = WordLangTuple();
5365 bool const to_end = to.empty();
5366 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5367 // OK, we start from here.
5368 for (; from != end; from.forwardPos()) {
5369 // This skips all insets with spell check disabled.
5370 while (!from.allowSpellCheck()) {
5374 // If from is at the end of the document (which is possible
5375 // when "from" was changed above) LyX will crash later otherwise.
5376 if (from.atEnd() || (!to_end && from >= end))
5379 from.paragraph().spellCheck();
5380 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5381 if (SpellChecker::misspelled(res)) {
5385 // Do not increase progress when from == to, otherwise the word
5386 // count will be wrong.
5396 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5398 bool inword = false;
5403 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5404 if (!dit.inTexted()) {
5409 Paragraph const & par = dit.paragraph();
5410 pos_type const pos = dit.pos();
5412 // Copied and adapted from isWordSeparator() in Paragraph
5413 if (pos == dit.lastpos()) {
5416 Inset const * ins = par.getInset(pos);
5417 if (ins && skipNoOutput && !ins->producesOutput()) {
5420 // stop if end of range was skipped
5421 if (!to.atEnd() && dit >= to)
5424 } else if (!par.isDeleted(pos)) {
5425 if (par.isWordSeparator(pos))
5431 if (ins && ins->isLetter())
5433 else if (ins && ins->isSpace())
5436 char_type const c = par.getChar(pos);
5437 if (isPrintableNonspace(c))
5439 else if (isSpace(c))
5449 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5451 d->updateStatistics(from, to, skipNoOutput);
5455 int Buffer::wordCount() const
5457 return d->wordCount();
5461 int Buffer::charCount(bool with_blanks) const
5463 return d->charCount(with_blanks);
5467 bool Buffer::areChangesPresent() const
5469 return inset().isChanged();
5473 Buffer::ReadStatus Buffer::reload()
5476 // c.f. bug https://www.lyx.org/trac/ticket/6587
5477 removeAutosaveFile();
5478 // e.g., read-only status could have changed due to version control
5479 d->filename.refresh();
5480 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5482 // clear parent. this will get reset if need be.
5483 d->setParent(nullptr);
5484 ReadStatus const status = loadLyXFile();
5485 if (status == ReadSuccess) {
5490 message(bformat(_("Document %1$s reloaded."), disp_fn));
5493 message(bformat(_("Could not reload document %1$s."), disp_fn));
5503 bool Buffer::saveAs(FileName const & fn)
5505 FileName const old_name = fileName();
5506 FileName const old_auto = getAutosaveFileName();
5507 bool const old_unnamed = isUnnamed();
5508 bool success = true;
5509 d->old_position = filePath();
5516 // bring the autosave file with us, just in case.
5517 moveAutosaveFile(old_auto);
5518 // validate version control data and
5519 // correct buffer title
5520 lyxvc().file_found_hook(fileName());
5522 // the file has now been saved to the new location.
5523 // we need to check that the locations of child buffers
5525 checkChildBuffers();
5526 checkMasterBuffer();
5529 // reset the old filename and unnamed state
5530 setFileName(old_name);
5531 setUnnamed(old_unnamed);
5535 d->old_position.clear();
5540 void Buffer::checkChildBuffers()
5542 for (auto const & bit : d->children_positions) {
5543 DocIterator dit = bit.second;
5544 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5545 if (!cbuf || !theBufferList().isLoaded(cbuf))
5547 Inset * inset = dit.nextInset();
5548 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5549 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5550 docstring const & incfile = inset_inc->getParam("filename");
5551 string oldloc = cbuf->absFileName();
5552 string newloc = makeAbsPath(to_utf8(incfile),
5553 onlyPath(absFileName())).absFileName();
5554 if (oldloc == newloc)
5556 // the location of the child file is incorrect.
5557 cbuf->setParent(nullptr);
5558 inset_inc->setChildBuffer(nullptr);
5560 // invalidate cache of children
5561 d->children_positions.clear();
5562 d->position_to_children.clear();
5566 // If a child has been saved under a different name/path, it might have been
5567 // orphaned. Therefore the master needs to be reset (bug 8161).
5568 void Buffer::checkMasterBuffer()
5570 Buffer const * const master = masterBuffer();
5574 // necessary to re-register the child (bug 5873)
5575 // FIXME: clean up updateMacros (here, only
5576 // child registering is needed).
5577 master->updateMacros();
5578 // (re)set master as master buffer, but only
5579 // if we are a real child
5580 if (master->isChild(this))
5587 string Buffer::includedFilePath(string const & name, string const & ext) const
5589 if (d->old_position.empty() ||
5590 equivalent(FileName(d->old_position), FileName(filePath())))
5593 bool isabsolute = FileName::isAbsolute(name);
5594 // both old_position and filePath() end with a path separator
5595 string absname = isabsolute ? name : d->old_position + name;
5597 // if old_position is set to origin, we need to do the equivalent of
5598 // getReferencedFileName() (see readDocument())
5599 if (!isabsolute && d->old_position == params().origin) {
5600 FileName const test(addExtension(filePath() + name, ext));
5602 absname = filePath() + name;
5605 if (!FileName(addExtension(absname, ext)).exists())
5609 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5611 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5612 from_utf8(filePath())));
5616 void Buffer::Impl::refreshFileMonitor()
5618 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5619 file_monitor_->refresh();
5623 // The previous file monitor is invalid
5624 // This also destroys the previous file monitor and all its connections
5625 file_monitor_ = FileSystemWatcher::monitor(filename);
5626 // file_monitor_ will be destroyed with *this, so it is not going to call a
5627 // destroyed object method.
5628 file_monitor_->connect([this](bool exists) {
5629 fileExternallyModified(exists);
5634 void Buffer::Impl::fileExternallyModified(bool const exists)
5636 // ignore notifications after our own saving operations
5637 if (checksum_ == filename.checksum()) {
5638 LYXERR(Debug::FILES, "External modification but "
5639 "checksum unchanged: " << filename);
5642 // If the file has been deleted, only mark the file as dirty since it is
5643 // pointless to prompt for reloading. If later a file is moved into this
5644 // location, then the externally modified warning will appear then.
5646 externally_modified_ = true;
5647 // Update external modification notification.
5648 // Dirty buffers must be visible at all times.
5649 if (wa_ && wa_->unhide(owner_))
5650 wa_->updateTitles();
5652 // Unable to unhide the buffer (e.g. no GUI or not current View)
5657 bool Buffer::notifiesExternalModification() const
5659 return d->externally_modified_;
5663 void Buffer::clearExternalModification() const
5665 d->externally_modified_ = false;
5667 d->wa_->updateTitles();