3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
59 #include "SpellChecker.h"
61 #include "texstream.h"
64 #include "TextClass.h"
65 #include "TocBackend.h"
67 #include "VCBackend.h"
69 #include "WordLangTuple.h"
72 #include "insets/InsetBibtex.h"
73 #include "insets/InsetBranch.h"
74 #include "insets/InsetInclude.h"
75 #include "insets/InsetTabular.h"
76 #include "insets/InsetText.h"
78 #include "mathed/InsetMathHull.h"
79 #include "mathed/MacroTable.h"
80 #include "mathed/InsetMathMacroTemplate.h"
81 #include "mathed/MathSupport.h"
83 #include "graphics/GraphicsCache.h"
84 #include "graphics/PreviewLoader.h"
86 #include "frontends/Application.h"
87 #include "frontends/alert.h"
88 #include "frontends/Delegates.h"
89 #include "frontends/WorkAreaManager.h"
91 #include "support/lassert.h"
92 #include "support/convert.h"
93 #include "support/debug.h"
94 #include "support/docstring_list.h"
95 #include "support/ExceptionMessage.h"
96 #include "support/FileMonitor.h"
97 #include "support/FileName.h"
98 #include "support/FileNameList.h"
99 #include "support/filetools.h"
100 #include "support/ForkedCalls.h"
101 #include "support/gettext.h"
102 #include "support/gzstream.h"
103 #include "support/lstrings.h"
104 #include "support/lyxalgo.h"
105 #include "support/mutex.h"
106 #include "support/os.h"
107 #include "support/Package.h"
108 #include "support/PathChanger.h"
109 #include "support/Systemcall.h"
110 #include "support/TempFile.h"
111 #include "support/textutils.h"
112 #include "support/types.h"
114 #include "support/bind.h"
126 using namespace lyx::support;
127 using namespace lyx::graphics;
131 namespace Alert = frontend::Alert;
132 namespace os = support::os;
136 int const LYX_FORMAT = LYX_FORMAT_LYX;
138 typedef map<string, bool> DepClean;
140 // Information about labels and their associated refs
145 InsetLabel const * inset;
146 /// associated references cache
147 Buffer::References references;
148 /// whether this label is active (i.e., not deleted)
152 typedef vector<LabelInfo> LabelCache;
154 typedef map<docstring, Buffer::References> RefCache;
159 // A storehouse for the cloned buffers.
160 list<CloneList *> cloned_buffers;
166 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
170 delete preview_loader_;
178 /// search for macro in local (buffer) table or in children
179 MacroData const * getBufferMacro(docstring const & name,
180 DocIterator const & pos) const;
182 /// Update macro table starting with position of it \param it in some
184 void updateMacros(DocIterator & it, DocIterator & scope);
186 void setLabel(ParIterator & it, UpdateType utype) const;
188 /** If we have branches that use the file suffix
189 feature, return the file name with suffix appended.
191 FileName exportFileName() const;
198 mutable TexRow texrow;
200 /// need to regenerate .tex?
204 mutable bool lyx_clean;
206 /// is autosave needed?
207 mutable bool bak_clean;
209 /// is this an unnamed file (New...)?
212 /// is this an internal bufffer?
213 bool internal_buffer;
218 /// name of the file the buffer is associated with.
221 /** Set to true only when the file is fully loaded.
222 * Used to prevent the premature generation of previews
223 * and by the citation inset.
225 bool file_fully_loaded;
227 /// original format of loaded file
230 /// if the file was originally loaded from an older format, do
231 /// we need to back it up still?
232 bool need_format_backup;
234 /// Ignore the parent (e.g. when exporting a child standalone)?
238 mutable TocBackend toc_backend;
243 ScopeMacro(DocIterator const & s, MacroData const & m)
244 : scope(s), macro(m) {}
248 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
249 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
250 /// map from the macro name to the position map,
251 /// which maps the macro definition position to the scope and the MacroData.
252 NamePositionScopeMacroMap macros;
253 /// This seem to change the way Buffer::getMacro() works
254 mutable bool macro_lock;
256 /// positions of child buffers in the buffer
257 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
259 ScopeBuffer() : buffer(0) {}
260 ScopeBuffer(DocIterator const & s, Buffer const * b)
261 : scope(s), buffer(b) {}
263 Buffer const * buffer;
265 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
266 /// position of children buffers in this buffer
267 BufferPositionMap children_positions;
268 /// map from children inclusion positions to their scope and their buffer
269 PositionScopeBufferMap position_to_children;
271 /// Contains the old buffer filePath() while saving-as, or the
272 /// directory where the document was last saved while loading.
275 /** Keeps track of the path of local layout files.
276 * If possible, it is always relative to the buffer path.
277 * Empty for layouts in system or user directory.
279 string layout_position;
281 /// Container for all sort of Buffer dependant errors.
282 map<string, ErrorList> errorLists;
284 /// checksum used to test if the file has been externally modified. Used to
285 /// double check whether the file had been externally modified when saving.
286 unsigned long checksum_;
289 frontend::WorkAreaManager * wa_;
291 frontend::GuiBufferDelegate * gui_;
296 /// A cache for the bibfiles (including bibfiles of loaded child
297 /// documents), needed for appropriate update of natbib labels.
298 mutable docstring_list bibfiles_cache_;
300 // FIXME The caching mechanism could be improved. At present, we have a
301 // cache for each Buffer, that caches all the bibliography info for that
302 // Buffer. A more efficient solution would be to have a global cache per
303 // file, and then to construct the Buffer's bibinfo from that.
304 /// A cache for bibliography info
305 mutable BiblioInfo bibinfo_;
306 /// whether the bibinfo cache is valid
307 mutable bool bibinfo_cache_valid_;
308 /// Cache of timestamps of .bib files
309 map<FileName, time_t> bibfile_status_;
310 /// Indicates whether the bibinfo has changed since the last time
311 /// we ran updateBuffer(), i.e., whether citation labels may need
313 mutable bool cite_labels_valid_;
314 /// Do we have a bibliography environment?
315 mutable bool have_bibitems_;
317 /// These two hold the file name and format, written to by
318 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
319 FileName preview_file_;
320 string preview_format_;
321 /// If there was an error when previewing, on the next preview we do
322 /// a fresh compile (e.g. in case the user installed a package that
326 /// Cache the references associated to a label and their positions
328 mutable RefCache ref_cache_;
329 /// Cache the label insets and their activity status.
330 mutable LabelCache label_cache_;
332 /// our Text that should be wrapped in an InsetText
336 PreviewLoader * preview_loader_;
338 /// This is here to force the test to be done whenever parent_buffer
340 Buffer const * parent() const
342 // ignore_parent temporarily "orphans" a buffer
343 // (e.g. if a child is compiled standalone)
346 // if parent_buffer is not loaded, then it has been unloaded,
347 // which means that parent_buffer is an invalid pointer. So we
348 // set it to null in that case.
349 // however, the BufferList doesn't know about cloned buffers, so
350 // they will always be regarded as unloaded. in that case, we hope
352 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
354 return parent_buffer;
358 void setParent(Buffer const * pb)
360 if (parent_buffer == pb)
363 if (!cloned_buffer_ && parent_buffer && pb)
364 LYXERR0("Warning: a buffer should not have two parents!");
366 if (!cloned_buffer_ && parent_buffer)
367 parent_buffer->invalidateBibinfoCache();
370 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
371 /// This one is useful for preview detached in a thread.
372 Buffer const * cloned_buffer_;
374 CloneList * clone_list_;
375 /// are we in the process of exporting this buffer?
376 mutable bool doing_export;
378 /// compute statistics
379 /// \p from initial position
380 /// \p to points to the end position
381 void updateStatistics(DocIterator & from, DocIterator & to,
382 bool skipNoOutput = true);
383 /// statistics accessor functions
384 int wordCount() const
388 int charCount(bool with_blanks) const
391 + (with_blanks ? blank_count_ : 0);
394 // does the buffer contain tracked changes? (if so, we automatically
395 // display the review toolbar, for instance)
396 mutable bool tracked_changes_present_;
398 // Make sure the file monitor monitors the good file.
399 void refreshFileMonitor();
401 /// Notify or clear of external modification
402 void fileExternallyModified(bool exists);
404 /// has been externally modified? Can be reset by the user.
405 mutable bool externally_modified_;
407 ///Binding LaTeX lines with buffer positions.
408 //Common routine for LaTeX and Reference errors listing.
409 void traverseErrors(TeXErrors::Errors::const_iterator err,
410 TeXErrors::Errors::const_iterator end,
411 ErrorList & errorList) const;
414 /// So we can force access via the accessors.
415 mutable Buffer const * parent_buffer;
421 FileMonitorPtr file_monitor_;
425 /// Creates the per buffer temporary directory
426 static FileName createBufferTmpDir()
428 // FIXME This would be the ideal application for a TempDir class (like
429 // TempFile but for directories)
434 Mutex::Locker locker(&mutex);
435 counter = convert<string>(count++);
437 // We are in our own directory. Why bother to mangle name?
438 // In fact I wrote this code to circumvent a problematic behaviour
439 // (bug?) of EMX mkstemp().
440 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
443 if (!tmpfl.createDirectory(0777)) {
444 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
445 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
446 from_utf8(tmpfl.absFileName())));
452 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
453 Buffer const * cloned_buffer)
454 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
455 internal_buffer(false), read_only(readonly_), filename(file),
456 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
457 ignore_parent(false), toc_backend(owner), macro_lock(false),
458 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
459 cite_labels_valid_(false), have_bibitems_(false), preview_error_(false),
460 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
461 clone_list_(0), doing_export(false),
462 tracked_changes_present_(0), externally_modified_(false), parent_buffer(0),
463 word_count_(0), char_count_(0), blank_count_(0)
465 refreshFileMonitor();
466 if (!cloned_buffer_) {
467 temppath = createBufferTmpDir();
468 lyxvc.setBuffer(owner_);
469 Language const * inplang = languages.getFromCode(theApp()->inputLanguageCode());
471 params.language = inplang;
473 wa_ = new frontend::WorkAreaManager;
476 temppath = cloned_buffer_->d->temppath;
477 file_fully_loaded = true;
478 params = cloned_buffer_->d->params;
479 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
480 bibinfo_ = cloned_buffer_->d->bibinfo_;
481 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
482 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
483 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
484 have_bibitems_ = cloned_buffer_->d->have_bibitems_;
485 unnamed = cloned_buffer_->d->unnamed;
486 internal_buffer = cloned_buffer_->d->internal_buffer;
487 layout_position = cloned_buffer_->d->layout_position;
488 preview_file_ = cloned_buffer_->d->preview_file_;
489 preview_format_ = cloned_buffer_->d->preview_format_;
490 preview_error_ = cloned_buffer_->d->preview_error_;
491 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
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 list<CloneList *>::iterator it =
547 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
548 if (it == cloned_buffers.end()) {
549 // We will leak in this case, but it is safe to continue.
552 cloned_buffers.erase(it);
553 delete d->clone_list_;
555 // FIXME Do we really need to do this right before we delete d?
556 // clear references to children in macro tables
557 d->children_positions.clear();
558 d->position_to_children.clear();
560 // loop over children
561 for (auto const & p : d->children_positions) {
562 Buffer * child = const_cast<Buffer *>(p.first);
563 if (theBufferList().isLoaded(child)) {
564 if (theBufferList().isOthersChild(this, child))
567 theBufferList().release(child);
572 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
574 msg += emergencyWrite();
576 msg += " " + _("Save failed! Document is lost.");
578 Alert::warning(_("Attempting to close changed document!"), msg);
581 // FIXME Do we really need to do this right before we delete d?
582 // clear references to children in macro tables
583 d->children_positions.clear();
584 d->position_to_children.clear();
586 if (!d->temppath.destroyDirectory()) {
587 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
588 from_utf8(d->temppath.absFileName())));
597 Buffer * Buffer::cloneWithChildren() const
600 cloned_buffers.push_back(new CloneList);
601 CloneList * clones = cloned_buffers.back();
603 cloneWithChildren(bufmap, clones);
605 // make sure we got cloned
606 BufferMap::const_iterator bit = bufmap.find(this);
607 LASSERT(bit != bufmap.end(), return 0);
608 Buffer * cloned_buffer = bit->second;
610 return cloned_buffer;
614 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
616 // have we already been cloned?
617 if (bufmap.find(this) != bufmap.end())
620 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
622 // The clone needs its own DocumentClass, since running updateBuffer() will
623 // modify it, and we would otherwise be sharing it with the original Buffer.
624 buffer_clone->params().makeDocumentClass(true);
626 cap::switchBetweenClasses(
627 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
628 static_cast<InsetText &>(buffer_clone->inset()), el);
630 bufmap[this] = buffer_clone;
631 clones->insert(buffer_clone);
632 buffer_clone->d->clone_list_ = clones;
633 buffer_clone->d->macro_lock = true;
634 buffer_clone->d->children_positions.clear();
636 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
637 // math macro caches need to be rethought and simplified.
638 // I am not sure wether we should handle Buffer cloning here or in BufferList.
639 // Right now BufferList knows nothing about buffer clones.
640 for (auto const & p : d->position_to_children) {
641 DocIterator dit = p.first.clone(buffer_clone);
642 dit.setBuffer(buffer_clone);
643 Buffer * child = const_cast<Buffer *>(p.second.buffer);
645 child->cloneWithChildren(bufmap, clones);
646 BufferMap::iterator const bit = bufmap.find(child);
647 LASSERT(bit != bufmap.end(), continue);
648 Buffer * child_clone = bit->second;
650 Inset * inset = dit.nextInset();
651 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
652 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
653 inset_inc->setChildBuffer(child_clone);
654 child_clone->d->setParent(buffer_clone);
655 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
656 buffer_clone->setChild(dit, child_clone);
658 buffer_clone->d->macro_lock = false;
663 Buffer * Buffer::cloneBufferOnly() const {
664 cloned_buffers.push_back(new CloneList);
665 CloneList * 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 dvipost = LaTeXFeatures::isAvailable("dvipost");
1035 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1036 LaTeXFeatures::isAvailable("xcolor");
1038 if (!dvipost && !xcolorulem) {
1039 Alert::warning(_("Changes not shown in LaTeX output"),
1040 _("Changes will not be highlighted in LaTeX output, "
1041 "because neither dvipost nor xcolor/ulem are installed.\n"
1042 "Please install these packages or redefine "
1043 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1044 } else if (!xcolorulem) {
1045 Alert::warning(_("Changes not shown in LaTeX output"),
1046 _("Changes will not be highlighted in LaTeX output "
1047 "when using pdflatex, because xcolor and ulem are not installed.\n"
1048 "Please install both packages or redefine "
1049 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1053 if (!parent() && !params().master.empty()) {
1054 FileName const master_file = makeAbsPath(params().master,
1055 onlyPath(absFileName()));
1056 if (isLyXFileName(master_file.absFileName())) {
1058 checkAndLoadLyXFile(master_file, true);
1060 // necessary e.g. after a reload
1061 // to re-register the child (bug 5873)
1062 // FIXME: clean up updateMacros (here, only
1063 // child registering is needed).
1064 master->updateMacros();
1065 // set master as master buffer, but only
1066 // if we are a real child
1067 if (master->isChild(this))
1069 // if the master is not fully loaded
1070 // it is probably just loading this
1071 // child. No warning needed then.
1072 else if (master->isFullyLoaded())
1073 LYXERR0("The master '"
1075 << "' assigned to this document ("
1077 << ") does not include "
1078 "this document. Ignoring the master assignment.");
1079 // If the master has just been created, un-hide it (#11162)
1080 if (!master->fileName().exists())
1081 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1082 master->absFileName()));
1087 // assure we have a default index
1088 params().indiceslist().addDefault(B_("Index"));
1091 if (FileName::isAbsolute(params().origin))
1092 d->old_position = params().origin;
1094 d->old_position = filePath();
1095 bool const res = text().read(lex, errorList, d->inset);
1096 d->old_position.clear();
1098 // inform parent buffer about local macros
1100 Buffer const * pbuf = parent();
1101 for (auto const & m : usermacros)
1102 pbuf->usermacros.insert(m);
1106 updateMacroInstances(InternalUpdate);
1111 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1113 Format const * fmt = theFormats().getFormat(format);
1116 // It is important to use the correct extension here, since some
1117 // converters create a wrong output file otherwise (e.g. html2latex)
1118 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1119 ofdocstream os(name.toFilesystemEncoding().c_str());
1120 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1121 bool const success = !(os << contents).fail();
1124 bool converted = false;
1126 params().compressed = false;
1128 // remove dummy empty par
1129 paragraphs().clear();
1131 converted = importFile(format, name, errorList);
1134 removeTempFile(name);
1139 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1141 if (!theConverters().isReachable(format, "lyx"))
1144 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1145 Converters::RetVal const retval =
1146 theConverters().convert(0, name, lyx, name, format, "lyx", errorList);
1147 if (retval == Converters::SUCCESS) {
1148 bool const success = readFile(lyx) == ReadSuccess;
1149 removeTempFile(lyx);
1157 bool Buffer::readString(string const & s)
1159 params().compressed = false;
1162 istringstream is(s);
1164 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1165 FileName const fn = tempfile.name();
1168 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1170 if (success && file_format != LYX_FORMAT) {
1171 // We need to call lyx2lyx, so write the input to a file
1172 ofstream os(fn.toFilesystemEncoding().c_str());
1175 // lyxvc in readFile
1176 if (readFile(fn) != ReadSuccess)
1180 if (readDocument(lex))
1186 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1190 if (!lex.setFile(fname)) {
1191 Alert::error(_("File Not Found"),
1192 bformat(_("Unable to open file `%1$s'."),
1193 from_utf8(fn.absFileName())));
1194 return ReadFileNotFound;
1198 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1199 if (ret_plf != ReadSuccess)
1202 if (file_format != LYX_FORMAT) {
1204 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1205 if (ret_clf != ReadSuccess)
1207 ret_clf = readFile(tmpFile);
1208 if (ret_clf == ReadSuccess) {
1209 d->file_format = file_format;
1210 d->need_format_backup = true;
1215 // FIXME: InsetInfo needs to know whether the file is under VCS
1216 // during the parse process, so this has to be done before.
1217 lyxvc().file_found_hook(d->filename);
1219 if (readDocument(lex)) {
1220 Alert::error(_("Document format failure"),
1221 bformat(_("%1$s ended unexpectedly, which means"
1222 " that it is probably corrupted."),
1223 from_utf8(fn.absFileName())));
1224 return ReadDocumentFailure;
1227 d->file_fully_loaded = true;
1228 d->read_only = !d->filename.isWritable();
1229 params().compressed = theFormats().isZippedFile(d->filename);
1235 bool Buffer::isFullyLoaded() const
1237 return d->file_fully_loaded;
1241 void Buffer::setFullyLoaded(bool value)
1243 d->file_fully_loaded = value;
1247 bool Buffer::lastPreviewError() const
1249 return d->preview_error_;
1253 PreviewLoader * Buffer::loader() const
1255 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1257 if (!d->preview_loader_)
1258 d->preview_loader_ = new PreviewLoader(*this);
1259 return d->preview_loader_;
1263 void Buffer::removePreviews() const
1265 delete d->preview_loader_;
1266 d->preview_loader_ = 0;
1270 void Buffer::updatePreviews() const
1272 PreviewLoader * ploader = loader();
1276 InsetIterator it = inset_iterator_begin(*d->inset);
1277 InsetIterator const end = inset_iterator_end(*d->inset);
1278 for (; it != end; ++it)
1279 it->addPreview(it, *ploader);
1281 ploader->startLoading();
1285 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1286 FileName const & fn, int & file_format) const
1288 if(!lex.checkFor("\\lyxformat")) {
1289 Alert::error(_("Document format failure"),
1290 bformat(_("%1$s is not a readable LyX document."),
1291 from_utf8(fn.absFileName())));
1292 return ReadNoLyXFormat;
1298 // LyX formats 217 and earlier were written as 2.17. This corresponds
1299 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1300 // these cases. See also: www.lyx.org/trac/changeset/1313.
1301 size_t dot = tmp_format.find_first_of(".,");
1302 if (dot != string::npos)
1303 tmp_format.erase(dot, 1);
1305 file_format = convert<int>(tmp_format);
1310 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1311 FileName & tmpfile, int from_format)
1313 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1314 tempfile.setAutoRemove(false);
1315 tmpfile = tempfile.name();
1316 if(tmpfile.empty()) {
1317 Alert::error(_("Conversion failed"),
1318 bformat(_("%1$s is from a different"
1319 " version of LyX, but a temporary"
1320 " file for converting it could"
1321 " not be created."),
1322 from_utf8(fn.absFileName())));
1323 return LyX2LyXNoTempFile;
1326 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1327 if (lyx2lyx.empty()) {
1328 Alert::error(_("Conversion script not found"),
1329 bformat(_("%1$s is from a different"
1330 " version of LyX, but the"
1331 " conversion script lyx2lyx"
1332 " could not be found."),
1333 from_utf8(fn.absFileName())));
1334 return LyX2LyXNotFound;
1338 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1339 ostringstream command;
1340 command << os::python()
1341 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1342 << " -t " << convert<string>(LYX_FORMAT)
1343 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1344 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1345 string const command_str = command.str();
1347 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1349 cmd_ret const ret = runCommand(command_str);
1350 if (ret.first != 0) {
1351 if (from_format < LYX_FORMAT) {
1352 Alert::error(_("Conversion script failed"),
1353 bformat(_("%1$s is from an older version"
1354 " of LyX and the lyx2lyx script"
1355 " failed to convert it."),
1356 from_utf8(fn.absFileName())));
1357 return LyX2LyXOlderFormat;
1359 Alert::error(_("Conversion script failed"),
1360 bformat(_("%1$s is from a newer version"
1361 " of LyX and the lyx2lyx script"
1362 " failed to convert it."),
1363 from_utf8(fn.absFileName())));
1364 return LyX2LyXNewerFormat;
1371 FileName Buffer::getBackupName() const {
1372 map<int, string> const file_formats = {
1389 FileName const & fn = fileName();
1390 string const fname = fn.onlyFileNameWithoutExt();
1391 string const fext = fn.extension() + "~";
1392 string const fpath = lyxrc.backupdir_path.empty() ?
1393 fn.onlyPath().absFileName() :
1394 lyxrc.backupdir_path;
1395 string backup_suffix;
1396 // If file format is from a stable series use version instead of file format
1397 auto const it = file_formats.find(d->file_format);
1398 if (it != file_formats.end())
1399 backup_suffix = "-lyx" + it->second;
1401 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1402 string const backname = fname + backup_suffix;
1403 FileName backup(addName(fpath, addExtension(backname, fext)));
1405 // limit recursion, just in case
1407 unsigned long orig_checksum = 0;
1408 while (backup.exists() && v < 100) {
1409 if (orig_checksum == 0)
1410 orig_checksum = fn.checksum();
1411 unsigned long new_checksum = backup.checksum();
1412 if (orig_checksum == new_checksum) {
1413 LYXERR(Debug::FILES, "Not backing up " << fn <<
1414 "since " << backup << "has the same checksum.");
1415 // a bit of a hack, but we have to check this anyway
1416 // below, and setting this is simpler than introducing
1417 // a special boolean for this purpose.
1421 string const newbackname = backname + "-" + convert<string>(v);
1422 backup.set(addName(fpath, addExtension(newbackname, fext)));
1425 return v < 100 ? backup : FileName();
1429 // Should probably be moved to somewhere else: BufferView? GuiView?
1430 bool Buffer::save() const
1432 docstring const file = makeDisplayPath(absFileName(), 20);
1433 d->filename.refresh();
1435 // check the read-only status before moving the file as a backup
1436 if (d->filename.exists()) {
1437 bool const read_only = !d->filename.isWritable();
1439 Alert::warning(_("File is read-only"),
1440 bformat(_("The file %1$s cannot be written because it "
1441 "is marked as read-only."), file));
1446 // ask if the disk file has been externally modified (use checksum method)
1447 if (fileName().exists() && isChecksumModified()) {
1449 bformat(_("Document %1$s has been externally modified. "
1450 "Are you sure you want to overwrite this file?"), file);
1451 int const ret = Alert::prompt(_("Overwrite modified file?"),
1452 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1457 // We don't need autosaves in the immediate future. (Asger)
1458 resetAutosaveTimers();
1460 // if the file does not yet exist, none of the backup activity
1461 // that follows is necessary
1462 if (!fileName().exists()) {
1463 if (!writeFile(fileName()))
1469 // we first write the file to a new name, then move it to its
1470 // proper location once that has been done successfully. that
1471 // way we preserve the original file if something goes wrong.
1472 string const justname = fileName().onlyFileNameWithoutExt();
1473 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1474 justname + "-XXXXXX.lyx");
1475 bool const symlink = fileName().isSymLink();
1477 tempfile->setAutoRemove(false);
1479 FileName savefile(tempfile->name());
1480 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1481 if (!savefile.clonePermissions(fileName()))
1482 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1484 if (!writeFile(savefile))
1487 // we will set this to false if we fail
1488 bool made_backup = true;
1490 FileName backupName;
1491 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1493 if (d->need_format_backup)
1494 backupName = getBackupName();
1496 // If we for some reason failed to find a backup name in case of
1497 // a format change, this will still set one. It's the best we can
1499 if (backupName.empty()) {
1500 backupName.set(fileName().absFileName() + "~");
1501 if (!lyxrc.backupdir_path.empty()) {
1502 string const mangledName =
1503 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1504 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1508 LYXERR(Debug::FILES, "Backing up original file to " <<
1509 backupName.absFileName());
1510 // Except file is symlink do not copy because of #6587.
1511 // Hard links have bad luck.
1512 made_backup = symlink ?
1513 fileName().copyTo(backupName):
1514 fileName().moveTo(backupName);
1517 Alert::error(_("Backup failure"),
1518 bformat(_("Cannot create backup file %1$s.\n"
1519 "Please check whether the directory exists and is writable."),
1520 from_utf8(backupName.absFileName())));
1521 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1522 } else if (d->need_format_backup) {
1523 // the original file has been backed up successfully, so we
1524 // will not need to do that again
1525 d->need_format_backup = false;
1529 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1530 // Only do this if tempfile is not in autoremove mode
1533 // If we have no symlink, we can simply rename the temp file.
1534 // Otherwise, we need to copy it so the symlink stays intact.
1535 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1536 savefile.moveTo(fileName()))
1538 // saveCheckSum() was already called by writeFile(), but the
1539 // time stamp is invalidated by copying/moving
1542 if (d->file_format != LYX_FORMAT)
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()
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_CJK = features.mustProvide("CJK");
1857 LYXERR(Debug::LATEX, " Buffer validation done.");
1859 bool const output_preamble =
1860 output == FullSource || output == OnlyPreamble;
1861 bool const output_body =
1862 output == FullSource || output == OnlyBody;
1864 // The starting paragraph of the coming rows is the
1865 // first paragraph of the document. (Asger)
1866 if (output_preamble && runparams.nice) {
1867 os << "%% LyX " << lyx_version << " created this file. "
1868 "For more info, see https://www.lyx.org/.\n"
1869 "%% Do not edit unless you really know what "
1872 LYXERR(Debug::INFO, "lyx document header finished");
1874 // There are a few differences between nice LaTeX and usual files:
1875 // usual files have \batchmode and special input@path to allow
1876 // inclusion of figures specified by an explicitly relative path
1877 // (i.e., a path starting with './' or '../') with either \input or
1878 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1879 // input@path is set when the actual parameter original_path is set.
1880 // This is done for usual tex-file, but not for nice-latex-file.
1881 // (Matthias 250696)
1882 // Note that input@path is only needed for something the user does
1883 // in the preamble, included .tex files or ERT, files included by
1884 // LyX work without it.
1885 if (output_preamble) {
1886 if (!runparams.nice) {
1887 // code for usual, NOT nice-latex-file
1888 os << "\\batchmode\n"; // changed from \nonstopmode
1890 if (!original_path.empty()) {
1892 // We don't know the encoding of inputpath
1893 docstring const inputpath = from_utf8(original_path);
1894 docstring uncodable_glyphs;
1895 Encoding const * const enc = runparams.encoding;
1897 for (size_t n = 0; n < inputpath.size(); ++n) {
1898 if (!enc->encodable(inputpath[n])) {
1899 docstring const glyph(1, inputpath[n]);
1900 LYXERR0("Uncodable character '"
1902 << "' in input path!");
1903 uncodable_glyphs += glyph;
1908 // warn user if we found uncodable glyphs.
1909 if (!uncodable_glyphs.empty()) {
1910 frontend::Alert::warning(
1911 _("Uncodable character in file path"),
1913 _("The path of your document\n"
1915 "contains glyphs that are unknown "
1916 "in the current document encoding "
1917 "(namely %2$s). This may result in "
1918 "incomplete output, unless "
1919 "TEXINPUTS contains the document "
1920 "directory and you don't use "
1921 "explicitly relative paths (i.e., "
1922 "paths starting with './' or "
1923 "'../') in the preamble or in ERT."
1924 "\n\nIn case of problems, choose "
1925 "an appropriate document encoding\n"
1926 "(such as utf8) or change the "
1928 inputpath, uncodable_glyphs));
1930 string docdir = os::latex_path(original_path);
1931 if (contains(docdir, '#')) {
1932 docdir = subst(docdir, "#", "\\#");
1933 os << "\\catcode`\\#=11"
1934 "\\def\\#{#}\\catcode`\\#=6\n";
1936 if (contains(docdir, '%')) {
1937 docdir = subst(docdir, "%", "\\%");
1938 os << "\\catcode`\\%=11"
1939 "\\def\\%{%}\\catcode`\\%=14\n";
1941 bool const detokenize = !isAscii(from_utf8(docdir))
1942 || contains(docdir, '~');
1943 bool const quote = contains(docdir, ' ');
1944 os << "\\makeatletter\n"
1945 << "\\def\\input@path{{";
1947 os << "\\detokenize{";
1956 << "\\makeatother\n";
1960 // get parent macros (if this buffer has a parent) which will be
1961 // written at the document begin further down.
1962 MacroSet parentMacros;
1963 listParentMacros(parentMacros, features);
1965 // Write the preamble
1966 runparams.use_babel = params().writeLaTeX(os, features,
1967 d->filename.onlyPath());
1969 // Biblatex bibliographies are loaded here
1970 if (params().useBiblatex()) {
1971 vector<pair<docstring, string>> const bibfiles =
1972 prepareBibFilePaths(runparams, getBibfiles(), true);
1973 for (pair<docstring, string> const & file: bibfiles) {
1974 os << "\\addbibresource";
1975 if (!file.second.empty())
1976 os << "[bibencoding=" << file.second << "]";
1977 os << "{" << file.first << "}\n";
1981 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1982 && !features.hasOnlyPolyglossiaLanguages()) {
1985 vector<string> bll = features.getBabelExclusiveLanguages();
1986 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1989 for (string const & sit : bll) {
1994 blangs = bll.size() > 1 ?
1995 bformat(_("The languages %1$s are only supported by Babel."), langs)
1996 : bformat(_("The language %1$s is only supported by Babel."), langs);
2000 for (string const & pit : pll) {
2005 plangs = pll.size() > 1 ?
2006 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
2007 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
2008 if (!blangs.empty())
2012 frontend::Alert::warning(
2013 _("Incompatible Languages!"),
2015 _("You cannot use the following languages "
2016 "together in one LaTeX document because "
2017 "they require conflicting language packages:\n"
2022 // Japanese might be required only in some children of a document,
2023 // but once required, we must keep use_japanese true.
2024 runparams.use_japanese |= features.isRequired("japanese");
2027 // Restore the parenthood if needed
2028 if (!runparams.is_child)
2029 d->ignore_parent = false;
2030 return ExportSuccess;
2034 // mark the beginning of the body to separate it from InPreamble insets
2035 os.texrow().start(TexRow::beginDocument());
2036 os << "\\begin{document}\n";
2038 // mark the start of a new paragraph by simulating a newline,
2039 // so that os.afterParbreak() returns true at document start
2042 // output the parent macros
2043 for (auto const & mac : parentMacros) {
2044 int num_lines = mac->write(os.os(), true);
2045 os.texrow().newlines(num_lines);
2048 } // output_preamble
2050 LYXERR(Debug::INFO, "preamble finished, now the body.");
2054 latexParagraphs(*this, text(), os, runparams);
2056 catch (ConversionException const &) { return ExportKilled; }
2058 // Restore the parenthood if needed
2059 if (!runparams.is_child)
2060 d->ignore_parent = false;
2062 // add this just in case after all the paragraphs
2065 if (output_preamble) {
2066 os << "\\end{document}\n";
2067 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2069 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2071 runparams_in.encoding = runparams.encoding;
2073 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2074 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2075 return ExportSuccess;
2079 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2080 OutputParams const & runparams,
2081 OutputWhat output) const
2083 LYXERR(Debug::LATEX, "makeDocBookFile...");
2086 if (!openFileWrite(ofs, fname))
2089 // make sure we are ready to export
2090 // this needs to be done before we validate
2092 updateMacroInstances(OutputUpdate);
2094 ExportStatus const retval =
2095 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2096 if (retval == ExportKilled)
2097 return ExportKilled;
2101 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2102 return ExportSuccess;
2106 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os, string const & fname,
2107 OutputParams const & runparams,
2108 OutputWhat output) const
2110 LaTeXFeatures features(*this, params(), runparams);
2115 DocumentClass const & tclass = params().documentClass();
2116 string const & top_element = tclass.latexname();
2118 bool const output_preamble =
2119 output == FullSource || output == OnlyPreamble;
2120 bool const output_body =
2121 output == FullSource || output == OnlyBody;
2123 if (output_preamble) {
2124 if (runparams.flavor == OutputParams::XML)
2125 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2128 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2131 if (! tclass.class_header().empty())
2132 os << from_ascii(tclass.class_header());
2133 else if (runparams.flavor == OutputParams::XML)
2134 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2135 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2137 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2139 docstring preamble = params().preamble;
2140 if (runparams.flavor != OutputParams::XML ) {
2141 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2142 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2143 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2144 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2147 string const name = runparams.nice
2148 ? changeExtension(absFileName(), ".sgml") : fname;
2149 preamble += features.getIncludedFiles(name);
2150 preamble += features.getLyXSGMLEntities();
2152 if (!preamble.empty()) {
2153 os << "\n [ " << preamble << " ]";
2159 string top = top_element;
2161 if (runparams.flavor == OutputParams::XML)
2162 top += params().language->code();
2164 top += params().language->code().substr(0, 2);
2167 if (!params().options.empty()) {
2169 top += params().options;
2172 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2173 << " file was created by LyX " << lyx_version
2174 << "\n See https://www.lyx.org/ for more information -->\n";
2176 params().documentClass().counters().reset();
2178 sgml::openTag(os, top);
2181 docbookParagraphs(text(), *this, os, runparams);
2183 catch (ConversionException const &) { return ExportKilled; }
2184 sgml::closeTag(os, top_element);
2186 return ExportSuccess;
2190 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2191 OutputParams const & runparams) const
2193 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2196 if (!openFileWrite(ofs, fname))
2199 // make sure we are ready to export
2200 // this has to be done before we validate
2201 updateBuffer(UpdateMaster, OutputUpdate);
2202 updateMacroInstances(OutputUpdate);
2204 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2205 if (retval == ExportKilled)
2210 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2215 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2216 OutputParams const & runparams,
2217 OutputWhat output) const
2219 LaTeXFeatures features(*this, params(), runparams);
2221 d->bibinfo_.makeCitationLabels(*this);
2223 bool const output_preamble =
2224 output == FullSource || output == OnlyPreamble;
2225 bool const output_body =
2226 output == FullSource || output == OnlyBody || output == IncludedFile;
2228 if (output_preamble) {
2229 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2230 << "<!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"
2231 // FIXME Language should be set properly.
2232 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2234 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2235 // FIXME Presumably need to set this right
2236 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2238 docstring const & doctitle = features.htmlTitle();
2240 << (doctitle.empty() ?
2241 from_ascii("LyX Document") :
2242 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2245 docstring styles = features.getTClassHTMLPreamble();
2246 if (!styles.empty())
2247 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2249 styles = features.getPreambleSnippets().str;
2250 if (!styles.empty())
2251 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2253 // we will collect CSS information in a stream, and then output it
2254 // either here, as part of the header, or else in a separate file.
2255 odocstringstream css;
2256 styles = features.getCSSSnippets();
2257 if (!styles.empty())
2258 css << "/* LyX Provided Styles */\n" << styles << '\n';
2260 styles = features.getTClassHTMLStyles();
2261 if (!styles.empty())
2262 css << "/* Layout-provided Styles */\n" << styles << '\n';
2264 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2265 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2266 if (needfg || needbg) {
2267 css << "\nbody {\n";
2270 << from_ascii(X11hexname(params().fontcolor))
2273 css << " background-color: "
2274 << from_ascii(X11hexname(params().backgroundcolor))
2279 docstring const dstyles = css.str();
2280 if (!dstyles.empty()) {
2281 bool written = false;
2282 if (params().html_css_as_file) {
2283 // open a file for CSS info
2285 string const fcssname = addName(temppath(), "docstyle.css");
2286 FileName const fcssfile = FileName(fcssname);
2287 if (openFileWrite(ocss, fcssfile)) {
2291 // write link to header
2292 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2294 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2297 // we are here if the CSS is supposed to be written to the header
2298 // or if we failed to write it to an external file.
2300 os << "<style type='text/css'>\n"
2309 bool const output_body_tag = (output != IncludedFile);
2310 if (output_body_tag)
2311 os << "<body dir=\"auto\">\n";
2313 if (output != IncludedFile)
2314 // if we're an included file, the counters are in the master.
2315 params().documentClass().counters().reset();
2317 xhtmlParagraphs(text(), *this, xs, runparams);
2319 catch (ConversionException const &) { return ExportKilled; }
2320 if (output_body_tag)
2324 if (output_preamble)
2327 return ExportSuccess;
2331 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2332 // Other flags: -wall -v0 -x
2333 int Buffer::runChktex()
2337 // get LaTeX-Filename
2338 FileName const path(temppath());
2339 string const name = addName(path.absFileName(), latexName());
2340 string const org_path = filePath();
2342 PathChanger p(path); // path to LaTeX file
2343 message(_("Running chktex..."));
2345 // Generate the LaTeX file if neccessary
2346 OutputParams runparams(¶ms().encoding());
2347 runparams.flavor = OutputParams::LATEX;
2348 runparams.nice = false;
2349 runparams.linelen = lyxrc.plaintext_linelen;
2350 ExportStatus const retval =
2351 makeLaTeXFile(FileName(name), org_path, runparams);
2352 if (retval != ExportSuccess) {
2353 // error code on failure
2358 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2359 int const res = chktex.run(terr); // run chktex
2362 Alert::error(_("chktex failure"),
2363 _("Could not run chktex successfully."));
2365 ErrorList & errlist = d->errorLists["ChkTeX"];
2367 bufferErrors(terr, errlist);
2372 if (runparams.silent)
2373 d->errorLists["ChkTeX"].clear();
2381 void Buffer::validate(LaTeXFeatures & features) const
2383 // Validate the buffer params, but not for included
2384 // files, since they also use the parent buffer's
2386 if (!features.runparams().is_child)
2387 params().validate(features);
2389 for (Paragraph const & p : paragraphs())
2390 p.validate(features);
2392 if (lyxerr.debugging(Debug::LATEX)) {
2393 features.showStruct();
2398 void Buffer::getLabelList(vector<docstring> & list) const
2400 // If this is a child document, use the master's list instead.
2402 masterBuffer()->getLabelList(list);
2407 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2408 for (auto const & tocit : *toc) {
2409 if (tocit.depth() == 0)
2410 list.push_back(tocit.str());
2415 void Buffer::invalidateBibinfoCache() const
2417 d->bibinfo_cache_valid_ = false;
2418 d->cite_labels_valid_ = false;
2419 removeBiblioTempFiles();
2420 // also invalidate the cache for the parent buffer
2421 Buffer const * const pbuf = d->parent();
2423 pbuf->invalidateBibinfoCache();
2427 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2429 // FIXME This is probably unnecessary, given where we call this.
2430 // If this is a child document, use the master instead.
2431 Buffer const * const pbuf = masterBuffer();
2432 if (pbuf != this && scope != UpdateChildOnly)
2433 return pbuf->getBibfiles();
2435 // In 2.3.x, we have:
2436 //if (!d->bibfile_cache_valid_)
2437 // this->updateBibfilesCache(scope);
2438 // I think that is a leftover, but there have been so many back-
2439 // and-forths with this, due to Windows issues, that I am not sure.
2441 return d->bibfiles_cache_;
2445 BiblioInfo const & Buffer::masterBibInfo() const
2447 Buffer const * const tmp = masterBuffer();
2449 return tmp->masterBibInfo();
2454 BiblioInfo const & Buffer::bibInfo() const
2460 void Buffer::registerBibfiles(const docstring_list & bf) const
2462 // We register the bib files in the master buffer,
2463 // if there is one, but also in every single buffer,
2464 // in case a child is compiled alone.
2465 Buffer const * const tmp = masterBuffer();
2467 tmp->registerBibfiles(bf);
2469 for (auto const & p : bf) {
2470 docstring_list::const_iterator temp =
2471 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2472 if (temp == d->bibfiles_cache_.end())
2473 d->bibfiles_cache_.push_back(p);
2478 static map<docstring, FileName> bibfileCache;
2480 FileName Buffer::getBibfilePath(docstring const & bibid) const
2482 map<docstring, FileName>::const_iterator it =
2483 bibfileCache.find(bibid);
2484 if (it != bibfileCache.end()) {
2485 // i.e., return bibfileCache[bibid];
2489 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2490 string const texfile = changeExtension(to_utf8(bibid), "bib");
2491 // we need to check first if this file exists where it's said to be.
2492 // there's a weird bug that occurs otherwise: if the file is in the
2493 // Buffer's directory but has the same name as some file that would be
2494 // found by kpsewhich, then we find the latter, not the former.
2495 FileName const local_file = makeAbsPath(texfile, filePath());
2496 FileName file = local_file;
2497 if (!file.exists()) {
2498 // there's no need now to check whether the file can be found
2500 file = findtexfile(texfile, "bib", true);
2504 LYXERR(Debug::FILES, "Found at: " << file);
2506 bibfileCache[bibid] = file;
2507 return bibfileCache[bibid];
2511 void Buffer::checkIfBibInfoCacheIsValid() const
2513 // use the master's cache
2514 Buffer const * const tmp = masterBuffer();
2516 tmp->checkIfBibInfoCacheIsValid();
2520 // If we already know the cache is invalid, stop here.
2521 // This is important in the case when the bibliography
2522 // environment (rather than Bib[la]TeX) is used.
2523 // In that case, the timestamp check below gives no
2524 // sensible result. Rather than that, the cache will
2525 // be invalidated explicitly via invalidateBibInfoCache()
2526 // by the Bibitem inset.
2527 // Same applies for bib encoding changes, which trigger
2528 // invalidateBibInfoCache() by InsetBibtex.
2529 if (!d->bibinfo_cache_valid_)
2532 if (d->have_bibitems_) {
2533 // We have a bibliography environment.
2534 // Invalidate the bibinfo cache unconditionally.
2535 // Cite labels will get invalidated by the inset if needed.
2536 d->bibinfo_cache_valid_ = false;
2540 // OK. This is with Bib(la)tex. We'll assume the cache
2541 // is valid and change this if we find changes in the bibs.
2542 d->bibinfo_cache_valid_ = true;
2543 d->cite_labels_valid_ = true;
2545 // compare the cached timestamps with the actual ones.
2546 docstring_list const & bibfiles_cache = getBibfiles();
2547 for (auto const & bf : bibfiles_cache) {
2548 FileName const fn = getBibfilePath(bf);
2549 time_t lastw = fn.lastModified();
2550 time_t prevw = d->bibfile_status_[fn];
2551 if (lastw != prevw) {
2552 d->bibinfo_cache_valid_ = false;
2553 d->cite_labels_valid_ = false;
2554 d->bibfile_status_[fn] = lastw;
2560 void Buffer::clearBibFileCache() const
2562 bibfileCache.clear();
2566 void Buffer::reloadBibInfoCache(bool const force) const
2568 // we should not need to do this for internal buffers
2572 // use the master's cache
2573 Buffer const * const tmp = masterBuffer();
2575 tmp->reloadBibInfoCache(force);
2580 checkIfBibInfoCacheIsValid();
2581 if (d->bibinfo_cache_valid_)
2585 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2586 // re-read file locations when this info changes
2587 // FIXME Is this sufficient? Or should we also force that
2588 // in some other cases? If so, then it is easy enough to
2589 // add the following line in some other places.
2590 clearBibFileCache();
2591 d->bibinfo_.clear();
2592 FileNameList checkedFiles;
2593 d->have_bibitems_ = false;
2594 collectBibKeys(checkedFiles);
2595 d->bibinfo_cache_valid_ = true;
2599 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2601 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2602 it->collectBibKeys(it, checkedFiles);
2603 if (it->lyxCode() == BIBITEM_CODE) {
2605 parent()->d->have_bibitems_ = true;
2607 d->have_bibitems_ = true;
2613 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2615 // We add the biblio info to the master buffer,
2616 // if there is one, but also to every single buffer,
2617 // in case a child is compiled alone.
2618 BiblioInfo & bi = d->bibinfo_;
2619 bi.mergeBiblioInfo(bin);
2621 if (parent() != 0) {
2622 BiblioInfo & masterbi = parent()->d->bibinfo_;
2623 masterbi.mergeBiblioInfo(bin);
2628 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2630 // We add the bibtex info to the master buffer,
2631 // if there is one, but also to every single buffer,
2632 // in case a child is compiled alone.
2633 BiblioInfo & bi = d->bibinfo_;
2636 if (parent() != 0) {
2637 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2638 masterbi[key] = bin;
2643 void Buffer::makeCitationLabels() const
2645 Buffer const * const master = masterBuffer();
2646 return d->bibinfo_.makeCitationLabels(*master);
2650 void Buffer::invalidateCiteLabels() const
2652 masterBuffer()->d->cite_labels_valid_ = false;
2655 bool Buffer::citeLabelsValid() const
2657 return masterBuffer()->d->cite_labels_valid_;
2661 void Buffer::removeBiblioTempFiles() const
2663 // We remove files that contain LaTeX commands specific to the
2664 // particular bibliographic style being used, in order to avoid
2665 // LaTeX errors when we switch style.
2666 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2667 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2668 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2669 aux_file.removeFile();
2670 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2671 bbl_file.removeFile();
2672 // Also for the parent buffer
2673 Buffer const * const pbuf = parent();
2675 pbuf->removeBiblioTempFiles();
2679 bool Buffer::isDepClean(string const & name) const
2681 DepClean::const_iterator const it = d->dep_clean.find(name);
2682 if (it == d->dep_clean.end())
2688 void Buffer::markDepClean(string const & name)
2690 d->dep_clean[name] = true;
2694 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2697 // FIXME? if there is an Buffer LFUN that can be dispatched even
2698 // if internal, put a switch '(cmd.action)' here.
2704 switch (cmd.action()) {
2706 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2707 flag.setOnOff(hasReadonlyFlag());
2710 // FIXME: There is need for a command-line import.
2711 //case LFUN_BUFFER_IMPORT:
2713 case LFUN_BUFFER_AUTO_SAVE:
2716 case LFUN_BUFFER_EXPORT_CUSTOM:
2717 // FIXME: Nothing to check here?
2720 case LFUN_BUFFER_EXPORT: {
2721 docstring const arg = cmd.argument();
2722 if (arg == "custom") {
2726 string format = (arg.empty() || arg == "default") ?
2727 params().getDefaultOutputFormat() : to_utf8(arg);
2728 size_t pos = format.find(' ');
2729 if (pos != string::npos)
2730 format = format.substr(0, pos);
2731 enable = params().isExportable(format, false);
2733 flag.message(bformat(
2734 _("Don't know how to export to format: %1$s"), arg));
2738 case LFUN_BUILD_PROGRAM:
2739 enable = params().isExportable("program", false);
2742 case LFUN_BRANCH_ACTIVATE:
2743 case LFUN_BRANCH_DEACTIVATE:
2744 case LFUN_BRANCH_MASTER_ACTIVATE:
2745 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2746 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2747 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2748 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2749 : params().branchlist();
2750 docstring const branchName = cmd.argument();
2751 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2755 case LFUN_BRANCH_ADD:
2756 case LFUN_BRANCHES_RENAME:
2757 // if no Buffer is present, then of course we won't be called!
2760 case LFUN_BUFFER_LANGUAGE:
2761 enable = !isReadonly();
2764 case LFUN_BUFFER_VIEW_CACHE:
2765 (d->preview_file_).refresh();
2766 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2769 case LFUN_CHANGES_TRACK:
2770 flag.setEnabled(true);
2771 flag.setOnOff(params().track_changes);
2774 case LFUN_CHANGES_OUTPUT:
2775 flag.setEnabled(true);
2776 flag.setOnOff(params().output_changes);
2779 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2780 flag.setOnOff(params().compressed);
2783 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2784 flag.setOnOff(params().output_sync);
2787 case LFUN_BUFFER_ANONYMIZE:
2793 flag.setEnabled(enable);
2798 void Buffer::dispatch(string const & command, DispatchResult & result)
2800 return dispatch(lyxaction.lookupFunc(command), result);
2804 // NOTE We can end up here even if we have no GUI, because we are called
2805 // by LyX::exec to handled command-line requests. So we may need to check
2806 // whether we have a GUI or not. The boolean use_gui holds this information.
2807 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2810 // FIXME? if there is an Buffer LFUN that can be dispatched even
2811 // if internal, put a switch '(cmd.action())' here.
2812 dr.dispatched(false);
2815 string const argument = to_utf8(func.argument());
2816 // We'll set this back to false if need be.
2817 bool dispatched = true;
2818 // This handles undo groups automagically
2819 UndoGroupHelper ugh(this);
2821 switch (func.action()) {
2822 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2823 if (lyxvc().inUse()) {
2824 string log = lyxvc().toggleReadOnly();
2829 setReadonly(!hasReadonlyFlag());
2832 case LFUN_BUFFER_EXPORT: {
2833 string const format = (argument.empty() || argument == "default") ?
2834 params().getDefaultOutputFormat() : argument;
2835 ExportStatus const status = doExport(format, false);
2836 dr.setError(status != ExportSuccess);
2837 if (status != ExportSuccess)
2838 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2839 from_utf8(format)));
2843 case LFUN_BUILD_PROGRAM: {
2844 ExportStatus const status = doExport("program", true);
2845 dr.setError(status != ExportSuccess);
2846 if (status != ExportSuccess)
2847 dr.setMessage(_("Error generating literate programming code."));
2851 case LFUN_BUFFER_EXPORT_CUSTOM: {
2853 string command = split(argument, format_name, ' ');
2854 Format const * format = theFormats().getFormat(format_name);
2856 lyxerr << "Format \"" << format_name
2857 << "\" not recognized!"
2862 // The name of the file created by the conversion process
2865 // Output to filename
2866 if (format->name() == "lyx") {
2867 string const latexname = latexName(false);
2868 filename = changeExtension(latexname,
2869 format->extension());
2870 filename = addName(temppath(), filename);
2872 if (!writeFile(FileName(filename)))
2876 doExport(format_name, true, filename);
2879 // Substitute $$FName for filename
2880 if (!contains(command, "$$FName"))
2881 command = "( " + command + " ) < $$FName";
2882 command = subst(command, "$$FName", filename);
2884 // Execute the command in the background
2886 call.startscript(Systemcall::DontWait, command,
2887 filePath(), layoutPos());
2891 // FIXME: There is need for a command-line import.
2893 case LFUN_BUFFER_IMPORT:
2898 case LFUN_BUFFER_AUTO_SAVE:
2900 resetAutosaveTimers();
2903 case LFUN_BRANCH_ACTIVATE:
2904 case LFUN_BRANCH_DEACTIVATE:
2905 case LFUN_BRANCH_MASTER_ACTIVATE:
2906 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2907 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2908 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2909 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2912 docstring const branch_name = func.argument();
2913 // the case without a branch name is handled elsewhere
2914 if (branch_name.empty()) {
2918 Branch * branch = buf->params().branchlist().find(branch_name);
2920 LYXERR0("Branch " << branch_name << " does not exist.");
2922 docstring const msg =
2923 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2927 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2928 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2929 if (branch->isSelected() != activate) {
2930 buf->undo().recordUndoBufferParams(CursorData());
2931 branch->setSelected(activate);
2933 dr.screenUpdate(Update::Force);
2934 dr.forceBufferUpdate();
2939 case LFUN_BRANCH_ADD: {
2940 docstring branchnames = func.argument();
2941 if (branchnames.empty()) {
2945 BranchList & branch_list = params().branchlist();
2946 vector<docstring> const branches =
2947 getVectorFromString(branchnames, branch_list.separator());
2949 for (docstring const & branch_name : branches) {
2950 Branch * branch = branch_list.find(branch_name);
2952 LYXERR0("Branch " << branch_name << " already exists.");
2956 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2958 undo().recordUndoBufferParams(CursorData());
2959 branch_list.add(branch_name);
2960 branch = branch_list.find(branch_name);
2961 string const x11hexname = X11hexname(branch->color());
2962 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2963 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2965 dr.screenUpdate(Update::Force);
2973 case LFUN_BRANCHES_RENAME: {
2974 if (func.argument().empty())
2977 docstring const oldname = from_utf8(func.getArg(0));
2978 docstring const newname = from_utf8(func.getArg(1));
2979 InsetIterator it = inset_iterator_begin(inset());
2980 InsetIterator const end = inset_iterator_end(inset());
2981 bool success = false;
2982 for (; it != end; ++it) {
2983 if (it->lyxCode() == BRANCH_CODE) {
2984 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2985 if (ins.branch() == oldname) {
2986 undo().recordUndo(CursorData(it));
2987 ins.rename(newname);
2992 if (it->lyxCode() == INCLUDE_CODE) {
2993 // get buffer of external file
2994 InsetInclude const & ins =
2995 static_cast<InsetInclude const &>(*it);
2996 Buffer * child = ins.getChildBuffer();
2999 child->dispatch(func, dr);
3004 dr.screenUpdate(Update::Force);
3005 dr.forceBufferUpdate();
3010 case LFUN_BUFFER_VIEW_CACHE:
3011 if (!theFormats().view(*this, d->preview_file_,
3012 d->preview_format_))
3013 dr.setMessage(_("Error viewing the output file."));
3016 case LFUN_CHANGES_TRACK:
3017 if (params().save_transient_properties)
3018 undo().recordUndoBufferParams(CursorData());
3019 params().track_changes = !params().track_changes;
3020 if (!params().track_changes)
3021 dr.forceChangesUpdate();
3024 case LFUN_CHANGES_OUTPUT:
3025 if (params().save_transient_properties)
3026 undo().recordUndoBufferParams(CursorData());
3027 params().output_changes = !params().output_changes;
3028 if (params().output_changes) {
3029 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
3030 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
3031 LaTeXFeatures::isAvailable("xcolor");
3033 if (!dvipost && !xcolorulem) {
3034 Alert::warning(_("Changes not shown in LaTeX output"),
3035 _("Changes will not be highlighted in LaTeX output, "
3036 "because neither dvipost nor xcolor/ulem are installed.\n"
3037 "Please install these packages or redefine "
3038 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3039 } else if (!xcolorulem) {
3040 Alert::warning(_("Changes not shown in LaTeX output"),
3041 _("Changes will not be highlighted in LaTeX output "
3042 "when using pdflatex, because xcolor and ulem are not installed.\n"
3043 "Please install both packages or redefine "
3044 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3049 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3050 // turn compression on/off
3051 undo().recordUndoBufferParams(CursorData());
3052 params().compressed = !params().compressed;
3055 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3056 undo().recordUndoBufferParams(CursorData());
3057 params().output_sync = !params().output_sync;
3060 case LFUN_BUFFER_ANONYMIZE: {
3061 undo().recordUndoFullBuffer(CursorData());
3062 CursorData cur(doc_iterator_begin(this));
3063 for ( ; cur ; cur.forwardPar())
3064 cur.paragraph().anonymize();
3065 dr.forceBufferUpdate();
3066 dr.screenUpdate(Update::Force);
3074 dr.dispatched(dispatched);
3078 void Buffer::changeLanguage(Language const * from, Language const * to)
3080 LASSERT(from, return);
3081 LASSERT(to, return);
3083 for_each(par_iterator_begin(),
3085 bind(&Paragraph::changeLanguage, _1, params(), from, to));
3089 bool Buffer::isMultiLingual() const
3091 ParConstIterator end = par_iterator_end();
3092 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3093 if (it->isMultiLingual(params()))
3100 std::set<Language const *> Buffer::getLanguages() const
3102 std::set<Language const *> langs;
3103 getLanguages(langs);
3108 void Buffer::getLanguages(std::set<Language const *> & langs) const
3110 ParConstIterator end = par_iterator_end();
3111 // add the buffer language, even if it's not actively used
3112 langs.insert(language());
3113 // iterate over the paragraphs
3114 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3115 it->getLanguages(langs);
3117 ListOfBuffers clist = getDescendents();
3118 for (auto const & cit : clist)
3119 cit->getLanguages(langs);
3123 DocIterator Buffer::getParFromID(int const id) const
3125 Buffer * buf = const_cast<Buffer *>(this);
3127 // This means non-existent
3128 return doc_iterator_end(buf);
3130 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3131 if (it.paragraph().id() == id)
3134 return doc_iterator_end(buf);
3138 bool Buffer::hasParWithID(int const id) const
3140 return !getParFromID(id).atEnd();
3144 ParIterator Buffer::par_iterator_begin()
3146 return ParIterator(doc_iterator_begin(this));
3150 ParIterator Buffer::par_iterator_end()
3152 return ParIterator(doc_iterator_end(this));
3156 ParConstIterator Buffer::par_iterator_begin() const
3158 return ParConstIterator(doc_iterator_begin(this));
3162 ParConstIterator Buffer::par_iterator_end() const
3164 return ParConstIterator(doc_iterator_end(this));
3168 Language const * Buffer::language() const
3170 return params().language;
3174 docstring const Buffer::B_(string const & l10n) const
3176 return params().B_(l10n);
3180 bool Buffer::isClean() const
3182 return d->lyx_clean;
3186 bool Buffer::isChecksumModified() const
3188 LASSERT(d->filename.exists(), return false);
3189 return d->checksum_ != d->filename.checksum();
3193 void Buffer::saveCheckSum() const
3195 FileName const & file = d->filename;
3197 d->checksum_ = file.exists() ? file.checksum()
3198 : 0; // in the case of save to a new file.
3202 void Buffer::markClean() const
3204 if (!d->lyx_clean) {
3205 d->lyx_clean = true;
3208 // if the .lyx file has been saved, we don't need an
3210 d->bak_clean = true;
3211 d->undo_.markDirty();
3212 clearExternalModification();
3216 void Buffer::setUnnamed(bool flag)
3222 bool Buffer::isUnnamed() const
3229 /// Don't check unnamed, here: isInternal() is used in
3230 /// newBuffer(), where the unnamed flag has not been set by anyone
3231 /// yet. Also, for an internal buffer, there should be no need for
3232 /// retrieving fileName() nor for checking if it is unnamed or not.
3233 bool Buffer::isInternal() const
3235 return d->internal_buffer;
3239 void Buffer::setInternal(bool flag)
3241 d->internal_buffer = flag;
3245 void Buffer::markDirty()
3248 d->lyx_clean = false;
3251 d->bak_clean = false;
3253 for (auto & depit : d->dep_clean)
3254 depit.second = false;
3258 FileName Buffer::fileName() const
3264 string Buffer::absFileName() const
3266 return d->filename.absFileName();
3270 string Buffer::filePath() const
3272 string const abs = d->filename.onlyPath().absFileName();
3275 int last = abs.length() - 1;
3277 return abs[last] == '/' ? abs : abs + '/';
3281 DocFileName Buffer::getReferencedFileName(string const & fn) const
3284 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3285 result.set(fn, filePath());
3287 // filePath() ends with a path separator
3288 FileName const test(filePath() + fn);
3290 result.set(fn, filePath());
3292 result.set(fn, params().origin);
3299 string const Buffer::prepareFileNameForLaTeX(string const & name,
3300 string const & ext, bool nice) const
3302 string const fname = makeAbsPath(name, filePath()).absFileName();
3303 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3309 return to_utf8(makeRelPath(from_utf8(fname),
3310 from_utf8(masterBuffer()->filePath())));
3314 vector<pair<docstring, string>> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3315 docstring_list const & bibfilelist,
3316 bool const add_extension) const
3318 // If we are processing the LaTeX file in a temp directory then
3319 // copy the .bib databases to this temp directory, mangling their
3320 // names in the process. Store this mangled name in the list of
3322 // (We need to do all this because BibTeX *really*, *really*
3323 // can't handle "files with spaces" and Windows users tend to
3324 // use such filenames.)
3325 // Otherwise, store the (maybe absolute) path to the original,
3326 // unmangled database name.
3328 vector<pair<docstring, string>> res;
3330 // determine the export format
3331 string const tex_format = flavor2format(runparams.flavor);
3333 // check for spaces in paths
3334 bool found_space = false;
3336 for (auto const & bit : bibfilelist) {
3337 string utf8input = to_utf8(bit);
3339 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3340 FileName try_in_file =
3341 makeAbsPath(database + ".bib", filePath());
3342 bool not_from_texmf = try_in_file.isReadableFile();
3343 // If the file has not been found, try with the real file name
3344 // (it might come from a child in a sub-directory)
3345 if (!not_from_texmf) {
3346 try_in_file = getBibfilePath(bit);
3347 if (try_in_file.isReadableFile()) {
3348 // Check if the file is in texmf
3349 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3350 not_from_texmf = kpsefile.empty()
3351 || kpsefile.absFileName() != try_in_file.absFileName();
3353 // If this exists, make path relative to the master
3356 removeExtension(prepareFileNameForLaTeX(
3357 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3358 from_utf8(filePath()))),
3359 ".bib", runparams.nice));
3363 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3365 // mangledFileName() needs the extension
3366 DocFileName const in_file = DocFileName(try_in_file);
3367 database = removeExtension(in_file.mangledFileName());
3368 FileName const out_file = makeAbsPath(database + ".bib",
3369 masterBuffer()->temppath());
3370 bool const success = in_file.copyTo(out_file);
3372 LYXERR0("Failed to copy '" << in_file
3373 << "' to '" << out_file << "'");
3375 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3376 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3377 if (!isValidLaTeXFileName(database)) {
3378 frontend::Alert::warning(_("Invalid filename"),
3379 _("The following filename will cause troubles "
3380 "when running the exported file through LaTeX: ") +
3381 from_utf8(database));
3383 if (!isValidDVIFileName(database)) {
3384 frontend::Alert::warning(_("Problematic filename for DVI"),
3385 _("The following filename can cause troubles "
3386 "when running the exported file through LaTeX "
3387 "and opening the resulting DVI: ") +
3388 from_utf8(database), true);
3396 docstring const path = from_utf8(latex_path(database));
3398 if (contains(path, ' '))
3401 if (params().useBiblatex() && !params().bibFileEncoding(utf8input).empty())
3402 enc = params().bibFileEncoding(utf8input);
3404 bool recorded = false;
3405 for (pair<docstring, string> pe : res) {
3406 if (pe.first == path) {
3413 res.push_back(make_pair(path, enc));
3416 // Check if there are spaces in the path and warn BibTeX users, if so.
3417 // (biber can cope with such paths)
3418 if (!prefixIs(runparams.bibtex_command, "biber")) {
3419 // Post this warning only once.
3420 static bool warned_about_spaces = false;
3421 if (!warned_about_spaces &&
3422 runparams.nice && found_space) {
3423 warned_about_spaces = true;
3424 Alert::warning(_("Export Warning!"),
3425 _("There are spaces in the paths to your BibTeX databases.\n"
3426 "BibTeX will be unable to find them."));
3435 string Buffer::layoutPos() const
3437 return d->layout_position;
3441 void Buffer::setLayoutPos(string const & path)
3444 d->layout_position.clear();
3448 LATTEST(FileName::isAbsolute(path));
3450 d->layout_position =
3451 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3453 if (d->layout_position.empty())
3454 d->layout_position = ".";
3458 bool Buffer::hasReadonlyFlag() const
3460 return d->read_only;
3464 bool Buffer::isReadonly() const
3466 return hasReadonlyFlag() || notifiesExternalModification();
3470 void Buffer::setParent(Buffer const * buffer)
3472 // Avoids recursive include.
3473 d->setParent(buffer == this ? 0 : buffer);
3478 Buffer const * Buffer::parent() const
3484 ListOfBuffers Buffer::allRelatives() const
3486 ListOfBuffers lb = masterBuffer()->getDescendents();
3487 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3492 Buffer const * Buffer::masterBuffer() const
3494 // FIXME Should be make sure we are not in some kind
3495 // of recursive include? A -> B -> A will crash this.
3496 Buffer const * const pbuf = d->parent();
3500 return pbuf->masterBuffer();
3504 bool Buffer::isChild(Buffer * child) const
3506 return d->children_positions.find(child) != d->children_positions.end();
3510 DocIterator Buffer::firstChildPosition(Buffer const * child)
3512 Impl::BufferPositionMap::iterator it;
3513 it = d->children_positions.find(child);
3514 if (it == d->children_positions.end())
3515 return DocIterator(this);
3520 bool Buffer::hasChildren() const
3522 return !d->children_positions.empty();
3526 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3528 // loop over children
3529 for (auto const & p : d->children_positions) {
3530 Buffer * child = const_cast<Buffer *>(p.first);
3532 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3533 if (bit != clist.end())
3535 clist.push_back(child);
3537 // there might be grandchildren
3538 child->collectChildren(clist, true);
3543 ListOfBuffers Buffer::getChildren() const
3546 collectChildren(v, false);
3547 // Make sure we have not included ourselves.
3548 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3549 if (bit != v.end()) {
3550 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3557 ListOfBuffers Buffer::getDescendents() const
3560 collectChildren(v, true);
3561 // Make sure we have not included ourselves.
3562 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3563 if (bit != v.end()) {
3564 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3571 template<typename M>
3572 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3577 typename M::const_iterator it = m.lower_bound(x);
3578 if (it == m.begin())
3586 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3587 DocIterator const & pos) const
3589 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3591 // if paragraphs have no macro context set, pos will be empty
3595 // we haven't found anything yet
3596 DocIterator bestPos = owner_->par_iterator_begin();
3597 MacroData const * bestData = 0;
3599 // find macro definitions for name
3600 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3601 if (nameIt != macros.end()) {
3602 // find last definition in front of pos or at pos itself
3603 PositionScopeMacroMap::const_iterator it
3604 = greatest_below(nameIt->second, pos);
3605 if (it != nameIt->second.end()) {
3607 // scope ends behind pos?
3608 if (pos < it->second.scope) {
3609 // Looks good, remember this. If there
3610 // is no external macro behind this,
3611 // we found the right one already.
3612 bestPos = it->first;
3613 bestData = &it->second.macro;
3617 // try previous macro if there is one
3618 if (it == nameIt->second.begin())
3625 // find macros in included files
3626 PositionScopeBufferMap::const_iterator it
3627 = greatest_below(position_to_children, pos);
3628 if (it == position_to_children.end())
3629 // no children before
3633 // do we know something better (i.e. later) already?
3634 if (it->first < bestPos )
3637 // scope ends behind pos?
3638 if (pos < it->second.scope
3639 && (cloned_buffer_ ||
3640 theBufferList().isLoaded(it->second.buffer))) {
3641 // look for macro in external file
3643 MacroData const * data
3644 = it->second.buffer->getMacro(name, false);
3647 bestPos = it->first;
3653 // try previous file if there is one
3654 if (it == position_to_children.begin())
3659 // return the best macro we have found
3664 MacroData const * Buffer::getMacro(docstring const & name,
3665 DocIterator const & pos, bool global) const
3670 // query buffer macros
3671 MacroData const * data = d->getBufferMacro(name, pos);
3675 // If there is a master buffer, query that
3676 Buffer const * const pbuf = d->parent();
3678 d->macro_lock = true;
3679 MacroData const * macro = pbuf->getMacro(
3680 name, *this, false);
3681 d->macro_lock = false;
3687 data = MacroTable::globalMacros().get(name);
3696 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3698 // set scope end behind the last paragraph
3699 DocIterator scope = par_iterator_begin();
3700 scope.pit() = scope.lastpit() + 1;
3702 return getMacro(name, scope, global);
3706 MacroData const * Buffer::getMacro(docstring const & name,
3707 Buffer const & child, bool global) const
3709 // look where the child buffer is included first
3710 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3711 if (it == d->children_positions.end())
3714 // check for macros at the inclusion position
3715 return getMacro(name, it->second, global);
3719 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3721 pit_type const lastpit = it.lastpit();
3723 // look for macros in each paragraph
3724 while (it.pit() <= lastpit) {
3725 Paragraph & par = it.paragraph();
3727 // FIXME Can this be done with the new-style iterators?
3728 // iterate over the insets of the current paragraph
3729 for (auto const & insit : par.insetList()) {
3730 it.pos() = insit.pos;
3732 // is it a nested text inset?
3733 if (insit.inset->asInsetText()) {
3734 // Inset needs its own scope?
3735 InsetText const * itext = insit.inset->asInsetText();
3736 bool newScope = itext->isMacroScope();
3738 // scope which ends just behind the inset
3739 DocIterator insetScope = it;
3742 // collect macros in inset
3743 it.push_back(CursorSlice(*insit.inset));
3744 updateMacros(it, newScope ? insetScope : scope);
3749 if (insit.inset->asInsetTabular()) {
3750 CursorSlice slice(*insit.inset);
3751 size_t const numcells = slice.nargs();
3752 for (; slice.idx() < numcells; slice.forwardIdx()) {
3753 it.push_back(slice);
3754 updateMacros(it, scope);
3760 // is it an external file?
3761 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3762 // get buffer of external file
3763 InsetInclude const & incinset =
3764 static_cast<InsetInclude const &>(*insit.inset);
3766 Buffer * child = incinset.getChildBuffer();
3771 // register its position, but only when it is
3772 // included first in the buffer
3773 if (children_positions.find(child) ==
3774 children_positions.end())
3775 children_positions[child] = it;
3777 // register child with its scope
3778 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3782 InsetMath * im = insit.inset->asInsetMath();
3783 if (doing_export && im) {
3784 InsetMathHull * hull = im->asHullInset();
3786 hull->recordLocation(it);
3789 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3793 InsetMathMacroTemplate & macroTemplate =
3794 *insit.inset->asInsetMath()->asMacroTemplate();
3795 MacroContext mc(owner_, it);
3796 macroTemplate.updateToContext(mc);
3799 bool valid = macroTemplate.validMacro();
3800 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3801 // then the BufferView's cursor will be invalid in
3802 // some cases which leads to crashes.
3807 // FIXME (Abdel), I don't understand why we pass 'it' here
3808 // instead of 'macroTemplate' defined above... is this correct?
3809 macros[macroTemplate.name()][it] =
3810 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3820 void Buffer::updateMacros() const
3825 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3827 // start with empty table
3829 d->children_positions.clear();
3830 d->position_to_children.clear();
3832 // Iterate over buffer, starting with first paragraph
3833 // The scope must be bigger than any lookup DocIterator
3834 // later. For the global lookup, lastpit+1 is used, hence
3835 // we use lastpit+2 here.
3836 DocIterator it = par_iterator_begin();
3837 DocIterator outerScope = it;
3838 outerScope.pit() = outerScope.lastpit() + 2;
3839 d->updateMacros(it, outerScope);
3843 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3845 InsetIterator it = inset_iterator_begin(inset());
3846 InsetIterator const end = inset_iterator_end(inset());
3847 for (; it != end; ++it) {
3848 if (it->lyxCode() == BRANCH_CODE) {
3849 InsetBranch & br = static_cast<InsetBranch &>(*it);
3850 docstring const name = br.branch();
3851 if (!from_master && !params().branchlist().find(name))
3852 result.push_back(name);
3853 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3854 result.push_back(name);
3857 if (it->lyxCode() == INCLUDE_CODE) {
3858 // get buffer of external file
3859 InsetInclude const & ins =
3860 static_cast<InsetInclude const &>(*it);
3861 Buffer * child = ins.getChildBuffer();
3864 child->getUsedBranches(result, true);
3867 // remove duplicates
3872 void Buffer::updateMacroInstances(UpdateType utype) const
3874 LYXERR(Debug::MACROS, "updateMacroInstances for "
3875 << d->filename.onlyFileName());
3876 DocIterator it = doc_iterator_begin(this);
3878 DocIterator const end = doc_iterator_end(this);
3879 for (; it != end; it.forwardInset()) {
3880 // look for MathData cells in InsetMathNest insets
3881 InsetMath * minset = it.nextInset()->asInsetMath();
3885 // update macro in all cells of the InsetMathNest
3886 DocIterator::idx_type n = minset->nargs();
3887 MacroContext mc = MacroContext(this, it);
3888 for (DocIterator::idx_type i = 0; i < n; ++i) {
3889 MathData & data = minset->cell(i);
3890 data.updateMacros(0, mc, utype, 0);
3896 void Buffer::listMacroNames(MacroNameSet & macros) const
3901 d->macro_lock = true;
3903 // loop over macro names
3904 for (auto const & nameit : d->macros)
3905 macros.insert(nameit.first);
3907 // loop over children
3908 for (auto const & p : d->children_positions) {
3909 Buffer * child = const_cast<Buffer *>(p.first);
3910 // The buffer might have been closed (see #10766).
3911 if (theBufferList().isLoaded(child))
3912 child->listMacroNames(macros);
3916 Buffer const * const pbuf = d->parent();
3918 pbuf->listMacroNames(macros);
3920 d->macro_lock = false;
3924 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3926 Buffer const * const pbuf = d->parent();
3931 pbuf->listMacroNames(names);
3934 for (auto const & mit : names) {
3936 MacroData const * data = pbuf->getMacro(mit, *this, false);
3938 macros.insert(data);
3940 // we cannot access the original InsetMathMacroTemplate anymore
3941 // here to calls validate method. So we do its work here manually.
3942 // FIXME: somehow make the template accessible here.
3943 if (data->optionals() > 0)
3944 features.require("xargs");
3950 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3953 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3955 RefCache::iterator it = d->ref_cache_.find(label);
3956 if (it != d->ref_cache_.end())
3959 static References const dummy_refs = References();
3960 it = d->ref_cache_.insert(
3961 make_pair(label, dummy_refs)).first;
3966 Buffer::References const & Buffer::references(docstring const & label) const
3968 return const_cast<Buffer *>(this)->getReferenceCache(label);
3972 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3974 References & refs = getReferenceCache(label);
3975 refs.push_back(make_pair(inset, it));
3979 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3983 linfo.label = label;
3985 linfo.active = active;
3986 masterBuffer()->d->label_cache_.push_back(linfo);
3990 InsetLabel const * Buffer::insetLabel(docstring const & label,
3991 bool const active) const
3993 for (auto & rc : masterBuffer()->d->label_cache_) {
3994 if (rc.label == label && (rc.active || !active))
4001 bool Buffer::activeLabel(docstring const & label) const
4003 if (!insetLabel(label, true))
4010 void Buffer::clearReferenceCache() const
4013 d->ref_cache_.clear();
4014 d->label_cache_.clear();
4019 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
4021 //FIXME: This does not work for child documents yet.
4022 reloadBibInfoCache();
4024 // Check if the label 'from' appears more than once
4025 vector<docstring> labels;
4026 for (auto const & bibit : masterBibInfo())
4027 labels.push_back(bibit.first);
4029 if (count(labels.begin(), labels.end(), from) > 1)
4032 string const paramName = "key";
4033 InsetIterator it = inset_iterator_begin(inset());
4035 if (it->lyxCode() != CITE_CODE)
4037 InsetCommand * inset = it->asInsetCommand();
4038 docstring const oldValue = inset->getParam(paramName);
4039 if (oldValue == from)
4040 inset->setParam(paramName, to);
4044 // returns NULL if id-to-row conversion is unsupported
4045 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4046 pit_type par_begin, pit_type par_end,
4047 OutputWhat output, bool master) const
4049 unique_ptr<TexRow> texrow;
4050 OutputParams runparams(¶ms().encoding());
4051 runparams.nice = true;
4052 runparams.flavor = params().getOutputFlavor(format);
4053 runparams.linelen = lyxrc.plaintext_linelen;
4054 // No side effect of file copying and image conversion
4055 runparams.dryrun = true;
4057 // Some macros rely on font encoding
4058 runparams.main_fontenc = params().main_font_encoding();
4060 if (output == CurrentParagraph) {
4061 runparams.par_begin = par_begin;
4062 runparams.par_end = par_end;
4063 if (par_begin + 1 == par_end) {
4065 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4069 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4070 convert<docstring>(par_begin),
4071 convert<docstring>(par_end - 1))
4074 // output paragraphs
4075 if (runparams.flavor == OutputParams::LYX) {
4076 Paragraph const & par = text().paragraphs()[par_begin];
4078 depth_type dt = par.getDepth();
4079 par.write(ods, params(), dt);
4080 os << from_utf8(ods.str());
4081 } else if (runparams.flavor == OutputParams::HTML) {
4083 setMathFlavor(runparams);
4084 xhtmlParagraphs(text(), *this, xs, runparams);
4085 } else if (runparams.flavor == OutputParams::TEXT) {
4087 // FIXME Handles only one paragraph, unlike the others.
4088 // Probably should have some routine with a signature like them.
4089 writePlaintextParagraph(*this,
4090 text().paragraphs()[par_begin], os, runparams, dummy);
4091 } else if (params().isDocBook()) {
4092 docbookParagraphs(text(), *this, os, runparams);
4094 // If we are previewing a paragraph, even if this is the
4095 // child of some other buffer, let's cut the link here,
4096 // so that no concurring settings from the master
4097 // (e.g. branch state) interfere (see #8101).
4099 d->ignore_parent = true;
4100 // We need to validate the Buffer params' features here
4101 // in order to know if we should output polyglossia
4102 // macros (instead of babel macros)
4103 LaTeXFeatures features(*this, params(), runparams);
4105 runparams.use_polyglossia = features.usePolyglossia();
4106 // latex or literate
4109 ots.texrow().newlines(2);
4111 latexParagraphs(*this, text(), ots, runparams);
4112 texrow = ots.releaseTexRow();
4114 // Restore the parenthood
4116 d->ignore_parent = false;
4120 if (output == FullSource)
4121 os << _("Preview source code");
4122 else if (output == OnlyPreamble)
4123 os << _("Preview preamble");
4124 else if (output == OnlyBody)
4125 os << _("Preview body");
4127 if (runparams.flavor == OutputParams::LYX) {
4129 if (output == FullSource)
4131 else if (output == OnlyPreamble)
4132 params().writeFile(ods, this);
4133 else if (output == OnlyBody)
4135 os << from_utf8(ods.str());
4136 } else if (runparams.flavor == OutputParams::HTML) {
4137 writeLyXHTMLSource(os, runparams, output);
4138 } else if (runparams.flavor == OutputParams::TEXT) {
4139 if (output == OnlyPreamble) {
4140 os << "% "<< _("Plain text does not have a preamble.");
4142 writePlaintextFile(*this, os, runparams);
4143 } else if (params().isDocBook()) {
4144 writeDocBookSource(os, absFileName(), runparams, output);
4146 // latex or literate
4149 ots.texrow().newlines(2);
4151 runparams.is_child = true;
4153 writeLaTeXSource(ots, string(), runparams, output);
4154 texrow = ots.releaseTexRow();
4161 ErrorList & Buffer::errorList(string const & type) const
4163 return d->errorLists[type];
4167 void Buffer::updateTocItem(std::string const & type,
4168 DocIterator const & dit) const
4171 d->gui_->updateTocItem(type, dit);
4175 void Buffer::structureChanged() const
4178 d->gui_->structureChanged();
4182 void Buffer::errors(string const & err, bool from_master) const
4185 d->gui_->errors(err, from_master);
4189 void Buffer::message(docstring const & msg) const
4192 d->gui_->message(msg);
4196 void Buffer::setBusy(bool on) const
4199 d->gui_->setBusy(on);
4203 void Buffer::updateTitles() const
4206 d->wa_->updateTitles();
4210 void Buffer::resetAutosaveTimers() const
4213 d->gui_->resetAutosaveTimers();
4217 bool Buffer::hasGuiDelegate() const
4223 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4232 class AutoSaveBuffer : public ForkedProcess {
4235 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4236 : buffer_(buffer), fname_(fname) {}
4238 virtual shared_ptr<ForkedProcess> clone() const
4240 return make_shared<AutoSaveBuffer>(*this);
4245 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4246 from_utf8(fname_.absFileName())));
4247 return run(DontWait);
4251 virtual int generateChild();
4253 Buffer const & buffer_;
4258 int AutoSaveBuffer::generateChild()
4260 #if defined(__APPLE__)
4261 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4262 * We should use something else like threads.
4264 * Since I do not know how to determine at run time what is the OS X
4265 * version, I just disable forking altogether for now (JMarc)
4267 pid_t const pid = -1;
4269 // tmp_ret will be located (usually) in /tmp
4270 // will that be a problem?
4271 // Note that this calls ForkedCalls::fork(), so it's
4272 // ok cross-platform.
4273 pid_t const pid = fork();
4274 // If you want to debug the autosave
4275 // you should set pid to -1, and comment out the fork.
4276 if (pid != 0 && pid != -1)
4280 // pid = -1 signifies that lyx was unable
4281 // to fork. But we will do the save
4283 bool failed = false;
4284 TempFile tempfile("lyxautoXXXXXX.lyx");
4285 tempfile.setAutoRemove(false);
4286 FileName const tmp_ret = tempfile.name();
4287 if (!tmp_ret.empty()) {
4288 if (!buffer_.writeFile(tmp_ret))
4290 else if (!tmp_ret.moveTo(fname_))
4296 // failed to write/rename tmp_ret so try writing direct
4297 if (!buffer_.writeFile(fname_)) {
4298 // It is dangerous to do this in the child,
4299 // but safe in the parent, so...
4300 if (pid == -1) // emit message signal.
4301 buffer_.message(_("Autosave failed!"));
4305 if (pid == 0) // we are the child so...
4314 FileName Buffer::getEmergencyFileName() const
4316 return FileName(d->filename.absFileName() + ".emergency");
4320 FileName Buffer::getAutosaveFileName() const
4322 // if the document is unnamed try to save in the backup dir, else
4323 // in the default document path, and as a last try in the filePath,
4324 // which will most often be the temporary directory
4327 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4328 : lyxrc.backupdir_path;
4329 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4332 string const fname = "#" + d->filename.onlyFileName() + "#";
4334 return makeAbsPath(fname, fpath);
4338 void Buffer::removeAutosaveFile() const
4340 FileName const f = getAutosaveFileName();
4346 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4348 FileName const newauto = getAutosaveFileName();
4350 if (newauto != oldauto && oldauto.exists())
4351 if (!oldauto.moveTo(newauto))
4352 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4356 bool Buffer::autoSave() const
4358 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4359 if (buf->d->bak_clean || hasReadonlyFlag())
4362 message(_("Autosaving current document..."));
4363 buf->d->bak_clean = true;
4365 FileName const fname = getAutosaveFileName();
4366 LASSERT(d->cloned_buffer_, return false);
4368 // If this buffer is cloned, we assume that
4369 // we are running in a separate thread already.
4370 TempFile tempfile("lyxautoXXXXXX.lyx");
4371 tempfile.setAutoRemove(false);
4372 FileName const tmp_ret = tempfile.name();
4373 if (!tmp_ret.empty()) {
4375 // assume successful write of tmp_ret
4376 if (tmp_ret.moveTo(fname))
4379 // failed to write/rename tmp_ret so try writing direct
4380 return writeFile(fname);
4384 void Buffer::setExportStatus(bool e) const
4386 d->doing_export = e;
4387 ListOfBuffers clist = getDescendents();
4388 for (auto const & bit : clist)
4389 bit->d->doing_export = e;
4393 bool Buffer::isExporting() const
4395 return d->doing_export;
4399 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4403 return doExport(target, put_in_tempdir, result_file);
4406 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4407 string & result_file) const
4409 bool const update_unincluded =
4410 params().maintain_unincluded_children
4411 && !params().getIncludedChildren().empty();
4413 // (1) export with all included children (omit \includeonly)
4414 if (update_unincluded) {
4415 ExportStatus const status =
4416 doExport(target, put_in_tempdir, true, result_file);
4417 if (status != ExportSuccess)
4420 // (2) export with included children only
4421 return doExport(target, put_in_tempdir, false, result_file);
4425 void Buffer::setMathFlavor(OutputParams & op) const
4427 switch (params().html_math_output) {
4428 case BufferParams::MathML:
4429 op.math_flavor = OutputParams::MathAsMathML;
4431 case BufferParams::HTML:
4432 op.math_flavor = OutputParams::MathAsHTML;
4434 case BufferParams::Images:
4435 op.math_flavor = OutputParams::MathAsImages;
4437 case BufferParams::LaTeX:
4438 op.math_flavor = OutputParams::MathAsLaTeX;
4444 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4445 bool includeall, string & result_file) const
4447 LYXERR(Debug::FILES, "target=" << target);
4448 OutputParams runparams(¶ms().encoding());
4449 string format = target;
4450 string dest_filename;
4451 size_t pos = target.find(' ');
4452 if (pos != string::npos) {
4453 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4454 format = target.substr(0, pos);
4455 if (format == "default")
4456 format = params().getDefaultOutputFormat();
4457 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4458 FileName(dest_filename).onlyPath().createPath();
4459 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4461 MarkAsExporting exporting(this);
4462 string backend_format;
4463 runparams.flavor = OutputParams::LATEX;
4464 runparams.linelen = lyxrc.plaintext_linelen;
4465 runparams.includeall = includeall;
4466 vector<string> backs = params().backends();
4467 Converters converters = theConverters();
4468 bool need_nice_file = false;
4469 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4470 // Get shortest path to format
4471 converters.buildGraph();
4472 Graph::EdgePath path;
4473 for (string const & sit : backs) {
4474 Graph::EdgePath p = converters.getPath(sit, format);
4475 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4476 backend_format = sit;
4481 if (!put_in_tempdir) {
4482 // Only show this alert if this is an export to a non-temporary
4483 // file (not for previewing).
4484 docstring s = bformat(_("No information for exporting the format %1$s."),
4485 theFormats().prettyName(format));
4486 if (format == "pdf4")
4488 + bformat(_("Hint: use non-TeX fonts or set input encoding "
4489 " to '%1$s'"), from_utf8(encodings.fromLyXName("ascii")->guiName()));
4490 Alert::error(_("Couldn't export file"), s);
4492 return ExportNoPathToFormat;
4494 runparams.flavor = converters.getFlavor(path, this);
4495 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4496 for (auto const & edge : path)
4497 if (theConverters().get(edge).nice()) {
4498 need_nice_file = true;
4503 backend_format = format;
4504 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4505 // FIXME: Don't hardcode format names here, but use a flag
4506 if (backend_format == "pdflatex")
4507 runparams.flavor = OutputParams::PDFLATEX;
4508 else if (backend_format == "luatex")
4509 runparams.flavor = OutputParams::LUATEX;
4510 else if (backend_format == "dviluatex")
4511 runparams.flavor = OutputParams::DVILUATEX;
4512 else if (backend_format == "xetex")
4513 runparams.flavor = OutputParams::XETEX;
4516 string filename = latexName(false);
4517 filename = addName(temppath(), filename);
4518 filename = changeExtension(filename,
4519 theFormats().extension(backend_format));
4520 LYXERR(Debug::FILES, "filename=" << filename);
4522 // Plain text backend
4523 if (backend_format == "text") {
4524 runparams.flavor = OutputParams::TEXT;
4526 writePlaintextFile(*this, FileName(filename), runparams);
4528 catch (ConversionException const &) { return ExportCancel; }
4531 else if (backend_format == "xhtml") {
4532 runparams.flavor = OutputParams::HTML;
4533 setMathFlavor(runparams);
4534 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4535 return ExportKilled;
4536 } else if (backend_format == "lyx")
4537 writeFile(FileName(filename));
4539 else if (params().isDocBook()) {
4540 runparams.nice = !put_in_tempdir;
4541 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4542 return ExportKilled;
4545 else if (backend_format == format || need_nice_file) {
4546 runparams.nice = true;
4547 ExportStatus const retval =
4548 makeLaTeXFile(FileName(filename), string(), runparams);
4549 if (retval == ExportKilled)
4550 return ExportKilled;
4551 if (d->cloned_buffer_)
4552 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4553 if (retval != ExportSuccess)
4555 } else if (!lyxrc.tex_allows_spaces
4556 && contains(filePath(), ' ')) {
4557 Alert::error(_("File name error"),
4558 bformat(_("The directory path to the document\n%1$s\n"
4559 "contains spaces, but your TeX installation does "
4560 "not allow them. You should save the file to a directory "
4561 "whose name does not contain spaces."), from_utf8(filePath())));
4562 return ExportTexPathHasSpaces;
4564 runparams.nice = false;
4565 ExportStatus const retval =
4566 makeLaTeXFile(FileName(filename), filePath(), runparams);
4567 if (retval == ExportKilled)
4568 return ExportKilled;
4569 if (d->cloned_buffer_)
4570 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4571 if (retval != ExportSuccess)
4575 string const error_type = (format == "program")
4576 ? "Build" : params().bufferFormat();
4577 ErrorList & error_list = d->errorLists[error_type];
4578 string const ext = theFormats().extension(format);
4579 FileName const tmp_result_file(changeExtension(filename, ext));
4580 Converters::RetVal const retval =
4581 converters.convert(this, FileName(filename), tmp_result_file,
4582 FileName(absFileName()), backend_format, format, error_list);
4583 if (retval == Converters::KILLED)
4584 return ExportCancel;
4585 bool success = (retval == Converters::SUCCESS);
4587 // Emit the signal to show the error list or copy it back to the
4588 // cloned Buffer so that it can be emitted afterwards.
4589 if (format != backend_format) {
4590 if (runparams.silent)
4592 else if (d->cloned_buffer_)
4593 d->cloned_buffer_->d->errorLists[error_type] =
4594 d->errorLists[error_type];
4597 // also to the children, in case of master-buffer-view
4598 ListOfBuffers clist = getDescendents();
4599 for (auto const & bit : clist) {
4600 if (runparams.silent)
4601 bit->d->errorLists[error_type].clear();
4602 else if (d->cloned_buffer_) {
4603 // Enable reverse search by copying back the
4604 // texrow object to the cloned buffer.
4605 // FIXME: this is not thread safe.
4606 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4607 bit->d->cloned_buffer_->d->errorLists[error_type] =
4608 bit->d->errorLists[error_type];
4610 bit->errors(error_type, true);
4614 if (d->cloned_buffer_) {
4615 // Enable reverse dvi or pdf to work by copying back the texrow
4616 // object to the cloned buffer.
4617 // FIXME: There is a possibility of concurrent access to texrow
4618 // here from the main GUI thread that should be securized.
4619 d->cloned_buffer_->d->texrow = d->texrow;
4620 string const err_type = params().bufferFormat();
4621 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4625 if (put_in_tempdir) {
4626 result_file = tmp_result_file.absFileName();
4627 return success ? ExportSuccess : ExportConverterError;
4630 if (dest_filename.empty())
4631 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4633 result_file = dest_filename;
4634 // We need to copy referenced files (e. g. included graphics
4635 // if format == "dvi") to the result dir.
4636 vector<ExportedFile> const files =
4637 runparams.exportdata->externalFiles(format);
4638 string const dest = runparams.export_folder.empty() ?
4639 onlyPath(result_file) : runparams.export_folder;
4640 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4641 : force_overwrite == ALL_FILES;
4642 CopyStatus status = use_force ? FORCE : SUCCESS;
4644 for (ExportedFile const & exp : files) {
4645 if (status == CANCEL) {
4646 message(_("Document export cancelled."));
4647 return ExportCancel;
4649 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4650 string fixedName = exp.exportName;
4651 if (!runparams.export_folder.empty()) {
4652 // Relative pathnames starting with ../ will be sanitized
4653 // if exporting to a different folder
4654 while (fixedName.substr(0, 3) == "../")
4655 fixedName = fixedName.substr(3, fixedName.length() - 3);
4657 FileName fixedFileName = makeAbsPath(fixedName, dest);
4658 fixedFileName.onlyPath().createPath();
4659 status = copyFile(fmt, exp.sourceName,
4661 exp.exportName, status == FORCE,
4662 runparams.export_folder.empty());
4666 if (tmp_result_file.exists()) {
4667 // Finally copy the main file
4668 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4669 : force_overwrite != NO_FILES;
4670 if (status == SUCCESS && use_force)
4672 status = copyFile(format, tmp_result_file,
4673 FileName(result_file), result_file,
4675 if (status == CANCEL) {
4676 message(_("Document export cancelled."));
4677 return ExportCancel;
4679 message(bformat(_("Document exported as %1$s "
4681 theFormats().prettyName(format),
4682 makeDisplayPath(result_file)));
4685 // This must be a dummy converter like fax (bug 1888)
4686 message(bformat(_("Document exported as %1$s"),
4687 theFormats().prettyName(format)));
4690 return success ? ExportSuccess : ExportConverterError;
4694 Buffer::ExportStatus Buffer::preview(string const & format) const
4696 bool const update_unincluded =
4697 params().maintain_unincluded_children
4698 && !params().getIncludedChildren().empty();
4699 return preview(format, update_unincluded);
4703 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4705 MarkAsExporting exporting(this);
4707 // (1) export with all included children (omit \includeonly)
4709 ExportStatus const status = doExport(format, true, true, result_file);
4710 if (status != ExportSuccess)
4713 // (2) export with included children only
4714 ExportStatus const status = doExport(format, true, false, result_file);
4715 FileName const previewFile(result_file);
4717 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4718 theimpl->preview_file_ = previewFile;
4719 theimpl->preview_format_ = format;
4720 theimpl->preview_error_ = (status != ExportSuccess);
4722 if (status != ExportSuccess)
4725 if (previewFile.exists())
4726 return theFormats().view(*this, previewFile, format) ?
4727 PreviewSuccess : PreviewError;
4729 // Successful export but no output file?
4730 // Probably a bug in error detection.
4731 LATTEST(status != ExportSuccess);
4736 Buffer::ReadStatus Buffer::extractFromVC()
4738 bool const found = LyXVC::file_not_found_hook(d->filename);
4740 return ReadFileNotFound;
4741 if (!d->filename.isReadableFile())
4747 Buffer::ReadStatus Buffer::loadEmergency()
4749 FileName const emergencyFile = getEmergencyFileName();
4750 if (!emergencyFile.exists()
4751 || emergencyFile.lastModified() <= d->filename.lastModified())
4752 return ReadFileNotFound;
4754 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4755 docstring const text = bformat(_("An emergency save of the document "
4756 "%1$s exists.\n\nRecover emergency save?"), file);
4758 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4759 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4765 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4766 bool const success = (ret_llf == ReadSuccess);
4768 if (hasReadonlyFlag()) {
4769 Alert::warning(_("File is read-only"),
4770 bformat(_("An emergency file is successfully loaded, "
4771 "but the original file %1$s is marked read-only. "
4772 "Please make sure to save the document as a different "
4773 "file."), from_utf8(d->filename.absFileName())));
4776 lyxvc().file_found_hook(d->filename);
4777 str = _("Document was successfully recovered.");
4779 str = _("Document was NOT successfully recovered.");
4780 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4781 makeDisplayPath(emergencyFile.absFileName()));
4783 int const del_emerg =
4784 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4785 _("&Remove"), _("&Keep"));
4786 if (del_emerg == 0) {
4787 emergencyFile.removeFile();
4789 Alert::warning(_("Emergency file deleted"),
4790 _("Do not forget to save your file now!"), true);
4792 return success ? ReadSuccess : ReadEmergencyFailure;
4795 int const del_emerg =
4796 Alert::prompt(_("Delete emergency file?"),
4797 _("Remove emergency file now?"), 1, 1,
4798 _("&Remove"), _("&Keep"));
4800 emergencyFile.removeFile();
4804 string const ename = emergencyFile.absFileName();
4806 // Surely we can find one in 100 tries?
4807 for (int i = 1; i < 100; ++i) {
4808 newname.set(ename + to_string(i) + ".lyx");
4809 if (!newname.exists()) {
4815 // renameTo returns true on success. So inverting that
4816 // will give us true if we fail.
4817 noname = !emergencyFile.renameTo(newname);
4820 Alert::warning(_("Can't rename emergency file!"),
4821 _("LyX was unable to rename the emergency file. "
4822 "You should do so manually. Otherwise, you will be "
4823 "asked about it again the next time you try to load "
4824 "this file, and may over-write your own work."));
4826 Alert::warning(_("Emergency File Renames"),
4827 bformat(_("Emergency file renamed as:\n %1$s"),
4828 from_utf8(newname.onlyFileName())));
4831 return ReadOriginal;
4841 Buffer::ReadStatus Buffer::loadAutosave()
4843 // Now check if autosave file is newer.
4844 FileName const autosaveFile = getAutosaveFileName();
4845 if (!autosaveFile.exists()
4846 || autosaveFile.lastModified() <= d->filename.lastModified())
4847 return ReadFileNotFound;
4849 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4850 docstring const text = bformat(_("The backup of the document %1$s "
4851 "is newer.\n\nLoad the backup instead?"), file);
4852 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4853 _("&Load backup"), _("Load &original"), _("&Cancel"));
4858 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4859 // the file is not saved if we load the autosave file.
4860 if (ret_llf == ReadSuccess) {
4861 if (hasReadonlyFlag()) {
4862 Alert::warning(_("File is read-only"),
4863 bformat(_("A backup file is successfully loaded, "
4864 "but the original file %1$s is marked read-only. "
4865 "Please make sure to save the document as a "
4867 from_utf8(d->filename.absFileName())));
4870 lyxvc().file_found_hook(d->filename);
4873 return ReadAutosaveFailure;
4876 // Here we delete the autosave
4877 autosaveFile.removeFile();
4878 return ReadOriginal;
4886 Buffer::ReadStatus Buffer::loadLyXFile()
4888 if (!d->filename.isReadableFile()) {
4889 ReadStatus const ret_rvc = extractFromVC();
4890 if (ret_rvc != ReadSuccess)
4894 ReadStatus const ret_re = loadEmergency();
4895 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4898 ReadStatus const ret_ra = loadAutosave();
4899 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4902 return loadThisLyXFile(d->filename);
4906 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4908 return readFile(fn);
4912 void Buffer::Impl::traverseErrors(TeXErrors::Errors::const_iterator err, TeXErrors::Errors::const_iterator end, ErrorList & errorList) const
4914 for (; err != end; ++err) {
4915 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4916 int errorRow = err->error_in_line;
4917 Buffer const * buf = 0;
4918 Impl const * p = this;
4919 if (err->child_name.empty())
4920 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4922 // The error occurred in a child
4923 for (Buffer const * child : owner_->getDescendents()) {
4924 string const child_name =
4925 DocFileName(changeExtension(child->absFileName(), "tex")).
4927 if (err->child_name != child_name)
4929 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4930 if (!TexRow::isNone(start)) {
4931 buf = this->cloned_buffer_
4932 ? child->d->cloned_buffer_->d->owner_
4939 errorList.push_back(ErrorItem(err->error_desc, err->error_text,
4945 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4947 TeXErrors::Errors::const_iterator err = terr.begin();
4948 TeXErrors::Errors::const_iterator end = terr.end();
4950 d->traverseErrors(err, end, errorList);
4954 void Buffer::bufferRefs(TeXErrors const & terr, ErrorList & errorList) const
4956 TeXErrors::Errors::const_iterator err = terr.begin_ref();
4957 TeXErrors::Errors::const_iterator end = terr.end_ref();
4959 d->traverseErrors(err, end, errorList);
4963 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4965 LBUFERR(!text().paragraphs().empty());
4967 // Use the master text class also for child documents
4968 Buffer const * const master = masterBuffer();
4969 DocumentClass const & textclass = master->params().documentClass();
4971 docstring_list old_bibfiles;
4972 // Do this only if we are the top-level Buffer. We also need to account
4973 // for the case of a previewed child with ignored parent here.
4974 if (master == this && !d->ignore_parent) {
4975 textclass.counters().reset(from_ascii("bibitem"));
4976 reloadBibInfoCache();
4977 // we will re-read this cache as we go through, but we need
4978 // to know whether it's changed to know whether we need to
4979 // update the bibinfo cache.
4980 old_bibfiles = d->bibfiles_cache_;
4981 d->bibfiles_cache_.clear();
4984 // keep the buffers to be children in this set. If the call from the
4985 // master comes back we can see which of them were actually seen (i.e.
4986 // via an InsetInclude). The remaining ones in the set need still be updated.
4987 static std::set<Buffer const *> bufToUpdate;
4988 if (scope == UpdateMaster) {
4989 // If this is a child document start with the master
4990 if (master != this) {
4991 bufToUpdate.insert(this);
4992 master->updateBuffer(UpdateMaster, utype);
4993 // If the master buffer has no gui associated with it, then the TocModel is
4994 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4995 // (bug 5699). The same happens if the master buffer is open in a different
4996 // window. This test catches both possibilities.
4997 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4998 // There remains a problem here: If there is another child open in yet a third
4999 // window, that TOC is not updated. So some more general solution is needed at
5001 if (master->d->gui_ != d->gui_)
5004 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
5005 if (bufToUpdate.find(this) == bufToUpdate.end())
5009 // start over the counters in the master
5010 textclass.counters().reset();
5013 // update will be done below for this buffer
5014 bufToUpdate.erase(this);
5016 // update all caches
5017 clearReferenceCache();
5019 setChangesPresent(false);
5021 Buffer & cbuf = const_cast<Buffer &>(*this);
5022 // if we are reloading, then we could have a dangling TOC,
5023 // in effect. so we need to go ahead and reset, even though
5024 // we will do so again when we rebuild the TOC later.
5025 cbuf.tocBackend().reset();
5028 ParIterator parit = cbuf.par_iterator_begin();
5029 updateBuffer(parit, utype);
5031 // If this document has siblings, then update the TocBackend later. The
5032 // reason is to ensure that later siblings are up to date when e.g. the
5033 // broken or not status of references is computed. The update is called
5034 // in InsetInclude::addToToc.
5038 // if the bibfiles changed, the cache of bibinfo is invalid
5039 docstring_list new_bibfiles = d->bibfiles_cache_;
5040 // this is a trick to determine whether the two vectors have
5041 // the same elements.
5042 sort(new_bibfiles.begin(), new_bibfiles.end());
5043 sort(old_bibfiles.begin(), old_bibfiles.end());
5044 if (old_bibfiles != new_bibfiles) {
5045 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
5046 invalidateBibinfoCache();
5047 reloadBibInfoCache();
5048 // We relied upon the bibinfo cache when recalculating labels. But that
5049 // cache was invalid, although we didn't find that out until now. So we
5050 // have to do it all again.
5051 // That said, the only thing we really need to do is update the citation
5052 // labels. Nothing else will have changed. So we could create a new
5053 // UpdateType that would signal that fact, if we needed to do so.
5054 parit = cbuf.par_iterator_begin();
5055 // we will be re-doing the counters and references and such.
5056 textclass.counters().reset();
5057 clearReferenceCache();
5058 // we should not need to do this again?
5060 setChangesPresent(false);
5061 updateBuffer(parit, utype);
5062 // this will already have been done by reloadBibInfoCache();
5063 // d->bibinfo_cache_valid_ = true;
5066 LYXERR(Debug::FILES, "Bibfiles unchanged.");
5067 // this is also set to true on the other path, by reloadBibInfoCache.
5068 d->bibinfo_cache_valid_ = true;
5070 d->cite_labels_valid_ = true;
5072 cbuf.tocBackend().update(true, utype);
5073 if (scope == UpdateMaster)
5074 cbuf.structureChanged();
5078 static depth_type getDepth(DocIterator const & it)
5080 depth_type depth = 0;
5081 for (size_t i = 0 ; i < it.depth() ; ++i)
5082 if (!it[i].inset().inMathed())
5083 depth += it[i].paragraph().getDepth() + 1;
5084 // remove 1 since the outer inset does not count
5085 // we should have at least one non-math inset, so
5086 // depth should nevery be 0. but maybe it is worth
5087 // marking this, just in case.
5089 // coverity[INTEGER_OVERFLOW]
5093 static depth_type getItemDepth(ParIterator const & it)
5095 Paragraph const & par = *it;
5096 LabelType const labeltype = par.layout().labeltype;
5098 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5101 // this will hold the lowest depth encountered up to now.
5102 depth_type min_depth = getDepth(it);
5103 ParIterator prev_it = it;
5106 --prev_it.top().pit();
5108 // start of nested inset: go to outer par
5110 if (prev_it.empty()) {
5111 // start of document: nothing to do
5116 // We search for the first paragraph with same label
5117 // that is not more deeply nested.
5118 Paragraph & prev_par = *prev_it;
5119 depth_type const prev_depth = getDepth(prev_it);
5120 if (labeltype == prev_par.layout().labeltype) {
5121 if (prev_depth < min_depth)
5122 return prev_par.itemdepth + 1;
5123 if (prev_depth == min_depth)
5124 return prev_par.itemdepth;
5126 min_depth = min(min_depth, prev_depth);
5127 // small optimization: if we are at depth 0, we won't
5128 // find anything else
5129 if (prev_depth == 0)
5135 static bool needEnumCounterReset(ParIterator const & it)
5137 Paragraph const & par = *it;
5138 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5139 depth_type const cur_depth = par.getDepth();
5140 ParIterator prev_it = it;
5141 while (prev_it.pit()) {
5142 --prev_it.top().pit();
5143 Paragraph const & prev_par = *prev_it;
5144 if (prev_par.getDepth() <= cur_depth)
5145 return prev_par.layout().name() != par.layout().name();
5147 // start of nested inset: reset
5152 // set the label of a paragraph. This includes the counters.
5153 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5155 BufferParams const & bp = owner_->masterBuffer()->params();
5156 DocumentClass const & textclass = bp.documentClass();
5157 Paragraph & par = it.paragraph();
5158 Layout const & layout = par.layout();
5159 Counters & counters = textclass.counters();
5161 if (par.params().startOfAppendix()) {
5162 // We want to reset the counter corresponding to toplevel sectioning
5163 Layout const & lay = textclass.getTOCLayout();
5164 docstring const cnt = lay.counter;
5166 counters.reset(cnt);
5167 counters.appendix(true);
5169 par.params().appendix(counters.appendix());
5171 // Compute the item depth of the paragraph
5172 par.itemdepth = getItemDepth(it);
5174 if (layout.margintype == MARGIN_MANUAL) {
5175 if (par.params().labelWidthString().empty())
5176 par.params().labelWidthString(par.expandLabel(layout, bp));
5177 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5178 // we do not need to do anything here, since the empty case is
5179 // handled during export.
5181 par.params().labelWidthString(docstring());
5184 switch(layout.labeltype) {
5185 case LABEL_ITEMIZE: {
5186 // At some point of time we should do something more
5187 // clever here, like:
5188 // par.params().labelString(
5189 // bp.user_defined_bullet(par.itemdepth).getText());
5190 // for now, use a simple hardcoded label
5191 docstring itemlabel;
5192 switch (par.itemdepth) {
5195 itemlabel = char_type(0x2022);
5199 itemlabel = char_type(0x2013);
5202 // ∗ U+2217 ASTERISK OPERATOR
5203 itemlabel = char_type(0x2217);
5206 // · U+00B7 MIDDLE DOT
5207 itemlabel = char_type(0x00b7);
5210 par.params().labelString(itemlabel);
5214 case LABEL_ENUMERATE: {
5215 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5217 switch (par.itemdepth) {
5228 enumcounter += "iv";
5231 // not a valid enumdepth...
5235 if (needEnumCounterReset(it)) {
5236 // Increase the master counter?
5237 if (layout.stepmastercounter)
5238 counters.stepMaster(enumcounter, utype);
5239 // Maybe we have to reset the enumeration counter.
5240 if (!layout.resumecounter)
5241 counters.reset(enumcounter);
5243 counters.step(enumcounter, utype);
5245 string const & lang = par.getParLanguage(bp)->code();
5246 par.params().labelString(counters.theCounter(enumcounter, lang));
5251 case LABEL_SENSITIVE: {
5252 string const & type = counters.current_float();
5253 docstring full_label;
5255 full_label = owner_->B_("Senseless!!! ");
5257 docstring name = owner_->B_(textclass.floats().getType(type).name());
5258 if (counters.hasCounter(from_utf8(type))) {
5259 string const & lang = par.getParLanguage(bp)->code();
5260 counters.step(from_utf8(type), utype);
5261 full_label = bformat(from_ascii("%1$s %2$s:"),
5263 counters.theCounter(from_utf8(type), lang));
5265 full_label = bformat(from_ascii("%1$s #:"), name);
5267 par.params().labelString(full_label);
5271 case LABEL_NO_LABEL:
5272 par.params().labelString(docstring());
5276 case LABEL_CENTERED:
5277 case LABEL_STATIC: {
5278 docstring const & lcounter = layout.counter;
5279 if (!lcounter.empty()) {
5280 if (layout.toclevel <= bp.secnumdepth
5281 && (layout.latextype != LATEX_ENVIRONMENT
5282 || it.text()->isFirstInSequence(it.pit()))) {
5283 if (counters.hasCounter(lcounter))
5284 counters.step(lcounter, utype);
5285 par.params().labelString(par.expandLabel(layout, bp));
5287 par.params().labelString(docstring());
5289 par.params().labelString(par.expandLabel(layout, bp));
5295 par.params().labelString(par.expandLabel(layout, bp));
5300 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5302 // LASSERT: Is it safe to continue here, or should we just return?
5303 LASSERT(parit.pit() == 0, /**/);
5305 // Set the position of the text in the buffer to be able
5306 // to resolve macros in it.
5307 parit.text()->setMacrocontextPosition(parit);
5309 // Reset bibitem counter in master (#8499)
5310 Buffer const * const master = masterBuffer();
5311 if (master == this && !d->ignore_parent)
5312 master->params().documentClass().counters().reset(from_ascii("bibitem"));
5314 depth_type maxdepth = 0;
5315 pit_type const lastpit = parit.lastpit();
5316 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5317 // reduce depth if necessary
5318 if (parit->params().depth() > maxdepth) {
5319 /** FIXME: this function is const, but
5320 * nevertheless it modifies the buffer. To be
5321 * cleaner, one should modify the buffer in
5322 * another function, which is actually
5323 * non-const. This would however be costly in
5324 * terms of code duplication.
5326 CursorData(parit).recordUndo();
5327 parit->params().depth(maxdepth);
5329 maxdepth = parit->getMaxDepthAfter();
5331 if (utype == OutputUpdate) {
5332 // track the active counters
5333 // we have to do this for the master buffer, since the local
5334 // buffer isn't tracking anything.
5335 masterBuffer()->params().documentClass().counters().
5336 setActiveLayout(parit->layout());
5339 // set the counter for this paragraph
5340 d->setLabel(parit, utype);
5342 // update change-tracking flag
5343 parit->addChangesToBuffer(*this);
5346 for (auto const & insit : parit->insetList()) {
5347 parit.pos() = insit.pos;
5348 insit.inset->updateBuffer(parit, utype);
5354 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5355 WordLangTuple & word_lang, docstring_list & suggestions) const
5359 suggestions.clear();
5360 word_lang = WordLangTuple();
5361 bool const to_end = to.empty();
5362 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5363 // OK, we start from here.
5364 for (; from != end; from.forwardPos()) {
5365 // This skips all insets with spell check disabled.
5366 while (!from.allowSpellCheck()) {
5370 // If from is at the end of the document (which is possible
5371 // when "from" was changed above) LyX will crash later otherwise.
5372 if (from.atEnd() || (!to_end && from >= end))
5375 from.paragraph().spellCheck();
5376 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5377 if (SpellChecker::misspelled(res)) {
5381 // Do not increase progress when from == to, otherwise the word
5382 // count will be wrong.
5392 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5394 bool inword = false;
5399 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5400 if (!dit.inTexted()) {
5405 Paragraph const & par = dit.paragraph();
5406 pos_type const pos = dit.pos();
5408 // Copied and adapted from isWordSeparator() in Paragraph
5409 if (pos == dit.lastpos()) {
5412 Inset const * ins = par.getInset(pos);
5413 if (ins && skipNoOutput && !ins->producesOutput()) {
5416 // stop if end of range was skipped
5417 if (!to.atEnd() && dit >= to)
5420 } else if (!par.isDeleted(pos)) {
5421 if (par.isWordSeparator(pos))
5427 if (ins && ins->isLetter())
5429 else if (ins && ins->isSpace())
5432 char_type const c = par.getChar(pos);
5433 if (isPrintableNonspace(c))
5435 else if (isSpace(c))
5445 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5447 d->updateStatistics(from, to, skipNoOutput);
5451 int Buffer::wordCount() const
5453 return d->wordCount();
5457 int Buffer::charCount(bool with_blanks) const
5459 return d->charCount(with_blanks);
5463 Buffer::ReadStatus Buffer::reload()
5466 // c.f. bug https://www.lyx.org/trac/ticket/6587
5467 removeAutosaveFile();
5468 // e.g., read-only status could have changed due to version control
5469 d->filename.refresh();
5470 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5472 // clear parent. this will get reset if need be.
5474 ReadStatus const status = loadLyXFile();
5475 if (status == ReadSuccess) {
5480 message(bformat(_("Document %1$s reloaded."), disp_fn));
5483 message(bformat(_("Could not reload document %1$s."), disp_fn));
5493 bool Buffer::saveAs(FileName const & fn)
5495 FileName const old_name = fileName();
5496 FileName const old_auto = getAutosaveFileName();
5497 bool const old_unnamed = isUnnamed();
5498 bool success = true;
5499 d->old_position = filePath();
5506 // bring the autosave file with us, just in case.
5507 moveAutosaveFile(old_auto);
5508 // validate version control data and
5509 // correct buffer title
5510 lyxvc().file_found_hook(fileName());
5512 // the file has now been saved to the new location.
5513 // we need to check that the locations of child buffers
5515 checkChildBuffers();
5516 checkMasterBuffer();
5519 // reset the old filename and unnamed state
5520 setFileName(old_name);
5521 setUnnamed(old_unnamed);
5525 d->old_position.clear();
5530 void Buffer::checkChildBuffers()
5532 for (auto const & bit : d->children_positions) {
5533 DocIterator dit = bit.second;
5534 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5535 if (!cbuf || !theBufferList().isLoaded(cbuf))
5537 Inset * inset = dit.nextInset();
5538 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5539 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5540 docstring const & incfile = inset_inc->getParam("filename");
5541 string oldloc = cbuf->absFileName();
5542 string newloc = makeAbsPath(to_utf8(incfile),
5543 onlyPath(absFileName())).absFileName();
5544 if (oldloc == newloc)
5546 // the location of the child file is incorrect.
5548 inset_inc->setChildBuffer(0);
5550 // invalidate cache of children
5551 d->children_positions.clear();
5552 d->position_to_children.clear();
5556 // If a child has been saved under a different name/path, it might have been
5557 // orphaned. Therefore the master needs to be reset (bug 8161).
5558 void Buffer::checkMasterBuffer()
5560 Buffer const * const master = masterBuffer();
5564 // necessary to re-register the child (bug 5873)
5565 // FIXME: clean up updateMacros (here, only
5566 // child registering is needed).
5567 master->updateMacros();
5568 // (re)set master as master buffer, but only
5569 // if we are a real child
5570 if (master->isChild(this))
5577 string Buffer::includedFilePath(string const & name, string const & ext) const
5579 if (d->old_position.empty() ||
5580 equivalent(FileName(d->old_position), FileName(filePath())))
5583 bool isabsolute = FileName::isAbsolute(name);
5584 // both old_position and filePath() end with a path separator
5585 string absname = isabsolute ? name : d->old_position + name;
5587 // if old_position is set to origin, we need to do the equivalent of
5588 // getReferencedFileName() (see readDocument())
5589 if (!isabsolute && d->old_position == params().origin) {
5590 FileName const test(addExtension(filePath() + name, ext));
5592 absname = filePath() + name;
5595 if (!FileName(addExtension(absname, ext)).exists())
5599 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5601 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5602 from_utf8(filePath())));
5606 void Buffer::setChangesPresent(bool b) const
5608 d->tracked_changes_present_ = b;
5612 bool Buffer::areChangesPresent() const
5614 return d->tracked_changes_present_;
5618 void Buffer::updateChangesPresent() const
5620 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5621 setChangesPresent(false);
5622 ParConstIterator it = par_iterator_begin();
5623 ParConstIterator const end = par_iterator_end();
5624 for (; !areChangesPresent() && it != end; ++it)
5625 it->addChangesToBuffer(*this);
5629 void Buffer::Impl::refreshFileMonitor()
5631 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5632 file_monitor_->refresh();
5636 // The previous file monitor is invalid
5637 // This also destroys the previous file monitor and all its connections
5638 file_monitor_ = FileSystemWatcher::monitor(filename);
5639 // file_monitor_ will be destroyed with *this, so it is not going to call a
5640 // destroyed object method.
5641 file_monitor_->connect([this](bool exists) {
5642 fileExternallyModified(exists);
5647 void Buffer::Impl::fileExternallyModified(bool const exists)
5649 // ignore notifications after our own saving operations
5650 if (checksum_ == filename.checksum()) {
5651 LYXERR(Debug::FILES, "External modification but "
5652 "checksum unchanged: " << filename);
5655 // If the file has been deleted, only mark the file as dirty since it is
5656 // pointless to prompt for reloading. If later a file is moved into this
5657 // location, then the externally modified warning will appear then.
5659 externally_modified_ = true;
5660 // Update external modification notification.
5661 // Dirty buffers must be visible at all times.
5662 if (wa_ && wa_->unhide(owner_))
5663 wa_->updateTitles();
5665 // Unable to unhide the buffer (e.g. no GUI or not current View)
5670 bool Buffer::notifiesExternalModification() const
5672 return d->externally_modified_;
5676 void Buffer::clearExternalModification() const
5678 d->externally_modified_ = false;
5680 d->wa_->updateTitles();