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/alert.h"
87 #include "frontends/Delegates.h"
88 #include "frontends/WorkAreaManager.h"
90 #include "support/lassert.h"
91 #include "support/convert.h"
92 #include "support/debug.h"
93 #include "support/docstring_list.h"
94 #include "support/ExceptionMessage.h"
95 #include "support/FileMonitor.h"
96 #include "support/FileName.h"
97 #include "support/FileNameList.h"
98 #include "support/filetools.h"
99 #include "support/ForkedCalls.h"
100 #include "support/gettext.h"
101 #include "support/gzstream.h"
102 #include "support/lstrings.h"
103 #include "support/lyxalgo.h"
104 #include "support/mutex.h"
105 #include "support/os.h"
106 #include "support/Package.h"
107 #include "support/PathChanger.h"
108 #include "support/Systemcall.h"
109 #include "support/TempFile.h"
110 #include "support/textutils.h"
111 #include "support/types.h"
113 #include "support/bind.h"
125 using namespace lyx::support;
126 using namespace lyx::graphics;
130 namespace Alert = frontend::Alert;
131 namespace os = support::os;
135 int const LYX_FORMAT = LYX_FORMAT_LYX;
137 typedef map<string, bool> DepClean;
139 // Information about labels and their associated refs
144 InsetLabel const * inset;
145 /// associated references cache
146 Buffer::References references;
147 /// whether this label is active (i.e., not deleted)
151 typedef vector<LabelInfo> LabelCache;
153 typedef map<docstring, Buffer::References> RefCache;
158 // A storehouse for the cloned buffers.
159 list<CloneList *> cloned_buffers;
165 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
169 delete preview_loader_;
177 /// search for macro in local (buffer) table or in children
178 MacroData const * getBufferMacro(docstring const & name,
179 DocIterator const & pos) const;
181 /// Update macro table starting with position of it \param it in some
183 void updateMacros(DocIterator & it, DocIterator & scope);
185 void setLabel(ParIterator & it, UpdateType utype) const;
187 /** If we have branches that use the file suffix
188 feature, return the file name with suffix appended.
190 FileName exportFileName() const;
197 mutable TexRow texrow;
199 /// need to regenerate .tex?
203 mutable bool lyx_clean;
205 /// is autosave needed?
206 mutable bool bak_clean;
208 /// is this an unnamed file (New...)?
211 /// is this an internal bufffer?
212 bool internal_buffer;
217 /// name of the file the buffer is associated with.
220 /** Set to true only when the file is fully loaded.
221 * Used to prevent the premature generation of previews
222 * and by the citation inset.
224 bool file_fully_loaded;
226 /// original format of loaded file
229 /// if the file was originally loaded from an older format, do
230 /// we need to back it up still?
231 bool need_format_backup;
233 /// Ignore the parent (e.g. when exporting a child standalone)?
237 mutable TocBackend toc_backend;
242 ScopeMacro(DocIterator const & s, MacroData const & m)
243 : scope(s), macro(m) {}
247 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
248 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
249 /// map from the macro name to the position map,
250 /// which maps the macro definition position to the scope and the MacroData.
251 NamePositionScopeMacroMap macros;
252 /// This seem to change the way Buffer::getMacro() works
253 mutable bool macro_lock;
255 /// positions of child buffers in the buffer
256 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
258 ScopeBuffer() : buffer(0) {}
259 ScopeBuffer(DocIterator const & s, Buffer const * b)
260 : scope(s), buffer(b) {}
262 Buffer const * buffer;
264 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
265 /// position of children buffers in this buffer
266 BufferPositionMap children_positions;
267 /// map from children inclusion positions to their scope and their buffer
268 PositionScopeBufferMap position_to_children;
270 /// Contains the old buffer filePath() while saving-as, or the
271 /// directory where the document was last saved while loading.
274 /** Keeps track of the path of local layout files.
275 * If possible, it is always relative to the buffer path.
276 * Empty for layouts in system or user directory.
278 string layout_position;
280 /// Container for all sort of Buffer dependant errors.
281 map<string, ErrorList> errorLists;
283 /// checksum used to test if the file has been externally modified. Used to
284 /// double check whether the file had been externally modified when saving.
285 unsigned long checksum_;
288 frontend::WorkAreaManager * wa_;
290 frontend::GuiBufferDelegate * gui_;
295 /// A cache for the bibfiles (including bibfiles of loaded child
296 /// documents), needed for appropriate update of natbib labels.
297 mutable docstring_list bibfiles_cache_;
299 // FIXME The caching mechanism could be improved. At present, we have a
300 // cache for each Buffer, that caches all the bibliography info for that
301 // Buffer. A more efficient solution would be to have a global cache per
302 // file, and then to construct the Buffer's bibinfo from that.
303 /// A cache for bibliography info
304 mutable BiblioInfo bibinfo_;
305 /// whether the bibinfo cache is valid
306 mutable bool bibinfo_cache_valid_;
307 /// Cache of timestamps of .bib files
308 map<FileName, time_t> bibfile_status_;
309 /// Indicates whether the bibinfo has changed since the last time
310 /// we ran updateBuffer(), i.e., whether citation labels may need
312 mutable bool cite_labels_valid_;
313 /// Do we have a bibliography environment?
314 mutable bool have_bibitems_;
316 /// These two hold the file name and format, written to by
317 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
318 FileName preview_file_;
319 string preview_format_;
320 /// If there was an error when previewing, on the next preview we do
321 /// a fresh compile (e.g. in case the user installed a package that
325 /// Cache the references associated to a label and their positions
327 mutable RefCache ref_cache_;
328 /// Cache the label insets and their activity status.
329 mutable LabelCache label_cache_;
331 /// our Text that should be wrapped in an InsetText
335 PreviewLoader * preview_loader_;
337 /// This is here to force the test to be done whenever parent_buffer
339 Buffer const * parent() const
341 // ignore_parent temporarily "orphans" a buffer
342 // (e.g. if a child is compiled standalone)
345 // if parent_buffer is not loaded, then it has been unloaded,
346 // which means that parent_buffer is an invalid pointer. So we
347 // set it to null in that case.
348 // however, the BufferList doesn't know about cloned buffers, so
349 // they will always be regarded as unloaded. in that case, we hope
351 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
353 return parent_buffer;
357 void setParent(Buffer const * pb)
359 if (parent_buffer == pb)
362 if (!cloned_buffer_ && parent_buffer && pb)
363 LYXERR0("Warning: a buffer should not have two parents!");
365 if (!cloned_buffer_ && parent_buffer)
366 parent_buffer->invalidateBibinfoCache();
369 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
370 /// This one is useful for preview detached in a thread.
371 Buffer const * cloned_buffer_;
373 CloneList * clone_list_;
374 /// are we in the process of exporting this buffer?
375 mutable bool doing_export;
377 /// compute statistics
378 /// \p from initial position
379 /// \p to points to the end position
380 void updateStatistics(DocIterator & from, DocIterator & to,
381 bool skipNoOutput = true);
382 /// statistics accessor functions
383 int wordCount() const
387 int charCount(bool with_blanks) const
390 + (with_blanks ? blank_count_ : 0);
393 // does the buffer contain tracked changes? (if so, we automatically
394 // display the review toolbar, for instance)
395 mutable bool tracked_changes_present_;
397 // Make sure the file monitor monitors the good file.
398 void refreshFileMonitor();
400 /// Notify or clear of external modification
401 void fileExternallyModified(bool exists);
403 /// has been externally modified? Can be reset by the user.
404 mutable bool externally_modified_;
406 ///Binding LaTeX lines with buffer positions.
407 //Common routine for LaTeX and Reference errors listing.
408 void traverseErrors(TeXErrors::Errors::const_iterator err,
409 TeXErrors::Errors::const_iterator end,
410 ErrorList & errorList) const;
413 /// So we can force access via the accessors.
414 mutable Buffer const * parent_buffer;
420 FileMonitorPtr file_monitor_;
424 /// Creates the per buffer temporary directory
425 static FileName createBufferTmpDir()
427 // FIXME This would be the ideal application for a TempDir class (like
428 // TempFile but for directories)
433 Mutex::Locker locker(&mutex);
434 counter = convert<string>(count++);
436 // We are in our own directory. Why bother to mangle name?
437 // In fact I wrote this code to circumvent a problematic behaviour
438 // (bug?) of EMX mkstemp().
439 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
442 if (!tmpfl.createDirectory(0777)) {
443 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
444 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
445 from_utf8(tmpfl.absFileName())));
451 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
452 Buffer const * cloned_buffer)
453 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
454 internal_buffer(false), read_only(readonly_), filename(file),
455 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
456 ignore_parent(false), toc_backend(owner), macro_lock(false),
457 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
458 cite_labels_valid_(false), have_bibitems_(false), preview_error_(false),
459 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
460 clone_list_(0), doing_export(false),
461 tracked_changes_present_(0), externally_modified_(false), parent_buffer(0),
462 word_count_(0), char_count_(0), blank_count_(0)
464 refreshFileMonitor();
465 if (!cloned_buffer_) {
466 temppath = createBufferTmpDir();
467 lyxvc.setBuffer(owner_);
469 wa_ = new frontend::WorkAreaManager;
472 temppath = cloned_buffer_->d->temppath;
473 file_fully_loaded = true;
474 params = cloned_buffer_->d->params;
475 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
476 bibinfo_ = cloned_buffer_->d->bibinfo_;
477 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
478 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
479 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
480 have_bibitems_ = cloned_buffer_->d->have_bibitems_;
481 unnamed = cloned_buffer_->d->unnamed;
482 internal_buffer = cloned_buffer_->d->internal_buffer;
483 layout_position = cloned_buffer_->d->layout_position;
484 preview_file_ = cloned_buffer_->d->preview_file_;
485 preview_format_ = cloned_buffer_->d->preview_format_;
486 preview_error_ = cloned_buffer_->d->preview_error_;
487 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
491 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
492 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
494 LYXERR(Debug::INFO, "Buffer::Buffer()");
496 d->inset = new InsetText(*cloned_buffer->d->inset);
497 d->inset->setBuffer(*this);
498 // FIXME: optimize this loop somewhat, maybe by creating a new
499 // general recursive Inset::setId().
500 DocIterator it = doc_iterator_begin(this);
501 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
502 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
503 it.paragraph().setId(cloned_it.paragraph().id());
505 d->inset = new InsetText(this);
506 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
512 LYXERR(Debug::INFO, "Buffer::~Buffer()");
513 // here the buffer should take care that it is
514 // saved properly, before it goes into the void.
516 // GuiView already destroyed
520 // No need to do additional cleanups for internal buffer.
526 // this is in case of recursive includes: we won't try to delete
527 // ourselves as a child.
528 d->clone_list_->erase(this);
529 // loop over children
530 for (auto const & p : d->children_positions) {
531 Buffer * child = const_cast<Buffer *>(p.first);
532 if (d->clone_list_->erase(child))
535 // if we're the master buffer, then we should get rid of the list
538 // If this is not empty, we have leaked something. Worse, one of the
539 // children still has a reference to this list. But we will try to
540 // continue, rather than shut down.
541 LATTEST(d->clone_list_->empty());
542 list<CloneList *>::iterator it =
543 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
544 if (it == cloned_buffers.end()) {
545 // We will leak in this case, but it is safe to continue.
548 cloned_buffers.erase(it);
549 delete d->clone_list_;
551 // FIXME Do we really need to do this right before we delete d?
552 // clear references to children in macro tables
553 d->children_positions.clear();
554 d->position_to_children.clear();
556 // loop over children
557 for (auto const & p : d->children_positions) {
558 Buffer * child = const_cast<Buffer *>(p.first);
559 if (theBufferList().isLoaded(child)) {
560 if (theBufferList().isOthersChild(this, child))
563 theBufferList().release(child);
568 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
570 msg += emergencyWrite();
572 msg += " " + _("Save failed! Document is lost.");
574 Alert::warning(_("Attempting to close changed document!"), msg);
577 // FIXME Do we really need to do this right before we delete d?
578 // clear references to children in macro tables
579 d->children_positions.clear();
580 d->position_to_children.clear();
582 if (!d->temppath.destroyDirectory()) {
583 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
584 from_utf8(d->temppath.absFileName())));
593 Buffer * Buffer::cloneWithChildren() const
596 cloned_buffers.push_back(new CloneList);
597 CloneList * clones = cloned_buffers.back();
599 cloneWithChildren(bufmap, clones);
601 // make sure we got cloned
602 BufferMap::const_iterator bit = bufmap.find(this);
603 LASSERT(bit != bufmap.end(), return 0);
604 Buffer * cloned_buffer = bit->second;
606 return cloned_buffer;
610 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
612 // have we already been cloned?
613 if (bufmap.find(this) != bufmap.end())
616 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
618 // The clone needs its own DocumentClass, since running updateBuffer() will
619 // modify it, and we would otherwise be sharing it with the original Buffer.
620 buffer_clone->params().makeDocumentClass(true);
622 cap::switchBetweenClasses(
623 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
624 static_cast<InsetText &>(buffer_clone->inset()), el);
626 bufmap[this] = buffer_clone;
627 clones->insert(buffer_clone);
628 buffer_clone->d->clone_list_ = clones;
629 buffer_clone->d->macro_lock = true;
630 buffer_clone->d->children_positions.clear();
632 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
633 // math macro caches need to be rethought and simplified.
634 // I am not sure wether we should handle Buffer cloning here or in BufferList.
635 // Right now BufferList knows nothing about buffer clones.
636 for (auto const & p : d->position_to_children) {
637 DocIterator dit = p.first.clone(buffer_clone);
638 dit.setBuffer(buffer_clone);
639 Buffer * child = const_cast<Buffer *>(p.second.buffer);
641 child->cloneWithChildren(bufmap, clones);
642 BufferMap::iterator const bit = bufmap.find(child);
643 LASSERT(bit != bufmap.end(), continue);
644 Buffer * child_clone = bit->second;
646 Inset * inset = dit.nextInset();
647 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
648 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
649 inset_inc->setChildBuffer(child_clone);
650 child_clone->d->setParent(buffer_clone);
651 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
652 buffer_clone->setChild(dit, child_clone);
654 buffer_clone->d->macro_lock = false;
659 Buffer * Buffer::cloneBufferOnly() const {
660 cloned_buffers.push_back(new CloneList);
661 CloneList * clones = cloned_buffers.back();
662 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
664 // The clone needs its own DocumentClass, since running updateBuffer() will
665 // modify it, and we would otherwise be sharing it with the original Buffer.
666 buffer_clone->params().makeDocumentClass(true);
668 cap::switchBetweenClasses(
669 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
670 static_cast<InsetText &>(buffer_clone->inset()), el);
672 clones->insert(buffer_clone);
673 buffer_clone->d->clone_list_ = clones;
675 // we won't be cloning the children
676 buffer_clone->d->children_positions.clear();
681 bool Buffer::isClone() const
683 return d->cloned_buffer_;
687 void Buffer::changed(bool update_metrics) const
690 d->wa_->redrawAll(update_metrics);
694 frontend::WorkAreaManager & Buffer::workAreaManager() const
701 Text & Buffer::text() const
703 return d->inset->text();
707 Inset & Buffer::inset() const
713 BufferParams & Buffer::params()
719 BufferParams const & Buffer::params() const
725 BufferParams const & Buffer::masterParams() const
727 if (masterBuffer() == this)
730 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
731 // Copy child authors to the params. We need those pointers.
732 for (Author const & a : params().authors())
733 mparams.authors().record(a);
738 double Buffer::fontScalingFactor() const
740 return isExporting() ? 75.0 * params().html_math_img_scale
741 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
745 ParagraphList & Buffer::paragraphs()
747 return text().paragraphs();
751 ParagraphList const & Buffer::paragraphs() const
753 return text().paragraphs();
757 LyXVC & Buffer::lyxvc()
763 LyXVC const & Buffer::lyxvc() const
769 string const Buffer::temppath() const
771 return d->temppath.absFileName();
775 TexRow & Buffer::texrow()
781 TexRow const & Buffer::texrow() const
787 TocBackend & Buffer::tocBackend() const
789 return d->toc_backend;
793 Undo & Buffer::undo()
799 void Buffer::setChild(DocIterator const & dit, Buffer * child)
801 d->children_positions[child] = dit;
805 string Buffer::latexName(bool const no_path) const
807 FileName latex_name =
808 makeLatexName(d->exportFileName());
809 return no_path ? latex_name.onlyFileName()
810 : latex_name.absFileName();
814 FileName Buffer::Impl::exportFileName() const
816 docstring const branch_suffix =
817 params.branchlist().getFileNameSuffix();
818 if (branch_suffix.empty())
821 string const name = addExtension(filename.onlyFileNameWithoutExt()
822 + to_utf8(branch_suffix), filename.extension());
823 FileName res(filename.onlyPath().absFileName() + "/" + name);
829 string Buffer::logName(LogType * type) const
831 string const filename = latexName(false);
833 if (filename.empty()) {
839 string const path = temppath();
841 FileName const fname(addName(temppath(),
842 onlyFileName(changeExtension(filename,
845 // FIXME: how do we know this is the name of the build log?
846 FileName const bname(
847 addName(path, onlyFileName(
848 changeExtension(filename,
849 theFormats().extension(params().bufferFormat()) + ".out"))));
851 // Also consider the master buffer log file
852 FileName masterfname = fname;
853 LogType mtype = latexlog;
854 if (masterBuffer() != this) {
855 string const mlogfile = masterBuffer()->logName(&mtype);
856 masterfname = FileName(mlogfile);
859 // If no Latex log or Build log is newer, show Build log
860 if (bname.exists() &&
861 ((!fname.exists() && !masterfname.exists())
862 || (fname.lastModified() < bname.lastModified()
863 && masterfname.lastModified() < bname.lastModified()))) {
864 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
867 return bname.absFileName();
868 // If we have a newer master file log or only a master log, show this
869 } else if (fname != masterfname
870 && (!fname.exists() && (masterfname.exists()
871 || fname.lastModified() < masterfname.lastModified()))) {
872 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
875 return masterfname.absFileName();
877 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
880 return fname.absFileName();
884 void Buffer::setReadonly(bool const flag)
886 if (d->read_only != flag) {
893 void Buffer::setFileName(FileName const & fname)
895 bool const changed = fname != d->filename;
897 d->refreshFileMonitor();
899 lyxvc().file_found_hook(fname);
900 setReadonly(d->filename.isReadOnly());
906 int Buffer::readHeader(Lexer & lex)
908 int unknown_tokens = 0;
910 int begin_header_line = -1;
912 // Initialize parameters that may be/go lacking in header:
913 params().branchlist().clear();
914 params().preamble.erase();
915 params().options.erase();
916 params().master.erase();
917 params().float_placement.erase();
918 params().float_alignment.erase();
919 params().paperwidth.erase();
920 params().paperheight.erase();
921 params().leftmargin.erase();
922 params().rightmargin.erase();
923 params().topmargin.erase();
924 params().bottommargin.erase();
925 params().headheight.erase();
926 params().headsep.erase();
927 params().footskip.erase();
928 params().columnsep.erase();
929 params().font_roman_opts.erase();
930 params().font_sans_opts.erase();
931 params().font_typewriter_opts.erase();
932 params().fonts_cjk.erase();
933 params().listings_params.clear();
934 params().clearLayoutModules();
935 params().clearRemovedModules();
936 params().clearIncludedChildren();
937 params().pdfoptions().clear();
938 params().indiceslist().clear();
939 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
940 params().isbackgroundcolor = false;
941 params().fontcolor = RGBColor(0, 0, 0);
942 params().isfontcolor = false;
943 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
944 params().boxbgcolor = RGBColor(0xFF, 0, 0);
945 params().html_latex_start.clear();
946 params().html_latex_end.clear();
947 params().html_math_img_scale = 1.0;
948 params().output_sync_macro.erase();
949 params().setLocalLayout(docstring(), false);
950 params().setLocalLayout(docstring(), true);
951 params().biblio_opts.erase();
952 params().biblatex_bibstyle.erase();
953 params().biblatex_citestyle.erase();
954 params().multibib.erase();
955 params().lineno_opts.clear();
957 for (int i = 0; i < 4; ++i) {
958 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
959 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
962 ErrorList & errorList = d->errorLists["Parse"];
971 if (token == "\\end_header")
975 if (token == "\\begin_header") {
976 begin_header_line = line;
980 LYXERR(Debug::PARSER, "Handling document header token: `"
983 string const result =
984 params().readToken(lex, token, d->filename.onlyPath());
985 if (!result.empty()) {
986 if (token == "\\textclass") {
987 d->layout_position = result;
990 docstring const s = bformat(_("Unknown token: "
994 errorList.push_back(ErrorItem(_("Document header error"), s));
998 if (begin_header_line) {
999 docstring const s = _("\\begin_header is missing");
1000 errorList.push_back(ErrorItem(_("Document header error"), s));
1003 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
1005 params().makeDocumentClass();
1007 return unknown_tokens;
1012 // changed to be public and have one parameter
1013 // Returns true if "\end_document" is not read (Asger)
1014 bool Buffer::readDocument(Lexer & lex)
1016 ErrorList & errorList = d->errorLists["Parse"];
1019 // remove dummy empty par
1020 paragraphs().clear();
1022 if (!lex.checkFor("\\begin_document")) {
1023 docstring const s = _("\\begin_document is missing");
1024 errorList.push_back(ErrorItem(_("Document header error"), s));
1029 if (params().output_changes) {
1030 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1031 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1032 LaTeXFeatures::isAvailable("xcolor");
1034 if (!dvipost && !xcolorulem) {
1035 Alert::warning(_("Changes not shown in LaTeX output"),
1036 _("Changes will not be highlighted in LaTeX output, "
1037 "because neither dvipost nor xcolor/ulem are installed.\n"
1038 "Please install these packages or redefine "
1039 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1040 } else if (!xcolorulem) {
1041 Alert::warning(_("Changes not shown in LaTeX output"),
1042 _("Changes will not be highlighted in LaTeX output "
1043 "when using pdflatex, because xcolor and ulem are not installed.\n"
1044 "Please install both packages or redefine "
1045 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1049 if (!parent() && !params().master.empty()) {
1050 FileName const master_file = makeAbsPath(params().master,
1051 onlyPath(absFileName()));
1052 if (isLyXFileName(master_file.absFileName())) {
1054 checkAndLoadLyXFile(master_file, true);
1056 // necessary e.g. after a reload
1057 // to re-register the child (bug 5873)
1058 // FIXME: clean up updateMacros (here, only
1059 // child registering is needed).
1060 master->updateMacros();
1061 // set master as master buffer, but only
1062 // if we are a real child
1063 if (master->isChild(this))
1065 // if the master is not fully loaded
1066 // it is probably just loading this
1067 // child. No warning needed then.
1068 else if (master->isFullyLoaded())
1069 LYXERR0("The master '"
1071 << "' assigned to this document ("
1073 << ") does not include "
1074 "this document. Ignoring the master assignment.");
1075 // If the master has just been created, un-hide it (#11162)
1076 if (!master->fileName().exists())
1077 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1078 master->absFileName()));
1083 // assure we have a default index
1084 params().indiceslist().addDefault(B_("Index"));
1087 if (FileName::isAbsolute(params().origin))
1088 d->old_position = params().origin;
1090 d->old_position = filePath();
1091 bool const res = text().read(lex, errorList, d->inset);
1092 d->old_position.clear();
1094 // inform parent buffer about local macros
1096 Buffer const * pbuf = parent();
1097 for (auto const & m : usermacros)
1098 pbuf->usermacros.insert(m);
1102 updateMacroInstances(InternalUpdate);
1107 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1109 Format const * fmt = theFormats().getFormat(format);
1112 // It is important to use the correct extension here, since some
1113 // converters create a wrong output file otherwise (e.g. html2latex)
1114 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1115 ofdocstream os(name.toFilesystemEncoding().c_str());
1116 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1117 bool const success = !(os << contents).fail();
1120 bool converted = false;
1122 params().compressed = false;
1124 // remove dummy empty par
1125 paragraphs().clear();
1127 converted = importFile(format, name, errorList);
1130 removeTempFile(name);
1135 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1137 if (!theConverters().isReachable(format, "lyx"))
1140 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1141 Converters::RetVal const retval =
1142 theConverters().convert(0, name, lyx, name, format, "lyx", errorList);
1143 if (retval == Converters::SUCCESS) {
1144 bool const success = readFile(lyx) == ReadSuccess;
1145 removeTempFile(lyx);
1153 bool Buffer::readString(string const & s)
1155 params().compressed = false;
1158 istringstream is(s);
1160 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1161 FileName const fn = tempfile.name();
1164 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1166 if (success && file_format != LYX_FORMAT) {
1167 // We need to call lyx2lyx, so write the input to a file
1168 ofstream os(fn.toFilesystemEncoding().c_str());
1171 // lyxvc in readFile
1172 if (readFile(fn) != ReadSuccess)
1176 if (readDocument(lex))
1182 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1186 if (!lex.setFile(fname)) {
1187 Alert::error(_("File Not Found"),
1188 bformat(_("Unable to open file `%1$s'."),
1189 from_utf8(fn.absFileName())));
1190 return ReadFileNotFound;
1194 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1195 if (ret_plf != ReadSuccess)
1198 if (file_format != LYX_FORMAT) {
1200 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1201 if (ret_clf != ReadSuccess)
1203 ret_clf = readFile(tmpFile);
1204 if (ret_clf == ReadSuccess) {
1205 d->file_format = file_format;
1206 d->need_format_backup = true;
1211 // FIXME: InsetInfo needs to know whether the file is under VCS
1212 // during the parse process, so this has to be done before.
1213 lyxvc().file_found_hook(d->filename);
1215 if (readDocument(lex)) {
1216 Alert::error(_("Document format failure"),
1217 bformat(_("%1$s ended unexpectedly, which means"
1218 " that it is probably corrupted."),
1219 from_utf8(fn.absFileName())));
1220 return ReadDocumentFailure;
1223 d->file_fully_loaded = true;
1224 d->read_only = !d->filename.isWritable();
1225 params().compressed = theFormats().isZippedFile(d->filename);
1231 bool Buffer::isFullyLoaded() const
1233 return d->file_fully_loaded;
1237 void Buffer::setFullyLoaded(bool value)
1239 d->file_fully_loaded = value;
1243 bool Buffer::lastPreviewError() const
1245 return d->preview_error_;
1249 PreviewLoader * Buffer::loader() const
1251 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1253 if (!d->preview_loader_)
1254 d->preview_loader_ = new PreviewLoader(*this);
1255 return d->preview_loader_;
1259 void Buffer::removePreviews() const
1261 delete d->preview_loader_;
1262 d->preview_loader_ = 0;
1266 void Buffer::updatePreviews() const
1268 PreviewLoader * ploader = loader();
1272 InsetIterator it = inset_iterator_begin(*d->inset);
1273 InsetIterator const end = inset_iterator_end(*d->inset);
1274 for (; it != end; ++it)
1275 it->addPreview(it, *ploader);
1277 ploader->startLoading();
1281 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1282 FileName const & fn, int & file_format) const
1284 if(!lex.checkFor("\\lyxformat")) {
1285 Alert::error(_("Document format failure"),
1286 bformat(_("%1$s is not a readable LyX document."),
1287 from_utf8(fn.absFileName())));
1288 return ReadNoLyXFormat;
1294 // LyX formats 217 and earlier were written as 2.17. This corresponds
1295 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1296 // these cases. See also: www.lyx.org/trac/changeset/1313.
1297 size_t dot = tmp_format.find_first_of(".,");
1298 if (dot != string::npos)
1299 tmp_format.erase(dot, 1);
1301 file_format = convert<int>(tmp_format);
1306 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1307 FileName & tmpfile, int from_format)
1309 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1310 tempfile.setAutoRemove(false);
1311 tmpfile = tempfile.name();
1312 if(tmpfile.empty()) {
1313 Alert::error(_("Conversion failed"),
1314 bformat(_("%1$s is from a different"
1315 " version of LyX, but a temporary"
1316 " file for converting it could"
1317 " not be created."),
1318 from_utf8(fn.absFileName())));
1319 return LyX2LyXNoTempFile;
1322 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1323 if (lyx2lyx.empty()) {
1324 Alert::error(_("Conversion script not found"),
1325 bformat(_("%1$s is from a different"
1326 " version of LyX, but the"
1327 " conversion script lyx2lyx"
1328 " could not be found."),
1329 from_utf8(fn.absFileName())));
1330 return LyX2LyXNotFound;
1334 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1335 ostringstream command;
1336 command << os::python()
1337 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1338 << " -t " << convert<string>(LYX_FORMAT)
1339 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1340 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1341 string const command_str = command.str();
1343 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1345 cmd_ret const ret = runCommand(command_str);
1346 if (ret.first != 0) {
1347 if (from_format < LYX_FORMAT) {
1348 Alert::error(_("Conversion script failed"),
1349 bformat(_("%1$s is from an older version"
1350 " of LyX and the lyx2lyx script"
1351 " failed to convert it."),
1352 from_utf8(fn.absFileName())));
1353 return LyX2LyXOlderFormat;
1355 Alert::error(_("Conversion script failed"),
1356 bformat(_("%1$s is from a newer version"
1357 " of LyX and the lyx2lyx script"
1358 " failed to convert it."),
1359 from_utf8(fn.absFileName())));
1360 return LyX2LyXNewerFormat;
1367 FileName Buffer::getBackupName() const {
1368 map<int, string> const file_formats = {
1385 FileName const & fn = fileName();
1386 string const fname = fn.onlyFileNameWithoutExt();
1387 string const fext = fn.extension() + "~";
1388 string const fpath = lyxrc.backupdir_path.empty() ?
1389 fn.onlyPath().absFileName() :
1390 lyxrc.backupdir_path;
1391 string backup_suffix;
1392 // If file format is from a stable series use version instead of file format
1393 auto const it = file_formats.find(d->file_format);
1394 if (it != file_formats.end())
1395 backup_suffix = "-lyx" + it->second;
1397 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1398 string const backname = fname + backup_suffix;
1399 FileName backup(addName(fpath, addExtension(backname, fext)));
1401 // limit recursion, just in case
1403 unsigned long orig_checksum = 0;
1404 while (backup.exists() && v < 100) {
1405 if (orig_checksum == 0)
1406 orig_checksum = fn.checksum();
1407 unsigned long new_checksum = backup.checksum();
1408 if (orig_checksum == new_checksum) {
1409 LYXERR(Debug::FILES, "Not backing up " << fn <<
1410 "since " << backup << "has the same checksum.");
1411 // a bit of a hack, but we have to check this anyway
1412 // below, and setting this is simpler than introducing
1413 // a special boolean for this purpose.
1417 string const newbackname = backname + "-" + convert<string>(v);
1418 backup.set(addName(fpath, addExtension(newbackname, fext)));
1421 return v < 100 ? backup : FileName();
1425 // Should probably be moved to somewhere else: BufferView? GuiView?
1426 bool Buffer::save() const
1428 docstring const file = makeDisplayPath(absFileName(), 20);
1429 d->filename.refresh();
1431 // check the read-only status before moving the file as a backup
1432 if (d->filename.exists()) {
1433 bool const read_only = !d->filename.isWritable();
1435 Alert::warning(_("File is read-only"),
1436 bformat(_("The file %1$s cannot be written because it "
1437 "is marked as read-only."), file));
1442 // ask if the disk file has been externally modified (use checksum method)
1443 if (fileName().exists() && isChecksumModified()) {
1445 bformat(_("Document %1$s has been externally modified. "
1446 "Are you sure you want to overwrite this file?"), file);
1447 int const ret = Alert::prompt(_("Overwrite modified file?"),
1448 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1453 // We don't need autosaves in the immediate future. (Asger)
1454 resetAutosaveTimers();
1456 // if the file does not yet exist, none of the backup activity
1457 // that follows is necessary
1458 if (!fileName().exists()) {
1459 if (!writeFile(fileName()))
1465 // we first write the file to a new name, then move it to its
1466 // proper location once that has been done successfully. that
1467 // way we preserve the original file if something goes wrong.
1468 string const justname = fileName().onlyFileNameWithoutExt();
1469 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1470 justname + "-XXXXXX.lyx");
1471 bool const symlink = fileName().isSymLink();
1473 tempfile->setAutoRemove(false);
1475 FileName savefile(tempfile->name());
1476 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1477 if (!savefile.clonePermissions(fileName()))
1478 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1480 if (!writeFile(savefile))
1483 // we will set this to false if we fail
1484 bool made_backup = true;
1486 FileName backupName;
1487 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1489 if (d->need_format_backup)
1490 backupName = getBackupName();
1492 // If we for some reason failed to find a backup name in case of
1493 // a format change, this will still set one. It's the best we can
1495 if (backupName.empty()) {
1496 backupName.set(fileName().absFileName() + "~");
1497 if (!lyxrc.backupdir_path.empty()) {
1498 string const mangledName =
1499 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1500 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1504 LYXERR(Debug::FILES, "Backing up original file to " <<
1505 backupName.absFileName());
1506 // Except file is symlink do not copy because of #6587.
1507 // Hard links have bad luck.
1508 made_backup = symlink ?
1509 fileName().copyTo(backupName):
1510 fileName().moveTo(backupName);
1513 Alert::error(_("Backup failure"),
1514 bformat(_("Cannot create backup file %1$s.\n"
1515 "Please check whether the directory exists and is writable."),
1516 from_utf8(backupName.absFileName())));
1517 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1518 } else if (d->need_format_backup) {
1519 // the original file has been backed up successfully, so we
1520 // will not need to do that again
1521 d->need_format_backup = false;
1525 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1526 // Only do this if tempfile is not in autoremove mode
1529 // If we have no symlink, we can simply rename the temp file.
1530 // Otherwise, we need to copy it so the symlink stays intact.
1531 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1532 savefile.moveTo(fileName()))
1534 // saveCheckSum() was already called by writeFile(), but the
1535 // time stamp is invalidated by copying/moving
1538 if (d->file_format != LYX_FORMAT)
1539 // the file associated with this buffer is now in the current format
1540 d->file_format = LYX_FORMAT;
1543 // else we saved the file, but failed to move it to the right location.
1545 if (needBackup && made_backup && !symlink) {
1546 // the original file was moved to some new location, so it will look
1547 // to the user as if it was deleted. (see bug #9234.) we could try
1548 // to restore it, but that would basically mean trying to do again
1549 // what we just failed to do. better to leave things as they are.
1550 Alert::error(_("Write failure"),
1551 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1552 "But LyX could not move it to:\n %2$s.\n"
1553 "Your original file has been backed up to:\n %3$s"),
1554 from_utf8(savefile.absFileName()),
1555 from_utf8(fileName().absFileName()),
1556 from_utf8(backupName.absFileName())));
1558 // either we did not try to make a backup, or else we tried and failed,
1559 // or else the original file was a symlink, in which case it was copied,
1560 // not moved. so the original file is intact.
1561 Alert::error(_("Write failure"),
1562 bformat(_("Cannot move saved file to:\n %1$s.\n"
1563 "But the file has successfully been saved as:\n %2$s."),
1564 from_utf8(fileName().absFileName()),
1565 from_utf8(savefile.absFileName())));
1571 bool Buffer::writeFile(FileName const & fname) const
1573 if (d->read_only && fname == d->filename)
1576 bool retval = false;
1578 docstring const str = bformat(_("Saving document %1$s..."),
1579 makeDisplayPath(fname.absFileName()));
1582 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1584 if (params().compressed) {
1585 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1586 retval = ofs && write(ofs);
1588 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1589 retval = ofs && write(ofs);
1593 message(str + _(" could not write file!"));
1598 // removeAutosaveFile();
1601 message(str + _(" done."));
1607 docstring Buffer::emergencyWrite()
1609 // No need to save if the buffer has not changed.
1613 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1615 docstring user_message = bformat(
1616 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1618 // We try to save three places:
1619 // 1) Same place as document. Unless it is an unnamed doc.
1621 string s = absFileName();
1624 if (writeFile(FileName(s))) {
1626 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1627 return user_message;
1629 user_message += " " + _("Save failed! Trying again...\n");
1633 // 2) In HOME directory.
1634 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1636 lyxerr << ' ' << s << endl;
1637 if (writeFile(FileName(s))) {
1639 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1640 return user_message;
1643 user_message += " " + _("Save failed! Trying yet again...\n");
1645 // 3) In "/tmp" directory.
1646 // MakeAbsPath to prepend the current
1647 // drive letter on OS/2
1648 s = addName(package().temp_dir().absFileName(), absFileName());
1650 lyxerr << ' ' << s << endl;
1651 if (writeFile(FileName(s))) {
1653 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1654 return user_message;
1657 user_message += " " + _("Save failed! Document is lost.");
1660 return user_message;
1664 bool Buffer::write(ostream & ofs) const
1667 // Use the standard "C" locale for file output.
1668 ofs.imbue(locale::classic());
1671 // The top of the file should not be written by params().
1673 // write out a comment in the top of the file
1674 // Important: Keep the version formatting in sync with lyx2lyx and
1675 // tex2lyx (bug 7951)
1676 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1677 << " created this file. For more info see https://www.lyx.org/\n"
1678 << "\\lyxformat " << LYX_FORMAT << "\n"
1679 << "\\begin_document\n";
1681 /// For each author, set 'used' to true if there is a change
1682 /// by this author in the document; otherwise set it to 'false'.
1683 for (Author const & a : params().authors())
1686 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1687 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1688 for ( ; it != end; ++it)
1689 it->checkAuthors(params().authors());
1691 // now write out the buffer parameters.
1692 ofs << "\\begin_header\n";
1693 params().writeFile(ofs, this);
1694 ofs << "\\end_header\n";
1697 ofs << "\n\\begin_body\n";
1699 ofs << "\n\\end_body\n";
1701 // Write marker that shows file is complete
1702 ofs << "\\end_document" << endl;
1704 // Shouldn't really be needed....
1707 // how to check if close went ok?
1708 // Following is an attempt... (BE 20001011)
1710 // good() returns false if any error occurred, including some
1711 // formatting error.
1712 // bad() returns true if something bad happened in the buffer,
1713 // which should include file system full errors.
1718 lyxerr << "File was not closed properly." << endl;
1725 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1726 string const & original_path,
1727 OutputParams const & runparams_in,
1728 OutputWhat output) const
1730 OutputParams runparams = runparams_in;
1732 string const encoding = runparams.encoding->iconvName();
1733 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1736 try { ofs.reset(encoding); }
1737 catch (iconv_codecvt_facet_exception const & e) {
1738 lyxerr << "Caught iconv exception: " << e.what() << endl;
1739 Alert::error(_("Iconv software exception Detected"),
1740 bformat(_("Please verify that the `iconv' support software is"
1741 " properly installed and supports the selected encoding"
1742 " (%1$s), or change the encoding in"
1743 " Document>Settings>Language."), from_ascii(encoding)));
1746 if (!openFileWrite(ofs, fname))
1749 ErrorList & errorList = d->errorLists["Export"];
1751 ExportStatus status = ExportSuccess;
1754 // make sure we are ready to export
1755 // this needs to be done before we validate
1756 // FIXME Do we need to do this all the time? I.e., in children
1757 // of a master we are exporting?
1759 updateMacroInstances(OutputUpdate);
1761 ExportStatus retval;
1763 retval = writeLaTeXSource(os, original_path, runparams, output);
1764 if (retval == ExportKilled)
1765 return ExportKilled;
1767 catch (EncodingException const & e) {
1768 docstring const failed(1, e.failed_char);
1770 oss << "0x" << hex << e.failed_char << dec;
1771 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1772 docstring msg = bformat(_("Uncodable character '%1$s'"
1773 " (code point %2$s)"),
1774 failed, from_utf8(oss.str()));
1775 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1776 "representable in specific verbatim contexts.\n"
1777 "Changing the document encoding to utf8 could help."),
1778 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1780 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1781 " (code point %2$s)"),
1782 failed, from_utf8(oss.str()));
1783 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1784 "representable in the chosen encoding.\n"
1785 "Changing the document encoding to utf8 could help."),
1786 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1788 status = ExportError;
1790 catch (iconv_codecvt_facet_exception const & e) {
1791 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1793 status = ExportError;
1795 catch (exception const & e) {
1796 errorList.push_back(ErrorItem(_("conversion failed"),
1798 lyxerr << e.what() << endl;
1799 status = ExportError;
1802 lyxerr << "Caught some really weird exception..." << endl;
1806 d->texrow = move(os.texrow());
1810 status = ExportError;
1811 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1814 if (runparams_in.silent)
1822 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1823 string const & original_path,
1824 OutputParams const & runparams_in,
1825 OutputWhat output) const
1827 // The child documents, if any, shall be already loaded at this point.
1829 OutputParams runparams = runparams_in;
1831 // Some macros rely on font encoding
1832 runparams.main_fontenc = params().main_font_encoding();
1834 // If we are compiling a file standalone, even if this is the
1835 // child of some other buffer, let's cut the link here, so the
1836 // file is really independent and no concurring settings from
1837 // the master (e.g. branch state) interfere (see #8100).
1838 if (!runparams.is_child)
1839 d->ignore_parent = true;
1841 // Classify the unicode characters appearing in math insets
1842 BufferEncodings::initUnicodeMath(*this);
1844 // validate the buffer.
1845 LYXERR(Debug::LATEX, " Validating buffer...");
1846 LaTeXFeatures features(*this, params(), runparams);
1848 // This is only set once per document (in master)
1849 if (!runparams.is_child) {
1850 runparams.use_polyglossia = features.usePolyglossia();
1851 runparams.use_CJK = features.mustProvide("CJK");
1853 LYXERR(Debug::LATEX, " Buffer validation done.");
1855 bool const output_preamble =
1856 output == FullSource || output == OnlyPreamble;
1857 bool const output_body =
1858 output == FullSource || output == OnlyBody;
1860 // The starting paragraph of the coming rows is the
1861 // first paragraph of the document. (Asger)
1862 if (output_preamble && runparams.nice) {
1863 os << "%% LyX " << lyx_version << " created this file. "
1864 "For more info, see https://www.lyx.org/.\n"
1865 "%% Do not edit unless you really know what "
1868 LYXERR(Debug::INFO, "lyx document header finished");
1870 // There are a few differences between nice LaTeX and usual files:
1871 // usual files have \batchmode and special input@path to allow
1872 // inclusion of figures specified by an explicitly relative path
1873 // (i.e., a path starting with './' or '../') with either \input or
1874 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1875 // input@path is set when the actual parameter original_path is set.
1876 // This is done for usual tex-file, but not for nice-latex-file.
1877 // (Matthias 250696)
1878 // Note that input@path is only needed for something the user does
1879 // in the preamble, included .tex files or ERT, files included by
1880 // LyX work without it.
1881 if (output_preamble) {
1882 if (!runparams.nice) {
1883 // code for usual, NOT nice-latex-file
1884 os << "\\batchmode\n"; // changed from \nonstopmode
1886 if (!original_path.empty()) {
1888 // We don't know the encoding of inputpath
1889 docstring const inputpath = from_utf8(original_path);
1890 docstring uncodable_glyphs;
1891 Encoding const * const enc = runparams.encoding;
1893 for (size_t n = 0; n < inputpath.size(); ++n) {
1894 if (!enc->encodable(inputpath[n])) {
1895 docstring const glyph(1, inputpath[n]);
1896 LYXERR0("Uncodable character '"
1898 << "' in input path!");
1899 uncodable_glyphs += glyph;
1904 // warn user if we found uncodable glyphs.
1905 if (!uncodable_glyphs.empty()) {
1906 frontend::Alert::warning(
1907 _("Uncodable character in file path"),
1909 _("The path of your document\n"
1911 "contains glyphs that are unknown "
1912 "in the current document encoding "
1913 "(namely %2$s). This may result in "
1914 "incomplete output, unless "
1915 "TEXINPUTS contains the document "
1916 "directory and you don't use "
1917 "explicitly relative paths (i.e., "
1918 "paths starting with './' or "
1919 "'../') in the preamble or in ERT."
1920 "\n\nIn case of problems, choose "
1921 "an appropriate document encoding\n"
1922 "(such as utf8) or change the "
1924 inputpath, uncodable_glyphs));
1926 string docdir = os::latex_path(original_path);
1927 if (contains(docdir, '#')) {
1928 docdir = subst(docdir, "#", "\\#");
1929 os << "\\catcode`\\#=11"
1930 "\\def\\#{#}\\catcode`\\#=6\n";
1932 if (contains(docdir, '%')) {
1933 docdir = subst(docdir, "%", "\\%");
1934 os << "\\catcode`\\%=11"
1935 "\\def\\%{%}\\catcode`\\%=14\n";
1937 bool const detokenize = !isAscii(from_utf8(docdir))
1938 || contains(docdir, '~');
1939 bool const quote = contains(docdir, ' ');
1940 os << "\\makeatletter\n"
1941 << "\\def\\input@path{{";
1943 os << "\\detokenize{";
1952 << "\\makeatother\n";
1956 // get parent macros (if this buffer has a parent) which will be
1957 // written at the document begin further down.
1958 MacroSet parentMacros;
1959 listParentMacros(parentMacros, features);
1961 // Write the preamble
1962 runparams.use_babel = params().writeLaTeX(os, features,
1963 d->filename.onlyPath());
1965 // Biblatex bibliographies are loaded here
1966 if (params().useBiblatex()) {
1967 vector<pair<docstring, string>> const bibfiles =
1968 prepareBibFilePaths(runparams, getBibfiles(), true);
1969 for (pair<docstring, string> const & file: bibfiles) {
1970 os << "\\addbibresource";
1971 if (!file.second.empty())
1972 os << "[bibencoding=" << file.second << "]";
1973 os << "{" << file.first << "}\n";
1977 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1978 && !features.hasOnlyPolyglossiaLanguages()) {
1981 vector<string> bll = features.getBabelExclusiveLanguages();
1982 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1985 for (string const & sit : bll) {
1990 blangs = bll.size() > 1 ?
1991 bformat(_("The languages %1$s are only supported by Babel."), langs)
1992 : bformat(_("The language %1$s is only supported by Babel."), langs);
1996 for (string const & pit : pll) {
2001 plangs = pll.size() > 1 ?
2002 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
2003 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
2004 if (!blangs.empty())
2008 frontend::Alert::warning(
2009 _("Incompatible Languages!"),
2011 _("You cannot use the following languages "
2012 "together in one LaTeX document because "
2013 "they require conflicting language packages:\n"
2018 // Japanese might be required only in some children of a document,
2019 // but once required, we must keep use_japanese true.
2020 runparams.use_japanese |= features.isRequired("japanese");
2023 // Restore the parenthood if needed
2024 if (!runparams.is_child)
2025 d->ignore_parent = false;
2026 return ExportSuccess;
2030 // mark the beginning of the body to separate it from InPreamble insets
2031 os.texrow().start(TexRow::beginDocument());
2032 os << "\\begin{document}\n";
2034 // mark the start of a new paragraph by simulating a newline,
2035 // so that os.afterParbreak() returns true at document start
2038 // output the parent macros
2039 for (auto const & mac : parentMacros) {
2040 int num_lines = mac->write(os.os(), true);
2041 os.texrow().newlines(num_lines);
2044 } // output_preamble
2046 LYXERR(Debug::INFO, "preamble finished, now the body.");
2050 latexParagraphs(*this, text(), os, runparams);
2052 catch (ConversionException const &) { return ExportKilled; }
2054 // Restore the parenthood if needed
2055 if (!runparams.is_child)
2056 d->ignore_parent = false;
2058 // add this just in case after all the paragraphs
2061 if (output_preamble) {
2062 os << "\\end{document}\n";
2063 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2065 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2067 runparams_in.encoding = runparams.encoding;
2069 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2070 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2071 return ExportSuccess;
2075 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2076 OutputParams const & runparams,
2077 OutputWhat output) const
2079 LYXERR(Debug::LATEX, "makeDocBookFile...");
2082 if (!openFileWrite(ofs, fname))
2085 // make sure we are ready to export
2086 // this needs to be done before we validate
2088 updateMacroInstances(OutputUpdate);
2090 ExportStatus const retval =
2091 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2092 if (retval == ExportKilled)
2093 return ExportKilled;
2097 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2098 return ExportSuccess;
2102 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os, string const & fname,
2103 OutputParams const & runparams,
2104 OutputWhat output) const
2106 LaTeXFeatures features(*this, params(), runparams);
2111 DocumentClass const & tclass = params().documentClass();
2112 string const & top_element = tclass.latexname();
2114 bool const output_preamble =
2115 output == FullSource || output == OnlyPreamble;
2116 bool const output_body =
2117 output == FullSource || output == OnlyBody;
2119 if (output_preamble) {
2120 if (runparams.flavor == OutputParams::XML)
2121 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2124 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2127 if (! tclass.class_header().empty())
2128 os << from_ascii(tclass.class_header());
2129 else if (runparams.flavor == OutputParams::XML)
2130 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2131 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2133 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2135 docstring preamble = params().preamble;
2136 if (runparams.flavor != OutputParams::XML ) {
2137 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2138 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2139 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2140 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2143 string const name = runparams.nice
2144 ? changeExtension(absFileName(), ".sgml") : fname;
2145 preamble += features.getIncludedFiles(name);
2146 preamble += features.getLyXSGMLEntities();
2148 if (!preamble.empty()) {
2149 os << "\n [ " << preamble << " ]";
2155 string top = top_element;
2157 if (runparams.flavor == OutputParams::XML)
2158 top += params().language->code();
2160 top += params().language->code().substr(0, 2);
2163 if (!params().options.empty()) {
2165 top += params().options;
2168 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2169 << " file was created by LyX " << lyx_version
2170 << "\n See https://www.lyx.org/ for more information -->\n";
2172 params().documentClass().counters().reset();
2174 sgml::openTag(os, top);
2177 docbookParagraphs(text(), *this, os, runparams);
2179 catch (ConversionException const &) { return ExportKilled; }
2180 sgml::closeTag(os, top_element);
2182 return ExportSuccess;
2186 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2187 OutputParams const & runparams) const
2189 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2192 if (!openFileWrite(ofs, fname))
2195 // make sure we are ready to export
2196 // this has to be done before we validate
2197 updateBuffer(UpdateMaster, OutputUpdate);
2198 updateMacroInstances(OutputUpdate);
2200 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2201 if (retval == ExportKilled)
2206 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2211 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2212 OutputParams const & runparams,
2213 OutputWhat output) const
2215 LaTeXFeatures features(*this, params(), runparams);
2217 d->bibinfo_.makeCitationLabels(*this);
2219 bool const output_preamble =
2220 output == FullSource || output == OnlyPreamble;
2221 bool const output_body =
2222 output == FullSource || output == OnlyBody || output == IncludedFile;
2224 if (output_preamble) {
2225 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2226 << "<!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"
2227 // FIXME Language should be set properly.
2228 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2230 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2231 // FIXME Presumably need to set this right
2232 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2234 docstring const & doctitle = features.htmlTitle();
2236 << (doctitle.empty() ?
2237 from_ascii("LyX Document") :
2238 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2241 docstring styles = features.getTClassHTMLPreamble();
2242 if (!styles.empty())
2243 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2245 styles = features.getPreambleSnippets().str;
2246 if (!styles.empty())
2247 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2249 // we will collect CSS information in a stream, and then output it
2250 // either here, as part of the header, or else in a separate file.
2251 odocstringstream css;
2252 styles = features.getCSSSnippets();
2253 if (!styles.empty())
2254 css << "/* LyX Provided Styles */\n" << styles << '\n';
2256 styles = features.getTClassHTMLStyles();
2257 if (!styles.empty())
2258 css << "/* Layout-provided Styles */\n" << styles << '\n';
2260 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2261 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2262 if (needfg || needbg) {
2263 css << "\nbody {\n";
2266 << from_ascii(X11hexname(params().fontcolor))
2269 css << " background-color: "
2270 << from_ascii(X11hexname(params().backgroundcolor))
2275 docstring const dstyles = css.str();
2276 if (!dstyles.empty()) {
2277 bool written = false;
2278 if (params().html_css_as_file) {
2279 // open a file for CSS info
2281 string const fcssname = addName(temppath(), "docstyle.css");
2282 FileName const fcssfile = FileName(fcssname);
2283 if (openFileWrite(ocss, fcssfile)) {
2287 // write link to header
2288 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2290 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2293 // we are here if the CSS is supposed to be written to the header
2294 // or if we failed to write it to an external file.
2296 os << "<style type='text/css'>\n"
2305 bool const output_body_tag = (output != IncludedFile);
2306 if (output_body_tag)
2307 os << "<body dir=\"auto\">\n";
2309 if (output != IncludedFile)
2310 // if we're an included file, the counters are in the master.
2311 params().documentClass().counters().reset();
2313 xhtmlParagraphs(text(), *this, xs, runparams);
2315 catch (ConversionException const &) { return ExportKilled; }
2316 if (output_body_tag)
2320 if (output_preamble)
2323 return ExportSuccess;
2327 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2328 // Other flags: -wall -v0 -x
2329 int Buffer::runChktex()
2333 // get LaTeX-Filename
2334 FileName const path(temppath());
2335 string const name = addName(path.absFileName(), latexName());
2336 string const org_path = filePath();
2338 PathChanger p(path); // path to LaTeX file
2339 message(_("Running chktex..."));
2341 // Generate the LaTeX file if neccessary
2342 OutputParams runparams(¶ms().encoding());
2343 runparams.flavor = OutputParams::LATEX;
2344 runparams.nice = false;
2345 runparams.linelen = lyxrc.plaintext_linelen;
2346 ExportStatus const retval =
2347 makeLaTeXFile(FileName(name), org_path, runparams);
2348 if (retval != ExportSuccess) {
2349 // error code on failure
2354 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2355 int const res = chktex.run(terr); // run chktex
2358 Alert::error(_("chktex failure"),
2359 _("Could not run chktex successfully."));
2361 ErrorList & errlist = d->errorLists["ChkTeX"];
2363 bufferErrors(terr, errlist);
2368 if (runparams.silent)
2369 d->errorLists["ChkTeX"].clear();
2377 void Buffer::validate(LaTeXFeatures & features) const
2379 // Validate the buffer params, but not for included
2380 // files, since they also use the parent buffer's
2382 if (!features.runparams().is_child)
2383 params().validate(features);
2385 for (Paragraph const & p : paragraphs())
2386 p.validate(features);
2388 if (lyxerr.debugging(Debug::LATEX)) {
2389 features.showStruct();
2394 void Buffer::getLabelList(vector<docstring> & list) const
2396 // If this is a child document, use the master's list instead.
2398 masterBuffer()->getLabelList(list);
2403 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2404 for (auto const & tocit : *toc) {
2405 if (tocit.depth() == 0)
2406 list.push_back(tocit.str());
2411 void Buffer::invalidateBibinfoCache() const
2413 d->bibinfo_cache_valid_ = false;
2414 d->cite_labels_valid_ = false;
2415 removeBiblioTempFiles();
2416 // also invalidate the cache for the parent buffer
2417 Buffer const * const pbuf = d->parent();
2419 pbuf->invalidateBibinfoCache();
2423 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2425 // FIXME This is probably unnecessary, given where we call this.
2426 // If this is a child document, use the master instead.
2427 Buffer const * const pbuf = masterBuffer();
2428 if (pbuf != this && scope != UpdateChildOnly)
2429 return pbuf->getBibfiles();
2431 // In 2.3.x, we have:
2432 //if (!d->bibfile_cache_valid_)
2433 // this->updateBibfilesCache(scope);
2434 // I think that is a leftover, but there have been so many back-
2435 // and-forths with this, due to Windows issues, that I am not sure.
2437 return d->bibfiles_cache_;
2441 BiblioInfo const & Buffer::masterBibInfo() const
2443 Buffer const * const tmp = masterBuffer();
2445 return tmp->masterBibInfo();
2450 BiblioInfo const & Buffer::bibInfo() const
2456 void Buffer::registerBibfiles(const docstring_list & bf) const
2458 // We register the bib files in the master buffer,
2459 // if there is one, but also in every single buffer,
2460 // in case a child is compiled alone.
2461 Buffer const * const tmp = masterBuffer();
2463 tmp->registerBibfiles(bf);
2465 for (auto const & p : bf) {
2466 docstring_list::const_iterator temp =
2467 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2468 if (temp == d->bibfiles_cache_.end())
2469 d->bibfiles_cache_.push_back(p);
2474 static map<docstring, FileName> bibfileCache;
2476 FileName Buffer::getBibfilePath(docstring const & bibid) const
2478 map<docstring, FileName>::const_iterator it =
2479 bibfileCache.find(bibid);
2480 if (it != bibfileCache.end()) {
2481 // i.e., return bibfileCache[bibid];
2485 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2486 string const texfile = changeExtension(to_utf8(bibid), "bib");
2487 // we need to check first if this file exists where it's said to be.
2488 // there's a weird bug that occurs otherwise: if the file is in the
2489 // Buffer's directory but has the same name as some file that would be
2490 // found by kpsewhich, then we find the latter, not the former.
2491 FileName const local_file = makeAbsPath(texfile, filePath());
2492 FileName file = local_file;
2493 if (!file.exists()) {
2494 // there's no need now to check whether the file can be found
2496 file = findtexfile(texfile, "bib", true);
2500 LYXERR(Debug::FILES, "Found at: " << file);
2502 bibfileCache[bibid] = file;
2503 return bibfileCache[bibid];
2507 void Buffer::checkIfBibInfoCacheIsValid() const
2509 // use the master's cache
2510 Buffer const * const tmp = masterBuffer();
2512 tmp->checkIfBibInfoCacheIsValid();
2516 // If we already know the cache is invalid, stop here.
2517 // This is important in the case when the bibliography
2518 // environment (rather than Bib[la]TeX) is used.
2519 // In that case, the timestamp check below gives no
2520 // sensible result. Rather than that, the cache will
2521 // be invalidated explicitly via invalidateBibInfoCache()
2522 // by the Bibitem inset.
2523 // Same applies for bib encoding changes, which trigger
2524 // invalidateBibInfoCache() by InsetBibtex.
2525 if (!d->bibinfo_cache_valid_)
2528 if (d->have_bibitems_) {
2529 // We have a bibliography environment.
2530 // Invalidate the bibinfo cache unconditionally.
2531 // Cite labels will get invalidated by the inset if needed.
2532 d->bibinfo_cache_valid_ = false;
2536 // OK. This is with Bib(la)tex. We'll assume the cache
2537 // is valid and change this if we find changes in the bibs.
2538 d->bibinfo_cache_valid_ = true;
2539 d->cite_labels_valid_ = true;
2541 // compare the cached timestamps with the actual ones.
2542 docstring_list const & bibfiles_cache = getBibfiles();
2543 for (auto const & bf : bibfiles_cache) {
2544 FileName const fn = getBibfilePath(bf);
2545 time_t lastw = fn.lastModified();
2546 time_t prevw = d->bibfile_status_[fn];
2547 if (lastw != prevw) {
2548 d->bibinfo_cache_valid_ = false;
2549 d->cite_labels_valid_ = false;
2550 d->bibfile_status_[fn] = lastw;
2556 void Buffer::clearBibFileCache() const
2558 bibfileCache.clear();
2562 void Buffer::reloadBibInfoCache(bool const force) const
2564 // we should not need to do this for internal buffers
2568 // use the master's cache
2569 Buffer const * const tmp = masterBuffer();
2571 tmp->reloadBibInfoCache(force);
2576 checkIfBibInfoCacheIsValid();
2577 if (d->bibinfo_cache_valid_)
2581 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2582 // re-read file locations when this info changes
2583 // FIXME Is this sufficient? Or should we also force that
2584 // in some other cases? If so, then it is easy enough to
2585 // add the following line in some other places.
2586 clearBibFileCache();
2587 d->bibinfo_.clear();
2588 FileNameList checkedFiles;
2589 d->have_bibitems_ = false;
2590 collectBibKeys(checkedFiles);
2591 d->bibinfo_cache_valid_ = true;
2595 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2597 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2598 it->collectBibKeys(it, checkedFiles);
2599 if (it->lyxCode() == BIBITEM_CODE) {
2601 parent()->d->have_bibitems_ = true;
2603 d->have_bibitems_ = true;
2609 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2611 // We add the biblio info to the master buffer,
2612 // if there is one, but also to every single buffer,
2613 // in case a child is compiled alone.
2614 BiblioInfo & bi = d->bibinfo_;
2615 bi.mergeBiblioInfo(bin);
2617 if (parent() != 0) {
2618 BiblioInfo & masterbi = parent()->d->bibinfo_;
2619 masterbi.mergeBiblioInfo(bin);
2624 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2626 // We add the bibtex info to the master buffer,
2627 // if there is one, but also to every single buffer,
2628 // in case a child is compiled alone.
2629 BiblioInfo & bi = d->bibinfo_;
2632 if (parent() != 0) {
2633 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2634 masterbi[key] = bin;
2639 void Buffer::makeCitationLabels() const
2641 Buffer const * const master = masterBuffer();
2642 return d->bibinfo_.makeCitationLabels(*master);
2646 void Buffer::invalidateCiteLabels() const
2648 masterBuffer()->d->cite_labels_valid_ = false;
2651 bool Buffer::citeLabelsValid() const
2653 return masterBuffer()->d->cite_labels_valid_;
2657 void Buffer::removeBiblioTempFiles() const
2659 // We remove files that contain LaTeX commands specific to the
2660 // particular bibliographic style being used, in order to avoid
2661 // LaTeX errors when we switch style.
2662 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2663 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2664 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2665 aux_file.removeFile();
2666 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2667 bbl_file.removeFile();
2668 // Also for the parent buffer
2669 Buffer const * const pbuf = parent();
2671 pbuf->removeBiblioTempFiles();
2675 bool Buffer::isDepClean(string const & name) const
2677 DepClean::const_iterator const it = d->dep_clean.find(name);
2678 if (it == d->dep_clean.end())
2684 void Buffer::markDepClean(string const & name)
2686 d->dep_clean[name] = true;
2690 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2693 // FIXME? if there is an Buffer LFUN that can be dispatched even
2694 // if internal, put a switch '(cmd.action)' here.
2700 switch (cmd.action()) {
2702 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2703 flag.setOnOff(hasReadonlyFlag());
2706 // FIXME: There is need for a command-line import.
2707 //case LFUN_BUFFER_IMPORT:
2709 case LFUN_BUFFER_AUTO_SAVE:
2712 case LFUN_BUFFER_EXPORT_CUSTOM:
2713 // FIXME: Nothing to check here?
2716 case LFUN_BUFFER_EXPORT: {
2717 docstring const arg = cmd.argument();
2718 if (arg == "custom") {
2722 string format = (arg.empty() || arg == "default") ?
2723 params().getDefaultOutputFormat() : to_utf8(arg);
2724 size_t pos = format.find(' ');
2725 if (pos != string::npos)
2726 format = format.substr(0, pos);
2727 enable = params().isExportable(format, false);
2729 flag.message(bformat(
2730 _("Don't know how to export to format: %1$s"), arg));
2734 case LFUN_BUILD_PROGRAM:
2735 enable = params().isExportable("program", false);
2738 case LFUN_BRANCH_ACTIVATE:
2739 case LFUN_BRANCH_DEACTIVATE:
2740 case LFUN_BRANCH_MASTER_ACTIVATE:
2741 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2742 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2743 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2744 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2745 : params().branchlist();
2746 docstring const branchName = cmd.argument();
2747 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2751 case LFUN_BRANCH_ADD:
2752 case LFUN_BRANCHES_RENAME:
2753 // if no Buffer is present, then of course we won't be called!
2756 case LFUN_BUFFER_LANGUAGE:
2757 enable = !isReadonly();
2760 case LFUN_BUFFER_VIEW_CACHE:
2761 (d->preview_file_).refresh();
2762 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2765 case LFUN_CHANGES_TRACK:
2766 flag.setEnabled(true);
2767 flag.setOnOff(params().track_changes);
2770 case LFUN_CHANGES_OUTPUT:
2771 flag.setEnabled(true);
2772 flag.setOnOff(params().output_changes);
2775 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2776 flag.setOnOff(params().compressed);
2779 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2780 flag.setOnOff(params().output_sync);
2783 case LFUN_BUFFER_ANONYMIZE:
2789 flag.setEnabled(enable);
2794 void Buffer::dispatch(string const & command, DispatchResult & result)
2796 return dispatch(lyxaction.lookupFunc(command), result);
2800 // NOTE We can end up here even if we have no GUI, because we are called
2801 // by LyX::exec to handled command-line requests. So we may need to check
2802 // whether we have a GUI or not. The boolean use_gui holds this information.
2803 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2806 // FIXME? if there is an Buffer LFUN that can be dispatched even
2807 // if internal, put a switch '(cmd.action())' here.
2808 dr.dispatched(false);
2811 string const argument = to_utf8(func.argument());
2812 // We'll set this back to false if need be.
2813 bool dispatched = true;
2814 // This handles undo groups automagically
2815 UndoGroupHelper ugh(this);
2817 switch (func.action()) {
2818 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2819 if (lyxvc().inUse()) {
2820 string log = lyxvc().toggleReadOnly();
2825 setReadonly(!hasReadonlyFlag());
2828 case LFUN_BUFFER_EXPORT: {
2829 string const format = (argument.empty() || argument == "default") ?
2830 params().getDefaultOutputFormat() : argument;
2831 ExportStatus const status = doExport(format, false);
2832 dr.setError(status != ExportSuccess);
2833 if (status != ExportSuccess)
2834 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2835 from_utf8(format)));
2839 case LFUN_BUILD_PROGRAM: {
2840 ExportStatus const status = doExport("program", true);
2841 dr.setError(status != ExportSuccess);
2842 if (status != ExportSuccess)
2843 dr.setMessage(_("Error generating literate programming code."));
2847 case LFUN_BUFFER_EXPORT_CUSTOM: {
2849 string command = split(argument, format_name, ' ');
2850 Format const * format = theFormats().getFormat(format_name);
2852 lyxerr << "Format \"" << format_name
2853 << "\" not recognized!"
2858 // The name of the file created by the conversion process
2861 // Output to filename
2862 if (format->name() == "lyx") {
2863 string const latexname = latexName(false);
2864 filename = changeExtension(latexname,
2865 format->extension());
2866 filename = addName(temppath(), filename);
2868 if (!writeFile(FileName(filename)))
2872 doExport(format_name, true, filename);
2875 // Substitute $$FName for filename
2876 if (!contains(command, "$$FName"))
2877 command = "( " + command + " ) < $$FName";
2878 command = subst(command, "$$FName", filename);
2880 // Execute the command in the background
2882 call.startscript(Systemcall::DontWait, command,
2883 filePath(), layoutPos());
2887 // FIXME: There is need for a command-line import.
2889 case LFUN_BUFFER_IMPORT:
2894 case LFUN_BUFFER_AUTO_SAVE:
2896 resetAutosaveTimers();
2899 case LFUN_BRANCH_ACTIVATE:
2900 case LFUN_BRANCH_DEACTIVATE:
2901 case LFUN_BRANCH_MASTER_ACTIVATE:
2902 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2903 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2904 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2905 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2908 docstring const branch_name = func.argument();
2909 // the case without a branch name is handled elsewhere
2910 if (branch_name.empty()) {
2914 Branch * branch = buf->params().branchlist().find(branch_name);
2916 LYXERR0("Branch " << branch_name << " does not exist.");
2918 docstring const msg =
2919 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2923 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2924 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2925 if (branch->isSelected() != activate) {
2926 buf->undo().recordUndoBufferParams(CursorData());
2927 branch->setSelected(activate);
2929 dr.screenUpdate(Update::Force);
2930 dr.forceBufferUpdate();
2935 case LFUN_BRANCH_ADD: {
2936 docstring branchnames = func.argument();
2937 if (branchnames.empty()) {
2941 BranchList & branch_list = params().branchlist();
2942 vector<docstring> const branches =
2943 getVectorFromString(branchnames, branch_list.separator());
2945 for (docstring const & branch_name : branches) {
2946 Branch * branch = branch_list.find(branch_name);
2948 LYXERR0("Branch " << branch_name << " already exists.");
2952 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2954 undo().recordUndoBufferParams(CursorData());
2955 branch_list.add(branch_name);
2956 branch = branch_list.find(branch_name);
2957 string const x11hexname = X11hexname(branch->color());
2958 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2959 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2961 dr.screenUpdate(Update::Force);
2969 case LFUN_BRANCHES_RENAME: {
2970 if (func.argument().empty())
2973 docstring const oldname = from_utf8(func.getArg(0));
2974 docstring const newname = from_utf8(func.getArg(1));
2975 InsetIterator it = inset_iterator_begin(inset());
2976 InsetIterator const end = inset_iterator_end(inset());
2977 bool success = false;
2978 for (; it != end; ++it) {
2979 if (it->lyxCode() == BRANCH_CODE) {
2980 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2981 if (ins.branch() == oldname) {
2982 undo().recordUndo(CursorData(it));
2983 ins.rename(newname);
2988 if (it->lyxCode() == INCLUDE_CODE) {
2989 // get buffer of external file
2990 InsetInclude const & ins =
2991 static_cast<InsetInclude const &>(*it);
2992 Buffer * child = ins.getChildBuffer();
2995 child->dispatch(func, dr);
3000 dr.screenUpdate(Update::Force);
3001 dr.forceBufferUpdate();
3006 case LFUN_BUFFER_VIEW_CACHE:
3007 if (!theFormats().view(*this, d->preview_file_,
3008 d->preview_format_))
3009 dr.setMessage(_("Error viewing the output file."));
3012 case LFUN_CHANGES_TRACK:
3013 if (params().save_transient_properties)
3014 undo().recordUndoBufferParams(CursorData());
3015 params().track_changes = !params().track_changes;
3016 if (!params().track_changes)
3017 dr.forceChangesUpdate();
3020 case LFUN_CHANGES_OUTPUT:
3021 if (params().save_transient_properties)
3022 undo().recordUndoBufferParams(CursorData());
3023 params().output_changes = !params().output_changes;
3024 if (params().output_changes) {
3025 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
3026 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
3027 LaTeXFeatures::isAvailable("xcolor");
3029 if (!dvipost && !xcolorulem) {
3030 Alert::warning(_("Changes not shown in LaTeX output"),
3031 _("Changes will not be highlighted in LaTeX output, "
3032 "because neither dvipost nor xcolor/ulem are installed.\n"
3033 "Please install these packages or redefine "
3034 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3035 } else if (!xcolorulem) {
3036 Alert::warning(_("Changes not shown in LaTeX output"),
3037 _("Changes will not be highlighted in LaTeX output "
3038 "when using pdflatex, because xcolor and ulem are not installed.\n"
3039 "Please install both packages or redefine "
3040 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3045 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3046 // turn compression on/off
3047 undo().recordUndoBufferParams(CursorData());
3048 params().compressed = !params().compressed;
3051 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3052 undo().recordUndoBufferParams(CursorData());
3053 params().output_sync = !params().output_sync;
3056 case LFUN_BUFFER_ANONYMIZE: {
3057 undo().recordUndoFullBuffer(CursorData());
3058 CursorData cur(doc_iterator_begin(this));
3059 for ( ; cur ; cur.forwardPar())
3060 cur.paragraph().anonymize();
3061 dr.forceBufferUpdate();
3062 dr.screenUpdate(Update::Force);
3070 dr.dispatched(dispatched);
3074 void Buffer::changeLanguage(Language const * from, Language const * to)
3076 LASSERT(from, return);
3077 LASSERT(to, return);
3079 for_each(par_iterator_begin(),
3081 bind(&Paragraph::changeLanguage, _1, params(), from, to));
3085 bool Buffer::isMultiLingual() const
3087 ParConstIterator end = par_iterator_end();
3088 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3089 if (it->isMultiLingual(params()))
3096 std::set<Language const *> Buffer::getLanguages() const
3098 std::set<Language const *> langs;
3099 getLanguages(langs);
3104 void Buffer::getLanguages(std::set<Language const *> & langs) const
3106 ParConstIterator end = par_iterator_end();
3107 // add the buffer language, even if it's not actively used
3108 langs.insert(language());
3109 // iterate over the paragraphs
3110 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3111 it->getLanguages(langs);
3113 ListOfBuffers clist = getDescendents();
3114 for (auto const & cit : clist)
3115 cit->getLanguages(langs);
3119 DocIterator Buffer::getParFromID(int const id) const
3121 Buffer * buf = const_cast<Buffer *>(this);
3123 // This means non-existent
3124 return doc_iterator_end(buf);
3126 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3127 if (it.paragraph().id() == id)
3130 return doc_iterator_end(buf);
3134 bool Buffer::hasParWithID(int const id) const
3136 return !getParFromID(id).atEnd();
3140 ParIterator Buffer::par_iterator_begin()
3142 return ParIterator(doc_iterator_begin(this));
3146 ParIterator Buffer::par_iterator_end()
3148 return ParIterator(doc_iterator_end(this));
3152 ParConstIterator Buffer::par_iterator_begin() const
3154 return ParConstIterator(doc_iterator_begin(this));
3158 ParConstIterator Buffer::par_iterator_end() const
3160 return ParConstIterator(doc_iterator_end(this));
3164 Language const * Buffer::language() const
3166 return params().language;
3170 docstring const Buffer::B_(string const & l10n) const
3172 return params().B_(l10n);
3176 bool Buffer::isClean() const
3178 return d->lyx_clean;
3182 bool Buffer::isChecksumModified() const
3184 LASSERT(d->filename.exists(), return false);
3185 return d->checksum_ != d->filename.checksum();
3189 void Buffer::saveCheckSum() const
3191 FileName const & file = d->filename;
3193 d->checksum_ = file.exists() ? file.checksum()
3194 : 0; // in the case of save to a new file.
3198 void Buffer::markClean() const
3200 if (!d->lyx_clean) {
3201 d->lyx_clean = true;
3204 // if the .lyx file has been saved, we don't need an
3206 d->bak_clean = true;
3207 d->undo_.markDirty();
3208 clearExternalModification();
3212 void Buffer::setUnnamed(bool flag)
3218 bool Buffer::isUnnamed() const
3225 /// Don't check unnamed, here: isInternal() is used in
3226 /// newBuffer(), where the unnamed flag has not been set by anyone
3227 /// yet. Also, for an internal buffer, there should be no need for
3228 /// retrieving fileName() nor for checking if it is unnamed or not.
3229 bool Buffer::isInternal() const
3231 return d->internal_buffer;
3235 void Buffer::setInternal(bool flag)
3237 d->internal_buffer = flag;
3241 void Buffer::markDirty()
3244 d->lyx_clean = false;
3247 d->bak_clean = false;
3249 for (auto & depit : d->dep_clean)
3250 depit.second = false;
3254 FileName Buffer::fileName() const
3260 string Buffer::absFileName() const
3262 return d->filename.absFileName();
3266 string Buffer::filePath() const
3268 string const abs = d->filename.onlyPath().absFileName();
3271 int last = abs.length() - 1;
3273 return abs[last] == '/' ? abs : abs + '/';
3277 DocFileName Buffer::getReferencedFileName(string const & fn) const
3280 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3281 result.set(fn, filePath());
3283 // filePath() ends with a path separator
3284 FileName const test(filePath() + fn);
3286 result.set(fn, filePath());
3288 result.set(fn, params().origin);
3295 string const Buffer::prepareFileNameForLaTeX(string const & name,
3296 string const & ext, bool nice) const
3298 string const fname = makeAbsPath(name, filePath()).absFileName();
3299 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3305 return to_utf8(makeRelPath(from_utf8(fname),
3306 from_utf8(masterBuffer()->filePath())));
3310 vector<pair<docstring, string>> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3311 docstring_list const & bibfilelist,
3312 bool const add_extension) const
3314 // If we are processing the LaTeX file in a temp directory then
3315 // copy the .bib databases to this temp directory, mangling their
3316 // names in the process. Store this mangled name in the list of
3318 // (We need to do all this because BibTeX *really*, *really*
3319 // can't handle "files with spaces" and Windows users tend to
3320 // use such filenames.)
3321 // Otherwise, store the (maybe absolute) path to the original,
3322 // unmangled database name.
3324 vector<pair<docstring, string>> res;
3326 // determine the export format
3327 string const tex_format = flavor2format(runparams.flavor);
3329 // check for spaces in paths
3330 bool found_space = false;
3332 for (auto const & bit : bibfilelist) {
3333 string utf8input = to_utf8(bit);
3335 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3336 FileName try_in_file =
3337 makeAbsPath(database + ".bib", filePath());
3338 bool not_from_texmf = try_in_file.isReadableFile();
3339 // If the file has not been found, try with the real file name
3340 // (it might come from a child in a sub-directory)
3341 if (!not_from_texmf) {
3342 try_in_file = getBibfilePath(bit);
3343 if (try_in_file.isReadableFile()) {
3344 // Check if the file is in texmf
3345 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3346 not_from_texmf = kpsefile.empty()
3347 || kpsefile.absFileName() != try_in_file.absFileName();
3349 // If this exists, make path relative to the master
3352 removeExtension(prepareFileNameForLaTeX(
3353 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3354 from_utf8(filePath()))),
3355 ".bib", runparams.nice));
3359 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3361 // mangledFileName() needs the extension
3362 DocFileName const in_file = DocFileName(try_in_file);
3363 database = removeExtension(in_file.mangledFileName());
3364 FileName const out_file = makeAbsPath(database + ".bib",
3365 masterBuffer()->temppath());
3366 bool const success = in_file.copyTo(out_file);
3368 LYXERR0("Failed to copy '" << in_file
3369 << "' to '" << out_file << "'");
3371 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3372 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3373 if (!isValidLaTeXFileName(database)) {
3374 frontend::Alert::warning(_("Invalid filename"),
3375 _("The following filename will cause troubles "
3376 "when running the exported file through LaTeX: ") +
3377 from_utf8(database));
3379 if (!isValidDVIFileName(database)) {
3380 frontend::Alert::warning(_("Problematic filename for DVI"),
3381 _("The following filename can cause troubles "
3382 "when running the exported file through LaTeX "
3383 "and opening the resulting DVI: ") +
3384 from_utf8(database), true);
3392 docstring const path = from_utf8(latex_path(database));
3394 if (contains(path, ' '))
3397 if (params().useBiblatex() && !params().bibFileEncoding(utf8input).empty())
3398 enc = params().bibFileEncoding(utf8input);
3400 bool recorded = false;
3401 for (pair<docstring, string> pe : res) {
3402 if (pe.first == path) {
3409 res.push_back(make_pair(path, enc));
3412 // Check if there are spaces in the path and warn BibTeX users, if so.
3413 // (biber can cope with such paths)
3414 if (!prefixIs(runparams.bibtex_command, "biber")) {
3415 // Post this warning only once.
3416 static bool warned_about_spaces = false;
3417 if (!warned_about_spaces &&
3418 runparams.nice && found_space) {
3419 warned_about_spaces = true;
3420 Alert::warning(_("Export Warning!"),
3421 _("There are spaces in the paths to your BibTeX databases.\n"
3422 "BibTeX will be unable to find them."));
3431 string Buffer::layoutPos() const
3433 return d->layout_position;
3437 void Buffer::setLayoutPos(string const & path)
3440 d->layout_position.clear();
3444 LATTEST(FileName::isAbsolute(path));
3446 d->layout_position =
3447 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3449 if (d->layout_position.empty())
3450 d->layout_position = ".";
3454 bool Buffer::hasReadonlyFlag() const
3456 return d->read_only;
3460 bool Buffer::isReadonly() const
3462 return hasReadonlyFlag() || notifiesExternalModification();
3466 void Buffer::setParent(Buffer const * buffer)
3468 // Avoids recursive include.
3469 d->setParent(buffer == this ? 0 : buffer);
3474 Buffer const * Buffer::parent() const
3480 ListOfBuffers Buffer::allRelatives() const
3482 ListOfBuffers lb = masterBuffer()->getDescendents();
3483 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3488 Buffer const * Buffer::masterBuffer() const
3490 // FIXME Should be make sure we are not in some kind
3491 // of recursive include? A -> B -> A will crash this.
3492 Buffer const * const pbuf = d->parent();
3496 return pbuf->masterBuffer();
3500 bool Buffer::isChild(Buffer * child) const
3502 return d->children_positions.find(child) != d->children_positions.end();
3506 DocIterator Buffer::firstChildPosition(Buffer const * child)
3508 Impl::BufferPositionMap::iterator it;
3509 it = d->children_positions.find(child);
3510 if (it == d->children_positions.end())
3511 return DocIterator(this);
3516 bool Buffer::hasChildren() const
3518 return !d->children_positions.empty();
3522 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3524 // loop over children
3525 for (auto const & p : d->children_positions) {
3526 Buffer * child = const_cast<Buffer *>(p.first);
3528 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3529 if (bit != clist.end())
3531 clist.push_back(child);
3533 // there might be grandchildren
3534 child->collectChildren(clist, true);
3539 ListOfBuffers Buffer::getChildren() const
3542 collectChildren(v, false);
3543 // Make sure we have not included ourselves.
3544 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3545 if (bit != v.end()) {
3546 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3553 ListOfBuffers Buffer::getDescendents() const
3556 collectChildren(v, true);
3557 // Make sure we have not included ourselves.
3558 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3559 if (bit != v.end()) {
3560 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3567 template<typename M>
3568 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3573 typename M::const_iterator it = m.lower_bound(x);
3574 if (it == m.begin())
3582 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3583 DocIterator const & pos) const
3585 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3587 // if paragraphs have no macro context set, pos will be empty
3591 // we haven't found anything yet
3592 DocIterator bestPos = owner_->par_iterator_begin();
3593 MacroData const * bestData = 0;
3595 // find macro definitions for name
3596 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3597 if (nameIt != macros.end()) {
3598 // find last definition in front of pos or at pos itself
3599 PositionScopeMacroMap::const_iterator it
3600 = greatest_below(nameIt->second, pos);
3601 if (it != nameIt->second.end()) {
3603 // scope ends behind pos?
3604 if (pos < it->second.scope) {
3605 // Looks good, remember this. If there
3606 // is no external macro behind this,
3607 // we found the right one already.
3608 bestPos = it->first;
3609 bestData = &it->second.macro;
3613 // try previous macro if there is one
3614 if (it == nameIt->second.begin())
3621 // find macros in included files
3622 PositionScopeBufferMap::const_iterator it
3623 = greatest_below(position_to_children, pos);
3624 if (it == position_to_children.end())
3625 // no children before
3629 // do we know something better (i.e. later) already?
3630 if (it->first < bestPos )
3633 // scope ends behind pos?
3634 if (pos < it->second.scope
3635 && (cloned_buffer_ ||
3636 theBufferList().isLoaded(it->second.buffer))) {
3637 // look for macro in external file
3639 MacroData const * data
3640 = it->second.buffer->getMacro(name, false);
3643 bestPos = it->first;
3649 // try previous file if there is one
3650 if (it == position_to_children.begin())
3655 // return the best macro we have found
3660 MacroData const * Buffer::getMacro(docstring const & name,
3661 DocIterator const & pos, bool global) const
3666 // query buffer macros
3667 MacroData const * data = d->getBufferMacro(name, pos);
3671 // If there is a master buffer, query that
3672 Buffer const * const pbuf = d->parent();
3674 d->macro_lock = true;
3675 MacroData const * macro = pbuf->getMacro(
3676 name, *this, false);
3677 d->macro_lock = false;
3683 data = MacroTable::globalMacros().get(name);
3692 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3694 // set scope end behind the last paragraph
3695 DocIterator scope = par_iterator_begin();
3696 scope.pit() = scope.lastpit() + 1;
3698 return getMacro(name, scope, global);
3702 MacroData const * Buffer::getMacro(docstring const & name,
3703 Buffer const & child, bool global) const
3705 // look where the child buffer is included first
3706 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3707 if (it == d->children_positions.end())
3710 // check for macros at the inclusion position
3711 return getMacro(name, it->second, global);
3715 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3717 pit_type const lastpit = it.lastpit();
3719 // look for macros in each paragraph
3720 while (it.pit() <= lastpit) {
3721 Paragraph & par = it.paragraph();
3723 // FIXME Can this be done with the new-style iterators?
3724 // iterate over the insets of the current paragraph
3725 for (auto const & insit : par.insetList()) {
3726 it.pos() = insit.pos;
3728 // is it a nested text inset?
3729 if (insit.inset->asInsetText()) {
3730 // Inset needs its own scope?
3731 InsetText const * itext = insit.inset->asInsetText();
3732 bool newScope = itext->isMacroScope();
3734 // scope which ends just behind the inset
3735 DocIterator insetScope = it;
3738 // collect macros in inset
3739 it.push_back(CursorSlice(*insit.inset));
3740 updateMacros(it, newScope ? insetScope : scope);
3745 if (insit.inset->asInsetTabular()) {
3746 CursorSlice slice(*insit.inset);
3747 size_t const numcells = slice.nargs();
3748 for (; slice.idx() < numcells; slice.forwardIdx()) {
3749 it.push_back(slice);
3750 updateMacros(it, scope);
3756 // is it an external file?
3757 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3758 // get buffer of external file
3759 InsetInclude const & incinset =
3760 static_cast<InsetInclude const &>(*insit.inset);
3762 Buffer * child = incinset.getChildBuffer();
3767 // register its position, but only when it is
3768 // included first in the buffer
3769 if (children_positions.find(child) ==
3770 children_positions.end())
3771 children_positions[child] = it;
3773 // register child with its scope
3774 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3778 InsetMath * im = insit.inset->asInsetMath();
3779 if (doing_export && im) {
3780 InsetMathHull * hull = im->asHullInset();
3782 hull->recordLocation(it);
3785 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3789 InsetMathMacroTemplate & macroTemplate =
3790 *insit.inset->asInsetMath()->asMacroTemplate();
3791 MacroContext mc(owner_, it);
3792 macroTemplate.updateToContext(mc);
3795 bool valid = macroTemplate.validMacro();
3796 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3797 // then the BufferView's cursor will be invalid in
3798 // some cases which leads to crashes.
3803 // FIXME (Abdel), I don't understand why we pass 'it' here
3804 // instead of 'macroTemplate' defined above... is this correct?
3805 macros[macroTemplate.name()][it] =
3806 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3816 void Buffer::updateMacros() const
3821 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3823 // start with empty table
3825 d->children_positions.clear();
3826 d->position_to_children.clear();
3828 // Iterate over buffer, starting with first paragraph
3829 // The scope must be bigger than any lookup DocIterator
3830 // later. For the global lookup, lastpit+1 is used, hence
3831 // we use lastpit+2 here.
3832 DocIterator it = par_iterator_begin();
3833 DocIterator outerScope = it;
3834 outerScope.pit() = outerScope.lastpit() + 2;
3835 d->updateMacros(it, outerScope);
3839 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3841 InsetIterator it = inset_iterator_begin(inset());
3842 InsetIterator const end = inset_iterator_end(inset());
3843 for (; it != end; ++it) {
3844 if (it->lyxCode() == BRANCH_CODE) {
3845 InsetBranch & br = static_cast<InsetBranch &>(*it);
3846 docstring const name = br.branch();
3847 if (!from_master && !params().branchlist().find(name))
3848 result.push_back(name);
3849 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3850 result.push_back(name);
3853 if (it->lyxCode() == INCLUDE_CODE) {
3854 // get buffer of external file
3855 InsetInclude const & ins =
3856 static_cast<InsetInclude const &>(*it);
3857 Buffer * child = ins.getChildBuffer();
3860 child->getUsedBranches(result, true);
3863 // remove duplicates
3868 void Buffer::updateMacroInstances(UpdateType utype) const
3870 LYXERR(Debug::MACROS, "updateMacroInstances for "
3871 << d->filename.onlyFileName());
3872 DocIterator it = doc_iterator_begin(this);
3874 DocIterator const end = doc_iterator_end(this);
3875 for (; it != end; it.forwardInset()) {
3876 // look for MathData cells in InsetMathNest insets
3877 InsetMath * minset = it.nextInset()->asInsetMath();
3881 // update macro in all cells of the InsetMathNest
3882 DocIterator::idx_type n = minset->nargs();
3883 MacroContext mc = MacroContext(this, it);
3884 for (DocIterator::idx_type i = 0; i < n; ++i) {
3885 MathData & data = minset->cell(i);
3886 data.updateMacros(0, mc, utype, 0);
3892 void Buffer::listMacroNames(MacroNameSet & macros) const
3897 d->macro_lock = true;
3899 // loop over macro names
3900 for (auto const & nameit : d->macros)
3901 macros.insert(nameit.first);
3903 // loop over children
3904 for (auto const & p : d->children_positions) {
3905 Buffer * child = const_cast<Buffer *>(p.first);
3906 // The buffer might have been closed (see #10766).
3907 if (theBufferList().isLoaded(child))
3908 child->listMacroNames(macros);
3912 Buffer const * const pbuf = d->parent();
3914 pbuf->listMacroNames(macros);
3916 d->macro_lock = false;
3920 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3922 Buffer const * const pbuf = d->parent();
3927 pbuf->listMacroNames(names);
3930 for (auto const & mit : names) {
3932 MacroData const * data = pbuf->getMacro(mit, *this, false);
3934 macros.insert(data);
3936 // we cannot access the original InsetMathMacroTemplate anymore
3937 // here to calls validate method. So we do its work here manually.
3938 // FIXME: somehow make the template accessible here.
3939 if (data->optionals() > 0)
3940 features.require("xargs");
3946 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3949 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3951 RefCache::iterator it = d->ref_cache_.find(label);
3952 if (it != d->ref_cache_.end())
3955 static References const dummy_refs = References();
3956 it = d->ref_cache_.insert(
3957 make_pair(label, dummy_refs)).first;
3962 Buffer::References const & Buffer::references(docstring const & label) const
3964 return const_cast<Buffer *>(this)->getReferenceCache(label);
3968 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3970 References & refs = getReferenceCache(label);
3971 refs.push_back(make_pair(inset, it));
3975 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3979 linfo.label = label;
3981 linfo.active = active;
3982 masterBuffer()->d->label_cache_.push_back(linfo);
3986 InsetLabel const * Buffer::insetLabel(docstring const & label,
3987 bool const active) const
3989 for (auto & rc : masterBuffer()->d->label_cache_) {
3990 if (rc.label == label && (rc.active || !active))
3997 bool Buffer::activeLabel(docstring const & label) const
3999 if (!insetLabel(label, true))
4006 void Buffer::clearReferenceCache() const
4009 d->ref_cache_.clear();
4010 d->label_cache_.clear();
4015 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
4017 //FIXME: This does not work for child documents yet.
4018 reloadBibInfoCache();
4020 // Check if the label 'from' appears more than once
4021 vector<docstring> labels;
4022 for (auto const & bibit : masterBibInfo())
4023 labels.push_back(bibit.first);
4025 if (count(labels.begin(), labels.end(), from) > 1)
4028 string const paramName = "key";
4029 InsetIterator it = inset_iterator_begin(inset());
4031 if (it->lyxCode() != CITE_CODE)
4033 InsetCommand * inset = it->asInsetCommand();
4034 docstring const oldValue = inset->getParam(paramName);
4035 if (oldValue == from)
4036 inset->setParam(paramName, to);
4040 // returns NULL if id-to-row conversion is unsupported
4041 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4042 pit_type par_begin, pit_type par_end,
4043 OutputWhat output, bool master) const
4045 unique_ptr<TexRow> texrow;
4046 OutputParams runparams(¶ms().encoding());
4047 runparams.nice = true;
4048 runparams.flavor = params().getOutputFlavor(format);
4049 runparams.linelen = lyxrc.plaintext_linelen;
4050 // No side effect of file copying and image conversion
4051 runparams.dryrun = true;
4053 // Some macros rely on font encoding
4054 runparams.main_fontenc = params().main_font_encoding();
4056 if (output == CurrentParagraph) {
4057 runparams.par_begin = par_begin;
4058 runparams.par_end = par_end;
4059 if (par_begin + 1 == par_end) {
4061 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4065 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4066 convert<docstring>(par_begin),
4067 convert<docstring>(par_end - 1))
4070 // output paragraphs
4071 if (runparams.flavor == OutputParams::LYX) {
4072 Paragraph const & par = text().paragraphs()[par_begin];
4074 depth_type dt = par.getDepth();
4075 par.write(ods, params(), dt);
4076 os << from_utf8(ods.str());
4077 } else if (runparams.flavor == OutputParams::HTML) {
4079 setMathFlavor(runparams);
4080 xhtmlParagraphs(text(), *this, xs, runparams);
4081 } else if (runparams.flavor == OutputParams::TEXT) {
4083 // FIXME Handles only one paragraph, unlike the others.
4084 // Probably should have some routine with a signature like them.
4085 writePlaintextParagraph(*this,
4086 text().paragraphs()[par_begin], os, runparams, dummy);
4087 } else if (params().isDocBook()) {
4088 docbookParagraphs(text(), *this, os, runparams);
4090 // If we are previewing a paragraph, even if this is the
4091 // child of some other buffer, let's cut the link here,
4092 // so that no concurring settings from the master
4093 // (e.g. branch state) interfere (see #8101).
4095 d->ignore_parent = true;
4096 // We need to validate the Buffer params' features here
4097 // in order to know if we should output polyglossia
4098 // macros (instead of babel macros)
4099 LaTeXFeatures features(*this, params(), runparams);
4101 runparams.use_polyglossia = features.usePolyglossia();
4102 // latex or literate
4105 ots.texrow().newlines(2);
4107 latexParagraphs(*this, text(), ots, runparams);
4108 texrow = ots.releaseTexRow();
4110 // Restore the parenthood
4112 d->ignore_parent = false;
4116 if (output == FullSource)
4117 os << _("Preview source code");
4118 else if (output == OnlyPreamble)
4119 os << _("Preview preamble");
4120 else if (output == OnlyBody)
4121 os << _("Preview body");
4123 if (runparams.flavor == OutputParams::LYX) {
4125 if (output == FullSource)
4127 else if (output == OnlyPreamble)
4128 params().writeFile(ods, this);
4129 else if (output == OnlyBody)
4131 os << from_utf8(ods.str());
4132 } else if (runparams.flavor == OutputParams::HTML) {
4133 writeLyXHTMLSource(os, runparams, output);
4134 } else if (runparams.flavor == OutputParams::TEXT) {
4135 if (output == OnlyPreamble) {
4136 os << "% "<< _("Plain text does not have a preamble.");
4138 writePlaintextFile(*this, os, runparams);
4139 } else if (params().isDocBook()) {
4140 writeDocBookSource(os, absFileName(), runparams, output);
4142 // latex or literate
4145 ots.texrow().newlines(2);
4147 runparams.is_child = true;
4149 writeLaTeXSource(ots, string(), runparams, output);
4150 texrow = ots.releaseTexRow();
4157 ErrorList & Buffer::errorList(string const & type) const
4159 return d->errorLists[type];
4163 void Buffer::updateTocItem(std::string const & type,
4164 DocIterator const & dit) const
4167 d->gui_->updateTocItem(type, dit);
4171 void Buffer::structureChanged() const
4174 d->gui_->structureChanged();
4178 void Buffer::errors(string const & err, bool from_master) const
4181 d->gui_->errors(err, from_master);
4185 void Buffer::message(docstring const & msg) const
4188 d->gui_->message(msg);
4192 void Buffer::setBusy(bool on) const
4195 d->gui_->setBusy(on);
4199 void Buffer::updateTitles() const
4202 d->wa_->updateTitles();
4206 void Buffer::resetAutosaveTimers() const
4209 d->gui_->resetAutosaveTimers();
4213 bool Buffer::hasGuiDelegate() const
4219 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4228 class AutoSaveBuffer : public ForkedProcess {
4231 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4232 : buffer_(buffer), fname_(fname) {}
4234 virtual shared_ptr<ForkedProcess> clone() const
4236 return make_shared<AutoSaveBuffer>(*this);
4241 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4242 from_utf8(fname_.absFileName())));
4243 return run(DontWait);
4247 virtual int generateChild();
4249 Buffer const & buffer_;
4254 int AutoSaveBuffer::generateChild()
4256 #if defined(__APPLE__)
4257 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4258 * We should use something else like threads.
4260 * Since I do not know how to determine at run time what is the OS X
4261 * version, I just disable forking altogether for now (JMarc)
4263 pid_t const pid = -1;
4265 // tmp_ret will be located (usually) in /tmp
4266 // will that be a problem?
4267 // Note that this calls ForkedCalls::fork(), so it's
4268 // ok cross-platform.
4269 pid_t const pid = fork();
4270 // If you want to debug the autosave
4271 // you should set pid to -1, and comment out the fork.
4272 if (pid != 0 && pid != -1)
4276 // pid = -1 signifies that lyx was unable
4277 // to fork. But we will do the save
4279 bool failed = false;
4280 TempFile tempfile("lyxautoXXXXXX.lyx");
4281 tempfile.setAutoRemove(false);
4282 FileName const tmp_ret = tempfile.name();
4283 if (!tmp_ret.empty()) {
4284 if (!buffer_.writeFile(tmp_ret))
4286 else if (!tmp_ret.moveTo(fname_))
4292 // failed to write/rename tmp_ret so try writing direct
4293 if (!buffer_.writeFile(fname_)) {
4294 // It is dangerous to do this in the child,
4295 // but safe in the parent, so...
4296 if (pid == -1) // emit message signal.
4297 buffer_.message(_("Autosave failed!"));
4301 if (pid == 0) // we are the child so...
4310 FileName Buffer::getEmergencyFileName() const
4312 return FileName(d->filename.absFileName() + ".emergency");
4316 FileName Buffer::getAutosaveFileName() const
4318 // if the document is unnamed try to save in the backup dir, else
4319 // in the default document path, and as a last try in the filePath,
4320 // which will most often be the temporary directory
4323 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4324 : lyxrc.backupdir_path;
4325 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4328 string const fname = "#" + d->filename.onlyFileName() + "#";
4330 return makeAbsPath(fname, fpath);
4334 void Buffer::removeAutosaveFile() const
4336 FileName const f = getAutosaveFileName();
4342 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4344 FileName const newauto = getAutosaveFileName();
4346 if (newauto != oldauto && oldauto.exists())
4347 if (!oldauto.moveTo(newauto))
4348 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4352 bool Buffer::autoSave() const
4354 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4355 if (buf->d->bak_clean || hasReadonlyFlag())
4358 message(_("Autosaving current document..."));
4359 buf->d->bak_clean = true;
4361 FileName const fname = getAutosaveFileName();
4362 LASSERT(d->cloned_buffer_, return false);
4364 // If this buffer is cloned, we assume that
4365 // we are running in a separate thread already.
4366 TempFile tempfile("lyxautoXXXXXX.lyx");
4367 tempfile.setAutoRemove(false);
4368 FileName const tmp_ret = tempfile.name();
4369 if (!tmp_ret.empty()) {
4371 // assume successful write of tmp_ret
4372 if (tmp_ret.moveTo(fname))
4375 // failed to write/rename tmp_ret so try writing direct
4376 return writeFile(fname);
4380 void Buffer::setExportStatus(bool e) const
4382 d->doing_export = e;
4383 ListOfBuffers clist = getDescendents();
4384 for (auto const & bit : clist)
4385 bit->d->doing_export = e;
4389 bool Buffer::isExporting() const
4391 return d->doing_export;
4395 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4399 return doExport(target, put_in_tempdir, result_file);
4402 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4403 string & result_file) const
4405 bool const update_unincluded =
4406 params().maintain_unincluded_children
4407 && !params().getIncludedChildren().empty();
4409 // (1) export with all included children (omit \includeonly)
4410 if (update_unincluded) {
4411 ExportStatus const status =
4412 doExport(target, put_in_tempdir, true, result_file);
4413 if (status != ExportSuccess)
4416 // (2) export with included children only
4417 return doExport(target, put_in_tempdir, false, result_file);
4421 void Buffer::setMathFlavor(OutputParams & op) const
4423 switch (params().html_math_output) {
4424 case BufferParams::MathML:
4425 op.math_flavor = OutputParams::MathAsMathML;
4427 case BufferParams::HTML:
4428 op.math_flavor = OutputParams::MathAsHTML;
4430 case BufferParams::Images:
4431 op.math_flavor = OutputParams::MathAsImages;
4433 case BufferParams::LaTeX:
4434 op.math_flavor = OutputParams::MathAsLaTeX;
4440 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4441 bool includeall, string & result_file) const
4443 LYXERR(Debug::FILES, "target=" << target);
4444 OutputParams runparams(¶ms().encoding());
4445 string format = target;
4446 string dest_filename;
4447 size_t pos = target.find(' ');
4448 if (pos != string::npos) {
4449 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4450 format = target.substr(0, pos);
4451 if (format == "default")
4452 format = params().getDefaultOutputFormat();
4453 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4454 FileName(dest_filename).onlyPath().createPath();
4455 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4457 MarkAsExporting exporting(this);
4458 string backend_format;
4459 runparams.flavor = OutputParams::LATEX;
4460 runparams.linelen = lyxrc.plaintext_linelen;
4461 runparams.includeall = includeall;
4462 vector<string> backs = params().backends();
4463 Converters converters = theConverters();
4464 bool need_nice_file = false;
4465 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4466 // Get shortest path to format
4467 converters.buildGraph();
4468 Graph::EdgePath path;
4469 for (string const & sit : backs) {
4470 Graph::EdgePath p = converters.getPath(sit, format);
4471 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4472 backend_format = sit;
4477 if (!put_in_tempdir) {
4478 // Only show this alert if this is an export to a non-temporary
4479 // file (not for previewing).
4480 docstring s = bformat(_("No information for exporting the format %1$s."),
4481 theFormats().prettyName(format));
4482 if (format == "pdf4")
4484 + bformat(_("Hint: use non-TeX fonts or set input encoding "
4485 " to '%1$s' or '%2$s'"),
4486 from_utf8(encodings.fromLyXName("utf8")->guiName()),
4487 from_utf8(encodings.fromLyXName("ascii")->guiName()));
4488 Alert::error(_("Couldn't export file"), s);
4490 return ExportNoPathToFormat;
4492 runparams.flavor = converters.getFlavor(path, this);
4493 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4494 for (auto const & edge : path)
4495 if (theConverters().get(edge).nice()) {
4496 need_nice_file = true;
4501 backend_format = format;
4502 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4503 // FIXME: Don't hardcode format names here, but use a flag
4504 if (backend_format == "pdflatex")
4505 runparams.flavor = OutputParams::PDFLATEX;
4506 else if (backend_format == "luatex")
4507 runparams.flavor = OutputParams::LUATEX;
4508 else if (backend_format == "dviluatex")
4509 runparams.flavor = OutputParams::DVILUATEX;
4510 else if (backend_format == "xetex")
4511 runparams.flavor = OutputParams::XETEX;
4514 string filename = latexName(false);
4515 filename = addName(temppath(), filename);
4516 filename = changeExtension(filename,
4517 theFormats().extension(backend_format));
4518 LYXERR(Debug::FILES, "filename=" << filename);
4520 // Plain text backend
4521 if (backend_format == "text") {
4522 runparams.flavor = OutputParams::TEXT;
4524 writePlaintextFile(*this, FileName(filename), runparams);
4526 catch (ConversionException const &) { return ExportCancel; }
4529 else if (backend_format == "xhtml") {
4530 runparams.flavor = OutputParams::HTML;
4531 setMathFlavor(runparams);
4532 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4533 return ExportKilled;
4534 } else if (backend_format == "lyx")
4535 writeFile(FileName(filename));
4537 else if (params().isDocBook()) {
4538 runparams.nice = !put_in_tempdir;
4539 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4540 return ExportKilled;
4543 else if (backend_format == format || need_nice_file) {
4544 runparams.nice = true;
4545 ExportStatus const retval =
4546 makeLaTeXFile(FileName(filename), string(), runparams);
4547 if (retval == ExportKilled)
4548 return ExportKilled;
4549 if (d->cloned_buffer_)
4550 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4551 if (retval != ExportSuccess)
4553 } else if (!lyxrc.tex_allows_spaces
4554 && contains(filePath(), ' ')) {
4555 Alert::error(_("File name error"),
4556 bformat(_("The directory path to the document\n%1$s\n"
4557 "contains spaces, but your TeX installation does "
4558 "not allow them. You should save the file to a directory "
4559 "whose name does not contain spaces."), from_utf8(filePath())));
4560 return ExportTexPathHasSpaces;
4562 runparams.nice = false;
4563 ExportStatus const retval =
4564 makeLaTeXFile(FileName(filename), filePath(), runparams);
4565 if (retval == ExportKilled)
4566 return ExportKilled;
4567 if (d->cloned_buffer_)
4568 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4569 if (retval != ExportSuccess)
4573 string const error_type = (format == "program")
4574 ? "Build" : params().bufferFormat();
4575 ErrorList & error_list = d->errorLists[error_type];
4576 string const ext = theFormats().extension(format);
4577 FileName const tmp_result_file(changeExtension(filename, ext));
4578 Converters::RetVal const retval =
4579 converters.convert(this, FileName(filename), tmp_result_file,
4580 FileName(absFileName()), backend_format, format, error_list);
4581 if (retval == Converters::KILLED)
4582 return ExportCancel;
4583 bool success = (retval == Converters::SUCCESS);
4585 // Emit the signal to show the error list or copy it back to the
4586 // cloned Buffer so that it can be emitted afterwards.
4587 if (format != backend_format) {
4588 if (runparams.silent)
4590 else if (d->cloned_buffer_)
4591 d->cloned_buffer_->d->errorLists[error_type] =
4592 d->errorLists[error_type];
4595 // also to the children, in case of master-buffer-view
4596 ListOfBuffers clist = getDescendents();
4597 for (auto const & bit : clist) {
4598 if (runparams.silent)
4599 bit->d->errorLists[error_type].clear();
4600 else if (d->cloned_buffer_) {
4601 // Enable reverse search by copying back the
4602 // texrow object to the cloned buffer.
4603 // FIXME: this is not thread safe.
4604 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4605 bit->d->cloned_buffer_->d->errorLists[error_type] =
4606 bit->d->errorLists[error_type];
4608 bit->errors(error_type, true);
4612 if (d->cloned_buffer_) {
4613 // Enable reverse dvi or pdf to work by copying back the texrow
4614 // object to the cloned buffer.
4615 // FIXME: There is a possibility of concurrent access to texrow
4616 // here from the main GUI thread that should be securized.
4617 d->cloned_buffer_->d->texrow = d->texrow;
4618 string const err_type = params().bufferFormat();
4619 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4623 if (put_in_tempdir) {
4624 result_file = tmp_result_file.absFileName();
4625 return success ? ExportSuccess : ExportConverterError;
4628 if (dest_filename.empty())
4629 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4631 result_file = dest_filename;
4632 // We need to copy referenced files (e. g. included graphics
4633 // if format == "dvi") to the result dir.
4634 vector<ExportedFile> const files =
4635 runparams.exportdata->externalFiles(format);
4636 string const dest = runparams.export_folder.empty() ?
4637 onlyPath(result_file) : runparams.export_folder;
4638 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4639 : force_overwrite == ALL_FILES;
4640 CopyStatus status = use_force ? FORCE : SUCCESS;
4642 for (ExportedFile const & exp : files) {
4643 if (status == CANCEL) {
4644 message(_("Document export cancelled."));
4645 return ExportCancel;
4647 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4648 string fixedName = exp.exportName;
4649 if (!runparams.export_folder.empty()) {
4650 // Relative pathnames starting with ../ will be sanitized
4651 // if exporting to a different folder
4652 while (fixedName.substr(0, 3) == "../")
4653 fixedName = fixedName.substr(3, fixedName.length() - 3);
4655 FileName fixedFileName = makeAbsPath(fixedName, dest);
4656 fixedFileName.onlyPath().createPath();
4657 status = copyFile(fmt, exp.sourceName,
4659 exp.exportName, status == FORCE,
4660 runparams.export_folder.empty());
4664 if (tmp_result_file.exists()) {
4665 // Finally copy the main file
4666 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4667 : force_overwrite != NO_FILES;
4668 if (status == SUCCESS && use_force)
4670 status = copyFile(format, tmp_result_file,
4671 FileName(result_file), result_file,
4673 if (status == CANCEL) {
4674 message(_("Document export cancelled."));
4675 return ExportCancel;
4677 message(bformat(_("Document exported as %1$s "
4679 theFormats().prettyName(format),
4680 makeDisplayPath(result_file)));
4683 // This must be a dummy converter like fax (bug 1888)
4684 message(bformat(_("Document exported as %1$s"),
4685 theFormats().prettyName(format)));
4688 return success ? ExportSuccess : ExportConverterError;
4692 Buffer::ExportStatus Buffer::preview(string const & format) const
4694 bool const update_unincluded =
4695 params().maintain_unincluded_children
4696 && !params().getIncludedChildren().empty();
4697 return preview(format, update_unincluded);
4701 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4703 MarkAsExporting exporting(this);
4705 // (1) export with all included children (omit \includeonly)
4707 ExportStatus const status = doExport(format, true, true, result_file);
4708 if (status != ExportSuccess)
4711 // (2) export with included children only
4712 ExportStatus const status = doExport(format, true, false, result_file);
4713 FileName const previewFile(result_file);
4715 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4716 theimpl->preview_file_ = previewFile;
4717 theimpl->preview_format_ = format;
4718 theimpl->preview_error_ = (status != ExportSuccess);
4720 if (status != ExportSuccess)
4723 if (previewFile.exists())
4724 return theFormats().view(*this, previewFile, format) ?
4725 PreviewSuccess : PreviewError;
4727 // Successful export but no output file?
4728 // Probably a bug in error detection.
4729 LATTEST(status != ExportSuccess);
4734 Buffer::ReadStatus Buffer::extractFromVC()
4736 bool const found = LyXVC::file_not_found_hook(d->filename);
4738 return ReadFileNotFound;
4739 if (!d->filename.isReadableFile())
4745 Buffer::ReadStatus Buffer::loadEmergency()
4747 FileName const emergencyFile = getEmergencyFileName();
4748 if (!emergencyFile.exists()
4749 || emergencyFile.lastModified() <= d->filename.lastModified())
4750 return ReadFileNotFound;
4752 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4753 docstring const text = bformat(_("An emergency save of the document "
4754 "%1$s exists.\n\nRecover emergency save?"), file);
4756 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4757 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4763 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4764 bool const success = (ret_llf == ReadSuccess);
4766 if (hasReadonlyFlag()) {
4767 Alert::warning(_("File is read-only"),
4768 bformat(_("An emergency file is successfully loaded, "
4769 "but the original file %1$s is marked read-only. "
4770 "Please make sure to save the document as a different "
4771 "file."), from_utf8(d->filename.absFileName())));
4774 lyxvc().file_found_hook(d->filename);
4775 str = _("Document was successfully recovered.");
4777 str = _("Document was NOT successfully recovered.");
4778 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4779 makeDisplayPath(emergencyFile.absFileName()));
4781 int const del_emerg =
4782 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4783 _("&Remove"), _("&Keep"));
4784 if (del_emerg == 0) {
4785 emergencyFile.removeFile();
4787 Alert::warning(_("Emergency file deleted"),
4788 _("Do not forget to save your file now!"), true);
4790 return success ? ReadSuccess : ReadEmergencyFailure;
4793 int const del_emerg =
4794 Alert::prompt(_("Delete emergency file?"),
4795 _("Remove emergency file now?"), 1, 1,
4796 _("&Remove"), _("&Keep"));
4798 emergencyFile.removeFile();
4802 string const ename = emergencyFile.absFileName();
4804 // Surely we can find one in 100 tries?
4805 for (int i = 1; i < 100; ++i) {
4806 newname.set(ename + to_string(i) + ".lyx");
4807 if (!newname.exists()) {
4813 // renameTo returns true on success. So inverting that
4814 // will give us true if we fail.
4815 noname = !emergencyFile.renameTo(newname);
4818 Alert::warning(_("Can't rename emergency file!"),
4819 _("LyX was unable to rename the emergency file. "
4820 "You should do so manually. Otherwise, you will be "
4821 "asked about it again the next time you try to load "
4822 "this file, and may over-write your own work."));
4824 Alert::warning(_("Emergency File Renames"),
4825 bformat(_("Emergency file renamed as:\n %1$s"),
4826 from_utf8(newname.onlyFileName())));
4829 return ReadOriginal;
4839 Buffer::ReadStatus Buffer::loadAutosave()
4841 // Now check if autosave file is newer.
4842 FileName const autosaveFile = getAutosaveFileName();
4843 if (!autosaveFile.exists()
4844 || autosaveFile.lastModified() <= d->filename.lastModified())
4845 return ReadFileNotFound;
4847 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4848 docstring const text = bformat(_("The backup of the document %1$s "
4849 "is newer.\n\nLoad the backup instead?"), file);
4850 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4851 _("&Load backup"), _("Load &original"), _("&Cancel"));
4856 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4857 // the file is not saved if we load the autosave file.
4858 if (ret_llf == ReadSuccess) {
4859 if (hasReadonlyFlag()) {
4860 Alert::warning(_("File is read-only"),
4861 bformat(_("A backup file is successfully loaded, "
4862 "but the original file %1$s is marked read-only. "
4863 "Please make sure to save the document as a "
4865 from_utf8(d->filename.absFileName())));
4868 lyxvc().file_found_hook(d->filename);
4871 return ReadAutosaveFailure;
4874 // Here we delete the autosave
4875 autosaveFile.removeFile();
4876 return ReadOriginal;
4884 Buffer::ReadStatus Buffer::loadLyXFile()
4886 if (!d->filename.isReadableFile()) {
4887 ReadStatus const ret_rvc = extractFromVC();
4888 if (ret_rvc != ReadSuccess)
4892 ReadStatus const ret_re = loadEmergency();
4893 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4896 ReadStatus const ret_ra = loadAutosave();
4897 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4900 return loadThisLyXFile(d->filename);
4904 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4906 return readFile(fn);
4910 void Buffer::Impl::traverseErrors(TeXErrors::Errors::const_iterator err, TeXErrors::Errors::const_iterator end, ErrorList & errorList) const
4912 for (; err != end; ++err) {
4913 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4914 int errorRow = err->error_in_line;
4915 Buffer const * buf = 0;
4916 Impl const * p = this;
4917 if (err->child_name.empty())
4918 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4920 // The error occurred in a child
4921 for (Buffer const * child : owner_->getDescendents()) {
4922 string const child_name =
4923 DocFileName(changeExtension(child->absFileName(), "tex")).
4925 if (err->child_name != child_name)
4927 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4928 if (!TexRow::isNone(start)) {
4929 buf = this->cloned_buffer_
4930 ? child->d->cloned_buffer_->d->owner_
4937 errorList.push_back(ErrorItem(err->error_desc, err->error_text,
4943 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4945 TeXErrors::Errors::const_iterator err = terr.begin();
4946 TeXErrors::Errors::const_iterator end = terr.end();
4948 d->traverseErrors(err, end, errorList);
4952 void Buffer::bufferRefs(TeXErrors const & terr, ErrorList & errorList) const
4954 TeXErrors::Errors::const_iterator err = terr.begin_ref();
4955 TeXErrors::Errors::const_iterator end = terr.end_ref();
4957 d->traverseErrors(err, end, errorList);
4961 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4963 LBUFERR(!text().paragraphs().empty());
4965 // Use the master text class also for child documents
4966 Buffer const * const master = masterBuffer();
4967 DocumentClass const & textclass = master->params().documentClass();
4969 docstring_list old_bibfiles;
4970 // Do this only if we are the top-level Buffer. We also need to account
4971 // for the case of a previewed child with ignored parent here.
4972 if (master == this && !d->ignore_parent) {
4973 textclass.counters().reset(from_ascii("bibitem"));
4974 reloadBibInfoCache();
4975 // we will re-read this cache as we go through, but we need
4976 // to know whether it's changed to know whether we need to
4977 // update the bibinfo cache.
4978 old_bibfiles = d->bibfiles_cache_;
4979 d->bibfiles_cache_.clear();
4982 // keep the buffers to be children in this set. If the call from the
4983 // master comes back we can see which of them were actually seen (i.e.
4984 // via an InsetInclude). The remaining ones in the set need still be updated.
4985 static std::set<Buffer const *> bufToUpdate;
4986 if (scope == UpdateMaster) {
4987 // If this is a child document start with the master
4988 if (master != this) {
4989 bufToUpdate.insert(this);
4990 master->updateBuffer(UpdateMaster, utype);
4991 // If the master buffer has no gui associated with it, then the TocModel is
4992 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4993 // (bug 5699). The same happens if the master buffer is open in a different
4994 // window. This test catches both possibilities.
4995 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4996 // There remains a problem here: If there is another child open in yet a third
4997 // window, that TOC is not updated. So some more general solution is needed at
4999 if (master->d->gui_ != d->gui_)
5002 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
5003 if (bufToUpdate.find(this) == bufToUpdate.end())
5007 // start over the counters in the master
5008 textclass.counters().reset();
5011 // update will be done below for this buffer
5012 bufToUpdate.erase(this);
5014 // update all caches
5015 clearReferenceCache();
5017 setChangesPresent(false);
5019 Buffer & cbuf = const_cast<Buffer &>(*this);
5020 // if we are reloading, then we could have a dangling TOC,
5021 // in effect. so we need to go ahead and reset, even though
5022 // we will do so again when we rebuild the TOC later.
5023 cbuf.tocBackend().reset();
5026 ParIterator parit = cbuf.par_iterator_begin();
5027 updateBuffer(parit, utype);
5029 // If this document has siblings, then update the TocBackend later. The
5030 // reason is to ensure that later siblings are up to date when e.g. the
5031 // broken or not status of references is computed. The update is called
5032 // in InsetInclude::addToToc.
5036 // if the bibfiles changed, the cache of bibinfo is invalid
5037 docstring_list new_bibfiles = d->bibfiles_cache_;
5038 // this is a trick to determine whether the two vectors have
5039 // the same elements.
5040 sort(new_bibfiles.begin(), new_bibfiles.end());
5041 sort(old_bibfiles.begin(), old_bibfiles.end());
5042 if (old_bibfiles != new_bibfiles) {
5043 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
5044 invalidateBibinfoCache();
5045 reloadBibInfoCache();
5046 // We relied upon the bibinfo cache when recalculating labels. But that
5047 // cache was invalid, although we didn't find that out until now. So we
5048 // have to do it all again.
5049 // That said, the only thing we really need to do is update the citation
5050 // labels. Nothing else will have changed. So we could create a new
5051 // UpdateType that would signal that fact, if we needed to do so.
5052 parit = cbuf.par_iterator_begin();
5053 // we will be re-doing the counters and references and such.
5054 textclass.counters().reset();
5055 clearReferenceCache();
5056 // we should not need to do this again?
5058 setChangesPresent(false);
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 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5315 // reduce depth if necessary
5316 if (parit->params().depth() > maxdepth) {
5317 /** FIXME: this function is const, but
5318 * nevertheless it modifies the buffer. To be
5319 * cleaner, one should modify the buffer in
5320 * another function, which is actually
5321 * non-const. This would however be costly in
5322 * terms of code duplication.
5324 CursorData(parit).recordUndo();
5325 parit->params().depth(maxdepth);
5327 maxdepth = parit->getMaxDepthAfter();
5329 if (utype == OutputUpdate) {
5330 // track the active counters
5331 // we have to do this for the master buffer, since the local
5332 // buffer isn't tracking anything.
5333 masterBuffer()->params().documentClass().counters().
5334 setActiveLayout(parit->layout());
5337 // set the counter for this paragraph
5338 d->setLabel(parit, utype);
5340 // update change-tracking flag
5341 parit->addChangesToBuffer(*this);
5344 for (auto const & insit : parit->insetList()) {
5345 parit.pos() = insit.pos;
5346 insit.inset->updateBuffer(parit, utype);
5352 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5353 WordLangTuple & word_lang, docstring_list & suggestions) const
5357 suggestions.clear();
5358 word_lang = WordLangTuple();
5359 bool const to_end = to.empty();
5360 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5361 // OK, we start from here.
5362 for (; from != end; from.forwardPos()) {
5363 // This skips all insets with spell check disabled.
5364 while (!from.allowSpellCheck()) {
5368 // If from is at the end of the document (which is possible
5369 // when "from" was changed above) LyX will crash later otherwise.
5370 if (from.atEnd() || (!to_end && from >= end))
5373 from.paragraph().spellCheck();
5374 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5375 if (SpellChecker::misspelled(res)) {
5379 // Do not increase progress when from == to, otherwise the word
5380 // count will be wrong.
5390 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5392 bool inword = false;
5397 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5398 if (!dit.inTexted()) {
5403 Paragraph const & par = dit.paragraph();
5404 pos_type const pos = dit.pos();
5406 // Copied and adapted from isWordSeparator() in Paragraph
5407 if (pos == dit.lastpos()) {
5410 Inset const * ins = par.getInset(pos);
5411 if (ins && skipNoOutput && !ins->producesOutput()) {
5414 // stop if end of range was skipped
5415 if (!to.atEnd() && dit >= to)
5418 } else if (!par.isDeleted(pos)) {
5419 if (par.isWordSeparator(pos))
5425 if (ins && ins->isLetter())
5427 else if (ins && ins->isSpace())
5430 char_type const c = par.getChar(pos);
5431 if (isPrintableNonspace(c))
5433 else if (isSpace(c))
5443 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5445 d->updateStatistics(from, to, skipNoOutput);
5449 int Buffer::wordCount() const
5451 return d->wordCount();
5455 int Buffer::charCount(bool with_blanks) const
5457 return d->charCount(with_blanks);
5461 Buffer::ReadStatus Buffer::reload()
5464 // c.f. bug https://www.lyx.org/trac/ticket/6587
5465 removeAutosaveFile();
5466 // e.g., read-only status could have changed due to version control
5467 d->filename.refresh();
5468 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5470 // clear parent. this will get reset if need be.
5472 ReadStatus const status = loadLyXFile();
5473 if (status == ReadSuccess) {
5478 message(bformat(_("Document %1$s reloaded."), disp_fn));
5481 message(bformat(_("Could not reload document %1$s."), disp_fn));
5491 bool Buffer::saveAs(FileName const & fn)
5493 FileName const old_name = fileName();
5494 FileName const old_auto = getAutosaveFileName();
5495 bool const old_unnamed = isUnnamed();
5496 bool success = true;
5497 d->old_position = filePath();
5504 // bring the autosave file with us, just in case.
5505 moveAutosaveFile(old_auto);
5506 // validate version control data and
5507 // correct buffer title
5508 lyxvc().file_found_hook(fileName());
5510 // the file has now been saved to the new location.
5511 // we need to check that the locations of child buffers
5513 checkChildBuffers();
5514 checkMasterBuffer();
5517 // reset the old filename and unnamed state
5518 setFileName(old_name);
5519 setUnnamed(old_unnamed);
5523 d->old_position.clear();
5528 void Buffer::checkChildBuffers()
5530 for (auto const & bit : d->children_positions) {
5531 DocIterator dit = bit.second;
5532 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5533 if (!cbuf || !theBufferList().isLoaded(cbuf))
5535 Inset * inset = dit.nextInset();
5536 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5537 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5538 docstring const & incfile = inset_inc->getParam("filename");
5539 string oldloc = cbuf->absFileName();
5540 string newloc = makeAbsPath(to_utf8(incfile),
5541 onlyPath(absFileName())).absFileName();
5542 if (oldloc == newloc)
5544 // the location of the child file is incorrect.
5546 inset_inc->setChildBuffer(0);
5548 // invalidate cache of children
5549 d->children_positions.clear();
5550 d->position_to_children.clear();
5554 // If a child has been saved under a different name/path, it might have been
5555 // orphaned. Therefore the master needs to be reset (bug 8161).
5556 void Buffer::checkMasterBuffer()
5558 Buffer const * const master = masterBuffer();
5562 // necessary to re-register the child (bug 5873)
5563 // FIXME: clean up updateMacros (here, only
5564 // child registering is needed).
5565 master->updateMacros();
5566 // (re)set master as master buffer, but only
5567 // if we are a real child
5568 if (master->isChild(this))
5575 string Buffer::includedFilePath(string const & name, string const & ext) const
5577 if (d->old_position.empty() ||
5578 equivalent(FileName(d->old_position), FileName(filePath())))
5581 bool isabsolute = FileName::isAbsolute(name);
5582 // both old_position and filePath() end with a path separator
5583 string absname = isabsolute ? name : d->old_position + name;
5585 // if old_position is set to origin, we need to do the equivalent of
5586 // getReferencedFileName() (see readDocument())
5587 if (!isabsolute && d->old_position == params().origin) {
5588 FileName const test(addExtension(filePath() + name, ext));
5590 absname = filePath() + name;
5593 if (!FileName(addExtension(absname, ext)).exists())
5597 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5599 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5600 from_utf8(filePath())));
5604 void Buffer::setChangesPresent(bool b) const
5606 d->tracked_changes_present_ = b;
5610 bool Buffer::areChangesPresent() const
5612 return d->tracked_changes_present_;
5616 void Buffer::updateChangesPresent() const
5618 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5619 setChangesPresent(false);
5620 ParConstIterator it = par_iterator_begin();
5621 ParConstIterator const end = par_iterator_end();
5622 for (; !areChangesPresent() && it != end; ++it)
5623 it->addChangesToBuffer(*this);
5627 void Buffer::Impl::refreshFileMonitor()
5629 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5630 file_monitor_->refresh();
5634 // The previous file monitor is invalid
5635 // This also destroys the previous file monitor and all its connections
5636 file_monitor_ = FileSystemWatcher::monitor(filename);
5637 // file_monitor_ will be destroyed with *this, so it is not going to call a
5638 // destroyed object method.
5639 file_monitor_->connect([this](bool exists) {
5640 fileExternallyModified(exists);
5645 void Buffer::Impl::fileExternallyModified(bool const exists)
5647 // ignore notifications after our own saving operations
5648 if (checksum_ == filename.checksum()) {
5649 LYXERR(Debug::FILES, "External modification but "
5650 "checksum unchanged: " << filename);
5653 // If the file has been deleted, only mark the file as dirty since it is
5654 // pointless to prompt for reloading. If later a file is moved into this
5655 // location, then the externally modified warning will appear then.
5657 externally_modified_ = true;
5658 // Update external modification notification.
5659 // Dirty buffers must be visible at all times.
5660 if (wa_ && wa_->unhide(owner_))
5661 wa_->updateTitles();
5663 // Unable to unhide the buffer (e.g. no GUI or not current View)
5668 bool Buffer::notifiesExternalModification() const
5670 return d->externally_modified_;
5674 void Buffer::clearExternalModification() const
5676 d->externally_modified_ = false;
5678 d->wa_->updateTitles();