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 & bi_in) const
2597 // We add the biblio info to the parent buffer,
2598 // if there is one, but also to this buffer, in case
2599 // it is compiled alone.
2600 BiblioInfo & our_bi = d->bibinfo_;
2601 our_bi.mergeBiblioInfo(bi_in);
2604 parent()->addBiblioInfo(bi_in);
2608 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2610 // We add the bibtex info to the master buffer,
2611 // if there is one, but also to every single buffer,
2612 // in case a child is compiled alone.
2613 BiblioInfo & bi = d->bibinfo_;
2616 if (parent() != nullptr) {
2617 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2618 masterbi[key] = bin;
2623 void Buffer::makeCitationLabels() const
2625 Buffer const * const master = masterBuffer();
2626 return d->bibinfo_.makeCitationLabels(*master);
2630 void Buffer::invalidateCiteLabels() const
2632 masterBuffer()->d->cite_labels_valid_ = false;
2635 bool Buffer::citeLabelsValid() const
2637 return masterBuffer()->d->cite_labels_valid_;
2641 void Buffer::removeBiblioTempFiles() const
2643 // We remove files that contain LaTeX commands specific to the
2644 // particular bibliographic style being used, in order to avoid
2645 // LaTeX errors when we switch style.
2646 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2647 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2648 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2649 aux_file.removeFile();
2650 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2651 bbl_file.removeFile();
2652 // Also for the parent buffer
2653 Buffer const * const pbuf = parent();
2655 pbuf->removeBiblioTempFiles();
2659 bool Buffer::isDepClean(string const & name) const
2661 DepClean::const_iterator const it = d->dep_clean.find(name);
2662 if (it == d->dep_clean.end())
2668 void Buffer::markDepClean(string const & name)
2670 d->dep_clean[name] = true;
2674 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2677 // FIXME? if there is an Buffer LFUN that can be dispatched even
2678 // if internal, put a switch '(cmd.action)' here.
2684 switch (cmd.action()) {
2686 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2687 flag.setOnOff(hasReadonlyFlag());
2690 // FIXME: There is need for a command-line import.
2691 //case LFUN_BUFFER_IMPORT:
2693 case LFUN_BUFFER_AUTO_SAVE:
2696 case LFUN_BUFFER_EXPORT_CUSTOM:
2697 // FIXME: Nothing to check here?
2700 case LFUN_BUFFER_EXPORT: {
2701 docstring const & arg = cmd.argument();
2702 if (arg == "custom") {
2706 string format = (arg.empty() || arg == "default") ?
2707 params().getDefaultOutputFormat() : to_utf8(arg);
2708 size_t pos = format.find(' ');
2709 if (pos != string::npos)
2710 format = format.substr(0, pos);
2711 enable = params().isExportable(format, false);
2713 flag.message(bformat(
2714 _("Don't know how to export to format: %1$s"), arg));
2718 case LFUN_BUILD_PROGRAM:
2719 enable = params().isExportable("program", false);
2722 case LFUN_BRANCH_ACTIVATE:
2723 case LFUN_BRANCH_DEACTIVATE:
2724 case LFUN_BRANCH_MASTER_ACTIVATE:
2725 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2726 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2727 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2728 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2729 : params().branchlist();
2730 docstring const & branchName = cmd.argument();
2731 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2735 case LFUN_BRANCH_ADD:
2736 case LFUN_BRANCHES_RENAME:
2737 // if no Buffer is present, then of course we won't be called!
2740 case LFUN_BUFFER_LANGUAGE:
2741 enable = !isReadonly();
2744 case LFUN_BUFFER_VIEW_CACHE:
2745 (d->preview_file_).refresh();
2746 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2749 case LFUN_CHANGES_TRACK:
2750 flag.setEnabled(true);
2751 flag.setOnOff(params().track_changes);
2754 case LFUN_CHANGES_OUTPUT:
2755 flag.setEnabled(true);
2756 flag.setOnOff(params().output_changes);
2759 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2760 flag.setOnOff(params().compressed);
2763 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2764 flag.setOnOff(params().output_sync);
2767 case LFUN_BUFFER_ANONYMIZE:
2773 flag.setEnabled(enable);
2778 void Buffer::dispatch(string const & command, DispatchResult & result)
2780 return dispatch(lyxaction.lookupFunc(command), result);
2784 // NOTE We can end up here even if we have no GUI, because we are called
2785 // by LyX::exec to handled command-line requests. So we may need to check
2786 // whether we have a GUI or not. The boolean use_gui holds this information.
2787 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2790 // FIXME? if there is an Buffer LFUN that can be dispatched even
2791 // if internal, put a switch '(cmd.action())' here.
2792 dr.dispatched(false);
2795 string const argument = to_utf8(func.argument());
2796 // We'll set this back to false if need be.
2797 bool dispatched = true;
2798 // This handles undo groups automagically
2799 UndoGroupHelper ugh(this);
2801 switch (func.action()) {
2802 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2803 if (lyxvc().inUse()) {
2804 string log = lyxvc().toggleReadOnly();
2809 setReadonly(!hasReadonlyFlag());
2812 case LFUN_BUFFER_EXPORT: {
2813 string const format = (argument.empty() || argument == "default") ?
2814 params().getDefaultOutputFormat() : argument;
2815 ExportStatus const status = doExport(format, false);
2816 dr.setError(status != ExportSuccess);
2817 if (status != ExportSuccess)
2818 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2819 from_utf8(format)));
2823 case LFUN_BUILD_PROGRAM: {
2824 ExportStatus const status = doExport("program", true);
2825 dr.setError(status != ExportSuccess);
2826 if (status != ExportSuccess)
2827 dr.setMessage(_("Error generating literate programming code."));
2831 case LFUN_BUFFER_EXPORT_CUSTOM: {
2833 string command = split(argument, format_name, ' ');
2834 Format const * format = theFormats().getFormat(format_name);
2836 lyxerr << "Format \"" << format_name
2837 << "\" not recognized!"
2842 // The name of the file created by the conversion process
2845 // Output to filename
2846 if (format->name() == "lyx") {
2847 string const latexname = latexName(false);
2848 filename = changeExtension(latexname,
2849 format->extension());
2850 filename = addName(temppath(), filename);
2852 if (!writeFile(FileName(filename)))
2856 doExport(format_name, true, filename);
2859 // Substitute $$FName for filename
2860 if (!contains(command, "$$FName"))
2861 command = "( " + command + " ) < $$FName";
2862 command = subst(command, "$$FName", filename);
2864 // Execute the command in the background
2866 call.startscript(Systemcall::DontWait, command,
2867 filePath(), layoutPos());
2871 // FIXME: There is need for a command-line import.
2873 case LFUN_BUFFER_IMPORT:
2878 case LFUN_BUFFER_AUTO_SAVE:
2880 resetAutosaveTimers();
2883 case LFUN_BRANCH_ACTIVATE:
2884 case LFUN_BRANCH_DEACTIVATE:
2885 case LFUN_BRANCH_MASTER_ACTIVATE:
2886 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2887 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2888 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2889 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2892 docstring const & branch_name = func.argument();
2893 // the case without a branch name is handled elsewhere
2894 if (branch_name.empty()) {
2898 Branch * branch = buf->params().branchlist().find(branch_name);
2900 LYXERR0("Branch " << branch_name << " does not exist.");
2902 docstring const msg =
2903 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2907 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2908 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2909 if (branch->isSelected() != activate) {
2910 buf->undo().recordUndoBufferParams(CursorData());
2911 branch->setSelected(activate);
2913 dr.screenUpdate(Update::Force);
2914 dr.forceBufferUpdate();
2919 case LFUN_BRANCH_ADD: {
2920 docstring const & branchnames = func.argument();
2921 if (branchnames.empty()) {
2925 BranchList & branch_list = params().branchlist();
2926 vector<docstring> const branches =
2927 getVectorFromString(branchnames, branch_list.separator());
2929 for (docstring const & branch_name : branches) {
2930 Branch * branch = branch_list.find(branch_name);
2932 LYXERR0("Branch " << branch_name << " already exists.");
2936 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2938 undo().recordUndoBufferParams(CursorData());
2939 branch_list.add(branch_name);
2940 branch = branch_list.find(branch_name);
2941 string const x11hexname = X11hexname(branch->color());
2942 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2943 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2945 dr.screenUpdate(Update::Force);
2953 case LFUN_BRANCHES_RENAME: {
2954 if (func.argument().empty())
2957 docstring const oldname = from_utf8(func.getArg(0));
2958 docstring const newname = from_utf8(func.getArg(1));
2959 InsetIterator it = begin(inset());
2960 InsetIterator const itend = end(inset());
2961 bool success = false;
2962 for (; it != itend; ++it) {
2963 if (it->lyxCode() == BRANCH_CODE) {
2964 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2965 if (ins.branch() == oldname) {
2966 undo().recordUndo(CursorData(it));
2967 ins.rename(newname);
2972 if (it->lyxCode() == INCLUDE_CODE) {
2973 // get buffer of external file
2974 InsetInclude const & ins =
2975 static_cast<InsetInclude const &>(*it);
2976 Buffer * child = ins.loadIfNeeded();
2979 child->dispatch(func, dr);
2984 dr.screenUpdate(Update::Force);
2985 dr.forceBufferUpdate();
2990 case LFUN_BUFFER_VIEW_CACHE:
2991 if (!theFormats().view(*this, d->preview_file_,
2992 d->preview_format_))
2993 dr.setMessage(_("Error viewing the output file."));
2996 case LFUN_CHANGES_TRACK:
2997 if (params().save_transient_properties)
2998 undo().recordUndoBufferParams(CursorData());
2999 params().track_changes = !params().track_changes;
3002 case LFUN_CHANGES_OUTPUT:
3003 if (params().save_transient_properties)
3004 undo().recordUndoBufferParams(CursorData());
3005 params().output_changes = !params().output_changes;
3006 if (params().output_changes) {
3007 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
3008 LaTeXFeatures::isAvailable("xcolor");
3011 Alert::warning(_("Changes not shown in LaTeX output"),
3012 _("Changes will not be highlighted in LaTeX output, "
3013 "because xcolor and ulem are not installed.\n"
3014 "Please install both packages or redefine "
3015 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3020 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3021 // turn compression on/off
3022 undo().recordUndoBufferParams(CursorData());
3023 params().compressed = !params().compressed;
3026 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3027 undo().recordUndoBufferParams(CursorData());
3028 params().output_sync = !params().output_sync;
3031 case LFUN_BUFFER_ANONYMIZE: {
3032 undo().recordUndoFullBuffer(CursorData());
3033 CursorData cur(doc_iterator_begin(this));
3034 for ( ; cur ; cur.forwardPar())
3035 cur.paragraph().anonymize();
3036 dr.forceBufferUpdate();
3037 dr.screenUpdate(Update::Force);
3045 dr.dispatched(dispatched);
3049 void Buffer::changeLanguage(Language const * from, Language const * to)
3051 LASSERT(from, return);
3052 LASSERT(to, return);
3054 ParIterator it = par_iterator_begin();
3055 ParIterator eit = par_iterator_end();
3056 for (; it != eit; ++it)
3057 it->changeLanguage(params(), from, to);
3061 bool Buffer::isMultiLingual() const
3063 ParConstIterator end = par_iterator_end();
3064 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3065 if (it->isMultiLingual(params()))
3072 std::set<Language const *> Buffer::getLanguages() const
3074 std::set<Language const *> langs;
3075 getLanguages(langs);
3080 void Buffer::getLanguages(std::set<Language const *> & langs) const
3082 ParConstIterator end = par_iterator_end();
3083 // add the buffer language, even if it's not actively used
3084 langs.insert(language());
3085 // iterate over the paragraphs
3086 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3087 it->getLanguages(langs);
3089 ListOfBuffers clist = getDescendants();
3090 for (auto const & cit : clist)
3091 cit->getLanguages(langs);
3095 DocIterator Buffer::getParFromID(int const id) const
3097 Buffer * buf = const_cast<Buffer *>(this);
3099 // This means non-existent
3100 return doc_iterator_end(buf);
3102 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3103 if (it.paragraph().id() == id)
3106 return doc_iterator_end(buf);
3110 bool Buffer::hasParWithID(int const id) const
3112 return !getParFromID(id).atEnd();
3116 ParIterator Buffer::par_iterator_begin()
3118 return ParIterator(doc_iterator_begin(this));
3122 ParIterator Buffer::par_iterator_end()
3124 return ParIterator(doc_iterator_end(this));
3128 ParConstIterator Buffer::par_iterator_begin() const
3130 return ParConstIterator(doc_iterator_begin(this));
3134 ParConstIterator Buffer::par_iterator_end() const
3136 return ParConstIterator(doc_iterator_end(this));
3139 bool Buffer::empty() const
3141 return paragraphs().size() == 1 && paragraphs().front().empty();
3145 Language const * Buffer::language() const
3147 return params().language;
3151 docstring Buffer::B_(string const & l10n) const
3153 return params().B_(l10n);
3157 bool Buffer::isClean() const
3159 return d->lyx_clean;
3163 bool Buffer::isChecksumModified() const
3165 LASSERT(d->filename.exists(), return false);
3166 return d->checksum_ != d->filename.checksum();
3170 void Buffer::saveCheckSum() const
3172 FileName const & file = d->filename;
3174 d->checksum_ = file.exists() ? file.checksum()
3175 : 0; // in the case of save to a new file.
3179 void Buffer::markClean() const
3181 if (!d->lyx_clean) {
3182 d->lyx_clean = true;
3185 // if the .lyx file has been saved, we don't need an
3187 d->bak_clean = true;
3188 d->undo_.markDirty();
3189 clearExternalModification();
3193 void Buffer::setUnnamed(bool flag)
3199 bool Buffer::isUnnamed() const
3206 /// Don't check unnamed, here: isInternal() is used in
3207 /// newBuffer(), where the unnamed flag has not been set by anyone
3208 /// yet. Also, for an internal buffer, there should be no need for
3209 /// retrieving fileName() nor for checking if it is unnamed or not.
3210 bool Buffer::isInternal() const
3212 return d->internal_buffer;
3216 void Buffer::setInternal(bool flag)
3218 d->internal_buffer = flag;
3222 void Buffer::markDirty()
3225 d->lyx_clean = false;
3228 d->bak_clean = false;
3230 for (auto & depit : d->dep_clean)
3231 depit.second = false;
3235 FileName Buffer::fileName() const
3241 string Buffer::absFileName() const
3243 return d->filename.absFileName();
3247 string Buffer::filePath() const
3249 string const abs = d->filename.onlyPath().absFileName();
3252 int last = abs.length() - 1;
3254 return abs[last] == '/' ? abs : abs + '/';
3258 DocFileName Buffer::getReferencedFileName(string const & fn) const
3261 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3262 result.set(fn, filePath());
3264 // filePath() ends with a path separator
3265 FileName const test(filePath() + fn);
3267 result.set(fn, filePath());
3269 result.set(fn, params().origin);
3276 string const Buffer::prepareFileNameForLaTeX(string const & name,
3277 string const & ext, bool nice) const
3279 string const fname = makeAbsPath(name, filePath()).absFileName();
3280 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3286 return to_utf8(makeRelPath(from_utf8(fname),
3287 from_utf8(masterBuffer()->filePath())));
3291 vector<pair<docstring, string>> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3292 docstring_list const & bibfilelist,
3293 bool const add_extension) const
3295 // If we are processing the LaTeX file in a temp directory then
3296 // copy the .bib databases to this temp directory, mangling their
3297 // names in the process. Store this mangled name in the list of
3299 // (We need to do all this because BibTeX *really*, *really*
3300 // can't handle "files with spaces" and Windows users tend to
3301 // use such filenames.)
3302 // Otherwise, store the (maybe absolute) path to the original,
3303 // unmangled database name.
3305 vector<pair<docstring, string>> res;
3307 // determine the export format
3308 string const tex_format = flavor2format(runparams.flavor);
3310 // check for spaces in paths
3311 bool found_space = false;
3313 for (auto const & bit : bibfilelist) {
3314 string utf8input = to_utf8(bit);
3316 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3317 FileName try_in_file =
3318 makeAbsPath(database + ".bib", filePath());
3319 bool not_from_texmf = try_in_file.isReadableFile();
3320 // If the file has not been found, try with the real file name
3321 // (it might come from a child in a sub-directory)
3322 if (!not_from_texmf) {
3323 try_in_file = getBibfilePath(bit);
3324 if (try_in_file.isReadableFile()) {
3325 // Check if the file is in texmf
3326 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3327 not_from_texmf = kpsefile.empty()
3328 || kpsefile.absFileName() != try_in_file.absFileName();
3330 // If this exists, make path relative to the master
3333 removeExtension(prepareFileNameForLaTeX(
3334 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3335 from_utf8(filePath()))),
3336 ".bib", runparams.nice));
3340 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3342 // mangledFileName() needs the extension
3343 DocFileName const in_file = DocFileName(try_in_file);
3344 database = removeExtension(in_file.mangledFileName());
3345 FileName const out_file = makeAbsPath(database + ".bib",
3346 masterBuffer()->temppath());
3347 bool const success = in_file.copyTo(out_file);
3349 LYXERR0("Failed to copy '" << in_file
3350 << "' to '" << out_file << "'");
3352 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3353 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3354 if (!isValidLaTeXFileName(database)) {
3355 frontend::Alert::warning(_("Invalid filename"),
3356 _("The following filename will cause troubles "
3357 "when running the exported file through LaTeX: ") +
3358 from_utf8(database));
3360 if (!isValidDVIFileName(database)) {
3361 frontend::Alert::warning(_("Problematic filename for DVI"),
3362 _("The following filename can cause troubles "
3363 "when running the exported file through LaTeX "
3364 "and opening the resulting DVI: ") +
3365 from_utf8(database), true);
3373 docstring const path = from_utf8(latex_path(database));
3375 if (contains(path, ' '))
3378 if (params().useBiblatex() && !params().bibFileEncoding(utf8input).empty())
3379 enc = params().bibFileEncoding(utf8input);
3381 bool recorded = false;
3382 for (auto const & pe : res) {
3383 if (pe.first == path) {
3390 res.push_back(make_pair(path, enc));
3393 // Check if there are spaces in the path and warn BibTeX users, if so.
3394 // (biber can cope with such paths)
3395 if (!prefixIs(runparams.bibtex_command, "biber")) {
3396 // Post this warning only once.
3397 static bool warned_about_spaces = false;
3398 if (!warned_about_spaces &&
3399 runparams.nice && found_space) {
3400 warned_about_spaces = true;
3401 Alert::warning(_("Export Warning!"),
3402 _("There are spaces in the paths to your BibTeX databases.\n"
3403 "BibTeX will be unable to find them."));
3412 string Buffer::layoutPos() const
3414 return d->layout_position;
3418 void Buffer::setLayoutPos(string const & path)
3421 d->layout_position.clear();
3425 LATTEST(FileName::isAbsolute(path));
3427 d->layout_position =
3428 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3430 if (d->layout_position.empty())
3431 d->layout_position = ".";
3435 bool Buffer::hasReadonlyFlag() const
3437 return d->read_only;
3441 bool Buffer::isReadonly() const
3443 return hasReadonlyFlag() || notifiesExternalModification();
3447 void Buffer::setParent(Buffer const * buffer)
3449 // We need to do some work here to avoid recursive parent structures.
3450 // This is the easy case.
3451 if (buffer == this) {
3452 LYXERR0("Ignoring attempt to set self as parent in\n" << fileName());
3455 // Now we check parents going upward, to make sure that IF we set the
3456 // parent as requested, we would not generate a recursive include.
3457 set<Buffer const *> sb;
3458 Buffer const * b = buffer;
3459 bool found_recursion = false;
3461 if (sb.find(b) != sb.end()) {
3462 found_recursion = true;
3469 if (found_recursion) {
3470 LYXERR0("Ignoring attempt to set parent of\n" <<
3473 buffer->fileName() <<
3474 "\nbecause that would create a recursive inclusion.");
3478 // We should be safe now.
3479 d->setParent(buffer);
3484 Buffer const * Buffer::parent() const
3490 ListOfBuffers Buffer::allRelatives() const
3492 ListOfBuffers lb = masterBuffer()->getDescendants();
3493 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3498 Buffer const * Buffer::masterBuffer() const
3500 Buffer const * const pbuf = d->parent();
3504 return pbuf->masterBuffer();
3508 bool Buffer::isChild(Buffer * child) const
3510 return d->children_positions.find(child) != d->children_positions.end();
3514 DocIterator Buffer::firstChildPosition(Buffer const * child)
3516 Impl::BufferPositionMap::iterator it;
3517 it = d->children_positions.find(child);
3518 if (it == d->children_positions.end())
3519 return DocIterator(this);
3524 bool Buffer::hasChildren() const
3526 return !d->children_positions.empty();
3530 void Buffer::collectChildren(ListOfBuffers & children, bool grand_children) const
3532 // loop over children
3533 for (auto const & p : d->children_positions) {
3534 Buffer * child = const_cast<Buffer *>(p.first);
3536 ListOfBuffers::const_iterator bit = find(children.begin(), children.end(), child);
3537 if (bit != children.end())
3539 children.push_back(child);
3541 // there might be grandchildren
3542 child->collectChildren(children, true);
3547 ListOfBuffers Buffer::getChildren() const
3550 collectChildren(v, false);
3551 // Make sure we have not included ourselves.
3552 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3553 if (bit != v.end()) {
3554 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3561 ListOfBuffers Buffer::getDescendants() const
3564 collectChildren(v, true);
3565 // Make sure we have not included ourselves.
3566 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3567 if (bit != v.end()) {
3568 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3575 template<typename M>
3576 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3581 typename M::const_iterator it = m.lower_bound(x);
3582 if (it == m.begin())
3590 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3591 DocIterator const & pos) const
3593 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3595 // if paragraphs have no macro context set, pos will be empty
3599 // we haven't found anything yet
3600 DocIterator bestPos = owner_->par_iterator_begin();
3601 MacroData const * bestData = nullptr;
3603 // find macro definitions for name
3604 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3605 if (nameIt != macros.end()) {
3606 // find last definition in front of pos or at pos itself
3607 PositionScopeMacroMap::const_iterator it
3608 = greatest_below(nameIt->second, pos);
3609 if (it != nameIt->second.end()) {
3611 // scope ends behind pos?
3612 if (pos < it->second.scope) {
3613 // Looks good, remember this. If there
3614 // is no external macro behind this,
3615 // we found the right one already.
3616 bestPos = it->first;
3617 bestData = &it->second.macro;
3621 // try previous macro if there is one
3622 if (it == nameIt->second.begin())
3629 // find macros in included files
3630 PositionScopeBufferMap::const_iterator it
3631 = greatest_below(position_to_children, pos);
3632 if (it == position_to_children.end())
3633 // no children before
3637 // do we know something better (i.e. later) already?
3638 if (it->first < bestPos )
3641 // scope ends behind pos?
3642 if (pos < it->second.scope
3643 && (cloned_buffer_ ||
3644 theBufferList().isLoaded(it->second.buffer))) {
3645 // look for macro in external file
3647 MacroData const * data
3648 = it->second.buffer->getMacro(name, false);
3651 bestPos = it->first;
3657 // try previous file if there is one
3658 if (it == position_to_children.begin())
3663 // return the best macro we have found
3668 MacroData const * Buffer::getMacro(docstring const & name,
3669 DocIterator const & pos, bool global) const
3674 // query buffer macros
3675 MacroData const * data = d->getBufferMacro(name, pos);
3676 if (data != nullptr)
3679 // If there is a master buffer, query that
3680 Buffer const * const pbuf = d->parent();
3682 d->macro_lock = true;
3683 MacroData const * macro = pbuf->getMacro(
3684 name, *this, false);
3685 d->macro_lock = false;
3691 data = MacroTable::globalMacros().get(name);
3692 if (data != nullptr)
3700 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3702 // set scope end behind the last paragraph
3703 DocIterator scope = par_iterator_begin();
3704 scope.pit() = scope.lastpit() + 1;
3706 return getMacro(name, scope, global);
3710 MacroData const * Buffer::getMacro(docstring const & name,
3711 Buffer const & child, bool global) const
3713 // look where the child buffer is included first
3714 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3715 if (it == d->children_positions.end())
3718 // check for macros at the inclusion position
3719 return getMacro(name, it->second, global);
3723 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3725 pit_type const lastpit = it.lastpit();
3727 // look for macros in each paragraph
3728 while (it.pit() <= lastpit) {
3729 Paragraph & par = it.paragraph();
3731 // iterate over the insets of the current paragraph
3732 for (auto const & insit : par.insetList()) {
3733 it.pos() = insit.pos;
3735 // is it a nested text inset?
3736 if (insit.inset->asInsetText()) {
3737 // Inset needs its own scope?
3738 InsetText const * itext = insit.inset->asInsetText();
3739 bool newScope = itext->isMacroScope();
3741 // scope which ends just behind the inset
3742 DocIterator insetScope = it;
3745 // collect macros in inset
3746 it.push_back(CursorSlice(*insit.inset));
3747 updateMacros(it, newScope ? insetScope : scope);
3752 if (insit.inset->asInsetTabular()) {
3753 CursorSlice slice(*insit.inset);
3754 size_t const numcells = slice.nargs();
3755 for (; slice.idx() < numcells; slice.forwardIdx()) {
3756 it.push_back(slice);
3757 updateMacros(it, scope);
3763 // is it an external file?
3764 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3765 // get buffer of external file
3766 InsetInclude const & incinset =
3767 static_cast<InsetInclude const &>(*insit.inset);
3769 Buffer * child = incinset.loadIfNeeded();
3774 // register its position, but only when it is
3775 // included first in the buffer
3776 children_positions.insert({child, it});
3778 // register child with its scope
3779 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3783 InsetMath * im = insit.inset->asInsetMath();
3784 if (doing_export && im) {
3785 InsetMathHull * hull = im->asHullInset();
3787 hull->recordLocation(it);
3790 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3794 InsetMathMacroTemplate & macroTemplate =
3795 *insit.inset->asInsetMath()->asMacroTemplate();
3796 MacroContext mc(owner_, it);
3797 macroTemplate.updateToContext(mc);
3800 bool valid = macroTemplate.validMacro();
3801 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3802 // then the BufferView's cursor will be invalid in
3803 // some cases which leads to crashes.
3808 // FIXME (Abdel), I don't understand why we pass 'it' here
3809 // instead of 'macroTemplate' defined above... is this correct?
3810 macros[macroTemplate.name()][it] =
3811 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3821 void Buffer::updateMacros() const
3826 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3828 // start with empty table
3830 d->children_positions.clear();
3831 d->position_to_children.clear();
3833 // Iterate over buffer, starting with first paragraph
3834 // The scope must be bigger than any lookup DocIterator
3835 // later. For the global lookup, lastpit+1 is used, hence
3836 // we use lastpit+2 here.
3837 DocIterator it = par_iterator_begin();
3838 DocIterator outerScope = it;
3839 outerScope.pit() = outerScope.lastpit() + 2;
3840 d->updateMacros(it, outerScope);
3844 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3846 for (Inset const & it : inset()) {
3847 if (it.lyxCode() == BRANCH_CODE) {
3848 InsetBranch const & br = static_cast<InsetBranch const &>(it);
3849 docstring const name = br.branch();
3850 if (!from_master && !params().branchlist().find(name))
3851 result.push_back(name);
3852 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3853 result.push_back(name);
3856 if (it.lyxCode() == INCLUDE_CODE) {
3857 // get buffer of external file
3858 InsetInclude const & ins =
3859 static_cast<InsetInclude const &>(it);
3860 Buffer * child = ins.loadIfNeeded();
3863 child->getUsedBranches(result, true);
3866 // remove duplicates
3871 void Buffer::updateMacroInstances(UpdateType utype) const
3873 LYXERR(Debug::MACROS, "updateMacroInstances for "
3874 << d->filename.onlyFileName());
3875 DocIterator it = doc_iterator_begin(this);
3877 DocIterator const end = doc_iterator_end(this);
3878 for (; it != end; it.forwardInset()) {
3879 // look for MathData cells in InsetMathNest insets
3880 InsetMath * minset = it.nextInset()->asInsetMath();
3884 // update macro in all cells of the InsetMathNest
3885 idx_type n = minset->nargs();
3886 MacroContext mc = MacroContext(this, it);
3887 for (idx_type i = 0; i < n; ++i) {
3888 MathData & data = minset->cell(i);
3889 data.updateMacros(nullptr, mc, utype, 0);
3895 void Buffer::listMacroNames(MacroNameSet & macros) const
3900 d->macro_lock = true;
3902 // loop over macro names
3903 for (auto const & nameit : d->macros)
3904 macros.insert(nameit.first);
3906 // loop over children
3907 for (auto const & p : d->children_positions) {
3908 Buffer * child = const_cast<Buffer *>(p.first);
3909 // The buffer might have been closed (see #10766).
3910 if (theBufferList().isLoaded(child))
3911 child->listMacroNames(macros);
3915 Buffer const * const pbuf = d->parent();
3917 pbuf->listMacroNames(macros);
3919 d->macro_lock = false;
3923 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3925 Buffer const * const pbuf = d->parent();
3930 pbuf->listMacroNames(names);
3933 for (auto const & mit : names) {
3935 MacroData const * data = pbuf->getMacro(mit, *this, false);
3937 macros.insert(data);
3939 // we cannot access the original InsetMathMacroTemplate anymore
3940 // here to calls validate method. So we do its work here manually.
3941 // FIXME: somehow make the template accessible here.
3942 if (data->optionals() > 0)
3943 features.require("xargs");
3949 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3952 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3954 RefCache::iterator it = d->ref_cache_.find(label);
3955 if (it != d->ref_cache_.end())
3958 static References const dummy_refs = References();
3959 it = d->ref_cache_.insert(
3960 make_pair(label, dummy_refs)).first;
3965 Buffer::References const & Buffer::references(docstring const & label) const
3967 return const_cast<Buffer *>(this)->getReferenceCache(label);
3971 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3973 References & refs = getReferenceCache(label);
3974 refs.push_back(make_pair(inset, it));
3978 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3982 linfo.label = label;
3984 linfo.active = active;
3985 masterBuffer()->d->label_cache_.push_back(linfo);
3989 InsetLabel const * Buffer::insetLabel(docstring const & label,
3990 bool const active) const
3992 for (auto const & rc : masterBuffer()->d->label_cache_) {
3993 if (rc.label == label && (rc.active || !active))
4000 bool Buffer::activeLabel(docstring const & label) const
4002 return insetLabel(label, true) != nullptr;
4006 void Buffer::clearReferenceCache() const
4009 d->ref_cache_.clear();
4010 d->label_cache_.clear();
4015 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
4017 //FIXME: This does not work for child documents yet.
4018 reloadBibInfoCache();
4020 // Check if the label 'from' appears more than once
4021 vector<docstring> labels;
4022 for (auto const & bibit : masterBibInfo())
4023 labels.push_back(bibit.first);
4025 if (count(labels.begin(), labels.end(), from) > 1)
4028 string const paramName = "key";
4029 UndoGroupHelper ugh(this);
4030 InsetIterator it = begin(inset());
4032 if (it->lyxCode() != CITE_CODE)
4034 InsetCommand * inset = it->asInsetCommand();
4035 docstring const oldValue = inset->getParam(paramName);
4036 if (oldValue == from) {
4037 undo().recordUndo(CursorData(it));
4038 inset->setParam(paramName, to);
4043 // returns NULL if id-to-row conversion is unsupported
4044 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4045 pit_type par_begin, pit_type par_end,
4046 OutputWhat output, bool master) const
4048 unique_ptr<TexRow> texrow;
4049 OutputParams runparams(¶ms().encoding());
4050 runparams.nice = true;
4051 runparams.flavor = params().getOutputFlavor(format);
4052 runparams.linelen = lyxrc.plaintext_linelen;
4053 // No side effect of file copying and image conversion
4054 runparams.dryrun = true;
4056 // Some macros rely on font encoding
4057 runparams.main_fontenc = params().main_font_encoding();
4059 if (output == CurrentParagraph) {
4060 runparams.par_begin = par_begin;
4061 runparams.par_end = par_end;
4062 if (par_begin + 1 == par_end) {
4064 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4068 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4069 convert<docstring>(par_begin),
4070 convert<docstring>(par_end - 1))
4073 // output paragraphs
4074 if (runparams.flavor == Flavor::LyX) {
4075 Paragraph const & par = text().paragraphs()[par_begin];
4077 depth_type dt = par.getDepth();
4078 par.write(ods, params(), dt);
4079 os << from_utf8(ods.str());
4080 } else if (runparams.flavor == Flavor::Html) {
4082 setMathFlavor(runparams);
4083 xhtmlParagraphs(text(), *this, xs, runparams);
4084 } else if (runparams.flavor == Flavor::Text) {
4086 // FIXME Handles only one paragraph, unlike the others.
4087 // Probably should have some routine with a signature like them.
4088 writePlaintextParagraph(*this,
4089 text().paragraphs()[par_begin], os, runparams, dummy);
4090 } else if (runparams.flavor == Flavor::DocBook5) {
4092 docbookParagraphs(text(), *this, xs, runparams);
4094 // If we are previewing a paragraph, even if this is the
4095 // child of some other buffer, let's cut the link here,
4096 // so that no concurring settings from the master
4097 // (e.g. branch state) interfere (see #8101).
4099 d->ignore_parent = true;
4100 // We need to validate the Buffer params' features here
4101 // in order to know if we should output polyglossia
4102 // macros (instead of babel macros)
4103 LaTeXFeatures features(*this, params(), runparams);
4105 runparams.use_polyglossia = features.usePolyglossia();
4106 runparams.use_hyperref = features.isRequired("hyperref");
4107 // latex or literate
4110 ots.texrow().newlines(2);
4112 latexParagraphs(*this, text(), ots, runparams);
4113 texrow = ots.releaseTexRow();
4115 // Restore the parenthood
4117 d->ignore_parent = false;
4121 if (output == FullSource)
4122 os << _("Preview source code");
4123 else if (output == OnlyPreamble)
4124 os << _("Preview preamble");
4125 else if (output == OnlyBody)
4126 os << _("Preview body");
4128 if (runparams.flavor == Flavor::LyX) {
4130 if (output == FullSource)
4132 else if (output == OnlyPreamble)
4133 params().writeFile(ods, this);
4134 else if (output == OnlyBody)
4136 os << from_utf8(ods.str());
4137 } else if (runparams.flavor == Flavor::Html) {
4138 writeLyXHTMLSource(os, runparams, output);
4139 } else if (runparams.flavor == Flavor::Text) {
4140 if (output == OnlyPreamble) {
4141 os << "% "<< _("Plain text does not have a preamble.");
4143 writePlaintextFile(*this, os, runparams);
4144 } else if (runparams.flavor == Flavor::DocBook5) {
4145 writeDocBookSource(os, runparams, output);
4147 // latex or literate
4150 ots.texrow().newlines(2);
4152 runparams.is_child = true;
4154 writeLaTeXSource(ots, string(), runparams, output);
4155 texrow = ots.releaseTexRow();
4162 ErrorList & Buffer::errorList(string const & type) const
4164 return d->errorLists[type];
4168 void Buffer::updateTocItem(std::string const & type,
4169 DocIterator const & dit) const
4172 d->gui_->updateTocItem(type, dit);
4176 void Buffer::structureChanged() const
4179 d->gui_->structureChanged();
4183 void Buffer::errors(string const & err, bool from_master) const
4186 d->gui_->errors(err, from_master);
4190 void Buffer::message(docstring const & msg) const
4193 d->gui_->message(msg);
4197 void Buffer::setBusy(bool on) const
4200 d->gui_->setBusy(on);
4204 void Buffer::updateTitles() const
4207 d->wa_->updateTitles();
4211 void Buffer::resetAutosaveTimers() const
4214 d->gui_->resetAutosaveTimers();
4218 bool Buffer::hasGuiDelegate() const
4224 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4230 FileName Buffer::getEmergencyFileName() const
4232 return FileName(d->filename.absFileName() + ".emergency");
4236 FileName Buffer::getAutosaveFileName() const
4238 // if the document is unnamed try to save in the backup dir, else
4239 // in the default document path, and as a last try in the filePath,
4240 // which will most often be the temporary directory
4243 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4244 : lyxrc.backupdir_path;
4245 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4248 string const fname = "#" + d->filename.onlyFileName() + "#";
4250 return makeAbsPath(fname, fpath);
4254 void Buffer::removeAutosaveFile() const
4256 FileName const f = getAutosaveFileName();
4262 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4264 FileName const newauto = getAutosaveFileName();
4266 if (newauto != oldauto && oldauto.exists())
4267 if (!oldauto.moveTo(newauto))
4268 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4272 bool Buffer::autoSave() const
4274 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4275 if (buf->d->bak_clean || hasReadonlyFlag())
4278 message(_("Autosaving current document..."));
4279 buf->d->bak_clean = true;
4281 FileName const fname = getAutosaveFileName();
4282 LASSERT(d->cloned_buffer_, return false);
4284 // If this buffer is cloned, we assume that
4285 // we are running in a separate thread already.
4286 TempFile tempfile("lyxautoXXXXXX.lyx");
4287 tempfile.setAutoRemove(false);
4288 FileName const tmp_ret = tempfile.name();
4289 if (!tmp_ret.empty()) {
4291 // assume successful write of tmp_ret
4292 if (tmp_ret.moveTo(fname))
4295 // failed to write/rename tmp_ret so try writing direct
4296 return writeFile(fname);
4300 void Buffer::setExportStatus(bool e) const
4302 d->doing_export = e;
4303 ListOfBuffers clist = getDescendants();
4304 for (auto const & bit : clist)
4305 bit->d->doing_export = e;
4309 bool Buffer::isExporting() const
4311 return d->doing_export;
4315 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4319 return doExport(target, put_in_tempdir, result_file);
4322 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4323 string & result_file) const
4325 bool const update_unincluded =
4326 params().maintain_unincluded_children != BufferParams::CM_None
4327 && !params().getIncludedChildren().empty();
4329 // (1) export with all included children (omit \includeonly)
4330 if (update_unincluded) {
4331 ExportStatus const status =
4332 doExport(target, put_in_tempdir, true, result_file);
4333 if (status != ExportSuccess)
4336 // (2) export with included children only
4337 return doExport(target, put_in_tempdir, false, result_file);
4341 void Buffer::setMathFlavor(OutputParams & op) const
4343 switch (params().html_math_output) {
4344 case BufferParams::MathML:
4345 op.math_flavor = OutputParams::MathAsMathML;
4347 case BufferParams::HTML:
4348 op.math_flavor = OutputParams::MathAsHTML;
4350 case BufferParams::Images:
4351 op.math_flavor = OutputParams::MathAsImages;
4353 case BufferParams::LaTeX:
4354 op.math_flavor = OutputParams::MathAsLaTeX;
4360 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4361 bool includeall, string & result_file) const
4363 LYXERR(Debug::FILES, "target=" << target);
4364 OutputParams runparams(¶ms().encoding());
4365 string format = target;
4366 string dest_filename;
4367 size_t pos = target.find(' ');
4368 if (pos != string::npos) {
4369 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4370 format = target.substr(0, pos);
4371 if (format == "default")
4372 format = params().getDefaultOutputFormat();
4373 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4374 FileName(dest_filename).onlyPath().createPath();
4375 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4377 MarkAsExporting exporting(this);
4378 string backend_format;
4379 runparams.flavor = Flavor::LaTeX;
4380 runparams.linelen = lyxrc.plaintext_linelen;
4381 runparams.includeall = includeall;
4382 vector<string> backs = params().backends();
4383 Converters converters = theConverters();
4384 bool need_nice_file = false;
4385 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4386 // Get shortest path to format
4387 converters.buildGraph();
4388 Graph::EdgePath path;
4389 for (string const & sit : backs) {
4390 Graph::EdgePath p = converters.getPath(sit, format);
4391 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4392 backend_format = sit;
4397 if (!put_in_tempdir) {
4398 // Only show this alert if this is an export to a non-temporary
4399 // file (not for previewing).
4400 docstring s = bformat(_("No information for exporting the format %1$s."),
4401 translateIfPossible(theFormats().prettyName(format)));
4402 if (format == "pdf4")
4404 + bformat(_("Hint: use non-TeX fonts or set input encoding "
4405 " to '%1$s'"), from_utf8(encodings.fromLyXName("ascii")->guiName()));
4406 Alert::error(_("Couldn't export file"), s);
4408 return ExportNoPathToFormat;
4410 runparams.flavor = converters.getFlavor(path, this);
4411 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4412 for (auto const & edge : path)
4413 if (theConverters().get(edge).nice()) {
4414 need_nice_file = true;
4419 backend_format = format;
4420 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4421 // FIXME: Don't hardcode format names here, but use a flag
4422 if (backend_format == "pdflatex")
4423 runparams.flavor = Flavor::PdfLaTeX;
4424 else if (backend_format == "luatex")
4425 runparams.flavor = Flavor::LuaTeX;
4426 else if (backend_format == "dviluatex")
4427 runparams.flavor = Flavor::DviLuaTeX;
4428 else if (backend_format == "xetex")
4429 runparams.flavor = Flavor::XeTeX;
4432 string filename = latexName(false);
4433 filename = addName(temppath(), filename);
4434 filename = changeExtension(filename,
4435 theFormats().extension(backend_format));
4436 LYXERR(Debug::FILES, "filename=" << filename);
4438 // Plain text backend
4439 if (backend_format == "text") {
4440 runparams.flavor = Flavor::Text;
4442 writePlaintextFile(*this, FileName(filename), runparams);
4444 catch (ConversionException const &) { return ExportCancel; }
4447 else if (backend_format == "xhtml") {
4448 runparams.flavor = Flavor::Html;
4449 setMathFlavor(runparams);
4450 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4451 return ExportKilled;
4452 } else if (backend_format == "lyx")
4453 writeFile(FileName(filename));
4455 else if (backend_format == "docbook5") {
4456 runparams.flavor = Flavor::DocBook5;
4457 runparams.nice = false;
4458 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4459 return ExportKilled;
4462 else if (backend_format == format || need_nice_file) {
4463 runparams.nice = true;
4464 ExportStatus const retval =
4465 makeLaTeXFile(FileName(filename), string(), runparams);
4466 if (retval == ExportKilled)
4467 return ExportKilled;
4468 if (d->cloned_buffer_)
4469 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4470 if (retval != ExportSuccess)
4472 } else if (!lyxrc.tex_allows_spaces
4473 && contains(filePath(), ' ')) {
4474 Alert::error(_("File name error"),
4475 bformat(_("The directory path to the document\n%1$s\n"
4476 "contains spaces, but your TeX installation does "
4477 "not allow them. You should save the file to a directory "
4478 "whose name does not contain spaces."), from_utf8(filePath())));
4479 return ExportTexPathHasSpaces;
4481 runparams.nice = false;
4482 ExportStatus const retval =
4483 makeLaTeXFile(FileName(filename), filePath(), runparams);
4484 if (retval == ExportKilled)
4485 return ExportKilled;
4486 if (d->cloned_buffer_)
4487 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4488 if (retval != ExportSuccess)
4492 string const error_type = (format == "program")
4493 ? "Build" : params().bufferFormat();
4494 ErrorList & error_list = d->errorLists[error_type];
4495 string const ext = theFormats().extension(format);
4496 FileName const tmp_result_file(changeExtension(filename, ext));
4497 Converters::RetVal const retval =
4498 converters.convert(this, FileName(filename), tmp_result_file,
4499 FileName(absFileName()), backend_format, format,
4500 error_list, Converters::none, includeall);
4501 if (retval == Converters::KILLED)
4502 return ExportCancel;
4503 bool success = (retval == Converters::SUCCESS);
4505 // Emit the signal to show the error list or copy it back to the
4506 // cloned Buffer so that it can be emitted afterwards.
4507 if (format != backend_format) {
4508 if (runparams.silent)
4510 else if (d->cloned_buffer_)
4511 d->cloned_buffer_->d->errorLists[error_type] =
4512 d->errorLists[error_type];
4515 // also to the children, in case of master-buffer-view
4516 ListOfBuffers clist = getDescendants();
4517 for (auto const & bit : clist) {
4518 if (runparams.silent)
4519 bit->d->errorLists[error_type].clear();
4520 else if (d->cloned_buffer_) {
4521 // Enable reverse search by copying back the
4522 // texrow object to the cloned buffer.
4523 // FIXME: this is not thread safe.
4524 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4525 bit->d->cloned_buffer_->d->errorLists[error_type] =
4526 bit->d->errorLists[error_type];
4528 bit->errors(error_type, true);
4532 if (d->cloned_buffer_) {
4533 // Enable reverse dvi or pdf to work by copying back the texrow
4534 // object to the cloned buffer.
4535 // FIXME: There is a possibility of concurrent access to texrow
4536 // here from the main GUI thread that should be securized.
4537 d->cloned_buffer_->d->texrow = d->texrow;
4538 string const err_type = params().bufferFormat();
4539 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4543 if (put_in_tempdir) {
4544 result_file = tmp_result_file.absFileName();
4545 return success ? ExportSuccess : ExportConverterError;
4548 if (dest_filename.empty())
4549 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4551 result_file = dest_filename;
4552 // We need to copy referenced files (e. g. included graphics
4553 // if format == "dvi") to the result dir.
4554 vector<ExportedFile> const extfiles =
4555 runparams.exportdata->externalFiles(format);
4556 string const dest = runparams.export_folder.empty() ?
4557 onlyPath(result_file) : runparams.export_folder;
4558 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4559 : force_overwrite == ALL_FILES;
4560 CopyStatus status = use_force ? FORCE : SUCCESS;
4562 for (ExportedFile const & exp : extfiles) {
4563 if (status == CANCEL) {
4564 message(_("Document export cancelled."));
4565 return ExportCancel;
4567 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4568 string fixedName = exp.exportName;
4569 if (!runparams.export_folder.empty()) {
4570 // Relative pathnames starting with ../ will be sanitized
4571 // if exporting to a different folder
4572 while (fixedName.substr(0, 3) == "../")
4573 fixedName = fixedName.substr(3, fixedName.length() - 3);
4575 FileName fixedFileName = makeAbsPath(fixedName, dest);
4576 fixedFileName.onlyPath().createPath();
4577 status = copyFile(fmt, exp.sourceName,
4579 exp.exportName, status == FORCE,
4580 runparams.export_folder.empty());
4584 if (tmp_result_file.exists()) {
4585 // Finally copy the main file
4586 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4587 : force_overwrite != NO_FILES;
4588 if (status == SUCCESS && use_force)
4590 status = copyFile(format, tmp_result_file,
4591 FileName(result_file), result_file,
4593 if (status == CANCEL) {
4594 message(_("Document export cancelled."));
4595 return ExportCancel;
4597 message(bformat(_("Document exported as %1$s "
4599 translateIfPossible(theFormats().prettyName(format)),
4600 makeDisplayPath(result_file)));
4603 // This must be a dummy converter like fax (bug 1888)
4604 message(bformat(_("Document exported as %1$s"),
4605 translateIfPossible(theFormats().prettyName(format))));
4608 return success ? ExportSuccess : ExportConverterError;
4612 Buffer::ExportStatus Buffer::preview(string const & format) const
4614 bool const update_unincluded =
4615 params().maintain_unincluded_children != BufferParams::CM_None
4616 && !params().getIncludedChildren().empty();
4617 return preview(format, update_unincluded);
4621 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4623 MarkAsExporting exporting(this);
4625 // (1) export with all included children (omit \includeonly)
4627 ExportStatus const status = doExport(format, true, true, result_file);
4628 if (status != ExportSuccess)
4631 // (2) export with included children only
4632 ExportStatus const status = doExport(format, true, false, result_file);
4633 FileName const previewFile(result_file);
4635 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4636 theimpl->preview_file_ = previewFile;
4637 theimpl->preview_format_ = format;
4638 theimpl->require_fresh_start_ = (status != ExportSuccess);
4640 if (status != ExportSuccess)
4643 if (previewFile.exists())
4644 return theFormats().view(*this, previewFile, format) ?
4645 PreviewSuccess : PreviewError;
4647 // Successful export but no output file?
4648 // Probably a bug in error detection.
4649 LATTEST(status != ExportSuccess);
4654 Buffer::ReadStatus Buffer::extractFromVC()
4656 bool const found = LyXVC::file_not_found_hook(d->filename);
4658 return ReadFileNotFound;
4659 if (!d->filename.isReadableFile())
4665 Buffer::ReadStatus Buffer::loadEmergency()
4667 FileName const emergencyFile = getEmergencyFileName();
4668 if (!emergencyFile.exists()
4669 || emergencyFile.lastModified() <= d->filename.lastModified())
4670 return ReadFileNotFound;
4672 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4673 docstring const text = bformat(_("An emergency save of the document "
4674 "%1$s exists.\n\nRecover emergency save?"), file);
4676 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4677 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4683 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4684 bool const success = (ret_llf == ReadSuccess);
4686 if (hasReadonlyFlag()) {
4687 Alert::warning(_("File is read-only"),
4688 bformat(_("An emergency file is successfully loaded, "
4689 "but the original file %1$s is marked read-only. "
4690 "Please make sure to save the document as a different "
4691 "file."), from_utf8(d->filename.absFileName())));
4694 lyxvc().file_found_hook(d->filename);
4695 str = _("Document was successfully recovered.");
4697 str = _("Document was NOT successfully recovered.");
4698 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4699 makeDisplayPath(emergencyFile.absFileName()));
4701 int const del_emerg =
4702 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4703 _("&Remove"), _("&Keep"));
4704 if (del_emerg == 0) {
4705 emergencyFile.removeFile();
4707 Alert::warning(_("Emergency file deleted"),
4708 _("Do not forget to save your file now!"), true);
4710 return success ? ReadSuccess : ReadEmergencyFailure;
4713 int const del_emerg =
4714 Alert::prompt(_("Delete emergency file?"),
4715 _("Remove emergency file now?"), 1, 1,
4716 _("&Remove"), _("&Keep"));
4718 emergencyFile.removeFile();
4722 string const ename = emergencyFile.absFileName();
4724 // Surely we can find one in 100 tries?
4725 for (int i = 1; i < 100; ++i) {
4726 newname.set(ename + to_string(i) + ".lyx");
4727 if (!newname.exists()) {
4733 // renameTo returns true on success. So inverting that
4734 // will give us true if we fail.
4735 noname = !emergencyFile.renameTo(newname);
4738 Alert::warning(_("Can't rename emergency file!"),
4739 _("LyX was unable to rename the emergency file. "
4740 "You should do so manually. Otherwise, you will be "
4741 "asked about it again the next time you try to load "
4742 "this file, and may over-write your own work."));
4744 Alert::warning(_("Emergency File Renames"),
4745 bformat(_("Emergency file renamed as:\n %1$s"),
4746 from_utf8(newname.onlyFileName())));
4749 return ReadOriginal;
4759 Buffer::ReadStatus Buffer::loadAutosave()
4761 // Now check if autosave file is newer.
4762 FileName const autosaveFile = getAutosaveFileName();
4763 if (!autosaveFile.exists()
4764 || autosaveFile.lastModified() <= d->filename.lastModified())
4765 return ReadFileNotFound;
4767 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4768 docstring const text = bformat(_("The backup of the document %1$s "
4769 "is newer.\n\nLoad the backup instead?"), file);
4770 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4771 _("&Load backup"), _("Load &original"), _("&Cancel"));
4776 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4777 // the file is not saved if we load the autosave file.
4778 if (ret_llf == ReadSuccess) {
4779 if (hasReadonlyFlag()) {
4780 Alert::warning(_("File is read-only"),
4781 bformat(_("A backup file is successfully loaded, "
4782 "but the original file %1$s is marked read-only. "
4783 "Please make sure to save the document as a "
4785 from_utf8(d->filename.absFileName())));
4788 lyxvc().file_found_hook(d->filename);
4791 return ReadAutosaveFailure;
4794 // Here we delete the autosave
4795 autosaveFile.removeFile();
4796 return ReadOriginal;
4804 Buffer::ReadStatus Buffer::loadLyXFile()
4806 if (!d->filename.isReadableFile()) {
4807 ReadStatus const ret_rvc = extractFromVC();
4808 if (ret_rvc != ReadSuccess)
4812 ReadStatus const ret_re = loadEmergency();
4813 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4816 ReadStatus const ret_ra = loadAutosave();
4817 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4820 return loadThisLyXFile(d->filename);
4824 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4826 return readFile(fn);
4830 void Buffer::Impl::traverseErrors(TeXErrors::Errors::const_iterator err, TeXErrors::Errors::const_iterator end, ErrorList & errorList) const
4832 for (; err != end; ++err) {
4833 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4834 int errorRow = err->error_in_line;
4835 Buffer const * buf = nullptr;
4836 Impl const * p = this;
4837 if (err->child_name.empty())
4838 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4840 // The error occurred in a child
4841 for (Buffer const * child : owner_->getDescendants()) {
4842 string const child_name =
4843 DocFileName(changeExtension(child->absFileName(), "tex")).
4845 if (err->child_name != child_name)
4847 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4848 if (!TexRow::isNone(start)) {
4849 buf = this->cloned_buffer_
4850 ? child->d->cloned_buffer_->d->owner_
4857 errorList.push_back(ErrorItem(err->error_desc, err->error_text,
4863 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4865 TeXErrors::Errors::const_iterator err = terr.begin();
4866 TeXErrors::Errors::const_iterator end = terr.end();
4868 d->traverseErrors(err, end, errorList);
4872 void Buffer::bufferRefs(TeXErrors const & terr, ErrorList & errorList) const
4874 TeXErrors::Errors::const_iterator err = terr.begin_ref();
4875 TeXErrors::Errors::const_iterator end = terr.end_ref();
4877 d->traverseErrors(err, end, errorList);
4881 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4883 LBUFERR(!text().paragraphs().empty());
4885 // Use the master text class also for child documents
4886 Buffer const * const master = masterBuffer();
4887 DocumentClass const & textclass = master->params().documentClass();
4889 docstring_list old_bibfiles;
4890 // Do this only if we are the top-level Buffer. We also need to account
4891 // for the case of a previewed child with ignored parent here.
4892 if (master == this && !d->ignore_parent) {
4893 textclass.counters().reset(from_ascii("bibitem"));
4894 reloadBibInfoCache();
4895 // we will re-read this cache as we go through, but we need
4896 // to know whether it's changed to know whether we need to
4897 // update the bibinfo cache.
4898 old_bibfiles = d->bibfiles_cache_;
4899 d->bibfiles_cache_.clear();
4902 // keep the buffers to be children in this set. If the call from the
4903 // master comes back we can see which of them were actually seen (i.e.
4904 // via an InsetInclude). The remaining ones in the set need still be updated.
4905 static std::set<Buffer const *> bufToUpdate;
4906 if (scope == UpdateMaster) {
4907 // If this is a child document start with the master
4908 if (master != this) {
4909 bufToUpdate.insert(this);
4910 master->updateBuffer(UpdateMaster, utype);
4911 // If the master buffer has no gui associated with it, then the TocModel is
4912 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4913 // (bug 5699). The same happens if the master buffer is open in a different
4914 // window. This test catches both possibilities.
4915 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4916 // There remains a problem here: If there is another child open in yet a third
4917 // window, that TOC is not updated. So some more general solution is needed at
4919 if (master->d->gui_ != d->gui_)
4922 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4923 if (bufToUpdate.find(this) == bufToUpdate.end())
4927 // start over the counters in the master
4928 textclass.counters().reset();
4931 // update will be done below for this buffer
4932 bufToUpdate.erase(this);
4934 // update all caches
4935 clearReferenceCache();
4938 Buffer & cbuf = const_cast<Buffer &>(*this);
4939 // if we are reloading, then we could have a dangling TOC,
4940 // in effect. so we need to go ahead and reset, even though
4941 // we will do so again when we rebuild the TOC later.
4942 cbuf.tocBackend().reset();
4945 ParIterator parit = cbuf.par_iterator_begin();
4946 if (scope == UpdateMaster)
4948 updateBuffer(parit, utype);
4950 // If this document has siblings, then update the TocBackend later. The
4951 // reason is to ensure that later siblings are up to date when e.g. the
4952 // broken or not status of references is computed. The update is called
4953 // in InsetInclude::addToToc.
4957 // if the bibfiles changed, the cache of bibinfo is invalid
4958 docstring_list new_bibfiles = d->bibfiles_cache_;
4959 // this is a trick to determine whether the two vectors have
4960 // the same elements.
4961 sort(new_bibfiles.begin(), new_bibfiles.end());
4962 sort(old_bibfiles.begin(), old_bibfiles.end());
4963 if (old_bibfiles != new_bibfiles) {
4964 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4965 invalidateBibinfoCache();
4966 reloadBibInfoCache();
4967 // We relied upon the bibinfo cache when recalculating labels. But that
4968 // cache was invalid, although we didn't find that out until now. So we
4969 // have to do it all again.
4970 // That said, the only thing we really need to do is update the citation
4971 // labels. Nothing else will have changed. So we could create a new
4972 // UpdateType that would signal that fact, if we needed to do so.
4973 parit = cbuf.par_iterator_begin();
4974 // we will be re-doing the counters and references and such.
4975 textclass.counters().reset();
4976 clearReferenceCache();
4977 // we should not need to do this again?
4979 updateBuffer(parit, utype);
4980 // this will already have been done by reloadBibInfoCache();
4981 // d->bibinfo_cache_valid_ = true;
4984 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4985 // this is also set to true on the other path, by reloadBibInfoCache.
4986 d->bibinfo_cache_valid_ = true;
4988 d->cite_labels_valid_ = true;
4991 cbuf.tocBackend().update(true, utype);
4992 if (scope == UpdateMaster)
4993 cbuf.structureChanged();
4997 static depth_type getDepth(DocIterator const & it)
4999 depth_type depth = 0;
5000 for (size_t i = 0 ; i < it.depth() ; ++i)
5001 if (!it[i].inset().inMathed())
5002 depth += it[i].paragraph().getDepth() + 1;
5003 // remove 1 since the outer inset does not count
5004 // we should have at least one non-math inset, so
5005 // depth should nevery be 0. but maybe it is worth
5006 // marking this, just in case.
5008 // coverity[INTEGER_OVERFLOW]
5012 static depth_type getItemDepth(ParIterator const & it)
5014 Paragraph const & par = *it;
5015 LabelType const labeltype = par.layout().labeltype;
5017 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5020 // this will hold the lowest depth encountered up to now.
5021 depth_type min_depth = getDepth(it);
5022 ParIterator prev_it = it;
5025 --prev_it.top().pit();
5027 // start of nested inset: go to outer par
5029 if (prev_it.empty()) {
5030 // start of document: nothing to do
5035 // We search for the first paragraph with same label
5036 // that is not more deeply nested.
5037 Paragraph & prev_par = *prev_it;
5038 depth_type const prev_depth = getDepth(prev_it);
5039 if (labeltype == prev_par.layout().labeltype) {
5040 if (prev_depth < min_depth)
5041 return prev_par.itemdepth + 1;
5042 if (prev_depth == min_depth)
5043 return prev_par.itemdepth;
5045 min_depth = min(min_depth, prev_depth);
5046 // small optimization: if we are at depth 0, we won't
5047 // find anything else
5048 if (prev_depth == 0)
5054 static bool needEnumCounterReset(ParIterator const & it)
5056 Paragraph const & par = *it;
5057 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5058 depth_type const cur_depth = par.getDepth();
5059 ParIterator prev_it = it;
5060 while (prev_it.pit()) {
5061 --prev_it.top().pit();
5062 Paragraph const & prev_par = *prev_it;
5063 if (prev_par.getDepth() <= cur_depth)
5064 return prev_par.layout().name() != par.layout().name();
5066 // start of nested inset: reset
5071 // set the label of a paragraph. This includes the counters.
5072 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5074 BufferParams const & bp = owner_->masterBuffer()->params();
5075 DocumentClass const & textclass = bp.documentClass();
5076 Paragraph & par = it.paragraph();
5077 Layout const & layout = par.layout();
5078 Counters & counters = textclass.counters();
5080 if (par.params().startOfAppendix()) {
5081 // We want to reset the counter corresponding to toplevel sectioning
5082 Layout const & lay = textclass.getTOCLayout();
5083 docstring const cnt = lay.counter;
5085 counters.reset(cnt);
5086 counters.appendix(true);
5088 par.params().appendix(counters.appendix());
5090 // Compute the item depth of the paragraph
5091 par.itemdepth = getItemDepth(it);
5093 if (layout.margintype == MARGIN_MANUAL) {
5094 if (par.params().labelWidthString().empty())
5095 par.params().labelWidthString(par.expandLabel(layout, bp));
5096 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5097 // we do not need to do anything here, since the empty case is
5098 // handled during export.
5100 par.params().labelWidthString(docstring());
5103 switch(layout.labeltype) {
5104 case LABEL_ITEMIZE: {
5105 // At some point of time we should do something more
5106 // clever here, like:
5107 // par.params().labelString(
5108 // bp.user_defined_bullet(par.itemdepth).getText());
5109 // for now, use a simple hardcoded label
5110 docstring itemlabel;
5111 switch (par.itemdepth) {
5114 itemlabel = char_type(0x2022);
5118 itemlabel = char_type(0x2013);
5121 // ∗ U+2217 ASTERISK OPERATOR
5122 itemlabel = char_type(0x2217);
5125 // · U+00B7 MIDDLE DOT
5126 itemlabel = char_type(0x00b7);
5129 par.params().labelString(itemlabel);
5133 case LABEL_ENUMERATE: {
5134 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5136 switch (par.itemdepth) {
5147 enumcounter += "iv";
5150 // not a valid enumdepth...
5154 if (needEnumCounterReset(it)) {
5155 // Increase the parent counter?
5156 if (layout.stepparentcounter)
5157 counters.stepParent(enumcounter, utype);
5158 // Maybe we have to reset the enumeration counter.
5159 if (!layout.resumecounter)
5160 counters.reset(enumcounter);
5162 counters.step(enumcounter, utype);
5164 string const & lang = par.getParLanguage(bp)->code();
5165 par.params().labelString(counters.theCounter(enumcounter, lang));
5170 case LABEL_SENSITIVE: {
5171 string const & type = counters.current_float();
5172 docstring full_label;
5174 full_label = owner_->B_("Senseless!!! ");
5176 docstring name = owner_->B_(textclass.floats().getType(type).name());
5177 if (counters.hasCounter(from_utf8(type))) {
5178 string const & lang = par.getParLanguage(bp)->code();
5179 counters.step(from_utf8(type), utype);
5180 full_label = bformat(from_ascii("%1$s %2$s:"),
5182 counters.theCounter(from_utf8(type), lang));
5184 full_label = bformat(from_ascii("%1$s #:"), name);
5186 par.params().labelString(full_label);
5190 case LABEL_NO_LABEL:
5191 par.params().labelString(docstring());
5195 case LABEL_CENTERED:
5196 case LABEL_STATIC: {
5197 docstring const & lcounter = layout.counter;
5198 if (!lcounter.empty()) {
5199 if (layout.toclevel <= bp.secnumdepth
5200 && (layout.latextype != LATEX_ENVIRONMENT
5201 || it.text()->isFirstInSequence(it.pit()))) {
5202 if (counters.hasCounter(lcounter))
5203 counters.step(lcounter, utype);
5204 par.params().labelString(par.expandLabel(layout, bp));
5206 par.params().labelString(docstring());
5208 par.params().labelString(par.expandLabel(layout, bp));
5214 par.params().labelString(par.expandLabel(layout, bp));
5219 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype, bool const deleted) const
5221 pushIncludedBuffer(this);
5222 // LASSERT: Is it safe to continue here, or should we just return?
5223 LASSERT(parit.pit() == 0, /**/);
5225 // Set the position of the text in the buffer to be able
5226 // to resolve macros in it.
5227 parit.text()->setMacrocontextPosition(parit);
5229 depth_type maxdepth = 0;
5230 pit_type const lastpit = parit.lastpit();
5231 bool changed = false;
5232 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5233 // reduce depth if necessary
5234 if (parit->params().depth() > maxdepth) {
5235 /** FIXME: this function is const, but
5236 * nevertheless it modifies the buffer. To be
5237 * cleaner, one should modify the buffer in
5238 * another function, which is actually
5239 * non-const. This would however be costly in
5240 * terms of code duplication.
5242 CursorData(parit).recordUndo();
5243 parit->params().depth(maxdepth);
5245 maxdepth = parit->getMaxDepthAfter();
5247 if (utype == OutputUpdate) {
5248 // track the active counters
5249 // we have to do this for the master buffer, since the local
5250 // buffer isn't tracking anything.
5251 masterBuffer()->params().documentClass().counters().
5252 setActiveLayout(parit->layout());
5255 // set the counter for this paragraph
5256 d->setLabel(parit, utype);
5259 for (auto const & insit : parit->insetList()) {
5260 parit.pos() = insit.pos;
5261 insit.inset->updateBuffer(parit, utype, deleted || parit->isDeleted(insit.pos));
5262 changed |= insit.inset->isChanged();
5265 // are there changes in this paragraph?
5266 changed |= parit->isChanged();
5269 // set change indicator for the inset (or the cell that the iterator
5270 // points to, if applicable).
5271 parit.text()->inset().isChanged(changed);
5272 popIncludedBuffer();
5276 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5277 WordLangTuple & word_lang, docstring_list & suggestions) const
5281 suggestions.clear();
5282 word_lang = WordLangTuple();
5283 bool const to_end = to.empty();
5284 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5285 // OK, we start from here.
5286 for (; from != end; from.forwardPos()) {
5287 // This skips all insets with spell check disabled.
5288 while (!from.allowSpellCheck()) {
5292 // If from is at the end of the document (which is possible
5293 // when "from" was changed above) LyX will crash later otherwise.
5294 if (from.atEnd() || (!to_end && from >= end))
5297 from.paragraph().spellCheck();
5298 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5299 if (SpellChecker::misspelled(res)) {
5303 // Do not increase progress when from == to, otherwise the word
5304 // count will be wrong.
5314 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5316 bool inword = false;
5321 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5322 if (!dit.inTexted()) {
5327 Paragraph const & par = dit.paragraph();
5328 pos_type const pos = dit.pos();
5330 // Copied and adapted from isWordSeparator() in Paragraph
5331 if (pos == dit.lastpos()) {
5334 Inset const * ins = par.getInset(pos);
5335 if (ins && skipNoOutput && !ins->producesOutput()) {
5338 // stop if end of range was skipped
5339 if (!to.atEnd() && dit >= to)
5342 } else if (!par.isDeleted(pos)) {
5343 if (par.isWordSeparator(pos))
5349 if (ins && ins->isLetter()) {
5350 odocstringstream os;
5352 char_count_ += os.str().length();
5354 else if (ins && ins->isSpace())
5357 char_type const c = par.getChar(pos);
5358 if (isPrintableNonspace(c))
5360 else if (isSpace(c))
5370 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5372 d->updateStatistics(from, to, skipNoOutput);
5376 int Buffer::wordCount() const
5378 return d->wordCount();
5382 int Buffer::charCount(bool with_blanks) const
5384 return d->charCount(with_blanks);
5388 bool Buffer::areChangesPresent() const
5390 return inset().isChanged();
5394 Buffer::ReadStatus Buffer::reload()
5397 // c.f. bug https://www.lyx.org/trac/ticket/6587
5398 removeAutosaveFile();
5399 // e.g., read-only status could have changed due to version control
5400 d->filename.refresh();
5401 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5403 // clear parent. this will get reset if need be.
5404 d->setParent(nullptr);
5405 ReadStatus const status = loadLyXFile();
5406 if (status == ReadSuccess) {
5411 message(bformat(_("Document %1$s reloaded."), disp_fn));
5414 message(bformat(_("Could not reload document %1$s."), disp_fn));
5424 bool Buffer::saveAs(FileName const & fn)
5426 FileName const old_name = fileName();
5427 FileName const old_auto = getAutosaveFileName();
5428 bool const old_unnamed = isUnnamed();
5429 bool success = true;
5430 d->old_position = filePath();
5437 // bring the autosave file with us, just in case.
5438 moveAutosaveFile(old_auto);
5439 // validate version control data and
5440 // correct buffer title
5441 lyxvc().file_found_hook(fileName());
5443 // the file has now been saved to the new location.
5444 // we need to check that the locations of child buffers
5446 checkChildBuffers();
5447 checkMasterBuffer();
5450 // reset the old filename and unnamed state
5451 setFileName(old_name);
5452 setUnnamed(old_unnamed);
5456 d->old_position.clear();
5461 void Buffer::checkChildBuffers()
5463 for (auto const & bit : d->children_positions) {
5464 DocIterator dit = bit.second;
5465 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5466 if (!cbuf || !theBufferList().isLoaded(cbuf))
5468 Inset * inset = dit.nextInset();
5469 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5470 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5471 docstring const & incfile = inset_inc->getParam("filename");
5472 string oldloc = cbuf->absFileName();
5473 string newloc = makeAbsPath(to_utf8(incfile),
5474 onlyPath(absFileName())).absFileName();
5475 if (oldloc == newloc)
5477 // the location of the child file is incorrect.
5478 cbuf->setParent(nullptr);
5479 inset_inc->setChildBuffer(nullptr);
5481 // invalidate cache of children
5482 d->children_positions.clear();
5483 d->position_to_children.clear();
5487 // If a child has been saved under a different name/path, it might have been
5488 // orphaned. Therefore the master needs to be reset (bug 8161).
5489 void Buffer::checkMasterBuffer()
5491 Buffer const * const master = masterBuffer();
5495 // necessary to re-register the child (bug 5873)
5496 // FIXME: clean up updateMacros (here, only
5497 // child registering is needed).
5498 master->updateMacros();
5499 // (re)set master as master buffer, but only
5500 // if we are a real child
5501 if (master->isChild(this))
5508 string Buffer::includedFilePath(string const & name, string const & ext) const
5510 if (d->old_position.empty() ||
5511 equivalent(FileName(d->old_position), FileName(filePath())))
5514 bool isabsolute = FileName::isAbsolute(name);
5515 // both old_position and filePath() end with a path separator
5516 string absname = isabsolute ? name : d->old_position + name;
5518 // if old_position is set to origin, we need to do the equivalent of
5519 // getReferencedFileName() (see readDocument())
5520 if (!isabsolute && d->old_position == params().origin) {
5521 FileName const test(addExtension(filePath() + name, ext));
5523 absname = filePath() + name;
5526 if (!FileName(addExtension(absname, ext)).exists())
5530 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5532 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5533 from_utf8(filePath())));
5537 void Buffer::Impl::refreshFileMonitor()
5539 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5540 file_monitor_->refresh();
5544 // The previous file monitor is invalid
5545 // This also destroys the previous file monitor and all its connections
5546 file_monitor_ = FileSystemWatcher::monitor(filename);
5547 // file_monitor_ will be destroyed with *this, so it is not going to call a
5548 // destroyed object method.
5549 file_monitor_->connect([this](bool exists) {
5550 fileExternallyModified(exists);
5555 void Buffer::Impl::fileExternallyModified(bool const exists)
5557 // ignore notifications after our own saving operations
5558 if (checksum_ == filename.checksum()) {
5559 LYXERR(Debug::FILES, "External modification but "
5560 "checksum unchanged: " << filename);
5563 // If the file has been deleted, only mark the file as dirty since it is
5564 // pointless to prompt for reloading. If later a file is moved into this
5565 // location, then the externally modified warning will appear then.
5567 externally_modified_ = true;
5568 // Update external modification notification.
5569 // Dirty buffers must be visible at all times.
5570 if (wa_ && wa_->unhide(owner_))
5571 wa_->updateTitles();
5573 // Unable to unhide the buffer (e.g. no GUI or not current View)
5578 bool Buffer::notifiesExternalModification() const
5580 return d->externally_modified_;
5584 void Buffer::clearExternalModification() const
5586 d->externally_modified_ = false;
5588 d->wa_->updateTitles();
5592 void Buffer::pushIncludedBuffer(Buffer const * buf) const
5594 masterBuffer()->d->include_list_.push_back(buf);
5595 if (lyxerr.debugging(Debug::FILES)) {
5596 LYXERR0("Pushed. Stack now:");
5597 if (masterBuffer()->d->include_list_.empty())
5600 for (auto const & b : masterBuffer()->d->include_list_)
5601 LYXERR0(b->fileName());
5606 void Buffer::popIncludedBuffer() const
5608 masterBuffer()->d->include_list_.pop_back();
5609 if (lyxerr.debugging(Debug::FILES)) {
5610 LYXERR0("Popped. Stack now:");
5611 if (masterBuffer()->d->include_list_.empty())
5614 for (auto const & b : masterBuffer()->d->include_list_)
5615 LYXERR0(b->fileName());
5620 bool Buffer::isBufferIncluded(Buffer const * buf) const
5624 if (lyxerr.debugging(Debug::FILES)) {
5625 LYXERR0("Checking for " << buf->fileName() << ". Stack now:");
5626 if (masterBuffer()->d->include_list_.empty())
5629 for (auto const & b : masterBuffer()->d->include_list_)
5630 LYXERR0(b->fileName());
5632 list<Buffer const *> const & blist = masterBuffer()->d->include_list_;
5633 return find(blist.begin(), blist.end(), buf) != blist.end();
5637 void Buffer::clearIncludeList() const
5639 LYXERR(Debug::FILES, "Clearing include list for " << fileName());
5640 d->include_list_.clear();