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 "BiblioInfo.h"
18 #include "BranchList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
24 #include "Converter.h"
27 #include "CutAndPaste.h"
28 #include "DispatchResult.h"
29 #include "DocIterator.h"
30 #include "BufferEncodings.h"
31 #include "ErrorList.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
36 #include "IndicesList.h"
37 #include "InsetIterator.h"
38 #include "InsetList.h"
40 #include "LaTeXFeatures.h"
44 #include "LyXAction.h"
49 #include "output_latex.h"
50 #include "output_docbook.h"
51 #include "output_plaintext.h"
52 #include "output_xhtml.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
58 #include "SpellChecker.h"
60 #include "texstream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
70 #include "insets/InsetBranch.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetText.h"
74 #include "mathed/InsetMathHull.h"
75 #include "mathed/MacroTable.h"
76 #include "mathed/InsetMathMacroTemplate.h"
77 #include "mathed/MathSupport.h"
79 #include "graphics/PreviewLoader.h"
81 #include "frontends/Application.h"
82 #include "frontends/alert.h"
83 #include "frontends/Delegates.h"
84 #include "frontends/WorkAreaManager.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileMonitor.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/mutex.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/PathChanger.h"
102 #include "support/Systemcall.h"
103 #include "support/TempFile.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
117 using namespace lyx::support;
118 using namespace lyx::graphics;
122 namespace Alert = frontend::Alert;
123 namespace os = support::os;
127 int const LYX_FORMAT = LYX_FORMAT_LYX;
129 typedef map<string, bool> DepClean;
131 // Information about labels and their associated refs
136 InsetLabel const * inset;
137 /// associated references cache
138 Buffer::References references;
139 /// whether this label is active (i.e., not deleted)
143 typedef vector<LabelInfo> LabelCache;
145 typedef map<docstring, Buffer::References> RefCache;
147 // A storehouse for the cloned buffers.
148 typedef list<CloneList_ptr> CloneStore;
149 CloneStore cloned_buffers;
158 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
162 delete preview_loader_;
170 /// search for macro in local (buffer) table or in children
171 MacroData const * getBufferMacro(docstring const & name,
172 DocIterator const & pos) const;
174 /// Update macro table starting with position of it \param it in some
176 void updateMacros(DocIterator & it, DocIterator & scope);
178 void setLabel(ParIterator & it, UpdateType utype) const;
180 /** If we have branches that use the file suffix
181 feature, return the file name with suffix appended.
183 FileName exportFileName() const;
190 mutable TexRow texrow;
192 /// need to regenerate .tex?
195 /// name of the file the buffer is associated with.
199 mutable TocBackend toc_backend;
204 ScopeMacro(DocIterator const & s, MacroData const & m)
205 : scope(s), macro(m) {}
209 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
210 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
211 /// map from the macro name to the position map,
212 /// which maps the macro definition position to the scope and the MacroData.
213 NamePositionScopeMacroMap macros;
215 /// positions of child buffers in the buffer
216 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
218 ScopeBuffer() : buffer(nullptr) {}
219 ScopeBuffer(DocIterator const & s, Buffer const * b)
220 : scope(s), buffer(b) {}
222 Buffer const * buffer;
224 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
225 /// position of children buffers in this buffer
226 BufferPositionMap children_positions;
227 /// map from children inclusion positions to their scope and their buffer
228 PositionScopeBufferMap position_to_children;
230 /// Contains the old buffer filePath() while saving-as, or the
231 /// directory where the document was last saved while loading.
234 /** Keeps track of the path of local layout files.
235 * If possible, it is always relative to the buffer path.
236 * Empty for layouts in system or user directory.
238 string layout_position;
240 /// Container for all sort of Buffer dependant errors.
241 map<string, ErrorList> errorLists;
243 /// checksum used to test if the file has been externally modified. Used to
244 /// double check whether the file had been externally modified when saving.
245 unsigned long checksum_;
248 frontend::WorkAreaManager * wa_;
250 frontend::GuiBufferDelegate * gui_;
255 /// A cache for the bibfiles (including bibfiles of loaded child
256 /// documents), needed for appropriate update of natbib labels.
257 mutable docstring_list bibfiles_cache_;
259 // FIXME The caching mechanism could be improved. At present, we have a
260 // cache for each Buffer, that caches all the bibliography info for that
261 // Buffer. A more efficient solution would be to have a global cache per
262 // file, and then to construct the Buffer's bibinfo from that.
263 /// A cache for bibliography info
264 mutable BiblioInfo bibinfo_;
265 /// Cache of timestamps of .bib files
266 map<FileName, time_t> bibfile_status_;
268 /// These two hold the file name and format, written to by
269 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
270 FileName preview_file_;
271 string preview_format_;
273 /// Cache the references associated to a label and their positions
275 mutable RefCache ref_cache_;
276 /// Cache the label insets and their activity status.
277 mutable LabelCache label_cache_;
279 /// our Text that should be wrapped in an InsetText
283 PreviewLoader * preview_loader_;
285 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
286 /// This one is useful for preview detached in a thread.
287 Buffer const * cloned_buffer_;
289 CloneList_ptr clone_list_;
292 std::list<Buffer const *> include_list_;
294 /// So we can force access via the accessors.
295 mutable Buffer const * parent_buffer;
297 FileMonitorPtr file_monitor_;
299 /// ints and bools are all listed last so as to avoid alignment issues
301 /// original format of loaded file
304 /// are we in the process of exporting this buffer?
305 mutable bool doing_export;
307 /// If there was an error when previewing, on the next preview we do
308 /// a fresh compile (e.g. in case the user installed a package that
310 bool require_fresh_start_;
312 /// Indicates whether the bibinfo has changed since the last time
313 /// we ran updateBuffer(), i.e., whether citation labels may need
315 mutable bool cite_labels_valid_;
316 /// Do we have a bibliography environment?
317 mutable bool have_bibitems_;
320 mutable bool lyx_clean;
322 /// is autosave needed?
323 mutable bool bak_clean;
325 /// is this an unnamed file (New...)?
328 /// is this an internal bufffer?
329 bool internal_buffer;
334 /** Set to true only when the file is fully loaded.
335 * Used to prevent the premature generation of previews
336 * and by the citation inset.
338 bool file_fully_loaded;
340 /// if the file was originally loaded from an older format, do
341 /// we need to back it up still?
342 bool need_format_backup;
344 /// Ignore the parent (e.g. when exporting a child standalone)?
347 /// This seem to change the way Buffer::getMacro() works
348 mutable bool macro_lock;
350 /// has been externally modified? Can be reset by the user.
351 mutable bool externally_modified_;
353 /// whether the bibinfo cache is valid
354 mutable bool bibinfo_cache_valid_;
362 /// This is here to force the test to be done whenever parent_buffer
364 Buffer const * parent() const
366 // ignore_parent temporarily "orphans" a buffer
367 // (e.g. if a child is compiled standalone)
370 // if parent_buffer is not loaded, then it has been unloaded,
371 // which means that parent_buffer is an invalid pointer. So we
372 // set it to null in that case.
373 // however, the BufferList doesn't know about cloned buffers, so
374 // they will always be regarded as unloaded. in that case, we hope
376 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
377 parent_buffer = nullptr;
378 return parent_buffer;
382 void setParent(Buffer const * pb)
384 if (parent_buffer == pb)
387 if (!cloned_buffer_ && parent_buffer && pb)
388 LYXERR0("Warning: a buffer should not have two parents!");
390 if (!cloned_buffer_ && parent_buffer)
391 parent_buffer->invalidateBibinfoCache();
394 /// compute statistics
395 /// \p from initial position
396 /// \p to points to the end position
397 void updateStatistics(DocIterator & from, DocIterator & to,
398 bool skipNoOutput = true);
399 /// statistics accessor functions
400 int wordCount() const
404 int charCount(bool with_blanks) const
407 + (with_blanks ? blank_count_ : 0);
410 // Make sure the file monitor monitors the good file.
411 void refreshFileMonitor();
413 /// Notify or clear of external modification
414 void fileExternallyModified(bool exists);
416 ///Binding LaTeX lines with buffer positions.
417 //Common routine for LaTeX and Reference errors listing.
418 void traverseErrors(TeXErrors::Errors::const_iterator err,
419 TeXErrors::Errors::const_iterator end,
420 ErrorList & errorList) const;
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), filename(file), toc_backend(owner), checksum_(0),
454 wa_(nullptr), gui_(nullptr), undo_(*owner), inset(nullptr),
455 preview_loader_(nullptr), cloned_buffer_(cloned_buffer),
456 clone_list_(nullptr), parent_buffer(nullptr), file_format(LYX_FORMAT),
457 doing_export(false), require_fresh_start_(false), cite_labels_valid_(false),
458 have_bibitems_(false), lyx_clean(true), bak_clean(true), unnamed(false),
459 internal_buffer(false), read_only(readonly_), file_fully_loaded(false),
460 need_format_backup(false), ignore_parent(false), macro_lock(false),
461 externally_modified_(false), bibinfo_cache_valid_(false),
462 word_count_(0), char_count_(0), blank_count_(0)
464 refreshFileMonitor();
465 if (!cloned_buffer_) {
466 temppath = createBufferTmpDir();
467 lyxvc.setBuffer(owner_);
468 Language const * inplang = theApp() ?
469 languages.getFromCode(theApp()->inputLanguageCode())
472 params.language = inplang;
474 wa_ = new frontend::WorkAreaManager;
477 temppath = cloned_buffer_->d->temppath;
478 file_fully_loaded = true;
479 params = cloned_buffer_->d->params;
480 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
481 bibinfo_ = cloned_buffer_->d->bibinfo_;
482 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
483 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
484 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
485 have_bibitems_ = cloned_buffer_->d->have_bibitems_;
486 unnamed = cloned_buffer_->d->unnamed;
487 internal_buffer = cloned_buffer_->d->internal_buffer;
488 layout_position = cloned_buffer_->d->layout_position;
489 preview_file_ = cloned_buffer_->d->preview_file_;
490 preview_format_ = cloned_buffer_->d->preview_format_;
491 require_fresh_start_ = cloned_buffer_->d->require_fresh_start_;
495 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
496 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
498 LYXERR(Debug::INFO, "Buffer::Buffer()");
500 d->inset = new InsetText(*cloned_buffer->d->inset);
501 d->inset->setBuffer(*this);
502 // FIXME: optimize this loop somewhat, maybe by creating a new
503 // general recursive Inset::setId().
504 DocIterator it = doc_iterator_begin(this);
505 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
506 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
507 it.paragraph().setId(cloned_it.paragraph().id());
509 d->inset = new InsetText(this);
510 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
516 LYXERR(Debug::INFO, "Buffer::~Buffer()");
517 // here the buffer should take care that it is
518 // saved properly, before it goes into the void.
520 // GuiView already destroyed
524 // No need to do additional cleanups for internal buffer.
530 // this is in case of recursive includes: we won't try to delete
531 // ourselves as a child.
532 d->clone_list_->erase(this);
533 // loop over children
534 for (auto const & p : d->children_positions) {
535 Buffer * child = const_cast<Buffer *>(p.first);
536 if (d->clone_list_->erase(child))
539 // if we're the master buffer, then we should get rid of the list
542 // If this is not empty, we have leaked something. Worse, one of the
543 // children still has a reference to this list. But we will try to
544 // continue, rather than shut down.
545 LATTEST(d->clone_list_->empty());
546 // The clone list itself is empty, but it's still referenced in our list
547 // of clones. So let's find it and remove it.
548 CloneStore::iterator it =
549 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
550 if (it == cloned_buffers.end()) {
551 // We will leak in this case, but it is safe to continue.
554 cloned_buffers.erase(it);
556 // FIXME Do we really need to do this right before we delete d?
557 // clear references to children in macro tables
558 d->children_positions.clear();
559 d->position_to_children.clear();
561 // loop over children
562 for (auto const & p : d->children_positions) {
563 Buffer * child = const_cast<Buffer *>(p.first);
564 if (theBufferList().isLoaded(child)) {
565 if (theBufferList().isOthersChild(this, child))
566 child->setParent(nullptr);
568 theBufferList().release(child);
573 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
575 msg += emergencyWrite();
577 msg += " " + _("Save failed! Document is lost.");
579 Alert::warning(_("Attempting to close changed document!"), msg);
582 // FIXME Do we really need to do this right before we delete d?
583 // clear references to children in macro tables
584 d->children_positions.clear();
585 d->position_to_children.clear();
587 if (!d->temppath.destroyDirectory()) {
588 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
589 from_utf8(d->temppath.absFileName())));
598 Buffer * Buffer::cloneWithChildren() const
601 cloned_buffers.emplace_back(new CloneList);
602 CloneList_ptr clones = cloned_buffers.back();
604 cloneWithChildren(bufmap, clones);
606 // make sure we got cloned
607 BufferMap::const_iterator bit = bufmap.find(this);
608 LASSERT(bit != bufmap.end(), return nullptr);
609 Buffer * cloned_buffer = bit->second;
611 return cloned_buffer;
615 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList_ptr clones) const
617 // have we already been cloned?
618 if (bufmap.find(this) != bufmap.end())
621 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
623 // The clone needs its own DocumentClass, since running updateBuffer() will
624 // modify it, and we would otherwise be sharing it with the original Buffer.
625 buffer_clone->params().makeDocumentClass(true);
627 cap::switchBetweenClasses(
628 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
629 static_cast<InsetText &>(buffer_clone->inset()), el);
631 bufmap[this] = buffer_clone;
632 clones->insert(buffer_clone);
633 buffer_clone->d->clone_list_ = clones;
634 buffer_clone->d->macro_lock = true;
635 buffer_clone->d->children_positions.clear();
637 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
638 // math macro caches need to be rethought and simplified.
639 // I am not sure wether we should handle Buffer cloning here or in BufferList.
640 // Right now BufferList knows nothing about buffer clones.
641 for (auto const & p : d->position_to_children) {
642 DocIterator dit = p.first.clone(buffer_clone);
643 dit.setBuffer(buffer_clone);
644 Buffer * child = const_cast<Buffer *>(p.second.buffer);
646 child->cloneWithChildren(bufmap, clones);
647 BufferMap::iterator const bit = bufmap.find(child);
648 LASSERT(bit != bufmap.end(), continue);
649 Buffer * child_clone = bit->second;
651 Inset * inset = dit.nextInset();
652 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
653 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
654 inset_inc->setChildBuffer(child_clone);
655 child_clone->d->setParent(buffer_clone);
656 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
657 buffer_clone->setChild(dit, child_clone);
659 buffer_clone->d->macro_lock = false;
663 Buffer * Buffer::cloneBufferOnly() const {
664 cloned_buffers.emplace_back(new CloneList);
665 CloneList_ptr clones = cloned_buffers.back();
666 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
668 // The clone needs its own DocumentClass, since running updateBuffer() will
669 // modify it, and we would otherwise be sharing it with the original Buffer.
670 buffer_clone->params().makeDocumentClass(true);
672 cap::switchBetweenClasses(
673 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
674 static_cast<InsetText &>(buffer_clone->inset()), el);
676 clones->insert(buffer_clone);
677 buffer_clone->d->clone_list_ = clones;
679 // we won't be cloning the children
680 buffer_clone->d->children_positions.clear();
685 bool Buffer::isClone() const
687 return d->cloned_buffer_;
691 void Buffer::changed(bool update_metrics) const
694 d->wa_->redrawAll(update_metrics);
698 frontend::WorkAreaManager & Buffer::workAreaManager() const
705 Text & Buffer::text() const
707 return d->inset->text();
711 Inset & Buffer::inset() const
717 BufferParams & Buffer::params()
723 BufferParams const & Buffer::params() const
729 BufferParams const & Buffer::masterParams() const
731 if (masterBuffer() == this)
734 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
735 // Copy child authors to the params. We need those pointers.
736 for (Author const & a : params().authors())
737 mparams.authors().record(a);
742 double Buffer::fontScalingFactor() const
744 return isExporting() ? 75.0 * params().html_math_img_scale
745 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
749 ParagraphList & Buffer::paragraphs()
751 return text().paragraphs();
755 ParagraphList const & Buffer::paragraphs() const
757 return text().paragraphs();
761 LyXVC & Buffer::lyxvc()
767 LyXVC const & Buffer::lyxvc() const
773 string const Buffer::temppath() const
775 return d->temppath.absFileName();
779 TexRow & Buffer::texrow()
785 TexRow const & Buffer::texrow() const
791 TocBackend & Buffer::tocBackend() const
793 return d->toc_backend;
797 Undo & Buffer::undo()
803 void Buffer::setChild(DocIterator const & dit, Buffer * child)
805 d->children_positions[child] = dit;
809 string Buffer::latexName(bool const no_path) const
811 FileName latex_name =
812 makeLatexName(d->exportFileName());
813 return no_path ? latex_name.onlyFileName()
814 : latex_name.absFileName();
818 FileName Buffer::Impl::exportFileName() const
820 docstring const branch_suffix =
821 params.branchlist().getFileNameSuffix();
822 if (branch_suffix.empty())
825 string const name = addExtension(filename.onlyFileNameWithoutExt()
826 + to_utf8(branch_suffix), filename.extension());
827 FileName res(filename.onlyPath().absFileName() + "/" + name);
833 string Buffer::logName(LogType * type) const
835 string const filename = latexName(false);
837 if (filename.empty()) {
843 string const path = temppath();
845 FileName const fname(addName(temppath(),
846 onlyFileName(changeExtension(filename,
849 // FIXME: how do we know this is the name of the build log?
850 FileName const bname(
851 addName(path, onlyFileName(
852 changeExtension(filename,
853 theFormats().extension(params().bufferFormat()) + ".out"))));
855 // Also consider the master buffer log file
856 FileName masterfname = fname;
857 LogType mtype = latexlog;
858 if (masterBuffer() != this) {
859 string const mlogfile = masterBuffer()->logName(&mtype);
860 masterfname = FileName(mlogfile);
863 // If no Latex log or Build log is newer, show Build log
864 if (bname.exists() &&
865 ((!fname.exists() && !masterfname.exists())
866 || (fname.lastModified() < bname.lastModified()
867 && masterfname.lastModified() < bname.lastModified()))) {
868 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
871 return bname.absFileName();
872 // If we have a newer master file log or only a master log, show this
873 } else if (fname != masterfname
874 && (!fname.exists() && (masterfname.exists()
875 || fname.lastModified() < masterfname.lastModified()))) {
876 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
879 return masterfname.absFileName();
881 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
884 return fname.absFileName();
888 void Buffer::setReadonly(bool const flag)
890 if (d->read_only != flag) {
897 void Buffer::setFileName(FileName const & fname)
899 bool const changed = fname != d->filename;
901 d->refreshFileMonitor();
903 lyxvc().file_found_hook(fname);
904 setReadonly(d->filename.isReadOnly());
910 int Buffer::readHeader(Lexer & lex)
912 int unknown_tokens = 0;
914 int begin_header_line = -1;
916 // Initialize parameters that may be/go lacking in header:
917 params().branchlist().clear();
918 params().preamble.erase();
919 params().options.erase();
920 params().master.erase();
921 params().float_placement.erase();
922 params().float_alignment.erase();
923 params().paperwidth.erase();
924 params().paperheight.erase();
925 params().leftmargin.erase();
926 params().rightmargin.erase();
927 params().topmargin.erase();
928 params().bottommargin.erase();
929 params().headheight.erase();
930 params().headsep.erase();
931 params().footskip.erase();
932 params().columnsep.erase();
933 params().font_roman_opts.erase();
934 params().font_sans_opts.erase();
935 params().font_typewriter_opts.erase();
936 params().fonts_cjk.erase();
937 params().listings_params.clear();
938 params().clearLayoutModules();
939 params().clearRemovedModules();
940 params().clearIncludedChildren();
941 params().pdfoptions().clear();
942 params().indiceslist().clear();
943 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
944 params().isbackgroundcolor = false;
945 params().fontcolor = RGBColor(0, 0, 0);
946 params().isfontcolor = false;
947 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
948 params().boxbgcolor = RGBColor(0xFF, 0, 0);
949 params().html_latex_start.clear();
950 params().html_latex_end.clear();
951 params().html_math_img_scale = 1.0;
952 params().output_sync_macro.erase();
953 params().setLocalLayout(docstring(), false);
954 params().setLocalLayout(docstring(), true);
955 params().biblio_opts.erase();
956 params().biblatex_bibstyle.erase();
957 params().biblatex_citestyle.erase();
958 params().multibib.erase();
959 params().lineno_opts.clear();
961 for (int i = 0; i < 4; ++i) {
962 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
963 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
966 ErrorList & errorList = d->errorLists["Parse"];
975 if (token == "\\end_header")
979 if (token == "\\begin_header") {
980 begin_header_line = line;
984 LYXERR(Debug::PARSER, "Handling document header token: `"
987 string const result =
988 params().readToken(lex, token, d->filename.onlyPath());
989 if (!result.empty()) {
990 if (token == "\\textclass") {
991 d->layout_position = result;
994 docstring const s = bformat(_("Unknown token: "
998 errorList.push_back(ErrorItem(_("Document header error"), s));
1002 if (begin_header_line) {
1003 docstring const s = _("\\begin_header is missing");
1004 errorList.push_back(ErrorItem(_("Document header error"), s));
1007 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
1009 params().makeDocumentClass();
1011 return unknown_tokens;
1016 // changed to be public and have one parameter
1017 // Returns true if "\end_document" is not read (Asger)
1018 bool Buffer::readDocument(Lexer & lex)
1020 ErrorList & errorList = d->errorLists["Parse"];
1023 // remove dummy empty par
1024 paragraphs().clear();
1026 if (!lex.checkFor("\\begin_document")) {
1027 docstring const s = _("\\begin_document is missing");
1028 errorList.push_back(ErrorItem(_("Document header error"), s));
1033 if (params().output_changes) {
1034 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1035 LaTeXFeatures::isAvailable("xcolor");
1038 Alert::warning(_("Changes not shown in LaTeX output"),
1039 _("Changes will not be highlighted in LaTeX output, "
1040 "because xcolor and ulem are not installed.\n"
1041 "Please install both packages or redefine "
1042 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1046 if (!parent() && !params().master.empty()) {
1047 FileName const master_file = makeAbsPath(params().master,
1048 onlyPath(absFileName()));
1049 if (isLyXFileName(master_file.absFileName())) {
1051 checkAndLoadLyXFile(master_file, true);
1053 // necessary e.g. after a reload
1054 // to re-register the child (bug 5873)
1055 // FIXME: clean up updateMacros (here, only
1056 // child registering is needed).
1057 master->updateMacros();
1058 // set master as master buffer, but only
1059 // if we are a real child
1060 if (master->isChild(this))
1062 // if the master is not fully loaded
1063 // it is probably just loading this
1064 // child. No warning needed then.
1065 else if (master->isFullyLoaded())
1066 LYXERR0("The master '"
1068 << "' assigned to this document ("
1070 << ") does not include "
1071 "this document. Ignoring the master assignment.");
1072 // If the master has just been created, un-hide it (#11162)
1073 if (!master->fileName().exists())
1074 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1075 master->absFileName()));
1080 // assure we have a default index
1081 params().indiceslist().addDefault(B_("Index"));
1084 if (FileName::isAbsolute(params().origin))
1085 d->old_position = params().origin;
1087 d->old_position = filePath();
1092 bool const res = text().read(lex, errorList, d->inset);
1093 d->old_position.clear();
1095 // inform parent buffer about local macros
1097 Buffer const * pbuf = parent();
1098 for (auto const & m : usermacros)
1099 pbuf->usermacros.insert(m);
1103 updateMacroInstances(InternalUpdate);
1108 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1110 Format const * fmt = theFormats().getFormat(format);
1113 // It is important to use the correct extension here, since some
1114 // converters create a wrong output file otherwise (e.g. html2latex)
1115 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1116 ofdocstream os(name.toFilesystemEncoding().c_str());
1117 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1118 bool const success = !(os << contents).fail();
1121 bool converted = false;
1123 params().compressed = false;
1125 // remove dummy empty par
1126 paragraphs().clear();
1128 converted = importFile(format, name, errorList);
1131 removeTempFile(name);
1136 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1138 if (!theConverters().isReachable(format, "lyx"))
1141 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1142 Converters::RetVal const retval =
1143 theConverters().convert(nullptr, name, lyx, name, format, "lyx", errorList);
1144 if (retval == Converters::SUCCESS) {
1145 bool const success = readFile(lyx) == ReadSuccess;
1146 removeTempFile(lyx);
1154 bool Buffer::readString(string const & s)
1156 params().compressed = false;
1159 istringstream is(s);
1161 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1162 FileName const fn = tempfile.name();
1165 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1167 if (success && file_format != LYX_FORMAT) {
1168 // We need to call lyx2lyx, so write the input to a file
1169 ofstream os(fn.toFilesystemEncoding().c_str());
1172 // lyxvc in readFile
1173 if (readFile(fn) != ReadSuccess)
1177 if (readDocument(lex))
1183 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1186 if (!lex.setFile(fn)) {
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::freshStartRequired() const
1245 return d->require_fresh_start_;
1248 void Buffer::requireFreshStart(bool const b) const
1250 d->require_fresh_start_ = b;
1254 PreviewLoader * Buffer::loader() const
1256 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1258 if (!d->preview_loader_)
1259 d->preview_loader_ = new PreviewLoader(*this);
1260 return d->preview_loader_;
1264 void Buffer::removePreviews() const
1266 delete d->preview_loader_;
1267 d->preview_loader_ = nullptr;
1271 void Buffer::updatePreviews() const
1273 PreviewLoader * ploader = loader();
1277 InsetIterator it = begin(*d->inset);
1278 InsetIterator const itend = end(*d->inset);
1279 for (; it != itend; ++it)
1280 it->addPreview(it, *ploader);
1282 ploader->startLoading();
1286 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1287 FileName const & fn, int & file_format) const
1289 if(!lex.checkFor("\\lyxformat")) {
1290 Alert::error(_("Document format failure"),
1291 bformat(_("%1$s is not a readable LyX document."),
1292 from_utf8(fn.absFileName())));
1293 return ReadNoLyXFormat;
1299 // LyX formats 217 and earlier were written as 2.17. This corresponds
1300 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1301 // these cases. See also: www.lyx.org/trac/changeset/1313.
1302 size_t dot = tmp_format.find_first_of(".,");
1303 if (dot != string::npos)
1304 tmp_format.erase(dot, 1);
1306 file_format = convert<int>(tmp_format);
1311 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1312 FileName & tmpfile, int from_format)
1314 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1315 tempfile.setAutoRemove(false);
1316 tmpfile = tempfile.name();
1317 if(tmpfile.empty()) {
1318 Alert::error(_("Conversion failed"),
1319 bformat(_("%1$s is from a different"
1320 " version of LyX, but a temporary"
1321 " file for converting it could"
1322 " not be created."),
1323 from_utf8(fn.absFileName())));
1324 return LyX2LyXNoTempFile;
1327 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1328 if (lyx2lyx.empty()) {
1329 Alert::error(_("Conversion script not found"),
1330 bformat(_("%1$s is from a different"
1331 " version of LyX, but the"
1332 " conversion script lyx2lyx"
1333 " could not be found."),
1334 from_utf8(fn.absFileName())));
1335 return LyX2LyXNotFound;
1339 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1340 ostringstream command;
1341 command << os::python()
1342 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1343 << " -t " << convert<string>(LYX_FORMAT)
1344 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1345 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1346 string const command_str = command.str();
1348 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1350 cmd_ret const ret = runCommand(command_str);
1352 if (from_format < LYX_FORMAT) {
1353 Alert::error(_("Conversion script failed"),
1354 bformat(_("%1$s is from an older version"
1355 " of LyX and the lyx2lyx script"
1356 " failed to convert it."),
1357 from_utf8(fn.absFileName())));
1358 return LyX2LyXOlderFormat;
1360 Alert::error(_("Conversion script failed"),
1361 bformat(_("%1$s is from a newer version"
1362 " of LyX and the lyx2lyx script"
1363 " failed to convert it."),
1364 from_utf8(fn.absFileName())));
1365 return LyX2LyXNewerFormat;
1372 FileName Buffer::getBackupName() const {
1373 map<int, string> const file_formats = {
1390 FileName const & fn = fileName();
1391 string const fname = fn.onlyFileNameWithoutExt();
1392 string const fext = fn.extension() + "~";
1393 string const fpath = lyxrc.backupdir_path.empty() ?
1394 fn.onlyPath().absFileName() :
1395 lyxrc.backupdir_path;
1396 string backup_suffix;
1397 // If file format is from a stable series use version instead of file format
1398 auto const it = file_formats.find(d->file_format);
1399 if (it != file_formats.end())
1400 backup_suffix = "-lyx" + it->second;
1402 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1403 string const backname = fname + backup_suffix;
1404 FileName backup(addName(fpath, addExtension(backname, fext)));
1406 // limit recursion, just in case
1408 unsigned long orig_checksum = 0;
1409 while (backup.exists() && v < 100) {
1410 if (orig_checksum == 0)
1411 orig_checksum = fn.checksum();
1412 unsigned long new_checksum = backup.checksum();
1413 if (orig_checksum == new_checksum) {
1414 LYXERR(Debug::FILES, "Not backing up " << fn <<
1415 "since " << backup << "has the same checksum.");
1416 // a bit of a hack, but we have to check this anyway
1417 // below, and setting this is simpler than introducing
1418 // a special boolean for this purpose.
1422 string const newbackname = backname + "-" + convert<string>(v);
1423 backup.set(addName(fpath, addExtension(newbackname, fext)));
1426 return v < 100 ? backup : FileName();
1430 // Should probably be moved to somewhere else: BufferView? GuiView?
1431 bool Buffer::save() const
1433 docstring const file = makeDisplayPath(absFileName(), 20);
1434 d->filename.refresh();
1436 // check the read-only status before moving the file as a backup
1437 if (d->filename.exists()) {
1438 bool const read_only = !d->filename.isWritable();
1440 Alert::warning(_("File is read-only"),
1441 bformat(_("The file %1$s cannot be written because it "
1442 "is marked as read-only."), file));
1447 // ask if the disk file has been externally modified (use checksum method)
1448 if (fileName().exists() && isChecksumModified()) {
1450 bformat(_("Document %1$s has been externally modified. "
1451 "Are you sure you want to overwrite this file?"), file);
1452 int const ret = Alert::prompt(_("Overwrite modified file?"),
1453 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1458 // We don't need autosaves in the immediate future. (Asger)
1459 resetAutosaveTimers();
1461 // if the file does not yet exist, none of the backup activity
1462 // that follows is necessary
1463 if (!fileName().exists()) {
1464 if (!writeFile(fileName()))
1470 // we first write the file to a new name, then move it to its
1471 // proper location once that has been done successfully. that
1472 // way we preserve the original file if something goes wrong.
1473 string const justname = fileName().onlyFileNameWithoutExt();
1474 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1475 justname + "-XXXXXX.lyx");
1476 bool const symlink = fileName().isSymLink();
1478 tempfile->setAutoRemove(false);
1480 FileName savefile(tempfile->name());
1481 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1482 if (!savefile.clonePermissions(fileName()))
1483 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1485 if (!writeFile(savefile))
1488 // we will set this to false if we fail
1489 bool made_backup = true;
1491 FileName backupName;
1492 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1494 if (d->need_format_backup)
1495 backupName = getBackupName();
1497 // If we for some reason failed to find a backup name in case of
1498 // a format change, this will still set one. It's the best we can
1500 if (backupName.empty()) {
1501 backupName.set(fileName().absFileName() + "~");
1502 if (!lyxrc.backupdir_path.empty()) {
1503 string const mangledName =
1504 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1505 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1509 LYXERR(Debug::FILES, "Backing up original file to " <<
1510 backupName.absFileName());
1511 // Except file is symlink do not copy because of #6587.
1512 // Hard links have bad luck.
1513 made_backup = symlink ?
1514 fileName().copyTo(backupName):
1515 fileName().moveTo(backupName);
1518 Alert::error(_("Backup failure"),
1519 bformat(_("Cannot create backup file %1$s.\n"
1520 "Please check whether the directory exists and is writable."),
1521 from_utf8(backupName.absFileName())));
1522 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1523 } else if (d->need_format_backup) {
1524 // the original file has been backed up successfully, so we
1525 // will not need to do that again
1526 d->need_format_backup = false;
1530 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1531 // Only do this if tempfile is not in autoremove mode
1534 // If we have no symlink, we can simply rename the temp file.
1535 // Otherwise, we need to copy it so the symlink stays intact.
1536 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1537 savefile.moveTo(fileName()))
1539 // saveCheckSum() was already called by writeFile(), but the
1540 // time stamp is invalidated by copying/moving
1543 // the file associated with this buffer is now in the current format
1544 d->file_format = LYX_FORMAT;
1547 // else we saved the file, but failed to move it to the right location.
1549 if (needBackup && made_backup && !symlink) {
1550 // the original file was moved to some new location, so it will look
1551 // to the user as if it was deleted. (see bug #9234.) we could try
1552 // to restore it, but that would basically mean trying to do again
1553 // what we just failed to do. better to leave things as they are.
1554 Alert::error(_("Write failure"),
1555 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1556 "But LyX could not move it to:\n %2$s.\n"
1557 "Your original file has been backed up to:\n %3$s"),
1558 from_utf8(savefile.absFileName()),
1559 from_utf8(fileName().absFileName()),
1560 from_utf8(backupName.absFileName())));
1562 // either we did not try to make a backup, or else we tried and failed,
1563 // or else the original file was a symlink, in which case it was copied,
1564 // not moved. so the original file is intact.
1565 Alert::error(_("Write failure"),
1566 bformat(_("Cannot move saved file to:\n %1$s.\n"
1567 "But the file has successfully been saved as:\n %2$s."),
1568 from_utf8(fileName().absFileName()),
1569 from_utf8(savefile.absFileName())));
1575 bool Buffer::writeFile(FileName const & fname) const
1577 if (d->read_only && fname == d->filename)
1580 bool retval = false;
1582 docstring const str = bformat(_("Saving document %1$s..."),
1583 makeDisplayPath(fname.absFileName()));
1586 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1588 if (params().compressed) {
1589 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1590 retval = ofs && write(ofs);
1592 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1593 retval = ofs && write(ofs);
1597 message(str + _(" could not write file!"));
1602 // removeAutosaveFile();
1605 message(str + _(" done."));
1611 docstring Buffer::emergencyWrite() const
1613 // No need to save if the buffer has not changed.
1617 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1619 docstring user_message = bformat(
1620 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1622 // We try to save three places:
1623 // 1) Same place as document. Unless it is an unnamed doc.
1625 string s = absFileName();
1628 if (writeFile(FileName(s))) {
1630 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1631 return user_message;
1633 user_message += " " + _("Save failed! Trying again...\n");
1637 // 2) In HOME directory.
1638 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1640 lyxerr << ' ' << s << endl;
1641 if (writeFile(FileName(s))) {
1643 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1644 return user_message;
1647 user_message += " " + _("Save failed! Trying yet again...\n");
1649 // 3) In "/tmp" directory.
1650 // MakeAbsPath to prepend the current
1651 // drive letter on OS/2
1652 s = addName(package().temp_dir().absFileName(), absFileName());
1654 lyxerr << ' ' << s << endl;
1655 if (writeFile(FileName(s))) {
1657 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1658 return user_message;
1661 user_message += " " + _("Save failed! Document is lost.");
1664 return user_message;
1668 bool Buffer::write(ostream & ofs) const
1671 // Use the standard "C" locale for file output.
1672 ofs.imbue(locale::classic());
1675 // The top of the file should not be written by params().
1677 // write out a comment in the top of the file
1678 // Important: Keep the version formatting in sync with lyx2lyx and
1679 // tex2lyx (bug 7951)
1680 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1681 << " created this file. For more info see https://www.lyx.org/\n"
1682 << "\\lyxformat " << LYX_FORMAT << "\n"
1683 << "\\begin_document\n";
1685 /// For each author, set 'used' to true if there is a change
1686 /// by this author in the document; otherwise set it to 'false'.
1687 for (Author const & a : params().authors())
1690 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1691 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1692 for ( ; it != end; ++it)
1693 it->checkAuthors(params().authors());
1695 // now write out the buffer parameters.
1696 ofs << "\\begin_header\n";
1697 params().writeFile(ofs, this);
1698 ofs << "\\end_header\n";
1701 ofs << "\n\\begin_body\n";
1703 ofs << "\n\\end_body\n";
1705 // Write marker that shows file is complete
1706 ofs << "\\end_document" << endl;
1708 // Shouldn't really be needed....
1711 // how to check if close went ok?
1712 // Following is an attempt... (BE 20001011)
1714 // good() returns false if any error occurred, including some
1715 // formatting error.
1716 // bad() returns true if something bad happened in the buffer,
1717 // which should include file system full errors.
1722 lyxerr << "File was not closed properly." << endl;
1729 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1730 string const & original_path,
1731 OutputParams const & runparams_in,
1732 OutputWhat output) const
1734 OutputParams runparams = runparams_in;
1736 string const encoding = runparams.encoding->iconvName();
1737 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1740 try { ofs.reset(encoding); }
1741 catch (iconv_codecvt_facet_exception const & e) {
1742 lyxerr << "Caught iconv exception: " << e.what() << endl;
1743 Alert::error(_("Iconv software exception Detected"),
1744 bformat(_("Please verify that the `iconv' support software is"
1745 " properly installed and supports the selected encoding"
1746 " (%1$s), or change the encoding in"
1747 " Document>Settings>Language."), from_ascii(encoding)));
1750 if (!openFileWrite(ofs, fname))
1753 ErrorList & errorList = d->errorLists["Export"];
1755 ExportStatus status = ExportSuccess;
1758 // make sure we are ready to export
1759 // this needs to be done before we validate
1760 // FIXME Do we need to do this all the time? I.e., in children
1761 // of a master we are exporting?
1763 updateMacroInstances(OutputUpdate);
1765 ExportStatus retval;
1767 retval = writeLaTeXSource(os, original_path, runparams, output);
1768 if (retval == ExportKilled)
1769 return ExportKilled;
1771 catch (EncodingException const & e) {
1772 docstring const failed(1, e.failed_char);
1774 oss << "0x" << hex << e.failed_char << dec;
1775 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1776 docstring msg = bformat(_("Uncodable character '%1$s'"
1777 " (code point %2$s)"),
1778 failed, from_utf8(oss.str()));
1779 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1780 "representable in specific verbatim contexts.\n"
1781 "Changing the document encoding to utf8 could help."),
1782 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1784 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1785 " (code point %2$s)"),
1786 failed, from_utf8(oss.str()));
1787 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1788 "representable in the chosen encoding.\n"
1789 "Changing the document encoding to utf8 could help."),
1790 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1792 status = ExportError;
1794 catch (iconv_codecvt_facet_exception const & e) {
1795 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1797 status = ExportError;
1799 catch (exception const & e) {
1800 errorList.push_back(ErrorItem(_("conversion failed"),
1802 lyxerr << e.what() << endl;
1803 status = ExportError;
1806 lyxerr << "Caught some really weird exception..." << endl;
1810 d->texrow = move(os.texrow());
1814 status = ExportError;
1815 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1818 if (runparams_in.silent)
1826 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1827 string const & original_path,
1828 OutputParams const & runparams_in,
1829 OutputWhat output) const
1831 // The child documents, if any, shall be already loaded at this point.
1833 OutputParams runparams = runparams_in;
1835 // Some macros rely on font encoding
1836 runparams.main_fontenc = params().main_font_encoding();
1838 // If we are compiling a file standalone, even if this is the
1839 // child of some other buffer, let's cut the link here, so the
1840 // file is really independent and no concurring settings from
1841 // the master (e.g. branch state) interfere (see #8100).
1842 if (!runparams.is_child)
1843 d->ignore_parent = true;
1845 // Classify the unicode characters appearing in math insets
1846 BufferEncodings::initUnicodeMath(*this);
1848 // validate the buffer.
1849 LYXERR(Debug::LATEX, " Validating buffer...");
1850 LaTeXFeatures features(*this, params(), runparams);
1852 // This is only set once per document (in master)
1853 if (!runparams.is_child) {
1854 runparams.use_polyglossia = features.usePolyglossia();
1855 runparams.use_hyperref = features.isRequired("hyperref");
1856 runparams.use_CJK = features.mustProvide("CJK");
1858 LYXERR(Debug::LATEX, " Buffer validation done.");
1860 bool const output_preamble =
1861 output == FullSource || output == OnlyPreamble;
1862 bool const output_body =
1863 output == FullSource || output == OnlyBody;
1865 // The starting paragraph of the coming rows is the
1866 // first paragraph of the document. (Asger)
1867 if (output_preamble && runparams.nice) {
1868 os << "%% LyX " << lyx_version << " created this file. "
1869 "For more info, see https://www.lyx.org/.\n"
1870 "%% Do not edit unless you really know what "
1873 LYXERR(Debug::INFO, "lyx document header finished");
1875 // There are a few differences between nice LaTeX and usual files:
1876 // usual files have \batchmode and special input@path to allow
1877 // inclusion of figures specified by an explicitly relative path
1878 // (i.e., a path starting with './' or '../') with either \input or
1879 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1880 // input@path is set when the actual parameter original_path is set.
1881 // This is done for usual tex-file, but not for nice-latex-file.
1882 // (Matthias 250696)
1883 // Note that input@path is only needed for something the user does
1884 // in the preamble, included .tex files or ERT, files included by
1885 // LyX work without it.
1886 if (output_preamble) {
1887 if (!runparams.nice) {
1888 // code for usual, NOT nice-latex-file
1889 os << "\\batchmode\n"; // changed from \nonstopmode
1891 if (!original_path.empty()) {
1893 // We don't know the encoding of inputpath
1894 docstring const inputpath = from_utf8(original_path);
1895 docstring uncodable_glyphs;
1896 Encoding const * const enc = runparams.encoding;
1898 for (char_type n : inputpath) {
1899 if (!enc->encodable(n)) {
1900 docstring const glyph(1, n);
1901 LYXERR0("Uncodable character '"
1903 << "' in input path!");
1904 uncodable_glyphs += glyph;
1909 // warn user if we found uncodable glyphs.
1910 if (!uncodable_glyphs.empty()) {
1911 frontend::Alert::warning(
1912 _("Uncodable character in file path"),
1914 _("The path of your document\n"
1916 "contains glyphs that are unknown "
1917 "in the current document encoding "
1918 "(namely %2$s). This may result in "
1919 "incomplete output, unless "
1920 "TEXINPUTS contains the document "
1921 "directory and you don't use "
1922 "explicitly relative paths (i.e., "
1923 "paths starting with './' or "
1924 "'../') in the preamble or in ERT."
1925 "\n\nIn case of problems, choose "
1926 "an appropriate document encoding\n"
1927 "(such as utf8) or change the "
1929 inputpath, uncodable_glyphs));
1931 string docdir = os::latex_path(original_path);
1932 if (contains(docdir, '#')) {
1933 docdir = subst(docdir, "#", "\\#");
1934 os << "\\catcode`\\#=11"
1935 "\\def\\#{#}\\catcode`\\#=6\n";
1937 if (contains(docdir, '%')) {
1938 docdir = subst(docdir, "%", "\\%");
1939 os << "\\catcode`\\%=11"
1940 "\\def\\%{%}\\catcode`\\%=14\n";
1942 if (contains(docdir, '~'))
1943 docdir = subst(docdir, "~", "\\string~");
1944 bool const nonascii = !isAscii(from_utf8(docdir));
1945 // LaTeX 2019/10/01 handles non-ascii path without detokenize
1946 bool const utfpathlatex = features.isAvailable("LaTeX-2019/10/01");
1947 bool const detokenize = !utfpathlatex && nonascii;
1948 bool const quote = contains(docdir, ' ');
1949 if (utfpathlatex && nonascii)
1950 os << "\\UseRawInputEncoding\n";
1951 os << "\\makeatletter\n"
1952 << "\\def\\input@path{{";
1954 os << "\\detokenize{";
1963 << "\\makeatother\n";
1967 // get parent macros (if this buffer has a parent) which will be
1968 // written at the document begin further down.
1969 MacroSet parentMacros;
1970 listParentMacros(parentMacros, features);
1972 // Write the preamble
1973 runparams.use_babel = params().writeLaTeX(os, features,
1974 d->filename.onlyPath());
1976 // Active characters
1977 runparams.active_chars = features.getActiveChars();
1979 // Biblatex bibliographies are loaded here
1980 if (params().useBiblatex()) {
1981 vector<pair<docstring, string>> const bibfiles =
1982 prepareBibFilePaths(runparams, getBibfiles(), true);
1983 for (pair<docstring, string> const & file: bibfiles) {
1984 os << "\\addbibresource";
1985 if (!file.second.empty())
1986 os << "[bibencoding=" << file.second << "]";
1987 os << "{" << file.first << "}\n";
1991 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1992 && !features.hasOnlyPolyglossiaLanguages()) {
1995 vector<string> bll = features.getBabelExclusiveLanguages();
1996 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1999 for (string const & sit : bll) {
2004 blangs = bll.size() > 1 ?
2005 bformat(_("The languages %1$s are only supported by Babel."), langs)
2006 : bformat(_("The language %1$s is only supported by Babel."), langs);
2010 for (string const & pit : pll) {
2015 plangs = pll.size() > 1 ?
2016 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
2017 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
2018 if (!blangs.empty())
2022 frontend::Alert::warning(
2023 _("Incompatible Languages!"),
2025 _("You cannot use the following languages "
2026 "together in one LaTeX document because "
2027 "they require conflicting language packages:\n"
2032 // Japanese might be required only in some children of a document,
2033 // but once required, we must keep use_japanese true.
2034 runparams.use_japanese |= features.isRequired("japanese");
2037 // Restore the parenthood if needed
2038 if (!runparams.is_child)
2039 d->ignore_parent = false;
2040 return ExportSuccess;
2044 // mark the beginning of the body to separate it from InPreamble insets
2045 os.texrow().start(TexRow::beginDocument());
2046 os << "\\begin{document}\n";
2048 // mark the start of a new paragraph by simulating a newline,
2049 // so that os.afterParbreak() returns true at document start
2052 // output the parent macros
2053 for (auto const & mac : parentMacros) {
2054 int num_lines = mac->write(os.os(), true);
2055 os.texrow().newlines(num_lines);
2058 } // output_preamble
2060 LYXERR(Debug::INFO, "preamble finished, now the body.");
2064 latexParagraphs(*this, text(), os, runparams);
2066 catch (ConversionException const &) { return ExportKilled; }
2068 // Restore the parenthood if needed
2069 if (!runparams.is_child)
2070 d->ignore_parent = false;
2072 // add this just in case after all the paragraphs
2075 if (output_preamble) {
2076 os << "\\end{document}\n";
2077 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2079 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2081 runparams_in.encoding = runparams.encoding;
2083 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2084 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2085 return ExportSuccess;
2089 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2090 OutputParams const & runparams,
2091 OutputWhat output) const
2093 LYXERR(Debug::LATEX, "makeDocBookFile...");
2096 if (!openFileWrite(ofs, fname))
2099 // make sure we are ready to export
2100 // this needs to be done before we validate
2102 updateMacroInstances(OutputUpdate);
2104 ExportStatus const retval =
2105 writeDocBookSource(ofs, runparams, output);
2106 if (retval == ExportKilled)
2107 return ExportKilled;
2111 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2112 return ExportSuccess;
2116 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os,
2117 OutputParams const & runparams,
2118 OutputWhat output) const
2120 LaTeXFeatures features(*this, params(), runparams);
2122 d->bibinfo_.makeCitationLabels(*this);
2126 DocumentClass const & tclass = params().documentClass();
2128 bool const output_preamble =
2129 output == FullSource || output == OnlyPreamble;
2130 bool const output_body =
2131 output == FullSource || output == OnlyBody || output == IncludedFile;
2133 if (output_preamble) {
2134 // XML preamble, no doctype needed.
2135 // Not using XMLStream for this, as the root tag would be in the tag stack and make troubles with the error
2136 // detection mechanisms (these are called before the end tag is output, and thus interact with the canary
2137 // parsep in output_docbook.cpp).
2138 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2139 << "<!-- This DocBook file was created by LyX " << lyx_version
2140 << "\n See http://www.lyx.org/ for more information -->\n";
2142 // Directly output the root tag, based on the current type of document.
2143 string languageCode = params().language->code();
2144 string params = "xml:lang=\"" + languageCode + '"'
2145 + " xmlns=\"http://docbook.org/ns/docbook\""
2146 + " xmlns:xlink=\"http://www.w3.org/1999/xlink\""
2147 + " xmlns:m=\"http://www.w3.org/1998/Math/MathML\""
2148 + " xmlns:xi=\"http://www.w3.org/2001/XInclude\""
2149 + " version=\"5.2\"";
2151 os << "<" << from_ascii(tclass.docbookroot()) << " " << from_ascii(params) << ">\n";
2155 // Start to output the document.
2157 docbookParagraphs(text(), *this, xs, runparams);
2160 if (output_preamble) {
2161 // Close the root element. No need for a line break, as free text is never allowed
2162 // in a root element, it must always be wrapped in some container.
2163 os << "</" << from_ascii(tclass.docbookroot()) << ">";
2166 return ExportSuccess;
2170 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2171 OutputParams const & runparams) const
2173 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2176 if (!openFileWrite(ofs, fname))
2179 // make sure we are ready to export
2180 // this has to be done before we validate
2181 updateBuffer(UpdateMaster, OutputUpdate);
2182 updateMacroInstances(OutputUpdate);
2184 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2185 if (retval == ExportKilled)
2190 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2195 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2196 OutputParams const & runparams,
2197 OutputWhat output) const
2199 LaTeXFeatures features(*this, params(), runparams);
2201 d->bibinfo_.makeCitationLabels(*this);
2203 bool const output_preamble =
2204 output == FullSource || output == OnlyPreamble;
2205 bool const output_body =
2206 output == FullSource || output == OnlyBody || output == IncludedFile;
2208 if (output_preamble) {
2209 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2210 << "<!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"
2211 // FIXME Language should be set properly.
2212 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2214 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2215 // FIXME Presumably need to set this right
2216 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2218 docstring const & doctitle = features.htmlTitle();
2220 << (doctitle.empty() ?
2221 from_ascii("LyX Document") :
2222 xml::escapeString(doctitle, XMLStream::ESCAPE_ALL))
2225 docstring styles = features.getTClassHTMLPreamble();
2226 if (!styles.empty())
2227 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2229 // we will collect CSS information in a stream, and then output it
2230 // either here, as part of the header, or else in a separate file.
2231 odocstringstream css;
2232 styles = features.getCSSSnippets();
2233 if (!styles.empty())
2234 css << "/* LyX Provided Styles */\n" << styles << '\n';
2236 styles = features.getTClassHTMLStyles();
2237 if (!styles.empty())
2238 css << "/* Layout-provided Styles */\n" << styles << '\n';
2240 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2241 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2242 if (needfg || needbg) {
2243 css << "\nbody {\n";
2246 << from_ascii(X11hexname(params().fontcolor))
2249 css << " background-color: "
2250 << from_ascii(X11hexname(params().backgroundcolor))
2255 docstring const dstyles = css.str();
2256 if (!dstyles.empty()) {
2257 bool written = false;
2258 if (params().html_css_as_file) {
2259 // open a file for CSS info
2261 string const fcssname = addName(temppath(), "docstyle.css");
2262 FileName const fcssfile = FileName(fcssname);
2263 if (openFileWrite(ocss, fcssfile)) {
2267 // write link to header
2268 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2270 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2273 // we are here if the CSS is supposed to be written to the header
2274 // or if we failed to write it to an external file.
2276 os << "<style type='text/css'>\n"
2285 bool const output_body_tag = (output != IncludedFile);
2286 if (output_body_tag)
2287 os << "<body dir=\"auto\">\n";
2289 if (output != IncludedFile)
2290 // if we're an included file, the counters are in the master.
2291 params().documentClass().counters().reset();
2293 xhtmlParagraphs(text(), *this, xs, runparams);
2295 catch (ConversionException const &) { return ExportKilled; }
2296 if (output_body_tag)
2300 if (output_preamble)
2303 return ExportSuccess;
2307 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2308 // Other flags: -wall -v0 -x
2309 int Buffer::runChktex()
2313 // get LaTeX-Filename
2314 FileName const path(temppath());
2315 string const name = addName(path.absFileName(), latexName());
2316 string const org_path = filePath();
2318 PathChanger p(path); // path to LaTeX file
2319 message(_("Running chktex..."));
2321 // Generate the LaTeX file if neccessary
2322 OutputParams runparams(¶ms().encoding());
2323 runparams.flavor = Flavor::LaTeX;
2324 runparams.nice = false;
2325 runparams.linelen = lyxrc.plaintext_linelen;
2326 ExportStatus const retval =
2327 makeLaTeXFile(FileName(name), org_path, runparams);
2328 if (retval != ExportSuccess) {
2329 // error code on failure
2334 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2335 int const res = chktex.run(terr); // run chktex
2338 Alert::error(_("chktex failure"),
2339 _("Could not run chktex successfully."));
2341 ErrorList & errlist = d->errorLists["ChkTeX"];
2343 bufferErrors(terr, errlist);
2348 if (runparams.silent)
2349 d->errorLists["ChkTeX"].clear();
2357 void Buffer::validate(LaTeXFeatures & features) const
2359 // Validate the buffer params, but not for included
2360 // files, since they also use the parent buffer's
2362 if (!features.runparams().is_child)
2363 params().validate(features);
2368 for (Paragraph const & p : paragraphs())
2369 p.validate(features);
2371 if (lyxerr.debugging(Debug::LATEX)) {
2372 features.showStruct();
2377 void Buffer::getLabelList(vector<docstring> & list) const
2379 // If this is a child document, use the master's list instead.
2381 masterBuffer()->getLabelList(list);
2386 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2387 for (auto const & tocit : *toc) {
2388 if (tocit.depth() == 0)
2389 list.push_back(tocit.str());
2394 void Buffer::invalidateBibinfoCache() const
2396 d->bibinfo_cache_valid_ = false;
2397 d->cite_labels_valid_ = false;
2398 removeBiblioTempFiles();
2399 // also invalidate the cache for the parent buffer
2400 Buffer const * const pbuf = d->parent();
2402 pbuf->invalidateBibinfoCache();
2406 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2408 // FIXME This is probably unnecessary, given where we call this.
2409 // If this is a child document, use the master instead.
2410 Buffer const * const pbuf = masterBuffer();
2411 if (pbuf != this && scope != UpdateChildOnly)
2412 return pbuf->getBibfiles();
2414 // In 2.3.x, we have:
2415 //if (!d->bibfile_cache_valid_)
2416 // this->updateBibfilesCache(scope);
2417 // I think that is a leftover, but there have been so many back-
2418 // and-forths with this, due to Windows issues, that I am not sure.
2420 return d->bibfiles_cache_;
2424 BiblioInfo const & Buffer::masterBibInfo() const
2426 Buffer const * const tmp = masterBuffer();
2428 return tmp->masterBibInfo();
2433 BiblioInfo const & Buffer::bibInfo() const
2439 void Buffer::registerBibfiles(const docstring_list & bf) const
2441 // We register the bib files in the master buffer,
2442 // if there is one, but also in every single buffer,
2443 // in case a child is compiled alone.
2444 Buffer const * const tmp = masterBuffer();
2446 tmp->registerBibfiles(bf);
2448 for (auto const & p : bf) {
2449 docstring_list::const_iterator temp =
2450 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2451 if (temp == d->bibfiles_cache_.end())
2452 d->bibfiles_cache_.push_back(p);
2457 static map<docstring, FileName> bibfileCache;
2459 FileName Buffer::getBibfilePath(docstring const & bibid) const
2461 map<docstring, FileName>::const_iterator it =
2462 bibfileCache.find(bibid);
2463 if (it != bibfileCache.end()) {
2464 // i.e., return bibfileCache[bibid];
2468 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2469 string const texfile = changeExtension(to_utf8(bibid), "bib");
2470 // we need to check first if this file exists where it's said to be.
2471 // there's a weird bug that occurs otherwise: if the file is in the
2472 // Buffer's directory but has the same name as some file that would be
2473 // found by kpsewhich, then we find the latter, not the former.
2474 FileName const local_file = makeAbsPath(texfile, filePath());
2475 FileName file = local_file;
2476 if (!file.exists()) {
2477 // there's no need now to check whether the file can be found
2479 file = findtexfile(texfile, "bib", true);
2483 LYXERR(Debug::FILES, "Found at: " << file);
2485 bibfileCache[bibid] = file;
2486 return bibfileCache[bibid];
2490 void Buffer::checkIfBibInfoCacheIsValid() const
2492 // use the master's cache
2493 Buffer const * const tmp = masterBuffer();
2495 tmp->checkIfBibInfoCacheIsValid();
2499 // If we already know the cache is invalid, stop here.
2500 // This is important in the case when the bibliography
2501 // environment (rather than Bib[la]TeX) is used.
2502 // In that case, the timestamp check below gives no
2503 // sensible result. Rather than that, the cache will
2504 // be invalidated explicitly via invalidateBibInfoCache()
2505 // by the Bibitem inset.
2506 // Same applies for bib encoding changes, which trigger
2507 // invalidateBibInfoCache() by InsetBibtex.
2508 if (!d->bibinfo_cache_valid_)
2511 if (d->have_bibitems_) {
2512 // We have a bibliography environment.
2513 // Invalidate the bibinfo cache unconditionally.
2514 // Cite labels will get invalidated by the inset if needed.
2515 d->bibinfo_cache_valid_ = false;
2519 // OK. This is with Bib(la)tex. We'll assume the cache
2520 // is valid and change this if we find changes in the bibs.
2521 d->bibinfo_cache_valid_ = true;
2522 d->cite_labels_valid_ = true;
2524 // compare the cached timestamps with the actual ones.
2525 docstring_list const & bibfiles_cache = getBibfiles();
2526 for (auto const & bf : bibfiles_cache) {
2527 FileName const fn = getBibfilePath(bf);
2528 time_t lastw = fn.lastModified();
2529 time_t prevw = d->bibfile_status_[fn];
2530 if (lastw != prevw) {
2531 d->bibinfo_cache_valid_ = false;
2532 d->cite_labels_valid_ = false;
2533 d->bibfile_status_[fn] = lastw;
2539 void Buffer::clearBibFileCache() const
2541 bibfileCache.clear();
2545 void Buffer::reloadBibInfoCache(bool const force) const
2547 // we should not need to do this for internal buffers
2551 // use the master's cache
2552 Buffer const * const tmp = masterBuffer();
2554 tmp->reloadBibInfoCache(force);
2559 checkIfBibInfoCacheIsValid();
2560 if (d->bibinfo_cache_valid_)
2564 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2565 // re-read file locations when this info changes
2566 // FIXME Is this sufficient? Or should we also force that
2567 // in some other cases? If so, then it is easy enough to
2568 // add the following line in some other places.
2569 clearBibFileCache();
2570 d->bibinfo_.clear();
2571 FileNameList checkedFiles;
2572 d->have_bibitems_ = false;
2573 collectBibKeys(checkedFiles);
2574 d->bibinfo_cache_valid_ = true;
2578 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2583 for (InsetIterator it = begin(inset()); it; ++it) {
2584 it->collectBibKeys(it, checkedFiles);
2585 if (it->lyxCode() == BIBITEM_CODE) {
2586 if (parent() != nullptr)
2587 parent()->d->have_bibitems_ = true;
2589 d->have_bibitems_ = true;
2595 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2597 // We add the biblio info to the master buffer,
2598 // if there is one, but also to every single buffer,
2599 // in case a child is compiled alone.
2600 BiblioInfo & bi = d->bibinfo_;
2601 bi.mergeBiblioInfo(bin);
2603 if (parent() != nullptr) {
2604 BiblioInfo & masterbi = parent()->d->bibinfo_;
2605 masterbi.mergeBiblioInfo(bin);
2610 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2612 // We add the bibtex info to the master buffer,
2613 // if there is one, but also to every single buffer,
2614 // in case a child is compiled alone.
2615 BiblioInfo & bi = d->bibinfo_;
2618 if (parent() != nullptr) {
2619 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2620 masterbi[key] = bin;
2625 void Buffer::makeCitationLabels() const
2627 Buffer const * const master = masterBuffer();
2628 return d->bibinfo_.makeCitationLabels(*master);
2632 void Buffer::invalidateCiteLabels() const
2634 masterBuffer()->d->cite_labels_valid_ = false;
2637 bool Buffer::citeLabelsValid() const
2639 return masterBuffer()->d->cite_labels_valid_;
2643 void Buffer::removeBiblioTempFiles() const
2645 // We remove files that contain LaTeX commands specific to the
2646 // particular bibliographic style being used, in order to avoid
2647 // LaTeX errors when we switch style.
2648 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2649 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2650 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2651 aux_file.removeFile();
2652 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2653 bbl_file.removeFile();
2654 // Also for the parent buffer
2655 Buffer const * const pbuf = parent();
2657 pbuf->removeBiblioTempFiles();
2661 bool Buffer::isDepClean(string const & name) const
2663 DepClean::const_iterator const it = d->dep_clean.find(name);
2664 if (it == d->dep_clean.end())
2670 void Buffer::markDepClean(string const & name)
2672 d->dep_clean[name] = true;
2676 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2679 // FIXME? if there is an Buffer LFUN that can be dispatched even
2680 // if internal, put a switch '(cmd.action)' here.
2686 switch (cmd.action()) {
2688 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2689 flag.setOnOff(hasReadonlyFlag());
2692 // FIXME: There is need for a command-line import.
2693 //case LFUN_BUFFER_IMPORT:
2695 case LFUN_BUFFER_AUTO_SAVE:
2698 case LFUN_BUFFER_EXPORT_CUSTOM:
2699 // FIXME: Nothing to check here?
2702 case LFUN_BUFFER_EXPORT: {
2703 docstring const & arg = cmd.argument();
2704 if (arg == "custom") {
2708 string format = (arg.empty() || arg == "default") ?
2709 params().getDefaultOutputFormat() : to_utf8(arg);
2710 size_t pos = format.find(' ');
2711 if (pos != string::npos)
2712 format = format.substr(0, pos);
2713 enable = params().isExportable(format, false);
2715 flag.message(bformat(
2716 _("Don't know how to export to format: %1$s"), arg));
2720 case LFUN_BUILD_PROGRAM:
2721 enable = params().isExportable("program", false);
2724 case LFUN_BRANCH_ACTIVATE:
2725 case LFUN_BRANCH_DEACTIVATE:
2726 case LFUN_BRANCH_MASTER_ACTIVATE:
2727 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2728 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2729 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2730 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2731 : params().branchlist();
2732 docstring const & branchName = cmd.argument();
2733 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2737 case LFUN_BRANCH_ADD:
2738 case LFUN_BRANCHES_RENAME:
2739 // if no Buffer is present, then of course we won't be called!
2742 case LFUN_BUFFER_LANGUAGE:
2743 enable = !isReadonly();
2746 case LFUN_BUFFER_VIEW_CACHE:
2747 (d->preview_file_).refresh();
2748 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2751 case LFUN_CHANGES_TRACK:
2752 flag.setEnabled(true);
2753 flag.setOnOff(params().track_changes);
2756 case LFUN_CHANGES_OUTPUT:
2757 flag.setEnabled(true);
2758 flag.setOnOff(params().output_changes);
2761 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2762 flag.setOnOff(params().compressed);
2765 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2766 flag.setOnOff(params().output_sync);
2769 case LFUN_BUFFER_ANONYMIZE:
2775 flag.setEnabled(enable);
2780 void Buffer::dispatch(string const & command, DispatchResult & result)
2782 return dispatch(lyxaction.lookupFunc(command), result);
2786 // NOTE We can end up here even if we have no GUI, because we are called
2787 // by LyX::exec to handled command-line requests. So we may need to check
2788 // whether we have a GUI or not. The boolean use_gui holds this information.
2789 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2792 // FIXME? if there is an Buffer LFUN that can be dispatched even
2793 // if internal, put a switch '(cmd.action())' here.
2794 dr.dispatched(false);
2797 string const argument = to_utf8(func.argument());
2798 // We'll set this back to false if need be.
2799 bool dispatched = true;
2800 // This handles undo groups automagically
2801 UndoGroupHelper ugh(this);
2803 switch (func.action()) {
2804 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2805 if (lyxvc().inUse()) {
2806 string log = lyxvc().toggleReadOnly();
2811 setReadonly(!hasReadonlyFlag());
2814 case LFUN_BUFFER_EXPORT: {
2815 string const format = (argument.empty() || argument == "default") ?
2816 params().getDefaultOutputFormat() : argument;
2817 ExportStatus const status = doExport(format, false);
2818 dr.setError(status != ExportSuccess);
2819 if (status != ExportSuccess)
2820 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2821 from_utf8(format)));
2825 case LFUN_BUILD_PROGRAM: {
2826 ExportStatus const status = doExport("program", true);
2827 dr.setError(status != ExportSuccess);
2828 if (status != ExportSuccess)
2829 dr.setMessage(_("Error generating literate programming code."));
2833 case LFUN_BUFFER_EXPORT_CUSTOM: {
2835 string command = split(argument, format_name, ' ');
2836 Format const * format = theFormats().getFormat(format_name);
2838 lyxerr << "Format \"" << format_name
2839 << "\" not recognized!"
2844 // The name of the file created by the conversion process
2847 // Output to filename
2848 if (format->name() == "lyx") {
2849 string const latexname = latexName(false);
2850 filename = changeExtension(latexname,
2851 format->extension());
2852 filename = addName(temppath(), filename);
2854 if (!writeFile(FileName(filename)))
2858 doExport(format_name, true, filename);
2861 // Substitute $$FName for filename
2862 if (!contains(command, "$$FName"))
2863 command = "( " + command + " ) < $$FName";
2864 command = subst(command, "$$FName", filename);
2866 // Execute the command in the background
2868 call.startscript(Systemcall::DontWait, command,
2869 filePath(), layoutPos());
2873 // FIXME: There is need for a command-line import.
2875 case LFUN_BUFFER_IMPORT:
2880 case LFUN_BUFFER_AUTO_SAVE:
2882 resetAutosaveTimers();
2885 case LFUN_BRANCH_ACTIVATE:
2886 case LFUN_BRANCH_DEACTIVATE:
2887 case LFUN_BRANCH_MASTER_ACTIVATE:
2888 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2889 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2890 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2891 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2894 docstring const & branch_name = func.argument();
2895 // the case without a branch name is handled elsewhere
2896 if (branch_name.empty()) {
2900 Branch * branch = buf->params().branchlist().find(branch_name);
2902 LYXERR0("Branch " << branch_name << " does not exist.");
2904 docstring const msg =
2905 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2909 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2910 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2911 if (branch->isSelected() != activate) {
2912 buf->undo().recordUndoBufferParams(CursorData());
2913 branch->setSelected(activate);
2915 dr.screenUpdate(Update::Force);
2916 dr.forceBufferUpdate();
2921 case LFUN_BRANCH_ADD: {
2922 docstring const & branchnames = func.argument();
2923 if (branchnames.empty()) {
2927 BranchList & branch_list = params().branchlist();
2928 vector<docstring> const branches =
2929 getVectorFromString(branchnames, branch_list.separator());
2931 for (docstring const & branch_name : branches) {
2932 Branch * branch = branch_list.find(branch_name);
2934 LYXERR0("Branch " << branch_name << " already exists.");
2938 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2940 undo().recordUndoBufferParams(CursorData());
2941 branch_list.add(branch_name);
2942 branch = branch_list.find(branch_name);
2943 string const x11hexname = X11hexname(branch->color());
2944 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2945 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2947 dr.screenUpdate(Update::Force);
2955 case LFUN_BRANCHES_RENAME: {
2956 if (func.argument().empty())
2959 docstring const oldname = from_utf8(func.getArg(0));
2960 docstring const newname = from_utf8(func.getArg(1));
2961 InsetIterator it = begin(inset());
2962 InsetIterator const itend = end(inset());
2963 bool success = false;
2964 for (; it != itend; ++it) {
2965 if (it->lyxCode() == BRANCH_CODE) {
2966 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2967 if (ins.branch() == oldname) {
2968 undo().recordUndo(CursorData(it));
2969 ins.rename(newname);
2974 if (it->lyxCode() == INCLUDE_CODE) {
2975 // get buffer of external file
2976 InsetInclude const & ins =
2977 static_cast<InsetInclude const &>(*it);
2978 Buffer * child = ins.loadIfNeeded();
2981 child->dispatch(func, dr);
2986 dr.screenUpdate(Update::Force);
2987 dr.forceBufferUpdate();
2992 case LFUN_BUFFER_VIEW_CACHE:
2993 if (!theFormats().view(*this, d->preview_file_,
2994 d->preview_format_))
2995 dr.setMessage(_("Error viewing the output file."));
2998 case LFUN_CHANGES_TRACK:
2999 if (params().save_transient_properties)
3000 undo().recordUndoBufferParams(CursorData());
3001 params().track_changes = !params().track_changes;
3004 case LFUN_CHANGES_OUTPUT:
3005 if (params().save_transient_properties)
3006 undo().recordUndoBufferParams(CursorData());
3007 params().output_changes = !params().output_changes;
3008 if (params().output_changes) {
3009 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
3010 LaTeXFeatures::isAvailable("xcolor");
3013 Alert::warning(_("Changes not shown in LaTeX output"),
3014 _("Changes will not be highlighted in LaTeX output, "
3015 "because xcolor and ulem are not installed.\n"
3016 "Please install both packages or redefine "
3017 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3022 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3023 // turn compression on/off
3024 undo().recordUndoBufferParams(CursorData());
3025 params().compressed = !params().compressed;
3028 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3029 undo().recordUndoBufferParams(CursorData());
3030 params().output_sync = !params().output_sync;
3033 case LFUN_BUFFER_ANONYMIZE: {
3034 undo().recordUndoFullBuffer(CursorData());
3035 CursorData cur(doc_iterator_begin(this));
3036 for ( ; cur ; cur.forwardPar())
3037 cur.paragraph().anonymize();
3038 dr.forceBufferUpdate();
3039 dr.screenUpdate(Update::Force);
3047 dr.dispatched(dispatched);
3051 void Buffer::changeLanguage(Language const * from, Language const * to)
3053 LASSERT(from, return);
3054 LASSERT(to, return);
3056 ParIterator it = par_iterator_begin();
3057 ParIterator eit = par_iterator_end();
3058 for (; it != eit; ++it)
3059 it->changeLanguage(params(), from, to);
3063 bool Buffer::isMultiLingual() const
3065 ParConstIterator end = par_iterator_end();
3066 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3067 if (it->isMultiLingual(params()))
3074 std::set<Language const *> Buffer::getLanguages() const
3076 std::set<Language const *> langs;
3077 getLanguages(langs);
3082 void Buffer::getLanguages(std::set<Language const *> & langs) const
3084 ParConstIterator end = par_iterator_end();
3085 // add the buffer language, even if it's not actively used
3086 langs.insert(language());
3087 // iterate over the paragraphs
3088 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3089 it->getLanguages(langs);
3091 ListOfBuffers clist = getDescendants();
3092 for (auto const & cit : clist)
3093 cit->getLanguages(langs);
3097 DocIterator Buffer::getParFromID(int const id) const
3099 Buffer * buf = const_cast<Buffer *>(this);
3101 // This means non-existent
3102 return doc_iterator_end(buf);
3104 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3105 if (it.paragraph().id() == id)
3108 return doc_iterator_end(buf);
3112 bool Buffer::hasParWithID(int const id) const
3114 return !getParFromID(id).atEnd();
3118 ParIterator Buffer::par_iterator_begin()
3120 return ParIterator(doc_iterator_begin(this));
3124 ParIterator Buffer::par_iterator_end()
3126 return ParIterator(doc_iterator_end(this));
3130 ParConstIterator Buffer::par_iterator_begin() const
3132 return ParConstIterator(doc_iterator_begin(this));
3136 ParConstIterator Buffer::par_iterator_end() const
3138 return ParConstIterator(doc_iterator_end(this));
3142 Language const * Buffer::language() const
3144 return params().language;
3148 docstring Buffer::B_(string const & l10n) const
3150 return params().B_(l10n);
3154 bool Buffer::isClean() const
3156 return d->lyx_clean;
3160 bool Buffer::isChecksumModified() const
3162 LASSERT(d->filename.exists(), return false);
3163 return d->checksum_ != d->filename.checksum();
3167 void Buffer::saveCheckSum() const
3169 FileName const & file = d->filename;
3171 d->checksum_ = file.exists() ? file.checksum()
3172 : 0; // in the case of save to a new file.
3176 void Buffer::markClean() const
3178 if (!d->lyx_clean) {
3179 d->lyx_clean = true;
3182 // if the .lyx file has been saved, we don't need an
3184 d->bak_clean = true;
3185 d->undo_.markDirty();
3186 clearExternalModification();
3190 void Buffer::setUnnamed(bool flag)
3196 bool Buffer::isUnnamed() const
3203 /// Don't check unnamed, here: isInternal() is used in
3204 /// newBuffer(), where the unnamed flag has not been set by anyone
3205 /// yet. Also, for an internal buffer, there should be no need for
3206 /// retrieving fileName() nor for checking if it is unnamed or not.
3207 bool Buffer::isInternal() const
3209 return d->internal_buffer;
3213 void Buffer::setInternal(bool flag)
3215 d->internal_buffer = flag;
3219 void Buffer::markDirty()
3222 d->lyx_clean = false;
3225 d->bak_clean = false;
3227 for (auto & depit : d->dep_clean)
3228 depit.second = false;
3232 FileName Buffer::fileName() const
3238 string Buffer::absFileName() const
3240 return d->filename.absFileName();
3244 string Buffer::filePath() const
3246 string const abs = d->filename.onlyPath().absFileName();
3249 int last = abs.length() - 1;
3251 return abs[last] == '/' ? abs : abs + '/';
3255 DocFileName Buffer::getReferencedFileName(string const & fn) const
3258 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3259 result.set(fn, filePath());
3261 // filePath() ends with a path separator
3262 FileName const test(filePath() + fn);
3264 result.set(fn, filePath());
3266 result.set(fn, params().origin);
3273 string const Buffer::prepareFileNameForLaTeX(string const & name,
3274 string const & ext, bool nice) const
3276 string const fname = makeAbsPath(name, filePath()).absFileName();
3277 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3283 return to_utf8(makeRelPath(from_utf8(fname),
3284 from_utf8(masterBuffer()->filePath())));
3288 vector<pair<docstring, string>> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3289 docstring_list const & bibfilelist,
3290 bool const add_extension) const
3292 // If we are processing the LaTeX file in a temp directory then
3293 // copy the .bib databases to this temp directory, mangling their
3294 // names in the process. Store this mangled name in the list of
3296 // (We need to do all this because BibTeX *really*, *really*
3297 // can't handle "files with spaces" and Windows users tend to
3298 // use such filenames.)
3299 // Otherwise, store the (maybe absolute) path to the original,
3300 // unmangled database name.
3302 vector<pair<docstring, string>> res;
3304 // determine the export format
3305 string const tex_format = flavor2format(runparams.flavor);
3307 // check for spaces in paths
3308 bool found_space = false;
3310 for (auto const & bit : bibfilelist) {
3311 string utf8input = to_utf8(bit);
3313 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3314 FileName try_in_file =
3315 makeAbsPath(database + ".bib", filePath());
3316 bool not_from_texmf = try_in_file.isReadableFile();
3317 // If the file has not been found, try with the real file name
3318 // (it might come from a child in a sub-directory)
3319 if (!not_from_texmf) {
3320 try_in_file = getBibfilePath(bit);
3321 if (try_in_file.isReadableFile()) {
3322 // Check if the file is in texmf
3323 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3324 not_from_texmf = kpsefile.empty()
3325 || kpsefile.absFileName() != try_in_file.absFileName();
3327 // If this exists, make path relative to the master
3330 removeExtension(prepareFileNameForLaTeX(
3331 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3332 from_utf8(filePath()))),
3333 ".bib", runparams.nice));
3337 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3339 // mangledFileName() needs the extension
3340 DocFileName const in_file = DocFileName(try_in_file);
3341 database = removeExtension(in_file.mangledFileName());
3342 FileName const out_file = makeAbsPath(database + ".bib",
3343 masterBuffer()->temppath());
3344 bool const success = in_file.copyTo(out_file);
3346 LYXERR0("Failed to copy '" << in_file
3347 << "' to '" << out_file << "'");
3349 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3350 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3351 if (!isValidLaTeXFileName(database)) {
3352 frontend::Alert::warning(_("Invalid filename"),
3353 _("The following filename will cause troubles "
3354 "when running the exported file through LaTeX: ") +
3355 from_utf8(database));
3357 if (!isValidDVIFileName(database)) {
3358 frontend::Alert::warning(_("Problematic filename for DVI"),
3359 _("The following filename can cause troubles "
3360 "when running the exported file through LaTeX "
3361 "and opening the resulting DVI: ") +
3362 from_utf8(database), true);
3370 docstring const path = from_utf8(latex_path(database));
3372 if (contains(path, ' '))
3375 if (params().useBiblatex() && !params().bibFileEncoding(utf8input).empty())
3376 enc = params().bibFileEncoding(utf8input);
3378 bool recorded = false;
3379 for (auto const & pe : res) {
3380 if (pe.first == path) {
3387 res.push_back(make_pair(path, enc));
3390 // Check if there are spaces in the path and warn BibTeX users, if so.
3391 // (biber can cope with such paths)
3392 if (!prefixIs(runparams.bibtex_command, "biber")) {
3393 // Post this warning only once.
3394 static bool warned_about_spaces = false;
3395 if (!warned_about_spaces &&
3396 runparams.nice && found_space) {
3397 warned_about_spaces = true;
3398 Alert::warning(_("Export Warning!"),
3399 _("There are spaces in the paths to your BibTeX databases.\n"
3400 "BibTeX will be unable to find them."));
3409 string Buffer::layoutPos() const
3411 return d->layout_position;
3415 void Buffer::setLayoutPos(string const & path)
3418 d->layout_position.clear();
3422 LATTEST(FileName::isAbsolute(path));
3424 d->layout_position =
3425 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3427 if (d->layout_position.empty())
3428 d->layout_position = ".";
3432 bool Buffer::hasReadonlyFlag() const
3434 return d->read_only;
3438 bool Buffer::isReadonly() const
3440 return hasReadonlyFlag() || notifiesExternalModification();
3444 void Buffer::setParent(Buffer const * buffer)
3446 // We need to do some work here to avoid recursive parent structures.
3447 // This is the easy case.
3448 if (buffer == this) {
3449 LYXERR0("Ignoring attempt to set self as parent in\n" << fileName());
3452 // Now we check parents going upward, to make sure that IF we set the
3453 // parent as requested, we would not generate a recursive include.
3454 set<Buffer const *> sb;
3455 Buffer const * b = buffer;
3456 bool found_recursion = false;
3458 if (sb.find(b) != sb.end()) {
3459 found_recursion = true;
3466 if (found_recursion) {
3467 LYXERR0("Ignoring attempt to set parent of\n" <<
3470 buffer->fileName() <<
3471 "\nbecause that would create a recursive inclusion.");
3475 // We should be safe now.
3476 d->setParent(buffer);
3481 Buffer const * Buffer::parent() const
3487 ListOfBuffers Buffer::allRelatives() const
3489 ListOfBuffers lb = masterBuffer()->getDescendants();
3490 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3495 Buffer const * Buffer::masterBuffer() const
3497 Buffer const * const pbuf = d->parent();
3501 return pbuf->masterBuffer();
3505 bool Buffer::isChild(Buffer * child) const
3507 return d->children_positions.find(child) != d->children_positions.end();
3511 DocIterator Buffer::firstChildPosition(Buffer const * child)
3513 Impl::BufferPositionMap::iterator it;
3514 it = d->children_positions.find(child);
3515 if (it == d->children_positions.end())
3516 return DocIterator(this);
3521 bool Buffer::hasChildren() const
3523 return !d->children_positions.empty();
3527 void Buffer::collectChildren(ListOfBuffers & children, bool grand_children) const
3529 // loop over children
3530 for (auto const & p : d->children_positions) {
3531 Buffer * child = const_cast<Buffer *>(p.first);
3533 ListOfBuffers::const_iterator bit = find(children.begin(), children.end(), child);
3534 if (bit != children.end())
3536 children.push_back(child);
3538 // there might be grandchildren
3539 child->collectChildren(children, true);
3544 ListOfBuffers Buffer::getChildren() const
3547 collectChildren(v, false);
3548 // Make sure we have not included ourselves.
3549 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3550 if (bit != v.end()) {
3551 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3558 ListOfBuffers Buffer::getDescendants() const
3561 collectChildren(v, true);
3562 // Make sure we have not included ourselves.
3563 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3564 if (bit != v.end()) {
3565 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3572 template<typename M>
3573 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3578 typename M::const_iterator it = m.lower_bound(x);
3579 if (it == m.begin())
3587 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3588 DocIterator const & pos) const
3590 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3592 // if paragraphs have no macro context set, pos will be empty
3596 // we haven't found anything yet
3597 DocIterator bestPos = owner_->par_iterator_begin();
3598 MacroData const * bestData = nullptr;
3600 // find macro definitions for name
3601 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3602 if (nameIt != macros.end()) {
3603 // find last definition in front of pos or at pos itself
3604 PositionScopeMacroMap::const_iterator it
3605 = greatest_below(nameIt->second, pos);
3606 if (it != nameIt->second.end()) {
3608 // scope ends behind pos?
3609 if (pos < it->second.scope) {
3610 // Looks good, remember this. If there
3611 // is no external macro behind this,
3612 // we found the right one already.
3613 bestPos = it->first;
3614 bestData = &it->second.macro;
3618 // try previous macro if there is one
3619 if (it == nameIt->second.begin())
3626 // find macros in included files
3627 PositionScopeBufferMap::const_iterator it
3628 = greatest_below(position_to_children, pos);
3629 if (it == position_to_children.end())
3630 // no children before
3634 // do we know something better (i.e. later) already?
3635 if (it->first < bestPos )
3638 // scope ends behind pos?
3639 if (pos < it->second.scope
3640 && (cloned_buffer_ ||
3641 theBufferList().isLoaded(it->second.buffer))) {
3642 // look for macro in external file
3644 MacroData const * data
3645 = it->second.buffer->getMacro(name, false);
3648 bestPos = it->first;
3654 // try previous file if there is one
3655 if (it == position_to_children.begin())
3660 // return the best macro we have found
3665 MacroData const * Buffer::getMacro(docstring const & name,
3666 DocIterator const & pos, bool global) const
3671 // query buffer macros
3672 MacroData const * data = d->getBufferMacro(name, pos);
3673 if (data != nullptr)
3676 // If there is a master buffer, query that
3677 Buffer const * const pbuf = d->parent();
3679 d->macro_lock = true;
3680 MacroData const * macro = pbuf->getMacro(
3681 name, *this, false);
3682 d->macro_lock = false;
3688 data = MacroTable::globalMacros().get(name);
3689 if (data != nullptr)
3697 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3699 // set scope end behind the last paragraph
3700 DocIterator scope = par_iterator_begin();
3701 scope.pit() = scope.lastpit() + 1;
3703 return getMacro(name, scope, global);
3707 MacroData const * Buffer::getMacro(docstring const & name,
3708 Buffer const & child, bool global) const
3710 // look where the child buffer is included first
3711 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3712 if (it == d->children_positions.end())
3715 // check for macros at the inclusion position
3716 return getMacro(name, it->second, global);
3720 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3722 pit_type const lastpit = it.lastpit();
3724 // look for macros in each paragraph
3725 while (it.pit() <= lastpit) {
3726 Paragraph & par = it.paragraph();
3728 // iterate over the insets of the current paragraph
3729 for (auto const & insit : par.insetList()) {
3730 it.pos() = insit.pos;
3732 // is it a nested text inset?
3733 if (insit.inset->asInsetText()) {
3734 // Inset needs its own scope?
3735 InsetText const * itext = insit.inset->asInsetText();
3736 bool newScope = itext->isMacroScope();
3738 // scope which ends just behind the inset
3739 DocIterator insetScope = it;
3742 // collect macros in inset
3743 it.push_back(CursorSlice(*insit.inset));
3744 updateMacros(it, newScope ? insetScope : scope);
3749 if (insit.inset->asInsetTabular()) {
3750 CursorSlice slice(*insit.inset);
3751 size_t const numcells = slice.nargs();
3752 for (; slice.idx() < numcells; slice.forwardIdx()) {
3753 it.push_back(slice);
3754 updateMacros(it, scope);
3760 // is it an external file?
3761 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3762 // get buffer of external file
3763 InsetInclude const & incinset =
3764 static_cast<InsetInclude const &>(*insit.inset);
3766 Buffer * child = incinset.loadIfNeeded();
3771 // register its position, but only when it is
3772 // included first in the buffer
3773 children_positions.insert({child, it});
3775 // register child with its scope
3776 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3780 InsetMath * im = insit.inset->asInsetMath();
3781 if (doing_export && im) {
3782 InsetMathHull * hull = im->asHullInset();
3784 hull->recordLocation(it);
3787 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3791 InsetMathMacroTemplate & macroTemplate =
3792 *insit.inset->asInsetMath()->asMacroTemplate();
3793 MacroContext mc(owner_, it);
3794 macroTemplate.updateToContext(mc);
3797 bool valid = macroTemplate.validMacro();
3798 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3799 // then the BufferView's cursor will be invalid in
3800 // some cases which leads to crashes.
3805 // FIXME (Abdel), I don't understand why we pass 'it' here
3806 // instead of 'macroTemplate' defined above... is this correct?
3807 macros[macroTemplate.name()][it] =
3808 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3818 void Buffer::updateMacros() const
3823 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3825 // start with empty table
3827 d->children_positions.clear();
3828 d->position_to_children.clear();
3830 // Iterate over buffer, starting with first paragraph
3831 // The scope must be bigger than any lookup DocIterator
3832 // later. For the global lookup, lastpit+1 is used, hence
3833 // we use lastpit+2 here.
3834 DocIterator it = par_iterator_begin();
3835 DocIterator outerScope = it;
3836 outerScope.pit() = outerScope.lastpit() + 2;
3837 d->updateMacros(it, outerScope);
3841 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3843 for (Inset const & it : inset()) {
3844 if (it.lyxCode() == BRANCH_CODE) {
3845 InsetBranch const & br = static_cast<InsetBranch const &>(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.loadIfNeeded();
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 idx_type n = minset->nargs();
3883 MacroContext mc = MacroContext(this, it);
3884 for (idx_type i = 0; i < n; ++i) {
3885 MathData & data = minset->cell(i);
3886 data.updateMacros(nullptr, 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 const & rc : masterBuffer()->d->label_cache_) {
3990 if (rc.label == label && (rc.active || !active))
3997 bool Buffer::activeLabel(docstring const & label) const
3999 return insetLabel(label, true) != nullptr;
4003 void Buffer::clearReferenceCache() const
4006 d->ref_cache_.clear();
4007 d->label_cache_.clear();
4012 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
4014 //FIXME: This does not work for child documents yet.
4015 reloadBibInfoCache();
4017 // Check if the label 'from' appears more than once
4018 vector<docstring> labels;
4019 for (auto const & bibit : masterBibInfo())
4020 labels.push_back(bibit.first);
4022 if (count(labels.begin(), labels.end(), from) > 1)
4025 string const paramName = "key";
4026 UndoGroupHelper ugh(this);
4027 InsetIterator it = begin(inset());
4029 if (it->lyxCode() != CITE_CODE)
4031 InsetCommand * inset = it->asInsetCommand();
4032 docstring const oldValue = inset->getParam(paramName);
4033 if (oldValue == from) {
4034 undo().recordUndo(CursorData(it));
4035 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 == Flavor::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 == Flavor::Html) {
4079 setMathFlavor(runparams);
4080 xhtmlParagraphs(text(), *this, xs, runparams);
4081 } else if (runparams.flavor == Flavor::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 (runparams.flavor == Flavor::DocBook5) {
4089 docbookParagraphs(text(), *this, xs, runparams);
4091 // If we are previewing a paragraph, even if this is the
4092 // child of some other buffer, let's cut the link here,
4093 // so that no concurring settings from the master
4094 // (e.g. branch state) interfere (see #8101).
4096 d->ignore_parent = true;
4097 // We need to validate the Buffer params' features here
4098 // in order to know if we should output polyglossia
4099 // macros (instead of babel macros)
4100 LaTeXFeatures features(*this, params(), runparams);
4102 runparams.use_polyglossia = features.usePolyglossia();
4103 runparams.use_hyperref = features.isRequired("hyperref");
4104 // latex or literate
4107 ots.texrow().newlines(2);
4109 latexParagraphs(*this, text(), ots, runparams);
4110 texrow = ots.releaseTexRow();
4112 // Restore the parenthood
4114 d->ignore_parent = false;
4118 if (output == FullSource)
4119 os << _("Preview source code");
4120 else if (output == OnlyPreamble)
4121 os << _("Preview preamble");
4122 else if (output == OnlyBody)
4123 os << _("Preview body");
4125 if (runparams.flavor == Flavor::LyX) {
4127 if (output == FullSource)
4129 else if (output == OnlyPreamble)
4130 params().writeFile(ods, this);
4131 else if (output == OnlyBody)
4133 os << from_utf8(ods.str());
4134 } else if (runparams.flavor == Flavor::Html) {
4135 writeLyXHTMLSource(os, runparams, output);
4136 } else if (runparams.flavor == Flavor::Text) {
4137 if (output == OnlyPreamble) {
4138 os << "% "<< _("Plain text does not have a preamble.");
4140 writePlaintextFile(*this, os, runparams);
4141 } else if (runparams.flavor == Flavor::DocBook5) {
4142 writeDocBookSource(os, runparams, output);
4144 // latex or literate
4147 ots.texrow().newlines(2);
4149 runparams.is_child = true;
4151 writeLaTeXSource(ots, string(), runparams, output);
4152 texrow = ots.releaseTexRow();
4159 ErrorList & Buffer::errorList(string const & type) const
4161 return d->errorLists[type];
4165 void Buffer::updateTocItem(std::string const & type,
4166 DocIterator const & dit) const
4169 d->gui_->updateTocItem(type, dit);
4173 void Buffer::structureChanged() const
4176 d->gui_->structureChanged();
4180 void Buffer::errors(string const & err, bool from_master) const
4183 d->gui_->errors(err, from_master);
4187 void Buffer::message(docstring const & msg) const
4190 d->gui_->message(msg);
4194 void Buffer::setBusy(bool on) const
4197 d->gui_->setBusy(on);
4201 void Buffer::updateTitles() const
4204 d->wa_->updateTitles();
4208 void Buffer::resetAutosaveTimers() const
4211 d->gui_->resetAutosaveTimers();
4215 bool Buffer::hasGuiDelegate() const
4221 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4227 FileName Buffer::getEmergencyFileName() const
4229 return FileName(d->filename.absFileName() + ".emergency");
4233 FileName Buffer::getAutosaveFileName() const
4235 // if the document is unnamed try to save in the backup dir, else
4236 // in the default document path, and as a last try in the filePath,
4237 // which will most often be the temporary directory
4240 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4241 : lyxrc.backupdir_path;
4242 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4245 string const fname = "#" + d->filename.onlyFileName() + "#";
4247 return makeAbsPath(fname, fpath);
4251 void Buffer::removeAutosaveFile() const
4253 FileName const f = getAutosaveFileName();
4259 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4261 FileName const newauto = getAutosaveFileName();
4263 if (newauto != oldauto && oldauto.exists())
4264 if (!oldauto.moveTo(newauto))
4265 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4269 bool Buffer::autoSave() const
4271 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4272 if (buf->d->bak_clean || hasReadonlyFlag())
4275 message(_("Autosaving current document..."));
4276 buf->d->bak_clean = true;
4278 FileName const fname = getAutosaveFileName();
4279 LASSERT(d->cloned_buffer_, return false);
4281 // If this buffer is cloned, we assume that
4282 // we are running in a separate thread already.
4283 TempFile tempfile("lyxautoXXXXXX.lyx");
4284 tempfile.setAutoRemove(false);
4285 FileName const tmp_ret = tempfile.name();
4286 if (!tmp_ret.empty()) {
4288 // assume successful write of tmp_ret
4289 if (tmp_ret.moveTo(fname))
4292 // failed to write/rename tmp_ret so try writing direct
4293 return writeFile(fname);
4297 void Buffer::setExportStatus(bool e) const
4299 d->doing_export = e;
4300 ListOfBuffers clist = getDescendants();
4301 for (auto const & bit : clist)
4302 bit->d->doing_export = e;
4306 bool Buffer::isExporting() const
4308 return d->doing_export;
4312 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4316 return doExport(target, put_in_tempdir, result_file);
4319 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4320 string & result_file) const
4322 bool const update_unincluded =
4323 params().maintain_unincluded_children != BufferParams::CM_None
4324 && !params().getIncludedChildren().empty();
4326 // (1) export with all included children (omit \includeonly)
4327 if (update_unincluded) {
4328 ExportStatus const status =
4329 doExport(target, put_in_tempdir, true, result_file);
4330 if (status != ExportSuccess)
4333 // (2) export with included children only
4334 return doExport(target, put_in_tempdir, false, result_file);
4338 void Buffer::setMathFlavor(OutputParams & op) const
4340 switch (params().html_math_output) {
4341 case BufferParams::MathML:
4342 op.math_flavor = OutputParams::MathAsMathML;
4344 case BufferParams::HTML:
4345 op.math_flavor = OutputParams::MathAsHTML;
4347 case BufferParams::Images:
4348 op.math_flavor = OutputParams::MathAsImages;
4350 case BufferParams::LaTeX:
4351 op.math_flavor = OutputParams::MathAsLaTeX;
4357 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4358 bool includeall, string & result_file) const
4360 LYXERR(Debug::FILES, "target=" << target);
4361 OutputParams runparams(¶ms().encoding());
4362 string format = target;
4363 string dest_filename;
4364 size_t pos = target.find(' ');
4365 if (pos != string::npos) {
4366 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4367 format = target.substr(0, pos);
4368 if (format == "default")
4369 format = params().getDefaultOutputFormat();
4370 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4371 FileName(dest_filename).onlyPath().createPath();
4372 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4374 MarkAsExporting exporting(this);
4375 string backend_format;
4376 runparams.flavor = Flavor::LaTeX;
4377 runparams.linelen = lyxrc.plaintext_linelen;
4378 runparams.includeall = includeall;
4379 vector<string> backs = params().backends();
4380 Converters converters = theConverters();
4381 bool need_nice_file = false;
4382 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4383 // Get shortest path to format
4384 converters.buildGraph();
4385 Graph::EdgePath path;
4386 for (string const & sit : backs) {
4387 Graph::EdgePath p = converters.getPath(sit, format);
4388 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4389 backend_format = sit;
4394 if (!put_in_tempdir) {
4395 // Only show this alert if this is an export to a non-temporary
4396 // file (not for previewing).
4397 docstring s = bformat(_("No information for exporting the format %1$s."),
4398 translateIfPossible(theFormats().prettyName(format)));
4399 if (format == "pdf4")
4401 + bformat(_("Hint: use non-TeX fonts or set input encoding "
4402 " to '%1$s'"), from_utf8(encodings.fromLyXName("ascii")->guiName()));
4403 Alert::error(_("Couldn't export file"), s);
4405 return ExportNoPathToFormat;
4407 runparams.flavor = converters.getFlavor(path, this);
4408 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4409 for (auto const & edge : path)
4410 if (theConverters().get(edge).nice()) {
4411 need_nice_file = true;
4416 backend_format = format;
4417 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4418 // FIXME: Don't hardcode format names here, but use a flag
4419 if (backend_format == "pdflatex")
4420 runparams.flavor = Flavor::PdfLaTeX;
4421 else if (backend_format == "luatex")
4422 runparams.flavor = Flavor::LuaTeX;
4423 else if (backend_format == "dviluatex")
4424 runparams.flavor = Flavor::DviLuaTeX;
4425 else if (backend_format == "xetex")
4426 runparams.flavor = Flavor::XeTeX;
4429 string filename = latexName(false);
4430 filename = addName(temppath(), filename);
4431 filename = changeExtension(filename,
4432 theFormats().extension(backend_format));
4433 LYXERR(Debug::FILES, "filename=" << filename);
4435 // Plain text backend
4436 if (backend_format == "text") {
4437 runparams.flavor = Flavor::Text;
4439 writePlaintextFile(*this, FileName(filename), runparams);
4441 catch (ConversionException const &) { return ExportCancel; }
4444 else if (backend_format == "xhtml") {
4445 runparams.flavor = Flavor::Html;
4446 setMathFlavor(runparams);
4447 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4448 return ExportKilled;
4449 } else if (backend_format == "lyx")
4450 writeFile(FileName(filename));
4452 else if (backend_format == "docbook5") {
4453 runparams.flavor = Flavor::DocBook5;
4454 runparams.nice = false;
4455 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4456 return ExportKilled;
4459 else if (backend_format == format || need_nice_file) {
4460 runparams.nice = true;
4461 ExportStatus const retval =
4462 makeLaTeXFile(FileName(filename), string(), runparams);
4463 if (retval == ExportKilled)
4464 return ExportKilled;
4465 if (d->cloned_buffer_)
4466 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4467 if (retval != ExportSuccess)
4469 } else if (!lyxrc.tex_allows_spaces
4470 && contains(filePath(), ' ')) {
4471 Alert::error(_("File name error"),
4472 bformat(_("The directory path to the document\n%1$s\n"
4473 "contains spaces, but your TeX installation does "
4474 "not allow them. You should save the file to a directory "
4475 "whose name does not contain spaces."), from_utf8(filePath())));
4476 return ExportTexPathHasSpaces;
4478 runparams.nice = false;
4479 ExportStatus const retval =
4480 makeLaTeXFile(FileName(filename), filePath(), runparams);
4481 if (retval == ExportKilled)
4482 return ExportKilled;
4483 if (d->cloned_buffer_)
4484 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4485 if (retval != ExportSuccess)
4489 string const error_type = (format == "program")
4490 ? "Build" : params().bufferFormat();
4491 ErrorList & error_list = d->errorLists[error_type];
4492 string const ext = theFormats().extension(format);
4493 FileName const tmp_result_file(changeExtension(filename, ext));
4494 Converters::RetVal const retval =
4495 converters.convert(this, FileName(filename), tmp_result_file,
4496 FileName(absFileName()), backend_format, format,
4497 error_list, Converters::none, includeall);
4498 if (retval == Converters::KILLED)
4499 return ExportCancel;
4500 bool success = (retval == Converters::SUCCESS);
4502 // Emit the signal to show the error list or copy it back to the
4503 // cloned Buffer so that it can be emitted afterwards.
4504 if (format != backend_format) {
4505 if (runparams.silent)
4507 else if (d->cloned_buffer_)
4508 d->cloned_buffer_->d->errorLists[error_type] =
4509 d->errorLists[error_type];
4512 // also to the children, in case of master-buffer-view
4513 ListOfBuffers clist = getDescendants();
4514 for (auto const & bit : clist) {
4515 if (runparams.silent)
4516 bit->d->errorLists[error_type].clear();
4517 else if (d->cloned_buffer_) {
4518 // Enable reverse search by copying back the
4519 // texrow object to the cloned buffer.
4520 // FIXME: this is not thread safe.
4521 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4522 bit->d->cloned_buffer_->d->errorLists[error_type] =
4523 bit->d->errorLists[error_type];
4525 bit->errors(error_type, true);
4529 if (d->cloned_buffer_) {
4530 // Enable reverse dvi or pdf to work by copying back the texrow
4531 // object to the cloned buffer.
4532 // FIXME: There is a possibility of concurrent access to texrow
4533 // here from the main GUI thread that should be securized.
4534 d->cloned_buffer_->d->texrow = d->texrow;
4535 string const err_type = params().bufferFormat();
4536 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4540 if (put_in_tempdir) {
4541 result_file = tmp_result_file.absFileName();
4542 return success ? ExportSuccess : ExportConverterError;
4545 if (dest_filename.empty())
4546 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4548 result_file = dest_filename;
4549 // We need to copy referenced files (e. g. included graphics
4550 // if format == "dvi") to the result dir.
4551 vector<ExportedFile> const extfiles =
4552 runparams.exportdata->externalFiles(format);
4553 string const dest = runparams.export_folder.empty() ?
4554 onlyPath(result_file) : runparams.export_folder;
4555 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4556 : force_overwrite == ALL_FILES;
4557 CopyStatus status = use_force ? FORCE : SUCCESS;
4559 for (ExportedFile const & exp : extfiles) {
4560 if (status == CANCEL) {
4561 message(_("Document export cancelled."));
4562 return ExportCancel;
4564 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4565 string fixedName = exp.exportName;
4566 if (!runparams.export_folder.empty()) {
4567 // Relative pathnames starting with ../ will be sanitized
4568 // if exporting to a different folder
4569 while (fixedName.substr(0, 3) == "../")
4570 fixedName = fixedName.substr(3, fixedName.length() - 3);
4572 FileName fixedFileName = makeAbsPath(fixedName, dest);
4573 fixedFileName.onlyPath().createPath();
4574 status = copyFile(fmt, exp.sourceName,
4576 exp.exportName, status == FORCE,
4577 runparams.export_folder.empty());
4581 if (tmp_result_file.exists()) {
4582 // Finally copy the main file
4583 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4584 : force_overwrite != NO_FILES;
4585 if (status == SUCCESS && use_force)
4587 status = copyFile(format, tmp_result_file,
4588 FileName(result_file), result_file,
4590 if (status == CANCEL) {
4591 message(_("Document export cancelled."));
4592 return ExportCancel;
4594 message(bformat(_("Document exported as %1$s "
4596 translateIfPossible(theFormats().prettyName(format)),
4597 makeDisplayPath(result_file)));
4600 // This must be a dummy converter like fax (bug 1888)
4601 message(bformat(_("Document exported as %1$s"),
4602 translateIfPossible(theFormats().prettyName(format))));
4605 return success ? ExportSuccess : ExportConverterError;
4609 Buffer::ExportStatus Buffer::preview(string const & format) const
4611 bool const update_unincluded =
4612 params().maintain_unincluded_children != BufferParams::CM_None
4613 && !params().getIncludedChildren().empty();
4614 return preview(format, update_unincluded);
4618 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4620 MarkAsExporting exporting(this);
4622 // (1) export with all included children (omit \includeonly)
4624 ExportStatus const status = doExport(format, true, true, result_file);
4625 if (status != ExportSuccess)
4628 // (2) export with included children only
4629 ExportStatus const status = doExport(format, true, false, result_file);
4630 FileName const previewFile(result_file);
4632 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4633 theimpl->preview_file_ = previewFile;
4634 theimpl->preview_format_ = format;
4635 theimpl->require_fresh_start_ = (status != ExportSuccess);
4637 if (status != ExportSuccess)
4640 if (previewFile.exists())
4641 return theFormats().view(*this, previewFile, format) ?
4642 PreviewSuccess : PreviewError;
4644 // Successful export but no output file?
4645 // Probably a bug in error detection.
4646 LATTEST(status != ExportSuccess);
4651 Buffer::ReadStatus Buffer::extractFromVC()
4653 bool const found = LyXVC::file_not_found_hook(d->filename);
4655 return ReadFileNotFound;
4656 if (!d->filename.isReadableFile())
4662 Buffer::ReadStatus Buffer::loadEmergency()
4664 FileName const emergencyFile = getEmergencyFileName();
4665 if (!emergencyFile.exists()
4666 || emergencyFile.lastModified() <= d->filename.lastModified())
4667 return ReadFileNotFound;
4669 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4670 docstring const text = bformat(_("An emergency save of the document "
4671 "%1$s exists.\n\nRecover emergency save?"), file);
4673 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4674 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4680 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4681 bool const success = (ret_llf == ReadSuccess);
4683 if (hasReadonlyFlag()) {
4684 Alert::warning(_("File is read-only"),
4685 bformat(_("An emergency file is successfully loaded, "
4686 "but the original file %1$s is marked read-only. "
4687 "Please make sure to save the document as a different "
4688 "file."), from_utf8(d->filename.absFileName())));
4691 lyxvc().file_found_hook(d->filename);
4692 str = _("Document was successfully recovered.");
4694 str = _("Document was NOT successfully recovered.");
4695 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4696 makeDisplayPath(emergencyFile.absFileName()));
4698 int const del_emerg =
4699 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4700 _("&Remove"), _("&Keep"));
4701 if (del_emerg == 0) {
4702 emergencyFile.removeFile();
4704 Alert::warning(_("Emergency file deleted"),
4705 _("Do not forget to save your file now!"), true);
4707 return success ? ReadSuccess : ReadEmergencyFailure;
4710 int const del_emerg =
4711 Alert::prompt(_("Delete emergency file?"),
4712 _("Remove emergency file now?"), 1, 1,
4713 _("&Remove"), _("&Keep"));
4715 emergencyFile.removeFile();
4719 string const ename = emergencyFile.absFileName();
4721 // Surely we can find one in 100 tries?
4722 for (int i = 1; i < 100; ++i) {
4723 newname.set(ename + to_string(i) + ".lyx");
4724 if (!newname.exists()) {
4730 // renameTo returns true on success. So inverting that
4731 // will give us true if we fail.
4732 noname = !emergencyFile.renameTo(newname);
4735 Alert::warning(_("Can't rename emergency file!"),
4736 _("LyX was unable to rename the emergency file. "
4737 "You should do so manually. Otherwise, you will be "
4738 "asked about it again the next time you try to load "
4739 "this file, and may over-write your own work."));
4741 Alert::warning(_("Emergency File Renames"),
4742 bformat(_("Emergency file renamed as:\n %1$s"),
4743 from_utf8(newname.onlyFileName())));
4746 return ReadOriginal;
4756 Buffer::ReadStatus Buffer::loadAutosave()
4758 // Now check if autosave file is newer.
4759 FileName const autosaveFile = getAutosaveFileName();
4760 if (!autosaveFile.exists()
4761 || autosaveFile.lastModified() <= d->filename.lastModified())
4762 return ReadFileNotFound;
4764 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4765 docstring const text = bformat(_("The backup of the document %1$s "
4766 "is newer.\n\nLoad the backup instead?"), file);
4767 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4768 _("&Load backup"), _("Load &original"), _("&Cancel"));
4773 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4774 // the file is not saved if we load the autosave file.
4775 if (ret_llf == ReadSuccess) {
4776 if (hasReadonlyFlag()) {
4777 Alert::warning(_("File is read-only"),
4778 bformat(_("A backup file is successfully loaded, "
4779 "but the original file %1$s is marked read-only. "
4780 "Please make sure to save the document as a "
4782 from_utf8(d->filename.absFileName())));
4785 lyxvc().file_found_hook(d->filename);
4788 return ReadAutosaveFailure;
4791 // Here we delete the autosave
4792 autosaveFile.removeFile();
4793 return ReadOriginal;
4801 Buffer::ReadStatus Buffer::loadLyXFile()
4803 if (!d->filename.isReadableFile()) {
4804 ReadStatus const ret_rvc = extractFromVC();
4805 if (ret_rvc != ReadSuccess)
4809 ReadStatus const ret_re = loadEmergency();
4810 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4813 ReadStatus const ret_ra = loadAutosave();
4814 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4817 return loadThisLyXFile(d->filename);
4821 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4823 return readFile(fn);
4827 void Buffer::Impl::traverseErrors(TeXErrors::Errors::const_iterator err, TeXErrors::Errors::const_iterator end, ErrorList & errorList) const
4829 for (; err != end; ++err) {
4830 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4831 int errorRow = err->error_in_line;
4832 Buffer const * buf = nullptr;
4833 Impl const * p = this;
4834 if (err->child_name.empty())
4835 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4837 // The error occurred in a child
4838 for (Buffer const * child : owner_->getDescendants()) {
4839 string const child_name =
4840 DocFileName(changeExtension(child->absFileName(), "tex")).
4842 if (err->child_name != child_name)
4844 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4845 if (!TexRow::isNone(start)) {
4846 buf = this->cloned_buffer_
4847 ? child->d->cloned_buffer_->d->owner_
4854 errorList.push_back(ErrorItem(err->error_desc, err->error_text,
4860 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4862 TeXErrors::Errors::const_iterator err = terr.begin();
4863 TeXErrors::Errors::const_iterator end = terr.end();
4865 d->traverseErrors(err, end, errorList);
4869 void Buffer::bufferRefs(TeXErrors const & terr, ErrorList & errorList) const
4871 TeXErrors::Errors::const_iterator err = terr.begin_ref();
4872 TeXErrors::Errors::const_iterator end = terr.end_ref();
4874 d->traverseErrors(err, end, errorList);
4878 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4880 LBUFERR(!text().paragraphs().empty());
4882 // Use the master text class also for child documents
4883 Buffer const * const master = masterBuffer();
4884 DocumentClass const & textclass = master->params().documentClass();
4886 docstring_list old_bibfiles;
4887 // Do this only if we are the top-level Buffer. We also need to account
4888 // for the case of a previewed child with ignored parent here.
4889 if (master == this && !d->ignore_parent) {
4890 textclass.counters().reset(from_ascii("bibitem"));
4891 reloadBibInfoCache();
4892 // we will re-read this cache as we go through, but we need
4893 // to know whether it's changed to know whether we need to
4894 // update the bibinfo cache.
4895 old_bibfiles = d->bibfiles_cache_;
4896 d->bibfiles_cache_.clear();
4899 // keep the buffers to be children in this set. If the call from the
4900 // master comes back we can see which of them were actually seen (i.e.
4901 // via an InsetInclude). The remaining ones in the set need still be updated.
4902 static std::set<Buffer const *> bufToUpdate;
4903 if (scope == UpdateMaster) {
4904 // If this is a child document start with the master
4905 if (master != this) {
4906 bufToUpdate.insert(this);
4907 master->updateBuffer(UpdateMaster, utype);
4908 // If the master buffer has no gui associated with it, then the TocModel is
4909 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4910 // (bug 5699). The same happens if the master buffer is open in a different
4911 // window. This test catches both possibilities.
4912 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4913 // There remains a problem here: If there is another child open in yet a third
4914 // window, that TOC is not updated. So some more general solution is needed at
4916 if (master->d->gui_ != d->gui_)
4919 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4920 if (bufToUpdate.find(this) == bufToUpdate.end())
4924 // start over the counters in the master
4925 textclass.counters().reset();
4928 // update will be done below for this buffer
4929 bufToUpdate.erase(this);
4931 // update all caches
4932 clearReferenceCache();
4935 Buffer & cbuf = const_cast<Buffer &>(*this);
4936 // if we are reloading, then we could have a dangling TOC,
4937 // in effect. so we need to go ahead and reset, even though
4938 // we will do so again when we rebuild the TOC later.
4939 cbuf.tocBackend().reset();
4942 ParIterator parit = cbuf.par_iterator_begin();
4943 if (scope == UpdateMaster)
4945 updateBuffer(parit, utype);
4947 // If this document has siblings, then update the TocBackend later. The
4948 // reason is to ensure that later siblings are up to date when e.g. the
4949 // broken or not status of references is computed. The update is called
4950 // in InsetInclude::addToToc.
4954 // if the bibfiles changed, the cache of bibinfo is invalid
4955 docstring_list new_bibfiles = d->bibfiles_cache_;
4956 // this is a trick to determine whether the two vectors have
4957 // the same elements.
4958 sort(new_bibfiles.begin(), new_bibfiles.end());
4959 sort(old_bibfiles.begin(), old_bibfiles.end());
4960 if (old_bibfiles != new_bibfiles) {
4961 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4962 invalidateBibinfoCache();
4963 reloadBibInfoCache();
4964 // We relied upon the bibinfo cache when recalculating labels. But that
4965 // cache was invalid, although we didn't find that out until now. So we
4966 // have to do it all again.
4967 // That said, the only thing we really need to do is update the citation
4968 // labels. Nothing else will have changed. So we could create a new
4969 // UpdateType that would signal that fact, if we needed to do so.
4970 parit = cbuf.par_iterator_begin();
4971 // we will be re-doing the counters and references and such.
4972 textclass.counters().reset();
4973 clearReferenceCache();
4974 // we should not need to do this again?
4976 updateBuffer(parit, utype);
4977 // this will already have been done by reloadBibInfoCache();
4978 // d->bibinfo_cache_valid_ = true;
4981 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4982 // this is also set to true on the other path, by reloadBibInfoCache.
4983 d->bibinfo_cache_valid_ = true;
4985 d->cite_labels_valid_ = true;
4988 cbuf.tocBackend().update(true, utype);
4989 if (scope == UpdateMaster)
4990 cbuf.structureChanged();
4994 static depth_type getDepth(DocIterator const & it)
4996 depth_type depth = 0;
4997 for (size_t i = 0 ; i < it.depth() ; ++i)
4998 if (!it[i].inset().inMathed())
4999 depth += it[i].paragraph().getDepth() + 1;
5000 // remove 1 since the outer inset does not count
5001 // we should have at least one non-math inset, so
5002 // depth should nevery be 0. but maybe it is worth
5003 // marking this, just in case.
5005 // coverity[INTEGER_OVERFLOW]
5009 static depth_type getItemDepth(ParIterator const & it)
5011 Paragraph const & par = *it;
5012 LabelType const labeltype = par.layout().labeltype;
5014 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5017 // this will hold the lowest depth encountered up to now.
5018 depth_type min_depth = getDepth(it);
5019 ParIterator prev_it = it;
5022 --prev_it.top().pit();
5024 // start of nested inset: go to outer par
5026 if (prev_it.empty()) {
5027 // start of document: nothing to do
5032 // We search for the first paragraph with same label
5033 // that is not more deeply nested.
5034 Paragraph & prev_par = *prev_it;
5035 depth_type const prev_depth = getDepth(prev_it);
5036 if (labeltype == prev_par.layout().labeltype) {
5037 if (prev_depth < min_depth)
5038 return prev_par.itemdepth + 1;
5039 if (prev_depth == min_depth)
5040 return prev_par.itemdepth;
5042 min_depth = min(min_depth, prev_depth);
5043 // small optimization: if we are at depth 0, we won't
5044 // find anything else
5045 if (prev_depth == 0)
5051 static bool needEnumCounterReset(ParIterator const & it)
5053 Paragraph const & par = *it;
5054 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5055 depth_type const cur_depth = par.getDepth();
5056 ParIterator prev_it = it;
5057 while (prev_it.pit()) {
5058 --prev_it.top().pit();
5059 Paragraph const & prev_par = *prev_it;
5060 if (prev_par.getDepth() <= cur_depth)
5061 return prev_par.layout().name() != par.layout().name();
5063 // start of nested inset: reset
5068 // set the label of a paragraph. This includes the counters.
5069 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5071 BufferParams const & bp = owner_->masterBuffer()->params();
5072 DocumentClass const & textclass = bp.documentClass();
5073 Paragraph & par = it.paragraph();
5074 Layout const & layout = par.layout();
5075 Counters & counters = textclass.counters();
5077 if (par.params().startOfAppendix()) {
5078 // We want to reset the counter corresponding to toplevel sectioning
5079 Layout const & lay = textclass.getTOCLayout();
5080 docstring const cnt = lay.counter;
5082 counters.reset(cnt);
5083 counters.appendix(true);
5085 par.params().appendix(counters.appendix());
5087 // Compute the item depth of the paragraph
5088 par.itemdepth = getItemDepth(it);
5090 if (layout.margintype == MARGIN_MANUAL) {
5091 if (par.params().labelWidthString().empty())
5092 par.params().labelWidthString(par.expandLabel(layout, bp));
5093 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5094 // we do not need to do anything here, since the empty case is
5095 // handled during export.
5097 par.params().labelWidthString(docstring());
5100 switch(layout.labeltype) {
5101 case LABEL_ITEMIZE: {
5102 // At some point of time we should do something more
5103 // clever here, like:
5104 // par.params().labelString(
5105 // bp.user_defined_bullet(par.itemdepth).getText());
5106 // for now, use a simple hardcoded label
5107 docstring itemlabel;
5108 switch (par.itemdepth) {
5111 itemlabel = char_type(0x2022);
5115 itemlabel = char_type(0x2013);
5118 // ∗ U+2217 ASTERISK OPERATOR
5119 itemlabel = char_type(0x2217);
5122 // · U+00B7 MIDDLE DOT
5123 itemlabel = char_type(0x00b7);
5126 par.params().labelString(itemlabel);
5130 case LABEL_ENUMERATE: {
5131 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5133 switch (par.itemdepth) {
5144 enumcounter += "iv";
5147 // not a valid enumdepth...
5151 if (needEnumCounterReset(it)) {
5152 // Increase the parent counter?
5153 if (layout.stepparentcounter)
5154 counters.stepParent(enumcounter, utype);
5155 // Maybe we have to reset the enumeration counter.
5156 if (!layout.resumecounter)
5157 counters.reset(enumcounter);
5159 counters.step(enumcounter, utype);
5161 string const & lang = par.getParLanguage(bp)->code();
5162 par.params().labelString(counters.theCounter(enumcounter, lang));
5167 case LABEL_SENSITIVE: {
5168 string const & type = counters.current_float();
5169 docstring full_label;
5171 full_label = owner_->B_("Senseless!!! ");
5173 docstring name = owner_->B_(textclass.floats().getType(type).name());
5174 if (counters.hasCounter(from_utf8(type))) {
5175 string const & lang = par.getParLanguage(bp)->code();
5176 counters.step(from_utf8(type), utype);
5177 full_label = bformat(from_ascii("%1$s %2$s:"),
5179 counters.theCounter(from_utf8(type), lang));
5181 full_label = bformat(from_ascii("%1$s #:"), name);
5183 par.params().labelString(full_label);
5187 case LABEL_NO_LABEL:
5188 par.params().labelString(docstring());
5192 case LABEL_CENTERED:
5193 case LABEL_STATIC: {
5194 docstring const & lcounter = layout.counter;
5195 if (!lcounter.empty()) {
5196 if (layout.toclevel <= bp.secnumdepth
5197 && (layout.latextype != LATEX_ENVIRONMENT
5198 || it.text()->isFirstInSequence(it.pit()))) {
5199 if (counters.hasCounter(lcounter))
5200 counters.step(lcounter, utype);
5201 par.params().labelString(par.expandLabel(layout, bp));
5203 par.params().labelString(docstring());
5205 par.params().labelString(par.expandLabel(layout, bp));
5211 par.params().labelString(par.expandLabel(layout, bp));
5216 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype, bool const deleted) const
5218 pushIncludedBuffer(this);
5219 // LASSERT: Is it safe to continue here, or should we just return?
5220 LASSERT(parit.pit() == 0, /**/);
5222 // Set the position of the text in the buffer to be able
5223 // to resolve macros in it.
5224 parit.text()->setMacrocontextPosition(parit);
5226 depth_type maxdepth = 0;
5227 pit_type const lastpit = parit.lastpit();
5228 bool changed = false;
5229 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5230 // reduce depth if necessary
5231 if (parit->params().depth() > maxdepth) {
5232 /** FIXME: this function is const, but
5233 * nevertheless it modifies the buffer. To be
5234 * cleaner, one should modify the buffer in
5235 * another function, which is actually
5236 * non-const. This would however be costly in
5237 * terms of code duplication.
5239 CursorData(parit).recordUndo();
5240 parit->params().depth(maxdepth);
5242 maxdepth = parit->getMaxDepthAfter();
5244 if (utype == OutputUpdate) {
5245 // track the active counters
5246 // we have to do this for the master buffer, since the local
5247 // buffer isn't tracking anything.
5248 masterBuffer()->params().documentClass().counters().
5249 setActiveLayout(parit->layout());
5252 // set the counter for this paragraph
5253 d->setLabel(parit, utype);
5256 for (auto const & insit : parit->insetList()) {
5257 parit.pos() = insit.pos;
5258 insit.inset->updateBuffer(parit, utype, deleted || parit->isDeleted(insit.pos));
5259 changed |= insit.inset->isChanged();
5262 // are there changes in this paragraph?
5263 changed |= parit->isChanged();
5266 // set change indicator for the inset (or the cell that the iterator
5267 // points to, if applicable).
5268 parit.text()->inset().isChanged(changed);
5269 popIncludedBuffer();
5273 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5274 WordLangTuple & word_lang, docstring_list & suggestions) const
5278 suggestions.clear();
5279 word_lang = WordLangTuple();
5280 bool const to_end = to.empty();
5281 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5282 // OK, we start from here.
5283 for (; from != end; from.forwardPos()) {
5284 // This skips all insets with spell check disabled.
5285 while (!from.allowSpellCheck()) {
5289 // If from is at the end of the document (which is possible
5290 // when "from" was changed above) LyX will crash later otherwise.
5291 if (from.atEnd() || (!to_end && from >= end))
5294 from.paragraph().spellCheck();
5295 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5296 if (SpellChecker::misspelled(res)) {
5300 // Do not increase progress when from == to, otherwise the word
5301 // count will be wrong.
5311 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5313 bool inword = false;
5318 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5319 if (!dit.inTexted()) {
5324 Paragraph const & par = dit.paragraph();
5325 pos_type const pos = dit.pos();
5327 // Copied and adapted from isWordSeparator() in Paragraph
5328 if (pos == dit.lastpos()) {
5331 Inset const * ins = par.getInset(pos);
5332 if (ins && skipNoOutput && !ins->producesOutput()) {
5335 // stop if end of range was skipped
5336 if (!to.atEnd() && dit >= to)
5339 } else if (!par.isDeleted(pos)) {
5340 if (par.isWordSeparator(pos))
5346 if (ins && ins->isLetter()) {
5347 odocstringstream os;
5349 char_count_ += os.str().length();
5351 else if (ins && ins->isSpace())
5354 char_type const c = par.getChar(pos);
5355 if (isPrintableNonspace(c))
5357 else if (isSpace(c))
5367 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5369 d->updateStatistics(from, to, skipNoOutput);
5373 int Buffer::wordCount() const
5375 return d->wordCount();
5379 int Buffer::charCount(bool with_blanks) const
5381 return d->charCount(with_blanks);
5385 bool Buffer::areChangesPresent() const
5387 return inset().isChanged();
5391 Buffer::ReadStatus Buffer::reload()
5394 // c.f. bug https://www.lyx.org/trac/ticket/6587
5395 removeAutosaveFile();
5396 // e.g., read-only status could have changed due to version control
5397 d->filename.refresh();
5398 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5400 // clear parent. this will get reset if need be.
5401 d->setParent(nullptr);
5402 ReadStatus const status = loadLyXFile();
5403 if (status == ReadSuccess) {
5408 message(bformat(_("Document %1$s reloaded."), disp_fn));
5411 message(bformat(_("Could not reload document %1$s."), disp_fn));
5421 bool Buffer::saveAs(FileName const & fn)
5423 FileName const old_name = fileName();
5424 FileName const old_auto = getAutosaveFileName();
5425 bool const old_unnamed = isUnnamed();
5426 bool success = true;
5427 d->old_position = filePath();
5434 // bring the autosave file with us, just in case.
5435 moveAutosaveFile(old_auto);
5436 // validate version control data and
5437 // correct buffer title
5438 lyxvc().file_found_hook(fileName());
5440 // the file has now been saved to the new location.
5441 // we need to check that the locations of child buffers
5443 checkChildBuffers();
5444 checkMasterBuffer();
5447 // reset the old filename and unnamed state
5448 setFileName(old_name);
5449 setUnnamed(old_unnamed);
5453 d->old_position.clear();
5458 void Buffer::checkChildBuffers()
5460 for (auto const & bit : d->children_positions) {
5461 DocIterator dit = bit.second;
5462 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5463 if (!cbuf || !theBufferList().isLoaded(cbuf))
5465 Inset * inset = dit.nextInset();
5466 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5467 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5468 docstring const & incfile = inset_inc->getParam("filename");
5469 string oldloc = cbuf->absFileName();
5470 string newloc = makeAbsPath(to_utf8(incfile),
5471 onlyPath(absFileName())).absFileName();
5472 if (oldloc == newloc)
5474 // the location of the child file is incorrect.
5475 cbuf->setParent(nullptr);
5476 inset_inc->setChildBuffer(nullptr);
5478 // invalidate cache of children
5479 d->children_positions.clear();
5480 d->position_to_children.clear();
5484 // If a child has been saved under a different name/path, it might have been
5485 // orphaned. Therefore the master needs to be reset (bug 8161).
5486 void Buffer::checkMasterBuffer()
5488 Buffer const * const master = masterBuffer();
5492 // necessary to re-register the child (bug 5873)
5493 // FIXME: clean up updateMacros (here, only
5494 // child registering is needed).
5495 master->updateMacros();
5496 // (re)set master as master buffer, but only
5497 // if we are a real child
5498 if (master->isChild(this))
5505 string Buffer::includedFilePath(string const & name, string const & ext) const
5507 if (d->old_position.empty() ||
5508 equivalent(FileName(d->old_position), FileName(filePath())))
5511 bool isabsolute = FileName::isAbsolute(name);
5512 // both old_position and filePath() end with a path separator
5513 string absname = isabsolute ? name : d->old_position + name;
5515 // if old_position is set to origin, we need to do the equivalent of
5516 // getReferencedFileName() (see readDocument())
5517 if (!isabsolute && d->old_position == params().origin) {
5518 FileName const test(addExtension(filePath() + name, ext));
5520 absname = filePath() + name;
5523 if (!FileName(addExtension(absname, ext)).exists())
5527 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5529 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5530 from_utf8(filePath())));
5534 void Buffer::Impl::refreshFileMonitor()
5536 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5537 file_monitor_->refresh();
5541 // The previous file monitor is invalid
5542 // This also destroys the previous file monitor and all its connections
5543 file_monitor_ = FileSystemWatcher::monitor(filename);
5544 // file_monitor_ will be destroyed with *this, so it is not going to call a
5545 // destroyed object method.
5546 file_monitor_->connect([this](bool exists) {
5547 fileExternallyModified(exists);
5552 void Buffer::Impl::fileExternallyModified(bool const exists)
5554 // ignore notifications after our own saving operations
5555 if (checksum_ == filename.checksum()) {
5556 LYXERR(Debug::FILES, "External modification but "
5557 "checksum unchanged: " << filename);
5560 // If the file has been deleted, only mark the file as dirty since it is
5561 // pointless to prompt for reloading. If later a file is moved into this
5562 // location, then the externally modified warning will appear then.
5564 externally_modified_ = true;
5565 // Update external modification notification.
5566 // Dirty buffers must be visible at all times.
5567 if (wa_ && wa_->unhide(owner_))
5568 wa_->updateTitles();
5570 // Unable to unhide the buffer (e.g. no GUI or not current View)
5575 bool Buffer::notifiesExternalModification() const
5577 return d->externally_modified_;
5581 void Buffer::clearExternalModification() const
5583 d->externally_modified_ = false;
5585 d->wa_->updateTitles();
5589 void Buffer::pushIncludedBuffer(Buffer const * buf) const
5591 masterBuffer()->d->include_list_.push_back(buf);
5592 if (lyxerr.debugging(Debug::FILES)) {
5593 LYXERR0("Pushed. Stack now:");
5594 if (masterBuffer()->d->include_list_.empty())
5597 for (auto const & b : masterBuffer()->d->include_list_)
5598 LYXERR0(b->fileName());
5603 void Buffer::popIncludedBuffer() const
5605 masterBuffer()->d->include_list_.pop_back();
5606 if (lyxerr.debugging(Debug::FILES)) {
5607 LYXERR0("Popped. Stack now:");
5608 if (masterBuffer()->d->include_list_.empty())
5611 for (auto const & b : masterBuffer()->d->include_list_)
5612 LYXERR0(b->fileName());
5617 bool Buffer::isBufferIncluded(Buffer const * buf) const
5621 if (lyxerr.debugging(Debug::FILES)) {
5622 LYXERR0("Checking for " << buf->fileName() << ". Stack now:");
5623 if (masterBuffer()->d->include_list_.empty())
5626 for (auto const & b : masterBuffer()->d->include_list_)
5627 LYXERR0(b->fileName());
5629 list<Buffer const *> const & blist = masterBuffer()->d->include_list_;
5630 return find(blist.begin(), blist.end(), buf) != blist.end();
5634 void Buffer::clearIncludeList() const
5636 LYXERR(Debug::FILES, "Clearing include list for " << fileName());
5637 d->include_list_.clear();