3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
59 #include "SpellChecker.h"
61 #include "texstream.h"
64 #include "TextClass.h"
65 #include "TocBackend.h"
67 #include "VCBackend.h"
69 #include "WordLangTuple.h"
72 #include "insets/InsetBibtex.h"
73 #include "insets/InsetBranch.h"
74 #include "insets/InsetInclude.h"
75 #include "insets/InsetTabular.h"
76 #include "insets/InsetText.h"
78 #include "mathed/InsetMathHull.h"
79 #include "mathed/MacroTable.h"
80 #include "mathed/InsetMathMacroTemplate.h"
81 #include "mathed/MathSupport.h"
83 #include "graphics/GraphicsCache.h"
84 #include "graphics/PreviewLoader.h"
86 #include "frontends/alert.h"
87 #include "frontends/Delegates.h"
88 #include "frontends/WorkAreaManager.h"
90 #include "support/lassert.h"
91 #include "support/convert.h"
92 #include "support/debug.h"
93 #include "support/docstring_list.h"
94 #include "support/ExceptionMessage.h"
95 #include "support/FileMonitor.h"
96 #include "support/FileName.h"
97 #include "support/FileNameList.h"
98 #include "support/filetools.h"
99 #include "support/ForkedCalls.h"
100 #include "support/gettext.h"
101 #include "support/gzstream.h"
102 #include "support/lstrings.h"
103 #include "support/lyxalgo.h"
104 #include "support/mutex.h"
105 #include "support/os.h"
106 #include "support/Package.h"
107 #include "support/PathChanger.h"
108 #include "support/Systemcall.h"
109 #include "support/TempFile.h"
110 #include "support/textutils.h"
111 #include "support/types.h"
113 #include "support/bind.h"
125 using namespace lyx::support;
126 using namespace lyx::graphics;
130 namespace Alert = frontend::Alert;
131 namespace os = support::os;
135 int const LYX_FORMAT = LYX_FORMAT_LYX;
137 typedef map<string, bool> DepClean;
138 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
143 // A storehouse for the cloned buffers.
144 list<CloneList *> cloned_buffers;
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
154 delete preview_loader_;
162 /// search for macro in local (buffer) table or in children
163 MacroData const * getBufferMacro(docstring const & name,
164 DocIterator const & pos) const;
166 /// Update macro table starting with position of it \param it in some
168 void updateMacros(DocIterator & it, DocIterator & scope);
170 void setLabel(ParIterator & it, UpdateType utype) const;
172 /** If we have branches that use the file suffix
173 feature, return the file name with suffix appended.
175 FileName exportFileName() const;
182 mutable TexRow texrow;
184 /// need to regenerate .tex?
188 mutable bool lyx_clean;
190 /// is autosave needed?
191 mutable bool bak_clean;
193 /// is this an unnamed file (New...)?
196 /// is this an internal bufffer?
197 bool internal_buffer;
202 /// name of the file the buffer is associated with.
205 /** Set to true only when the file is fully loaded.
206 * Used to prevent the premature generation of previews
207 * and by the citation inset.
209 bool file_fully_loaded;
211 /// original format of loaded file
214 /// if the file was originally loaded from an older format, do
215 /// we need to back it up still?
216 bool need_format_backup;
218 /// Ignore the parent (e.g. when exporting a child standalone)?
222 mutable TocBackend toc_backend;
227 ScopeMacro(DocIterator const & s, MacroData const & m)
228 : scope(s), macro(m) {}
232 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
233 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
234 /// map from the macro name to the position map,
235 /// which maps the macro definition position to the scope and the MacroData.
236 NamePositionScopeMacroMap macros;
237 /// This seem to change the way Buffer::getMacro() works
238 mutable bool macro_lock;
240 /// positions of child buffers in the buffer
241 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
243 ScopeBuffer() : buffer(0) {}
244 ScopeBuffer(DocIterator const & s, Buffer const * b)
245 : scope(s), buffer(b) {}
247 Buffer const * buffer;
249 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
250 /// position of children buffers in this buffer
251 BufferPositionMap children_positions;
252 /// map from children inclusion positions to their scope and their buffer
253 PositionScopeBufferMap position_to_children;
255 /// Contains the old buffer filePath() while saving-as, or the
256 /// directory where the document was last saved while loading.
259 /** Keeps track of the path of local layout files.
260 * If possible, it is always relative to the buffer path.
261 * Empty for layouts in system or user directory.
263 string layout_position;
265 /// Container for all sort of Buffer dependant errors.
266 map<string, ErrorList> errorLists;
268 /// checksum used to test if the file has been externally modified. Used to
269 /// double check whether the file had been externally modified when saving.
270 unsigned long checksum_;
273 frontend::WorkAreaManager * wa_;
275 frontend::GuiBufferDelegate * gui_;
280 /// A cache for the bibfiles (including bibfiles of loaded child
281 /// documents), needed for appropriate update of natbib labels.
282 mutable FileNamePairList bibfiles_cache_;
284 // FIXME The caching mechanism could be improved. At present, we have a
285 // cache for each Buffer, that caches all the bibliography info for that
286 // Buffer. A more efficient solution would be to have a global cache per
287 // file, and then to construct the Buffer's bibinfo from that.
288 /// A cache for bibliography info
289 mutable BiblioInfo bibinfo_;
290 /// whether the bibinfo cache is valid
291 mutable bool bibinfo_cache_valid_;
292 /// Cache of timestamps of .bib files
293 map<FileName, time_t> bibfile_status_;
294 /// Indicates whether the bibinfo has changed since the last time
295 /// we ran updateBuffer(), i.e., whether citation labels may need
297 mutable bool cite_labels_valid_;
299 /// These two hold the file name and format, written to by
300 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
301 FileName preview_file_;
302 string preview_format_;
303 /// If there was an error when previewing, on the next preview we do
304 /// a fresh compile (e.g. in case the user installed a package that
308 mutable RefCache ref_cache_;
310 /// our Text that should be wrapped in an InsetText
314 PreviewLoader * preview_loader_;
316 /// This is here to force the test to be done whenever parent_buffer
318 Buffer const * parent() const
320 // ignore_parent temporarily "orphans" a buffer
321 // (e.g. if a child is compiled standalone)
324 // if parent_buffer is not loaded, then it has been unloaded,
325 // which means that parent_buffer is an invalid pointer. So we
326 // set it to null in that case.
327 // however, the BufferList doesn't know about cloned buffers, so
328 // they will always be regarded as unloaded. in that case, we hope
330 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
332 return parent_buffer;
336 void setParent(Buffer const * pb)
338 if (parent_buffer == pb)
341 if (!cloned_buffer_ && parent_buffer && pb)
342 LYXERR0("Warning: a buffer should not have two parents!");
344 if (!cloned_buffer_ && parent_buffer)
345 parent_buffer->invalidateBibinfoCache();
348 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
349 /// This one is useful for preview detached in a thread.
350 Buffer const * cloned_buffer_;
352 CloneList * clone_list_;
353 /// are we in the process of exporting this buffer?
354 mutable bool doing_export;
356 /// compute statistics
357 /// \p from initial position
358 /// \p to points to the end position
359 void updateStatistics(DocIterator & from, DocIterator & to,
360 bool skipNoOutput = true);
361 /// statistics accessor functions
362 int wordCount() const
366 int charCount(bool with_blanks) const
369 + (with_blanks ? blank_count_ : 0);
372 // does the buffer contain tracked changes? (if so, we automatically
373 // display the review toolbar, for instance)
374 mutable bool tracked_changes_present_;
376 // Make sure the file monitor monitors the good file.
377 void refreshFileMonitor();
379 /// Notify or clear of external modification
380 void fileExternallyModified(bool exists);
382 /// has been externally modified? Can be reset by the user.
383 mutable bool externally_modified_;
386 /// So we can force access via the accessors.
387 mutable Buffer const * parent_buffer;
393 FileMonitorPtr file_monitor_;
397 /// Creates the per buffer temporary directory
398 static FileName createBufferTmpDir()
400 // FIXME This would be the ideal application for a TempDir class (like
401 // TempFile but for directories)
406 Mutex::Locker locker(&mutex);
407 counter = convert<string>(count++);
409 // We are in our own directory. Why bother to mangle name?
410 // In fact I wrote this code to circumvent a problematic behaviour
411 // (bug?) of EMX mkstemp().
412 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
415 if (!tmpfl.createDirectory(0777)) {
416 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
417 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
418 from_utf8(tmpfl.absFileName())));
424 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
425 Buffer const * cloned_buffer)
426 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
427 internal_buffer(false), read_only(readonly_), filename(file),
428 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
429 ignore_parent(false), toc_backend(owner), macro_lock(false),
430 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
431 cite_labels_valid_(false), preview_error_(false),
432 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
433 clone_list_(0), doing_export(false),
434 tracked_changes_present_(0), externally_modified_(false), parent_buffer(0),
435 word_count_(0), char_count_(0), blank_count_(0)
437 refreshFileMonitor();
438 if (!cloned_buffer_) {
439 temppath = createBufferTmpDir();
440 lyxvc.setBuffer(owner_);
442 wa_ = new frontend::WorkAreaManager;
445 temppath = cloned_buffer_->d->temppath;
446 file_fully_loaded = true;
447 params = cloned_buffer_->d->params;
448 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
449 bibinfo_ = cloned_buffer_->d->bibinfo_;
450 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
451 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
452 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
453 unnamed = cloned_buffer_->d->unnamed;
454 internal_buffer = cloned_buffer_->d->internal_buffer;
455 layout_position = cloned_buffer_->d->layout_position;
456 preview_file_ = cloned_buffer_->d->preview_file_;
457 preview_format_ = cloned_buffer_->d->preview_format_;
458 preview_error_ = cloned_buffer_->d->preview_error_;
459 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
463 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
464 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
466 LYXERR(Debug::INFO, "Buffer::Buffer()");
468 d->inset = new InsetText(*cloned_buffer->d->inset);
469 d->inset->setBuffer(*this);
470 // FIXME: optimize this loop somewhat, maybe by creating a new
471 // general recursive Inset::setId().
472 DocIterator it = doc_iterator_begin(this);
473 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
474 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
475 it.paragraph().setId(cloned_it.paragraph().id());
477 d->inset = new InsetText(this);
478 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
484 LYXERR(Debug::INFO, "Buffer::~Buffer()");
485 // here the buffer should take care that it is
486 // saved properly, before it goes into the void.
488 // GuiView already destroyed
492 // No need to do additional cleanups for internal buffer.
498 // this is in case of recursive includes: we won't try to delete
499 // ourselves as a child.
500 d->clone_list_->erase(this);
501 // loop over children
502 for (auto const & p : d->children_positions) {
503 Buffer * child = const_cast<Buffer *>(p.first);
504 if (d->clone_list_->erase(child))
507 // if we're the master buffer, then we should get rid of the list
510 // If this is not empty, we have leaked something. Worse, one of the
511 // children still has a reference to this list. But we will try to
512 // continue, rather than shut down.
513 LATTEST(d->clone_list_->empty());
514 list<CloneList *>::iterator it =
515 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
516 if (it == cloned_buffers.end()) {
517 // We will leak in this case, but it is safe to continue.
520 cloned_buffers.erase(it);
521 delete d->clone_list_;
523 // FIXME Do we really need to do this right before we delete d?
524 // clear references to children in macro tables
525 d->children_positions.clear();
526 d->position_to_children.clear();
528 // loop over children
529 for (auto const & p : d->children_positions) {
530 Buffer * child = const_cast<Buffer *>(p.first);
531 if (theBufferList().isLoaded(child)) {
532 if (theBufferList().isOthersChild(this, child))
535 theBufferList().release(child);
540 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
542 msg += emergencyWrite();
544 msg += " " + _("Save failed! Document is lost.");
546 Alert::warning(_("Attempting to close changed document!"), msg);
549 // FIXME Do we really need to do this right before we delete d?
550 // clear references to children in macro tables
551 d->children_positions.clear();
552 d->position_to_children.clear();
554 if (!d->temppath.destroyDirectory()) {
555 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
556 from_utf8(d->temppath.absFileName())));
565 Buffer * Buffer::cloneWithChildren() const
568 cloned_buffers.push_back(new CloneList);
569 CloneList * clones = cloned_buffers.back();
571 cloneWithChildren(bufmap, clones);
573 // make sure we got cloned
574 BufferMap::const_iterator bit = bufmap.find(this);
575 LASSERT(bit != bufmap.end(), return 0);
576 Buffer * cloned_buffer = bit->second;
578 return cloned_buffer;
582 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
584 // have we already been cloned?
585 if (bufmap.find(this) != bufmap.end())
588 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
590 // The clone needs its own DocumentClass, since running updateBuffer() will
591 // modify it, and we would otherwise be sharing it with the original Buffer.
592 buffer_clone->params().makeDocumentClass(true);
594 cap::switchBetweenClasses(
595 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
596 static_cast<InsetText &>(buffer_clone->inset()), el);
598 bufmap[this] = buffer_clone;
599 clones->insert(buffer_clone);
600 buffer_clone->d->clone_list_ = clones;
601 buffer_clone->d->macro_lock = true;
602 buffer_clone->d->children_positions.clear();
604 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
605 // math macro caches need to be rethought and simplified.
606 // I am not sure wether we should handle Buffer cloning here or in BufferList.
607 // Right now BufferList knows nothing about buffer clones.
608 for (auto const & p : d->position_to_children) {
609 DocIterator dit = p.first.clone(buffer_clone);
610 dit.setBuffer(buffer_clone);
611 Buffer * child = const_cast<Buffer *>(p.second.buffer);
613 child->cloneWithChildren(bufmap, clones);
614 BufferMap::iterator const bit = bufmap.find(child);
615 LASSERT(bit != bufmap.end(), continue);
616 Buffer * child_clone = bit->second;
618 Inset * inset = dit.nextInset();
619 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
620 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
621 inset_inc->setChildBuffer(child_clone);
622 child_clone->d->setParent(buffer_clone);
623 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
624 buffer_clone->setChild(dit, child_clone);
626 buffer_clone->d->macro_lock = false;
631 Buffer * Buffer::cloneBufferOnly() const {
632 cloned_buffers.push_back(new CloneList);
633 CloneList * clones = cloned_buffers.back();
634 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
636 // The clone needs its own DocumentClass, since running updateBuffer() will
637 // modify it, and we would otherwise be sharing it with the original Buffer.
638 buffer_clone->params().makeDocumentClass(true);
640 cap::switchBetweenClasses(
641 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
642 static_cast<InsetText &>(buffer_clone->inset()), el);
644 clones->insert(buffer_clone);
645 buffer_clone->d->clone_list_ = clones;
647 // we won't be cloning the children
648 buffer_clone->d->children_positions.clear();
653 bool Buffer::isClone() const
655 return d->cloned_buffer_;
659 void Buffer::changed(bool update_metrics) const
662 d->wa_->redrawAll(update_metrics);
666 frontend::WorkAreaManager & Buffer::workAreaManager() const
673 Text & Buffer::text() const
675 return d->inset->text();
679 Inset & Buffer::inset() const
685 BufferParams & Buffer::params()
691 BufferParams const & Buffer::params() const
697 BufferParams const & Buffer::masterParams() const
699 if (masterBuffer() == this)
702 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
703 // Copy child authors to the params. We need those pointers.
704 for (Author const & a : params().authors())
705 mparams.authors().record(a);
710 double Buffer::fontScalingFactor() const
712 return isExporting() ? 75.0 * params().html_math_img_scale
713 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
717 ParagraphList & Buffer::paragraphs()
719 return text().paragraphs();
723 ParagraphList const & Buffer::paragraphs() const
725 return text().paragraphs();
729 LyXVC & Buffer::lyxvc()
735 LyXVC const & Buffer::lyxvc() const
741 string const Buffer::temppath() const
743 return d->temppath.absFileName();
747 TexRow & Buffer::texrow()
753 TexRow const & Buffer::texrow() const
759 TocBackend & Buffer::tocBackend() const
761 return d->toc_backend;
765 Undo & Buffer::undo()
771 void Buffer::setChild(DocIterator const & dit, Buffer * child)
773 d->children_positions[child] = dit;
777 string Buffer::latexName(bool const no_path) const
779 FileName latex_name =
780 makeLatexName(d->exportFileName());
781 return no_path ? latex_name.onlyFileName()
782 : latex_name.absFileName();
786 FileName Buffer::Impl::exportFileName() const
788 docstring const branch_suffix =
789 params.branchlist().getFileNameSuffix();
790 if (branch_suffix.empty())
793 string const name = filename.onlyFileNameWithoutExt()
794 + to_utf8(branch_suffix);
795 FileName res(filename.onlyPath().absFileName() + "/" + name);
796 res.changeExtension(filename.extension());
802 string Buffer::logName(LogType * type) const
804 string const filename = latexName(false);
806 if (filename.empty()) {
812 string const path = temppath();
814 FileName const fname(addName(temppath(),
815 onlyFileName(changeExtension(filename,
818 // FIXME: how do we know this is the name of the build log?
819 FileName const bname(
820 addName(path, onlyFileName(
821 changeExtension(filename,
822 theFormats().extension(params().bufferFormat()) + ".out"))));
824 // Also consider the master buffer log file
825 FileName masterfname = fname;
826 LogType mtype = latexlog;
827 if (masterBuffer() != this) {
828 string const mlogfile = masterBuffer()->logName(&mtype);
829 masterfname = FileName(mlogfile);
832 // If no Latex log or Build log is newer, show Build log
833 if (bname.exists() &&
834 ((!fname.exists() && !masterfname.exists())
835 || (fname.lastModified() < bname.lastModified()
836 && masterfname.lastModified() < bname.lastModified()))) {
837 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
840 return bname.absFileName();
841 // If we have a newer master file log or only a master log, show this
842 } else if (fname != masterfname
843 && (!fname.exists() && (masterfname.exists()
844 || fname.lastModified() < masterfname.lastModified()))) {
845 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
848 return masterfname.absFileName();
850 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
853 return fname.absFileName();
857 void Buffer::setReadonly(bool const flag)
859 if (d->read_only != flag) {
866 void Buffer::setFileName(FileName const & fname)
868 bool const changed = fname != d->filename;
870 d->refreshFileMonitor();
872 lyxvc().file_found_hook(fname);
873 setReadonly(d->filename.isReadOnly());
879 int Buffer::readHeader(Lexer & lex)
881 int unknown_tokens = 0;
883 int begin_header_line = -1;
885 // Initialize parameters that may be/go lacking in header:
886 params().branchlist().clear();
887 params().preamble.erase();
888 params().options.erase();
889 params().master.erase();
890 params().float_placement.erase();
891 params().float_alignment.erase();
892 params().paperwidth.erase();
893 params().paperheight.erase();
894 params().leftmargin.erase();
895 params().rightmargin.erase();
896 params().topmargin.erase();
897 params().bottommargin.erase();
898 params().headheight.erase();
899 params().headsep.erase();
900 params().footskip.erase();
901 params().columnsep.erase();
902 params().fonts_cjk.erase();
903 params().listings_params.clear();
904 params().clearLayoutModules();
905 params().clearRemovedModules();
906 params().clearIncludedChildren();
907 params().pdfoptions().clear();
908 params().indiceslist().clear();
909 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
910 params().isbackgroundcolor = false;
911 params().fontcolor = RGBColor(0, 0, 0);
912 params().isfontcolor = false;
913 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
914 params().boxbgcolor = RGBColor(0xFF, 0, 0);
915 params().html_latex_start.clear();
916 params().html_latex_end.clear();
917 params().html_math_img_scale = 1.0;
918 params().output_sync_macro.erase();
919 params().setLocalLayout(docstring(), false);
920 params().setLocalLayout(docstring(), true);
921 params().biblio_opts.erase();
922 params().biblatex_bibstyle.erase();
923 params().biblatex_citestyle.erase();
924 params().multibib.erase();
926 for (int i = 0; i < 4; ++i) {
927 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
928 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
931 ErrorList & errorList = d->errorLists["Parse"];
940 if (token == "\\end_header")
944 if (token == "\\begin_header") {
945 begin_header_line = line;
949 LYXERR(Debug::PARSER, "Handling document header token: `"
952 string const result =
953 params().readToken(lex, token, d->filename.onlyPath());
954 if (!result.empty()) {
955 if (token == "\\textclass") {
956 d->layout_position = result;
959 docstring const s = bformat(_("Unknown token: "
963 errorList.push_back(ErrorItem(_("Document header error"), s));
967 if (begin_header_line) {
968 docstring const s = _("\\begin_header is missing");
969 errorList.push_back(ErrorItem(_("Document header error"), s));
972 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
974 params().makeDocumentClass();
976 return unknown_tokens;
981 // changed to be public and have one parameter
982 // Returns true if "\end_document" is not read (Asger)
983 bool Buffer::readDocument(Lexer & lex)
985 ErrorList & errorList = d->errorLists["Parse"];
988 // remove dummy empty par
989 paragraphs().clear();
991 if (!lex.checkFor("\\begin_document")) {
992 docstring const s = _("\\begin_document is missing");
993 errorList.push_back(ErrorItem(_("Document header error"), s));
998 if (params().output_changes) {
999 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1000 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1001 LaTeXFeatures::isAvailable("xcolor");
1003 if (!dvipost && !xcolorulem) {
1004 Alert::warning(_("Changes not shown in LaTeX output"),
1005 _("Changes will not be highlighted in LaTeX output, "
1006 "because neither dvipost nor xcolor/ulem are installed.\n"
1007 "Please install these packages or redefine "
1008 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1009 } else if (!xcolorulem) {
1010 Alert::warning(_("Changes not shown in LaTeX output"),
1011 _("Changes will not be highlighted in LaTeX output "
1012 "when using pdflatex, because xcolor and ulem are not installed.\n"
1013 "Please install both packages or redefine "
1014 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1018 if (!parent() && !params().master.empty()) {
1019 FileName const master_file = makeAbsPath(params().master,
1020 onlyPath(absFileName()));
1021 if (isLyXFileName(master_file.absFileName())) {
1023 checkAndLoadLyXFile(master_file, true);
1025 // necessary e.g. after a reload
1026 // to re-register the child (bug 5873)
1027 // FIXME: clean up updateMacros (here, only
1028 // child registering is needed).
1029 master->updateMacros();
1030 // set master as master buffer, but only
1031 // if we are a real child
1032 if (master->isChild(this))
1034 // if the master is not fully loaded
1035 // it is probably just loading this
1036 // child. No warning needed then.
1037 else if (master->isFullyLoaded())
1038 LYXERR0("The master '"
1040 << "' assigned to this document ("
1042 << ") does not include "
1043 "this document. Ignoring the master assignment.");
1048 // assure we have a default index
1049 params().indiceslist().addDefault(B_("Index"));
1052 if (FileName::isAbsolute(params().origin))
1053 d->old_position = params().origin;
1055 d->old_position = filePath();
1056 bool const res = text().read(lex, errorList, d->inset);
1057 d->old_position.clear();
1059 // inform parent buffer about local macros
1061 Buffer const * pbuf = parent();
1062 for (auto const & m : usermacros)
1063 pbuf->usermacros.insert(m);
1067 updateMacroInstances(InternalUpdate);
1072 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1074 Format const * fmt = theFormats().getFormat(format);
1077 // It is important to use the correct extension here, since some
1078 // converters create a wrong output file otherwise (e.g. html2latex)
1079 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1080 ofdocstream os(name.toFilesystemEncoding().c_str());
1081 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1082 bool const success = !(os << contents).fail();
1085 bool converted = false;
1087 params().compressed = false;
1089 // remove dummy empty par
1090 paragraphs().clear();
1092 converted = importFile(format, name, errorList);
1095 removeTempFile(name);
1100 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1102 if (!theConverters().isReachable(format, "lyx"))
1105 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1106 Converters::RetVal const retval =
1107 theConverters().convert(0, name, lyx, name, format, "lyx", errorList);
1108 if (retval == Converters::SUCCESS) {
1109 bool const success = readFile(lyx) == ReadSuccess;
1110 removeTempFile(lyx);
1118 bool Buffer::readString(string const & s)
1120 params().compressed = false;
1123 istringstream is(s);
1125 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1126 FileName const fn = tempfile.name();
1129 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1131 if (success && file_format != LYX_FORMAT) {
1132 // We need to call lyx2lyx, so write the input to a file
1133 ofstream os(fn.toFilesystemEncoding().c_str());
1136 // lyxvc in readFile
1137 if (readFile(fn) != ReadSuccess)
1141 if (readDocument(lex))
1147 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1151 if (!lex.setFile(fname)) {
1152 Alert::error(_("File Not Found"),
1153 bformat(_("Unable to open file `%1$s'."),
1154 from_utf8(fn.absFileName())));
1155 return ReadFileNotFound;
1159 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1160 if (ret_plf != ReadSuccess)
1163 if (file_format != LYX_FORMAT) {
1165 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1166 if (ret_clf != ReadSuccess)
1168 ret_clf = readFile(tmpFile);
1169 if (ret_clf == ReadSuccess) {
1170 d->file_format = file_format;
1171 d->need_format_backup = true;
1176 // FIXME: InsetInfo needs to know whether the file is under VCS
1177 // during the parse process, so this has to be done before.
1178 lyxvc().file_found_hook(d->filename);
1180 if (readDocument(lex)) {
1181 Alert::error(_("Document format failure"),
1182 bformat(_("%1$s ended unexpectedly, which means"
1183 " that it is probably corrupted."),
1184 from_utf8(fn.absFileName())));
1185 return ReadDocumentFailure;
1188 d->file_fully_loaded = true;
1189 d->read_only = !d->filename.isWritable();
1190 params().compressed = theFormats().isZippedFile(d->filename);
1196 bool Buffer::isFullyLoaded() const
1198 return d->file_fully_loaded;
1202 void Buffer::setFullyLoaded(bool value)
1204 d->file_fully_loaded = value;
1208 bool Buffer::lastPreviewError() const
1210 return d->preview_error_;
1214 PreviewLoader * Buffer::loader() const
1216 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1218 if (!d->preview_loader_)
1219 d->preview_loader_ = new PreviewLoader(*this);
1220 return d->preview_loader_;
1224 void Buffer::removePreviews() const
1226 delete d->preview_loader_;
1227 d->preview_loader_ = 0;
1231 void Buffer::updatePreviews() const
1233 PreviewLoader * ploader = loader();
1237 InsetIterator it = inset_iterator_begin(*d->inset);
1238 InsetIterator const end = inset_iterator_end(*d->inset);
1239 for (; it != end; ++it)
1240 it->addPreview(it, *ploader);
1242 ploader->startLoading();
1246 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1247 FileName const & fn, int & file_format) const
1249 if(!lex.checkFor("\\lyxformat")) {
1250 Alert::error(_("Document format failure"),
1251 bformat(_("%1$s is not a readable LyX document."),
1252 from_utf8(fn.absFileName())));
1253 return ReadNoLyXFormat;
1259 // LyX formats 217 and earlier were written as 2.17. This corresponds
1260 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1261 // these cases. See also: www.lyx.org/trac/changeset/1313.
1262 size_t dot = tmp_format.find_first_of(".,");
1263 if (dot != string::npos)
1264 tmp_format.erase(dot, 1);
1266 file_format = convert<int>(tmp_format);
1271 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1272 FileName & tmpfile, int from_format)
1274 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1275 tempfile.setAutoRemove(false);
1276 tmpfile = tempfile.name();
1277 if(tmpfile.empty()) {
1278 Alert::error(_("Conversion failed"),
1279 bformat(_("%1$s is from a different"
1280 " version of LyX, but a temporary"
1281 " file for converting it could"
1282 " not be created."),
1283 from_utf8(fn.absFileName())));
1284 return LyX2LyXNoTempFile;
1287 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1288 if (lyx2lyx.empty()) {
1289 Alert::error(_("Conversion script not found"),
1290 bformat(_("%1$s is from a different"
1291 " version of LyX, but the"
1292 " conversion script lyx2lyx"
1293 " could not be found."),
1294 from_utf8(fn.absFileName())));
1295 return LyX2LyXNotFound;
1299 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1300 ostringstream command;
1301 command << os::python()
1302 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1303 << " -t " << convert<string>(LYX_FORMAT)
1304 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1305 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1306 string const command_str = command.str();
1308 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1310 cmd_ret const ret = runCommand(command_str);
1311 if (ret.first != 0) {
1312 if (from_format < LYX_FORMAT) {
1313 Alert::error(_("Conversion script failed"),
1314 bformat(_("%1$s is from an older version"
1315 " of LyX and the lyx2lyx script"
1316 " failed to convert it."),
1317 from_utf8(fn.absFileName())));
1318 return LyX2LyXOlderFormat;
1320 Alert::error(_("Conversion script failed"),
1321 bformat(_("%1$s is from a newer version"
1322 " of LyX and the lyx2lyx script"
1323 " failed to convert it."),
1324 from_utf8(fn.absFileName())));
1325 return LyX2LyXNewerFormat;
1332 FileName Buffer::getBackupName() const {
1333 map<int, string> const file_formats = {
1350 FileName const & fn = fileName();
1351 string const fname = fn.onlyFileNameWithoutExt();
1352 string const fext = fn.extension() + "~";
1353 string const fpath = lyxrc.backupdir_path.empty() ?
1354 fn.onlyPath().absFileName() :
1355 lyxrc.backupdir_path;
1356 string backup_suffix;
1357 // If file format is from a stable series use version instead of file format
1358 auto const it = file_formats.find(d->file_format);
1359 if (it != file_formats.end())
1360 backup_suffix = "-lyx" + it->second;
1362 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1363 string const backname = fname + backup_suffix;
1364 FileName backup(addName(fpath, addExtension(backname, fext)));
1366 // limit recursion, just in case
1368 unsigned long orig_checksum = 0;
1369 while (backup.exists() && v < 100) {
1370 if (orig_checksum == 0)
1371 orig_checksum = fn.checksum();
1372 unsigned long new_checksum = backup.checksum();
1373 if (orig_checksum == new_checksum) {
1374 LYXERR(Debug::FILES, "Not backing up " << fn <<
1375 "since " << backup << "has the same checksum.");
1376 // a bit of a hack, but we have to check this anyway
1377 // below, and setting this is simpler than introducing
1378 // a special boolean for this purpose.
1382 string const newbackname = backname + "-" + convert<string>(v);
1383 backup.set(addName(fpath, addExtension(newbackname, fext)));
1386 return v < 100 ? backup : FileName();
1390 // Should probably be moved to somewhere else: BufferView? GuiView?
1391 bool Buffer::save() const
1393 docstring const file = makeDisplayPath(absFileName(), 20);
1394 d->filename.refresh();
1396 // check the read-only status before moving the file as a backup
1397 if (d->filename.exists()) {
1398 bool const read_only = !d->filename.isWritable();
1400 Alert::warning(_("File is read-only"),
1401 bformat(_("The file %1$s cannot be written because it "
1402 "is marked as read-only."), file));
1407 // ask if the disk file has been externally modified (use checksum method)
1408 if (fileName().exists() && isChecksumModified()) {
1410 bformat(_("Document %1$s has been externally modified. "
1411 "Are you sure you want to overwrite this file?"), file);
1412 int const ret = Alert::prompt(_("Overwrite modified file?"),
1413 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1418 // We don't need autosaves in the immediate future. (Asger)
1419 resetAutosaveTimers();
1421 // if the file does not yet exist, none of the backup activity
1422 // that follows is necessary
1423 if (!fileName().exists()) {
1424 if (!writeFile(fileName()))
1430 // we first write the file to a new name, then move it to its
1431 // proper location once that has been done successfully. that
1432 // way we preserve the original file if something goes wrong.
1433 string const justname = fileName().onlyFileNameWithoutExt();
1434 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1435 justname + "-XXXXXX.lyx");
1436 bool const symlink = fileName().isSymLink();
1438 tempfile->setAutoRemove(false);
1440 FileName savefile(tempfile->name());
1441 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1442 if (!writeFile(savefile))
1445 // we will set this to false if we fail
1446 bool made_backup = true;
1448 FileName backupName;
1449 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1451 if (d->need_format_backup)
1452 backupName = getBackupName();
1454 // If we for some reason failed to find a backup name in case of
1455 // a format change, this will still set one. It's the best we can
1457 if (backupName.empty()) {
1458 backupName.set(fileName().absFileName() + "~");
1459 if (!lyxrc.backupdir_path.empty()) {
1460 string const mangledName =
1461 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1462 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1466 LYXERR(Debug::FILES, "Backing up original file to " <<
1467 backupName.absFileName());
1468 // Except file is symlink do not copy because of #6587.
1469 // Hard links have bad luck.
1470 made_backup = symlink ?
1471 fileName().copyTo(backupName):
1472 fileName().moveTo(backupName);
1475 Alert::error(_("Backup failure"),
1476 bformat(_("Cannot create backup file %1$s.\n"
1477 "Please check whether the directory exists and is writable."),
1478 from_utf8(backupName.absFileName())));
1479 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1480 } else if (d->need_format_backup) {
1481 // the original file has been backed up successfully, so we
1482 // will not need to do that again
1483 d->need_format_backup = false;
1487 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1488 // Only do this if tempfile is not in autoremove mode
1491 // If we have no symlink, we can simply rename the temp file.
1492 // Otherwise, we need to copy it so the symlink stays intact.
1493 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1494 savefile.moveTo(fileName()))
1496 // saveCheckSum() was already called by writeFile(), but the
1497 // time stamp is invalidated by copying/moving
1500 if (d->file_format != LYX_FORMAT)
1501 // the file associated with this buffer is now in the current format
1502 d->file_format = LYX_FORMAT;
1505 // else we saved the file, but failed to move it to the right location.
1507 if (needBackup && made_backup && !symlink) {
1508 // the original file was moved to some new location, so it will look
1509 // to the user as if it was deleted. (see bug #9234.) we could try
1510 // to restore it, but that would basically mean trying to do again
1511 // what we just failed to do. better to leave things as they are.
1512 Alert::error(_("Write failure"),
1513 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1514 "But LyX could not move it to:\n %2$s.\n"
1515 "Your original file has been backed up to:\n %3$s"),
1516 from_utf8(savefile.absFileName()),
1517 from_utf8(fileName().absFileName()),
1518 from_utf8(backupName.absFileName())));
1520 // either we did not try to make a backup, or else we tried and failed,
1521 // or else the original file was a symlink, in which case it was copied,
1522 // not moved. so the original file is intact.
1523 Alert::error(_("Write failure"),
1524 bformat(_("Cannot move saved file to:\n %1$s.\n"
1525 "But the file has successfully been saved as:\n %2$s."),
1526 from_utf8(fileName().absFileName()),
1527 from_utf8(savefile.absFileName())));
1533 bool Buffer::writeFile(FileName const & fname) const
1535 if (d->read_only && fname == d->filename)
1538 bool retval = false;
1540 docstring const str = bformat(_("Saving document %1$s..."),
1541 makeDisplayPath(fname.absFileName()));
1544 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1546 if (params().compressed) {
1547 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1548 retval = ofs && write(ofs);
1550 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1551 retval = ofs && write(ofs);
1555 message(str + _(" could not write file!"));
1560 // removeAutosaveFile();
1563 message(str + _(" done."));
1569 docstring Buffer::emergencyWrite()
1571 // No need to save if the buffer has not changed.
1575 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1577 docstring user_message = bformat(
1578 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1580 // We try to save three places:
1581 // 1) Same place as document. Unless it is an unnamed doc.
1583 string s = absFileName();
1586 if (writeFile(FileName(s))) {
1588 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1589 return user_message;
1591 user_message += " " + _("Save failed! Trying again...\n");
1595 // 2) In HOME directory.
1596 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1598 lyxerr << ' ' << s << endl;
1599 if (writeFile(FileName(s))) {
1601 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1602 return user_message;
1605 user_message += " " + _("Save failed! Trying yet again...\n");
1607 // 3) In "/tmp" directory.
1608 // MakeAbsPath to prepend the current
1609 // drive letter on OS/2
1610 s = addName(package().temp_dir().absFileName(), absFileName());
1612 lyxerr << ' ' << s << endl;
1613 if (writeFile(FileName(s))) {
1615 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1616 return user_message;
1619 user_message += " " + _("Save failed! Document is lost.");
1622 return user_message;
1626 bool Buffer::write(ostream & ofs) const
1629 // Use the standard "C" locale for file output.
1630 ofs.imbue(locale::classic());
1633 // The top of the file should not be written by params().
1635 // write out a comment in the top of the file
1636 // Important: Keep the version formatting in sync with lyx2lyx and
1637 // tex2lyx (bug 7951)
1638 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1639 << " created this file. For more info see https://www.lyx.org/\n"
1640 << "\\lyxformat " << LYX_FORMAT << "\n"
1641 << "\\begin_document\n";
1643 /// For each author, set 'used' to true if there is a change
1644 /// by this author in the document; otherwise set it to 'false'.
1645 for (Author const & a : params().authors())
1648 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1649 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1650 for ( ; it != end; ++it)
1651 it->checkAuthors(params().authors());
1653 // now write out the buffer parameters.
1654 ofs << "\\begin_header\n";
1655 params().writeFile(ofs, this);
1656 ofs << "\\end_header\n";
1659 ofs << "\n\\begin_body\n";
1661 ofs << "\n\\end_body\n";
1663 // Write marker that shows file is complete
1664 ofs << "\\end_document" << endl;
1666 // Shouldn't really be needed....
1669 // how to check if close went ok?
1670 // Following is an attempt... (BE 20001011)
1672 // good() returns false if any error occurred, including some
1673 // formatting error.
1674 // bad() returns true if something bad happened in the buffer,
1675 // which should include file system full errors.
1680 lyxerr << "File was not closed properly." << endl;
1687 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1688 string const & original_path,
1689 OutputParams const & runparams_in,
1690 OutputWhat output) const
1692 OutputParams runparams = runparams_in;
1694 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1695 // Check here, because the "flavor" is not known in BufferParams::encoding()
1696 // (power users can override this safety measure selecting "utf8-plain").
1697 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1698 && (runparams.encoding->name() != "utf8-plain"))
1699 runparams.encoding = encodings.fromLyXName("ascii");
1701 string const encoding = runparams.encoding->iconvName();
1702 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1705 try { ofs.reset(encoding); }
1706 catch (iconv_codecvt_facet_exception const & e) {
1707 lyxerr << "Caught iconv exception: " << e.what() << endl;
1708 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1709 "verify that the support software for your encoding (%1$s) is "
1710 "properly installed"), from_ascii(encoding)));
1713 if (!openFileWrite(ofs, fname))
1716 ErrorList & errorList = d->errorLists["Export"];
1718 ExportStatus status = ExportSuccess;
1721 // make sure we are ready to export
1722 // this needs to be done before we validate
1723 // FIXME Do we need to do this all the time? I.e., in children
1724 // of a master we are exporting?
1726 updateMacroInstances(OutputUpdate);
1728 ExportStatus retval;
1730 retval = writeLaTeXSource(os, original_path, runparams, output);
1731 if (retval == ExportKilled)
1732 return ExportKilled;
1734 catch (EncodingException const & e) {
1735 docstring const failed(1, e.failed_char);
1737 oss << "0x" << hex << e.failed_char << dec;
1738 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1739 docstring msg = bformat(_("Uncodable character '%1$s'"
1740 " (code point %2$s)"),
1741 failed, from_utf8(oss.str()));
1742 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1743 "representable in specific verbatim contexts.\n"
1744 "Changing the document encoding to utf8 could help."),
1745 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1747 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1748 " (code point %2$s)"),
1749 failed, from_utf8(oss.str()));
1750 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1751 "representable in the chosen encoding.\n"
1752 "Changing the document encoding to utf8 could help."),
1753 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1755 status = ExportError;
1757 catch (iconv_codecvt_facet_exception const & e) {
1758 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1760 status = ExportError;
1762 catch (exception const & e) {
1763 errorList.push_back(ErrorItem(_("conversion failed"),
1765 lyxerr << e.what() << endl;
1766 status = ExportError;
1769 lyxerr << "Caught some really weird exception..." << endl;
1773 d->texrow = move(os.texrow());
1777 status = ExportError;
1778 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1781 if (runparams_in.silent)
1789 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1790 string const & original_path,
1791 OutputParams const & runparams_in,
1792 OutputWhat output) const
1794 // The child documents, if any, shall be already loaded at this point.
1796 OutputParams runparams = runparams_in;
1798 // XeTeX with TeX fonts is only safe with ASCII encoding,
1799 // Check here, because the "flavor" is not known in BufferParams::encoding()
1800 // (power users can override this safety measure selecting "utf8-plain").
1801 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1802 && (runparams.encoding->name() != "utf8-plain"))
1803 runparams.encoding = encodings.fromLyXName("ascii");
1804 // FIXME: when only the current paragraph is shown, this is ignored
1805 // (or not reached) and characters encodable in the current
1806 // encoding are not converted to ASCII-representation.
1808 // Some macros rely on font encoding
1809 runparams.main_fontenc = params().main_font_encoding();
1811 // If we are compiling a file standalone, even if this is the
1812 // child of some other buffer, let's cut the link here, so the
1813 // file is really independent and no concurring settings from
1814 // the master (e.g. branch state) interfere (see #8100).
1815 if (!runparams.is_child)
1816 d->ignore_parent = true;
1818 // Classify the unicode characters appearing in math insets
1819 BufferEncodings::initUnicodeMath(*this);
1821 // validate the buffer.
1822 LYXERR(Debug::LATEX, " Validating buffer...");
1823 LaTeXFeatures features(*this, params(), runparams);
1825 // This is only set once per document (in master)
1826 if (!runparams.is_child)
1827 runparams.use_polyglossia = features.usePolyglossia();
1828 LYXERR(Debug::LATEX, " Buffer validation done.");
1830 bool const output_preamble =
1831 output == FullSource || output == OnlyPreamble;
1832 bool const output_body =
1833 output == FullSource || output == OnlyBody;
1835 // The starting paragraph of the coming rows is the
1836 // first paragraph of the document. (Asger)
1837 if (output_preamble && runparams.nice) {
1838 os << "%% LyX " << lyx_version << " created this file. "
1839 "For more info, see https://www.lyx.org/.\n"
1840 "%% Do not edit unless you really know what "
1843 LYXERR(Debug::INFO, "lyx document header finished");
1845 // There are a few differences between nice LaTeX and usual files:
1846 // usual files have \batchmode and special input@path to allow
1847 // inclusion of figures specified by an explicitly relative path
1848 // (i.e., a path starting with './' or '../') with either \input or
1849 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1850 // input@path is set when the actual parameter original_path is set.
1851 // This is done for usual tex-file, but not for nice-latex-file.
1852 // (Matthias 250696)
1853 // Note that input@path is only needed for something the user does
1854 // in the preamble, included .tex files or ERT, files included by
1855 // LyX work without it.
1856 if (output_preamble) {
1857 if (!runparams.nice) {
1858 // code for usual, NOT nice-latex-file
1859 os << "\\batchmode\n"; // changed from \nonstopmode
1861 if (!original_path.empty()) {
1863 // We don't know the encoding of inputpath
1864 docstring const inputpath = from_utf8(original_path);
1865 docstring uncodable_glyphs;
1866 Encoding const * const enc = runparams.encoding;
1868 for (size_t n = 0; n < inputpath.size(); ++n) {
1869 if (!enc->encodable(inputpath[n])) {
1870 docstring const glyph(1, inputpath[n]);
1871 LYXERR0("Uncodable character '"
1873 << "' in input path!");
1874 uncodable_glyphs += glyph;
1879 // warn user if we found uncodable glyphs.
1880 if (!uncodable_glyphs.empty()) {
1881 frontend::Alert::warning(
1882 _("Uncodable character in file path"),
1884 _("The path of your document\n"
1886 "contains glyphs that are unknown "
1887 "in the current document encoding "
1888 "(namely %2$s). This may result in "
1889 "incomplete output, unless "
1890 "TEXINPUTS contains the document "
1891 "directory and you don't use "
1892 "explicitly relative paths (i.e., "
1893 "paths starting with './' or "
1894 "'../') in the preamble or in ERT."
1895 "\n\nIn case of problems, choose "
1896 "an appropriate document encoding\n"
1897 "(such as utf8) or change the "
1899 inputpath, uncodable_glyphs));
1902 latex_path(original_path);
1903 if (contains(docdir, '#')) {
1904 docdir = subst(docdir, "#", "\\#");
1905 os << "\\catcode`\\#=11"
1906 "\\def\\#{#}\\catcode`\\#=6\n";
1908 if (contains(docdir, '%')) {
1909 docdir = subst(docdir, "%", "\\%");
1910 os << "\\catcode`\\%=11"
1911 "\\def\\%{%}\\catcode`\\%=14\n";
1913 os << "\\makeatletter\n"
1914 << "\\def\\input@path{{"
1916 << "\\makeatother\n";
1920 // get parent macros (if this buffer has a parent) which will be
1921 // written at the document begin further down.
1922 MacroSet parentMacros;
1923 listParentMacros(parentMacros, features);
1925 // Write the preamble
1926 runparams.use_babel = params().writeLaTeX(os, features,
1927 d->filename.onlyPath());
1929 // Biblatex bibliographies are loaded here
1930 if (params().useBiblatex()) {
1931 vector<docstring> const bibfiles =
1932 prepareBibFilePaths(runparams, getBibfiles(), true);
1933 for (docstring const & file: bibfiles)
1934 os << "\\addbibresource{" << file << "}\n";
1937 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1938 && !features.hasOnlyPolyglossiaLanguages()) {
1941 vector<string> bll = features.getBabelExclusiveLanguages();
1942 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1945 for (string const & sit : bll) {
1950 blangs = bll.size() > 1 ?
1951 bformat(_("The languages %1$s are only supported by Babel."), langs)
1952 : bformat(_("The language %1$s is only supported by Babel."), langs);
1956 for (string const & pit : pll) {
1961 plangs = pll.size() > 1 ?
1962 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1963 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1964 if (!blangs.empty())
1968 frontend::Alert::warning(
1969 _("Incompatible Languages!"),
1971 _("You cannot use the following languages "
1972 "together in one LaTeX document because "
1973 "they require conflicting language packages:\n"
1978 // Japanese might be required only in some children of a document,
1979 // but once required, we must keep use_japanese true.
1980 runparams.use_japanese |= features.isRequired("japanese");
1983 // Restore the parenthood if needed
1984 if (!runparams.is_child)
1985 d->ignore_parent = false;
1986 return ExportSuccess;
1990 // mark the beginning of the body to separate it from InPreamble insets
1991 os.texrow().start(TexRow::beginDocument());
1992 os << "\\begin{document}\n";
1994 // mark the start of a new paragraph by simulating a newline,
1995 // so that os.afterParbreak() returns true at document start
1998 // output the parent macros
1999 for (auto const & mac : parentMacros) {
2000 int num_lines = mac->write(os.os(), true);
2001 os.texrow().newlines(num_lines);
2004 } // output_preamble
2006 LYXERR(Debug::INFO, "preamble finished, now the body.");
2010 latexParagraphs(*this, text(), os, runparams);
2012 catch (ConversionException const &) { return ExportKilled; }
2014 // Restore the parenthood if needed
2015 if (!runparams.is_child)
2016 d->ignore_parent = false;
2018 // add this just in case after all the paragraphs
2021 if (output_preamble) {
2022 os << "\\end{document}\n";
2023 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2025 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2027 runparams_in.encoding = runparams.encoding;
2029 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2030 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2031 return ExportSuccess;
2035 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2036 OutputParams const & runparams,
2037 OutputWhat output) const
2039 LYXERR(Debug::LATEX, "makeDocBookFile...");
2042 if (!openFileWrite(ofs, fname))
2045 // make sure we are ready to export
2046 // this needs to be done before we validate
2048 updateMacroInstances(OutputUpdate);
2050 ExportStatus const retval =
2051 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2052 if (retval == ExportKilled)
2053 return ExportKilled;
2057 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2058 return ExportSuccess;
2062 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os, string const & fname,
2063 OutputParams const & runparams,
2064 OutputWhat output) const
2066 LaTeXFeatures features(*this, params(), runparams);
2071 DocumentClass const & tclass = params().documentClass();
2072 string const & top_element = tclass.latexname();
2074 bool const output_preamble =
2075 output == FullSource || output == OnlyPreamble;
2076 bool const output_body =
2077 output == FullSource || output == OnlyBody;
2079 if (output_preamble) {
2080 if (runparams.flavor == OutputParams::XML)
2081 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2084 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2087 if (! tclass.class_header().empty())
2088 os << from_ascii(tclass.class_header());
2089 else if (runparams.flavor == OutputParams::XML)
2090 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2091 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2093 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2095 docstring preamble = params().preamble;
2096 if (runparams.flavor != OutputParams::XML ) {
2097 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2098 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2099 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2100 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2103 string const name = runparams.nice
2104 ? changeExtension(absFileName(), ".sgml") : fname;
2105 preamble += features.getIncludedFiles(name);
2106 preamble += features.getLyXSGMLEntities();
2108 if (!preamble.empty()) {
2109 os << "\n [ " << preamble << " ]";
2115 string top = top_element;
2117 if (runparams.flavor == OutputParams::XML)
2118 top += params().language->code();
2120 top += params().language->code().substr(0, 2);
2123 if (!params().options.empty()) {
2125 top += params().options;
2128 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2129 << " file was created by LyX " << lyx_version
2130 << "\n See https://www.lyx.org/ for more information -->\n";
2132 params().documentClass().counters().reset();
2134 sgml::openTag(os, top);
2137 docbookParagraphs(text(), *this, os, runparams);
2139 catch (ConversionException const &) { return ExportKilled; }
2140 sgml::closeTag(os, top_element);
2142 return ExportSuccess;
2146 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2147 OutputParams const & runparams) const
2149 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2152 if (!openFileWrite(ofs, fname))
2155 // make sure we are ready to export
2156 // this has to be done before we validate
2157 updateBuffer(UpdateMaster, OutputUpdate);
2158 updateMacroInstances(OutputUpdate);
2160 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2161 if (retval == ExportKilled)
2166 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2171 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2172 OutputParams const & runparams,
2173 OutputWhat output) const
2175 LaTeXFeatures features(*this, params(), runparams);
2177 d->bibinfo_.makeCitationLabels(*this);
2179 bool const output_preamble =
2180 output == FullSource || output == OnlyPreamble;
2181 bool const output_body =
2182 output == FullSource || output == OnlyBody || output == IncludedFile;
2184 if (output_preamble) {
2185 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2186 << "<!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"
2187 // FIXME Language should be set properly.
2188 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2190 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2191 // FIXME Presumably need to set this right
2192 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2194 docstring const & doctitle = features.htmlTitle();
2196 << (doctitle.empty() ?
2197 from_ascii("LyX Document") :
2198 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2201 docstring styles = features.getTClassHTMLPreamble();
2202 if (!styles.empty())
2203 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2205 styles = features.getPreambleSnippets().str;
2206 if (!styles.empty())
2207 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2209 // we will collect CSS information in a stream, and then output it
2210 // either here, as part of the header, or else in a separate file.
2211 odocstringstream css;
2212 styles = features.getCSSSnippets();
2213 if (!styles.empty())
2214 css << "/* LyX Provided Styles */\n" << styles << '\n';
2216 styles = features.getTClassHTMLStyles();
2217 if (!styles.empty())
2218 css << "/* Layout-provided Styles */\n" << styles << '\n';
2220 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2221 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2222 if (needfg || needbg) {
2223 css << "\nbody {\n";
2226 << from_ascii(X11hexname(params().fontcolor))
2229 css << " background-color: "
2230 << from_ascii(X11hexname(params().backgroundcolor))
2235 docstring const dstyles = css.str();
2236 if (!dstyles.empty()) {
2237 bool written = false;
2238 if (params().html_css_as_file) {
2239 // open a file for CSS info
2241 string const fcssname = addName(temppath(), "docstyle.css");
2242 FileName const fcssfile = FileName(fcssname);
2243 if (openFileWrite(ocss, fcssfile)) {
2247 // write link to header
2248 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2250 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2253 // we are here if the CSS is supposed to be written to the header
2254 // or if we failed to write it to an external file.
2256 os << "<style type='text/css'>\n"
2265 bool const output_body_tag = (output != IncludedFile);
2266 if (output_body_tag)
2267 os << "<body dir=\"auto\">\n";
2269 if (output != IncludedFile)
2270 // if we're an included file, the counters are in the master.
2271 params().documentClass().counters().reset();
2273 xhtmlParagraphs(text(), *this, xs, runparams);
2275 catch (ConversionException const &) { return ExportKilled; }
2276 if (output_body_tag)
2280 if (output_preamble)
2283 return ExportSuccess;
2287 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2288 // Other flags: -wall -v0 -x
2289 int Buffer::runChktex()
2293 // get LaTeX-Filename
2294 FileName const path(temppath());
2295 string const name = addName(path.absFileName(), latexName());
2296 string const org_path = filePath();
2298 PathChanger p(path); // path to LaTeX file
2299 message(_("Running chktex..."));
2301 // Generate the LaTeX file if neccessary
2302 OutputParams runparams(¶ms().encoding());
2303 runparams.flavor = OutputParams::LATEX;
2304 runparams.nice = false;
2305 runparams.linelen = lyxrc.plaintext_linelen;
2306 ExportStatus const retval =
2307 makeLaTeXFile(FileName(name), org_path, runparams);
2308 if (retval != ExportSuccess) {
2309 // error code on failure
2314 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2315 int const res = chktex.run(terr); // run chktex
2318 Alert::error(_("chktex failure"),
2319 _("Could not run chktex successfully."));
2321 ErrorList & errlist = d->errorLists["ChkTeX"];
2323 bufferErrors(terr, errlist);
2328 if (runparams.silent)
2329 d->errorLists["ChkTeX"].clear();
2337 void Buffer::validate(LaTeXFeatures & features) const
2339 // Validate the buffer params, but not for included
2340 // files, since they also use the parent buffer's
2342 if (!features.runparams().is_child)
2343 params().validate(features);
2345 for (Paragraph const & p : paragraphs())
2346 p.validate(features);
2348 if (lyxerr.debugging(Debug::LATEX)) {
2349 features.showStruct();
2354 void Buffer::getLabelList(vector<docstring> & list) const
2356 // If this is a child document, use the master's list instead.
2358 masterBuffer()->getLabelList(list);
2363 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2364 for (auto const & tocit : *toc) {
2365 if (tocit.depth() == 0)
2366 list.push_back(tocit.str());
2371 void Buffer::invalidateBibinfoCache() const
2373 d->bibinfo_cache_valid_ = false;
2374 d->cite_labels_valid_ = false;
2375 removeBiblioTempFiles();
2376 // also invalidate the cache for the parent buffer
2377 Buffer const * const pbuf = d->parent();
2379 pbuf->invalidateBibinfoCache();
2383 FileNamePairList const & Buffer::getBibfiles(UpdateScope scope) const
2385 // FIXME This is probably unnecessary, given where we call this.
2386 // If this is a child document, use the master instead.
2387 Buffer const * const pbuf = masterBuffer();
2388 if (pbuf != this && scope != UpdateChildOnly)
2389 return pbuf->getBibfiles();
2390 return d->bibfiles_cache_;
2394 BiblioInfo const & Buffer::masterBibInfo() const
2396 Buffer const * const tmp = masterBuffer();
2398 return tmp->masterBibInfo();
2403 BiblioInfo const & Buffer::bibInfo() const
2409 void Buffer::registerBibfiles(FileNamePairList const & bf) const {
2410 // We register the bib files in the master buffer,
2411 // if there is one, but also in every single buffer,
2412 // in case a child is compiled alone.
2413 Buffer const * const tmp = masterBuffer();
2415 tmp->registerBibfiles(bf);
2417 for (auto const & p : bf) {
2418 FileNamePairList::const_iterator temp =
2419 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2420 if (temp == d->bibfiles_cache_.end())
2421 d->bibfiles_cache_.push_back(p);
2426 void Buffer::checkIfBibInfoCacheIsValid() const
2428 // use the master's cache
2429 Buffer const * const tmp = masterBuffer();
2431 tmp->checkIfBibInfoCacheIsValid();
2435 // if we already know the cache is invalid, no need to check
2437 if (!d->bibinfo_cache_valid_)
2440 // compare the cached timestamps with the actual ones.
2441 FileNamePairList const & bibfiles_cache = getBibfiles();
2442 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2443 FileNamePairList::const_iterator en = bibfiles_cache.end();
2444 for (; ei != en; ++ ei) {
2445 FileName const fn = ei->second;
2446 time_t lastw = fn.lastModified();
2447 time_t prevw = d->bibfile_status_[fn];
2448 if (lastw != prevw) {
2449 d->bibinfo_cache_valid_ = false;
2450 d->cite_labels_valid_ = false;
2451 d->bibfile_status_[fn] = lastw;
2457 void Buffer::reloadBibInfoCache() const
2459 // use the master's cache
2460 Buffer const * const tmp = masterBuffer();
2462 tmp->reloadBibInfoCache();
2466 checkIfBibInfoCacheIsValid();
2467 if (d->bibinfo_cache_valid_)
2470 d->bibinfo_.clear();
2471 FileNameList checkedFiles;
2472 collectBibKeys(checkedFiles);
2473 d->bibinfo_cache_valid_ = true;
2477 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2479 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2480 it->collectBibKeys(it, checkedFiles);
2484 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2486 // We add the biblio info to the master buffer,
2487 // if there is one, but also to every single buffer,
2488 // in case a child is compiled alone.
2489 BiblioInfo & bi = d->bibinfo_;
2490 bi.mergeBiblioInfo(bin);
2492 if (parent() != 0) {
2493 BiblioInfo & masterbi = parent()->d->bibinfo_;
2494 masterbi.mergeBiblioInfo(bin);
2499 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2501 // We add the bibtex info to the master buffer,
2502 // if there is one, but also to every single buffer,
2503 // in case a child is compiled alone.
2504 BiblioInfo & bi = d->bibinfo_;
2507 if (parent() != 0) {
2508 BiblioInfo & masterbi = parent()->d->bibinfo_;
2509 masterbi[key] = bin;
2514 void Buffer::makeCitationLabels() const
2516 Buffer const * const master = masterBuffer();
2517 return d->bibinfo_.makeCitationLabels(*master);
2521 void Buffer::invalidateCiteLabels() const
2523 masterBuffer()->d->cite_labels_valid_ = false;
2526 bool Buffer::citeLabelsValid() const
2528 return masterBuffer()->d->cite_labels_valid_;
2532 void Buffer::removeBiblioTempFiles() const
2534 // We remove files that contain LaTeX commands specific to the
2535 // particular bibliographic style being used, in order to avoid
2536 // LaTeX errors when we switch style.
2537 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2538 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2539 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2540 aux_file.removeFile();
2541 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2542 bbl_file.removeFile();
2543 // Also for the parent buffer
2544 Buffer const * const pbuf = parent();
2546 pbuf->removeBiblioTempFiles();
2550 bool Buffer::isDepClean(string const & name) const
2552 DepClean::const_iterator const it = d->dep_clean.find(name);
2553 if (it == d->dep_clean.end())
2559 void Buffer::markDepClean(string const & name)
2561 d->dep_clean[name] = true;
2565 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2568 // FIXME? if there is an Buffer LFUN that can be dispatched even
2569 // if internal, put a switch '(cmd.action)' here.
2575 switch (cmd.action()) {
2577 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2578 flag.setOnOff(hasReadonlyFlag());
2581 // FIXME: There is need for a command-line import.
2582 //case LFUN_BUFFER_IMPORT:
2584 case LFUN_BUFFER_AUTO_SAVE:
2587 case LFUN_BUFFER_EXPORT_CUSTOM:
2588 // FIXME: Nothing to check here?
2591 case LFUN_BUFFER_EXPORT: {
2592 docstring const arg = cmd.argument();
2593 if (arg == "custom") {
2597 string format = (arg.empty() || arg == "default") ?
2598 params().getDefaultOutputFormat() : to_utf8(arg);
2599 size_t pos = format.find(' ');
2600 if (pos != string::npos)
2601 format = format.substr(0, pos);
2602 enable = params().isExportable(format, false);
2604 flag.message(bformat(
2605 _("Don't know how to export to format: %1$s"), arg));
2609 case LFUN_BUILD_PROGRAM:
2610 enable = params().isExportable("program", false);
2613 case LFUN_BRANCH_ACTIVATE:
2614 case LFUN_BRANCH_DEACTIVATE:
2615 case LFUN_BRANCH_MASTER_ACTIVATE:
2616 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2617 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2618 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2619 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2620 : params().branchlist();
2621 docstring const branchName = cmd.argument();
2622 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2626 case LFUN_BRANCH_ADD:
2627 case LFUN_BRANCHES_RENAME:
2628 // if no Buffer is present, then of course we won't be called!
2631 case LFUN_BUFFER_LANGUAGE:
2632 enable = !isReadonly();
2635 case LFUN_BUFFER_VIEW_CACHE:
2636 (d->preview_file_).refresh();
2637 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2640 case LFUN_CHANGES_TRACK:
2641 flag.setEnabled(true);
2642 flag.setOnOff(params().track_changes);
2645 case LFUN_CHANGES_OUTPUT:
2646 flag.setEnabled(true);
2647 flag.setOnOff(params().output_changes);
2650 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2651 flag.setOnOff(params().compressed);
2654 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2655 flag.setOnOff(params().output_sync);
2658 case LFUN_BUFFER_ANONYMIZE:
2664 flag.setEnabled(enable);
2669 void Buffer::dispatch(string const & command, DispatchResult & result)
2671 return dispatch(lyxaction.lookupFunc(command), result);
2675 // NOTE We can end up here even if we have no GUI, because we are called
2676 // by LyX::exec to handled command-line requests. So we may need to check
2677 // whether we have a GUI or not. The boolean use_gui holds this information.
2678 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2681 // FIXME? if there is an Buffer LFUN that can be dispatched even
2682 // if internal, put a switch '(cmd.action())' here.
2683 dr.dispatched(false);
2686 string const argument = to_utf8(func.argument());
2687 // We'll set this back to false if need be.
2688 bool dispatched = true;
2689 // This handles undo groups automagically
2690 UndoGroupHelper ugh(this);
2692 switch (func.action()) {
2693 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2694 if (lyxvc().inUse()) {
2695 string log = lyxvc().toggleReadOnly();
2700 setReadonly(!hasReadonlyFlag());
2703 case LFUN_BUFFER_EXPORT: {
2704 string const format = (argument.empty() || argument == "default") ?
2705 params().getDefaultOutputFormat() : argument;
2706 ExportStatus const status = doExport(format, false);
2707 dr.setError(status != ExportSuccess);
2708 if (status != ExportSuccess)
2709 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2710 from_utf8(format)));
2714 case LFUN_BUILD_PROGRAM: {
2715 ExportStatus const status = doExport("program", true);
2716 dr.setError(status != ExportSuccess);
2717 if (status != ExportSuccess)
2718 dr.setMessage(_("Error generating literate programming code."));
2722 case LFUN_BUFFER_EXPORT_CUSTOM: {
2724 string command = split(argument, format_name, ' ');
2725 Format const * format = theFormats().getFormat(format_name);
2727 lyxerr << "Format \"" << format_name
2728 << "\" not recognized!"
2733 // The name of the file created by the conversion process
2736 // Output to filename
2737 if (format->name() == "lyx") {
2738 string const latexname = latexName(false);
2739 filename = changeExtension(latexname,
2740 format->extension());
2741 filename = addName(temppath(), filename);
2743 if (!writeFile(FileName(filename)))
2747 doExport(format_name, true, filename);
2750 // Substitute $$FName for filename
2751 if (!contains(command, "$$FName"))
2752 command = "( " + command + " ) < $$FName";
2753 command = subst(command, "$$FName", filename);
2755 // Execute the command in the background
2757 call.startscript(Systemcall::DontWait, command,
2758 filePath(), layoutPos());
2762 // FIXME: There is need for a command-line import.
2764 case LFUN_BUFFER_IMPORT:
2769 case LFUN_BUFFER_AUTO_SAVE:
2771 resetAutosaveTimers();
2774 case LFUN_BRANCH_ACTIVATE:
2775 case LFUN_BRANCH_DEACTIVATE:
2776 case LFUN_BRANCH_MASTER_ACTIVATE:
2777 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2778 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2779 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2780 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2783 docstring const branch_name = func.argument();
2784 // the case without a branch name is handled elsewhere
2785 if (branch_name.empty()) {
2789 Branch * branch = buf->params().branchlist().find(branch_name);
2791 LYXERR0("Branch " << branch_name << " does not exist.");
2793 docstring const msg =
2794 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2798 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2799 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2800 if (branch->isSelected() != activate) {
2801 buf->undo().recordUndoBufferParams(CursorData());
2802 branch->setSelected(activate);
2804 dr.screenUpdate(Update::Force);
2805 dr.forceBufferUpdate();
2810 case LFUN_BRANCH_ADD: {
2811 docstring branchnames = func.argument();
2812 if (branchnames.empty()) {
2816 BranchList & branch_list = params().branchlist();
2817 vector<docstring> const branches =
2818 getVectorFromString(branchnames, branch_list.separator());
2820 for (docstring const & branch_name : branches) {
2821 Branch * branch = branch_list.find(branch_name);
2823 LYXERR0("Branch " << branch_name << " already exists.");
2827 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2829 undo().recordUndoBufferParams(CursorData());
2830 branch_list.add(branch_name);
2831 branch = branch_list.find(branch_name);
2832 string const x11hexname = X11hexname(branch->color());
2833 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2834 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2836 dr.screenUpdate(Update::Force);
2844 case LFUN_BRANCHES_RENAME: {
2845 if (func.argument().empty())
2848 docstring const oldname = from_utf8(func.getArg(0));
2849 docstring const newname = from_utf8(func.getArg(1));
2850 InsetIterator it = inset_iterator_begin(inset());
2851 InsetIterator const end = inset_iterator_end(inset());
2852 bool success = false;
2853 for (; it != end; ++it) {
2854 if (it->lyxCode() == BRANCH_CODE) {
2855 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2856 if (ins.branch() == oldname) {
2857 undo().recordUndo(CursorData(it));
2858 ins.rename(newname);
2863 if (it->lyxCode() == INCLUDE_CODE) {
2864 // get buffer of external file
2865 InsetInclude const & ins =
2866 static_cast<InsetInclude const &>(*it);
2867 Buffer * child = ins.getChildBuffer();
2870 child->dispatch(func, dr);
2875 dr.screenUpdate(Update::Force);
2876 dr.forceBufferUpdate();
2881 case LFUN_BUFFER_VIEW_CACHE:
2882 if (!theFormats().view(*this, d->preview_file_,
2883 d->preview_format_))
2884 dr.setMessage(_("Error viewing the output file."));
2887 case LFUN_CHANGES_TRACK:
2888 if (params().save_transient_properties)
2889 undo().recordUndoBufferParams(CursorData());
2890 params().track_changes = !params().track_changes;
2891 if (!params().track_changes)
2892 dr.forceChangesUpdate();
2895 case LFUN_CHANGES_OUTPUT:
2896 if (params().save_transient_properties)
2897 undo().recordUndoBufferParams(CursorData());
2898 params().output_changes = !params().output_changes;
2899 if (params().output_changes) {
2900 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2901 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2902 LaTeXFeatures::isAvailable("xcolor");
2904 if (!dvipost && !xcolorulem) {
2905 Alert::warning(_("Changes not shown in LaTeX output"),
2906 _("Changes will not be highlighted in LaTeX output, "
2907 "because neither dvipost nor xcolor/ulem are installed.\n"
2908 "Please install these packages or redefine "
2909 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2910 } else if (!xcolorulem) {
2911 Alert::warning(_("Changes not shown in LaTeX output"),
2912 _("Changes will not be highlighted in LaTeX output "
2913 "when using pdflatex, because xcolor and ulem are not installed.\n"
2914 "Please install both packages or redefine "
2915 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2920 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2921 // turn compression on/off
2922 undo().recordUndoBufferParams(CursorData());
2923 params().compressed = !params().compressed;
2926 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2927 undo().recordUndoBufferParams(CursorData());
2928 params().output_sync = !params().output_sync;
2931 case LFUN_BUFFER_ANONYMIZE: {
2932 undo().recordUndoFullBuffer(CursorData());
2933 CursorData cur(doc_iterator_begin(this));
2934 for ( ; cur ; cur.forwardPar())
2935 cur.paragraph().anonymize();
2936 dr.forceBufferUpdate();
2944 dr.dispatched(dispatched);
2948 void Buffer::changeLanguage(Language const * from, Language const * to)
2950 LASSERT(from, return);
2951 LASSERT(to, return);
2953 for_each(par_iterator_begin(),
2955 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2959 bool Buffer::isMultiLingual() const
2961 ParConstIterator end = par_iterator_end();
2962 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2963 if (it->isMultiLingual(params()))
2970 std::set<Language const *> Buffer::getLanguages() const
2972 std::set<Language const *> langs;
2973 getLanguages(langs);
2978 void Buffer::getLanguages(std::set<Language const *> & langs) const
2980 ParConstIterator end = par_iterator_end();
2981 // add the buffer language, even if it's not actively used
2982 langs.insert(language());
2983 // iterate over the paragraphs
2984 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2985 it->getLanguages(langs);
2987 ListOfBuffers clist = getDescendents();
2988 for (auto const & cit : clist)
2989 cit->getLanguages(langs);
2993 DocIterator Buffer::getParFromID(int const id) const
2995 Buffer * buf = const_cast<Buffer *>(this);
2997 // This means non-existent
2998 return doc_iterator_end(buf);
3000 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3001 if (it.paragraph().id() == id)
3004 return doc_iterator_end(buf);
3008 bool Buffer::hasParWithID(int const id) const
3010 return !getParFromID(id).atEnd();
3014 ParIterator Buffer::par_iterator_begin()
3016 return ParIterator(doc_iterator_begin(this));
3020 ParIterator Buffer::par_iterator_end()
3022 return ParIterator(doc_iterator_end(this));
3026 ParConstIterator Buffer::par_iterator_begin() const
3028 return ParConstIterator(doc_iterator_begin(this));
3032 ParConstIterator Buffer::par_iterator_end() const
3034 return ParConstIterator(doc_iterator_end(this));
3038 Language const * Buffer::language() const
3040 return params().language;
3044 docstring const Buffer::B_(string const & l10n) const
3046 return params().B_(l10n);
3050 bool Buffer::isClean() const
3052 return d->lyx_clean;
3056 bool Buffer::isChecksumModified() const
3058 LASSERT(d->filename.exists(), return false);
3059 return d->checksum_ != d->filename.checksum();
3063 void Buffer::saveCheckSum() const
3065 FileName const & file = d->filename;
3067 d->checksum_ = file.exists() ? file.checksum()
3068 : 0; // in the case of save to a new file.
3072 void Buffer::markClean() const
3074 if (!d->lyx_clean) {
3075 d->lyx_clean = true;
3078 // if the .lyx file has been saved, we don't need an
3080 d->bak_clean = true;
3081 d->undo_.markDirty();
3082 clearExternalModification();
3086 void Buffer::setUnnamed(bool flag)
3092 bool Buffer::isUnnamed() const
3099 /// Don't check unnamed, here: isInternal() is used in
3100 /// newBuffer(), where the unnamed flag has not been set by anyone
3101 /// yet. Also, for an internal buffer, there should be no need for
3102 /// retrieving fileName() nor for checking if it is unnamed or not.
3103 bool Buffer::isInternal() const
3105 return d->internal_buffer;
3109 void Buffer::setInternal(bool flag)
3111 d->internal_buffer = flag;
3115 void Buffer::markDirty()
3118 d->lyx_clean = false;
3121 d->bak_clean = false;
3123 for (auto & depit : d->dep_clean)
3124 depit.second = false;
3128 FileName Buffer::fileName() const
3134 string Buffer::absFileName() const
3136 return d->filename.absFileName();
3140 string Buffer::filePath() const
3142 string const abs = d->filename.onlyPath().absFileName();
3145 int last = abs.length() - 1;
3147 return abs[last] == '/' ? abs : abs + '/';
3151 DocFileName Buffer::getReferencedFileName(string const & fn) const
3154 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3155 result.set(fn, filePath());
3157 // filePath() ends with a path separator
3158 FileName const test(filePath() + fn);
3160 result.set(fn, filePath());
3162 result.set(fn, params().origin);
3169 string const Buffer::prepareFileNameForLaTeX(string const & name,
3170 string const & ext, bool nice) const
3172 string const fname = makeAbsPath(name, filePath()).absFileName();
3173 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3179 return to_utf8(makeRelPath(from_utf8(fname),
3180 from_utf8(masterBuffer()->filePath())));
3184 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3185 FileNamePairList const bibfilelist,
3186 bool const add_extension) const
3188 // If we are processing the LaTeX file in a temp directory then
3189 // copy the .bib databases to this temp directory, mangling their
3190 // names in the process. Store this mangled name in the list of
3192 // (We need to do all this because BibTeX *really*, *really*
3193 // can't handle "files with spaces" and Windows users tend to
3194 // use such filenames.)
3195 // Otherwise, store the (maybe absolute) path to the original,
3196 // unmangled database name.
3198 vector<docstring> res;
3200 // determine the export format
3201 string const tex_format = flavor2format(runparams.flavor);
3203 // check for spaces in paths
3204 bool found_space = false;
3206 for (auto const & bit : bibfilelist) {
3207 string utf8input = to_utf8(bit.first);
3209 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3210 FileName try_in_file =
3211 makeAbsPath(database + ".bib", filePath());
3212 bool not_from_texmf = try_in_file.isReadableFile();
3213 // If the file has not been found, try with the real file name
3214 // (it might come from a child in a sub-directory)
3215 if (!not_from_texmf) {
3216 try_in_file = bit.second;
3217 if (try_in_file.isReadableFile()) {
3218 // Check if the file is in texmf
3219 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3220 not_from_texmf = kpsefile.empty()
3221 || kpsefile.absFileName() != try_in_file.absFileName();
3223 // If this exists, make path relative to the master
3226 removeExtension(prepareFileNameForLaTeX(
3227 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3228 from_utf8(filePath()))),
3229 ".bib", runparams.nice));
3233 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3235 // mangledFileName() needs the extension
3236 DocFileName const in_file = DocFileName(try_in_file);
3237 database = removeExtension(in_file.mangledFileName());
3238 FileName const out_file = makeAbsPath(database + ".bib",
3239 masterBuffer()->temppath());
3240 bool const success = in_file.copyTo(out_file);
3242 LYXERR0("Failed to copy '" << in_file
3243 << "' to '" << out_file << "'");
3245 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3246 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3247 if (!isValidLaTeXFileName(database)) {
3248 frontend::Alert::warning(_("Invalid filename"),
3249 _("The following filename will cause troubles "
3250 "when running the exported file through LaTeX: ") +
3251 from_utf8(database));
3253 if (!isValidDVIFileName(database)) {
3254 frontend::Alert::warning(_("Problematic filename for DVI"),
3255 _("The following filename can cause troubles "
3256 "when running the exported file through LaTeX "
3257 "and opening the resulting DVI: ") +
3258 from_utf8(database), true);
3266 docstring const path = from_utf8(latex_path(database));
3268 if (contains(path, ' '))
3271 if (find(res.begin(), res.end(), path) == res.end())
3272 res.push_back(path);
3275 // Check if there are spaces in the path and warn BibTeX users, if so.
3276 // (biber can cope with such paths)
3277 if (!prefixIs(runparams.bibtex_command, "biber")) {
3278 // Post this warning only once.
3279 static bool warned_about_spaces = false;
3280 if (!warned_about_spaces &&
3281 runparams.nice && found_space) {
3282 warned_about_spaces = true;
3283 Alert::warning(_("Export Warning!"),
3284 _("There are spaces in the paths to your BibTeX databases.\n"
3285 "BibTeX will be unable to find them."));
3294 string Buffer::layoutPos() const
3296 return d->layout_position;
3300 void Buffer::setLayoutPos(string const & path)
3303 d->layout_position.clear();
3307 LATTEST(FileName::isAbsolute(path));
3309 d->layout_position =
3310 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3312 if (d->layout_position.empty())
3313 d->layout_position = ".";
3317 bool Buffer::hasReadonlyFlag() const
3319 return d->read_only;
3323 bool Buffer::isReadonly() const
3325 return hasReadonlyFlag() || notifiesExternalModification();
3329 void Buffer::setParent(Buffer const * buffer)
3331 // Avoids recursive include.
3332 d->setParent(buffer == this ? 0 : buffer);
3337 Buffer const * Buffer::parent() const
3343 ListOfBuffers Buffer::allRelatives() const
3345 ListOfBuffers lb = masterBuffer()->getDescendents();
3346 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3351 Buffer const * Buffer::masterBuffer() const
3353 // FIXME Should be make sure we are not in some kind
3354 // of recursive include? A -> B -> A will crash this.
3355 Buffer const * const pbuf = d->parent();
3359 return pbuf->masterBuffer();
3363 bool Buffer::isChild(Buffer * child) const
3365 return d->children_positions.find(child) != d->children_positions.end();
3369 DocIterator Buffer::firstChildPosition(Buffer const * child)
3371 Impl::BufferPositionMap::iterator it;
3372 it = d->children_positions.find(child);
3373 if (it == d->children_positions.end())
3374 return DocIterator(this);
3379 bool Buffer::hasChildren() const
3381 return !d->children_positions.empty();
3385 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3387 // loop over children
3388 for (auto const & p : d->children_positions) {
3389 Buffer * child = const_cast<Buffer *>(p.first);
3391 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3392 if (bit != clist.end())
3394 clist.push_back(child);
3396 // there might be grandchildren
3397 child->collectChildren(clist, true);
3402 ListOfBuffers Buffer::getChildren() const
3405 collectChildren(v, false);
3406 // Make sure we have not included ourselves.
3407 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3408 if (bit != v.end()) {
3409 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3416 ListOfBuffers Buffer::getDescendents() const
3419 collectChildren(v, true);
3420 // Make sure we have not included ourselves.
3421 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3422 if (bit != v.end()) {
3423 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3430 template<typename M>
3431 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3436 typename M::const_iterator it = m.lower_bound(x);
3437 if (it == m.begin())
3445 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3446 DocIterator const & pos) const
3448 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3450 // if paragraphs have no macro context set, pos will be empty
3454 // we haven't found anything yet
3455 DocIterator bestPos = owner_->par_iterator_begin();
3456 MacroData const * bestData = 0;
3458 // find macro definitions for name
3459 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3460 if (nameIt != macros.end()) {
3461 // find last definition in front of pos or at pos itself
3462 PositionScopeMacroMap::const_iterator it
3463 = greatest_below(nameIt->second, pos);
3464 if (it != nameIt->second.end()) {
3466 // scope ends behind pos?
3467 if (pos < it->second.scope) {
3468 // Looks good, remember this. If there
3469 // is no external macro behind this,
3470 // we found the right one already.
3471 bestPos = it->first;
3472 bestData = &it->second.macro;
3476 // try previous macro if there is one
3477 if (it == nameIt->second.begin())
3484 // find macros in included files
3485 PositionScopeBufferMap::const_iterator it
3486 = greatest_below(position_to_children, pos);
3487 if (it == position_to_children.end())
3488 // no children before
3492 // do we know something better (i.e. later) already?
3493 if (it->first < bestPos )
3496 // scope ends behind pos?
3497 if (pos < it->second.scope
3498 && (cloned_buffer_ ||
3499 theBufferList().isLoaded(it->second.buffer))) {
3500 // look for macro in external file
3502 MacroData const * data
3503 = it->second.buffer->getMacro(name, false);
3506 bestPos = it->first;
3512 // try previous file if there is one
3513 if (it == position_to_children.begin())
3518 // return the best macro we have found
3523 MacroData const * Buffer::getMacro(docstring const & name,
3524 DocIterator const & pos, bool global) const
3529 // query buffer macros
3530 MacroData const * data = d->getBufferMacro(name, pos);
3534 // If there is a master buffer, query that
3535 Buffer const * const pbuf = d->parent();
3537 d->macro_lock = true;
3538 MacroData const * macro = pbuf->getMacro(
3539 name, *this, false);
3540 d->macro_lock = false;
3546 data = MacroTable::globalMacros().get(name);
3555 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3557 // set scope end behind the last paragraph
3558 DocIterator scope = par_iterator_begin();
3559 scope.pit() = scope.lastpit() + 1;
3561 return getMacro(name, scope, global);
3565 MacroData const * Buffer::getMacro(docstring const & name,
3566 Buffer const & child, bool global) const
3568 // look where the child buffer is included first
3569 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3570 if (it == d->children_positions.end())
3573 // check for macros at the inclusion position
3574 return getMacro(name, it->second, global);
3578 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3580 pit_type const lastpit = it.lastpit();
3582 // look for macros in each paragraph
3583 while (it.pit() <= lastpit) {
3584 Paragraph & par = it.paragraph();
3586 // FIXME Can this be done with the new-style iterators?
3587 // iterate over the insets of the current paragraph
3588 for (auto const & insit : par.insetList()) {
3589 it.pos() = insit.pos;
3591 // is it a nested text inset?
3592 if (insit.inset->asInsetText()) {
3593 // Inset needs its own scope?
3594 InsetText const * itext = insit.inset->asInsetText();
3595 bool newScope = itext->isMacroScope();
3597 // scope which ends just behind the inset
3598 DocIterator insetScope = it;
3601 // collect macros in inset
3602 it.push_back(CursorSlice(*insit.inset));
3603 updateMacros(it, newScope ? insetScope : scope);
3608 if (insit.inset->asInsetTabular()) {
3609 CursorSlice slice(*insit.inset);
3610 size_t const numcells = slice.nargs();
3611 for (; slice.idx() < numcells; slice.forwardIdx()) {
3612 it.push_back(slice);
3613 updateMacros(it, scope);
3619 // is it an external file?
3620 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3621 // get buffer of external file
3622 InsetInclude const & incinset =
3623 static_cast<InsetInclude const &>(*insit.inset);
3625 Buffer * child = incinset.getChildBuffer();
3630 // register its position, but only when it is
3631 // included first in the buffer
3632 if (children_positions.find(child) ==
3633 children_positions.end())
3634 children_positions[child] = it;
3636 // register child with its scope
3637 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3641 InsetMath * im = insit.inset->asInsetMath();
3642 if (doing_export && im) {
3643 InsetMathHull * hull = im->asHullInset();
3645 hull->recordLocation(it);
3648 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3652 InsetMathMacroTemplate & macroTemplate =
3653 *insit.inset->asInsetMath()->asMacroTemplate();
3654 MacroContext mc(owner_, it);
3655 macroTemplate.updateToContext(mc);
3658 bool valid = macroTemplate.validMacro();
3659 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3660 // then the BufferView's cursor will be invalid in
3661 // some cases which leads to crashes.
3666 // FIXME (Abdel), I don't understand why we pass 'it' here
3667 // instead of 'macroTemplate' defined above... is this correct?
3668 macros[macroTemplate.name()][it] =
3669 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3679 void Buffer::updateMacros() const
3684 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3686 // start with empty table
3688 d->children_positions.clear();
3689 d->position_to_children.clear();
3691 // Iterate over buffer, starting with first paragraph
3692 // The scope must be bigger than any lookup DocIterator
3693 // later. For the global lookup, lastpit+1 is used, hence
3694 // we use lastpit+2 here.
3695 DocIterator it = par_iterator_begin();
3696 DocIterator outerScope = it;
3697 outerScope.pit() = outerScope.lastpit() + 2;
3698 d->updateMacros(it, outerScope);
3702 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3704 InsetIterator it = inset_iterator_begin(inset());
3705 InsetIterator const end = inset_iterator_end(inset());
3706 for (; it != end; ++it) {
3707 if (it->lyxCode() == BRANCH_CODE) {
3708 InsetBranch & br = static_cast<InsetBranch &>(*it);
3709 docstring const name = br.branch();
3710 if (!from_master && !params().branchlist().find(name))
3711 result.push_back(name);
3712 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3713 result.push_back(name);
3716 if (it->lyxCode() == INCLUDE_CODE) {
3717 // get buffer of external file
3718 InsetInclude const & ins =
3719 static_cast<InsetInclude const &>(*it);
3720 Buffer * child = ins.getChildBuffer();
3723 child->getUsedBranches(result, true);
3726 // remove duplicates
3731 void Buffer::updateMacroInstances(UpdateType utype) const
3733 LYXERR(Debug::MACROS, "updateMacroInstances for "
3734 << d->filename.onlyFileName());
3735 DocIterator it = doc_iterator_begin(this);
3737 DocIterator const end = doc_iterator_end(this);
3738 for (; it != end; it.forwardInset()) {
3739 // look for MathData cells in InsetMathNest insets
3740 InsetMath * minset = it.nextInset()->asInsetMath();
3744 // update macro in all cells of the InsetMathNest
3745 DocIterator::idx_type n = minset->nargs();
3746 MacroContext mc = MacroContext(this, it);
3747 for (DocIterator::idx_type i = 0; i < n; ++i) {
3748 MathData & data = minset->cell(i);
3749 data.updateMacros(0, mc, utype, 0);
3755 void Buffer::listMacroNames(MacroNameSet & macros) const
3760 d->macro_lock = true;
3762 // loop over macro names
3763 for (auto const & nameit : d->macros)
3764 macros.insert(nameit.first);
3766 // loop over children
3767 for (auto const & p : d->children_positions) {
3768 Buffer * child = const_cast<Buffer *>(p.first);
3769 // The buffer might have been closed (see #10766).
3770 if (theBufferList().isLoaded(child))
3771 child->listMacroNames(macros);
3775 Buffer const * const pbuf = d->parent();
3777 pbuf->listMacroNames(macros);
3779 d->macro_lock = false;
3783 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3785 Buffer const * const pbuf = d->parent();
3790 pbuf->listMacroNames(names);
3793 for (auto const & mit : names) {
3795 MacroData const * data = pbuf->getMacro(mit, *this, false);
3797 macros.insert(data);
3799 // we cannot access the original InsetMathMacroTemplate anymore
3800 // here to calls validate method. So we do its work here manually.
3801 // FIXME: somehow make the template accessible here.
3802 if (data->optionals() > 0)
3803 features.require("xargs");
3809 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3812 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3814 RefCache::iterator it = d->ref_cache_.find(label);
3815 if (it != d->ref_cache_.end())
3816 return it->second.second;
3818 static InsetLabel const * dummy_il = 0;
3819 static References const dummy_refs = References();
3820 it = d->ref_cache_.insert(
3821 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3822 return it->second.second;
3826 Buffer::References const & Buffer::references(docstring const & label) const
3828 return const_cast<Buffer *>(this)->getReferenceCache(label);
3832 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3834 References & refs = getReferenceCache(label);
3835 refs.push_back(make_pair(inset, it));
3839 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3841 masterBuffer()->d->ref_cache_[label].first = il;
3845 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3847 return masterBuffer()->d->ref_cache_[label].first;
3851 void Buffer::clearReferenceCache() const
3854 d->ref_cache_.clear();
3858 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3860 //FIXME: This does not work for child documents yet.
3861 reloadBibInfoCache();
3863 // Check if the label 'from' appears more than once
3864 vector<docstring> labels;
3865 for (auto const & bibit : masterBibInfo())
3866 labels.push_back(bibit.first);
3868 if (count(labels.begin(), labels.end(), from) > 1)
3871 string const paramName = "key";
3872 InsetIterator it = inset_iterator_begin(inset());
3874 if (it->lyxCode() != CITE_CODE)
3876 InsetCommand * inset = it->asInsetCommand();
3877 docstring const oldValue = inset->getParam(paramName);
3878 if (oldValue == from)
3879 inset->setParam(paramName, to);
3883 // returns NULL if id-to-row conversion is unsupported
3884 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3885 pit_type par_begin, pit_type par_end,
3886 OutputWhat output, bool master) const
3888 unique_ptr<TexRow> texrow;
3889 OutputParams runparams(¶ms().encoding());
3890 runparams.nice = true;
3891 runparams.flavor = params().getOutputFlavor(format);
3892 runparams.linelen = lyxrc.plaintext_linelen;
3893 // No side effect of file copying and image conversion
3894 runparams.dryrun = true;
3896 // Some macros rely on font encoding
3897 runparams.main_fontenc = params().main_font_encoding();
3899 if (output == CurrentParagraph) {
3900 runparams.par_begin = par_begin;
3901 runparams.par_end = par_end;
3902 if (par_begin + 1 == par_end) {
3904 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3908 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3909 convert<docstring>(par_begin),
3910 convert<docstring>(par_end - 1))
3913 // output paragraphs
3914 if (runparams.flavor == OutputParams::LYX) {
3915 Paragraph const & par = text().paragraphs()[par_begin];
3917 depth_type dt = par.getDepth();
3918 par.write(ods, params(), dt);
3919 os << from_utf8(ods.str());
3920 } else if (runparams.flavor == OutputParams::HTML) {
3922 setMathFlavor(runparams);
3923 xhtmlParagraphs(text(), *this, xs, runparams);
3924 } else if (runparams.flavor == OutputParams::TEXT) {
3926 // FIXME Handles only one paragraph, unlike the others.
3927 // Probably should have some routine with a signature like them.
3928 writePlaintextParagraph(*this,
3929 text().paragraphs()[par_begin], os, runparams, dummy);
3930 } else if (params().isDocBook()) {
3931 docbookParagraphs(text(), *this, os, runparams);
3933 // If we are previewing a paragraph, even if this is the
3934 // child of some other buffer, let's cut the link here,
3935 // so that no concurring settings from the master
3936 // (e.g. branch state) interfere (see #8101).
3938 d->ignore_parent = true;
3939 // We need to validate the Buffer params' features here
3940 // in order to know if we should output polyglossia
3941 // macros (instead of babel macros)
3942 LaTeXFeatures features(*this, params(), runparams);
3944 runparams.use_polyglossia = features.usePolyglossia();
3945 // latex or literate
3948 ots.texrow().newlines(2);
3950 latexParagraphs(*this, text(), ots, runparams);
3951 texrow = ots.releaseTexRow();
3953 // Restore the parenthood
3955 d->ignore_parent = false;
3959 if (output == FullSource)
3960 os << _("Preview source code");
3961 else if (output == OnlyPreamble)
3962 os << _("Preview preamble");
3963 else if (output == OnlyBody)
3964 os << _("Preview body");
3966 if (runparams.flavor == OutputParams::LYX) {
3968 if (output == FullSource)
3970 else if (output == OnlyPreamble)
3971 params().writeFile(ods, this);
3972 else if (output == OnlyBody)
3974 os << from_utf8(ods.str());
3975 } else if (runparams.flavor == OutputParams::HTML) {
3976 writeLyXHTMLSource(os, runparams, output);
3977 } else if (runparams.flavor == OutputParams::TEXT) {
3978 if (output == OnlyPreamble) {
3979 os << "% "<< _("Plain text does not have a preamble.");
3981 writePlaintextFile(*this, os, runparams);
3982 } else if (params().isDocBook()) {
3983 writeDocBookSource(os, absFileName(), runparams, output);
3985 // latex or literate
3988 ots.texrow().newlines(2);
3990 runparams.is_child = true;
3992 writeLaTeXSource(ots, string(), runparams, output);
3993 texrow = ots.releaseTexRow();
4000 ErrorList & Buffer::errorList(string const & type) const
4002 return d->errorLists[type];
4006 void Buffer::updateTocItem(std::string const & type,
4007 DocIterator const & dit) const
4010 d->gui_->updateTocItem(type, dit);
4014 void Buffer::structureChanged() const
4017 d->gui_->structureChanged();
4021 void Buffer::errors(string const & err, bool from_master) const
4024 d->gui_->errors(err, from_master);
4028 void Buffer::message(docstring const & msg) const
4031 d->gui_->message(msg);
4035 void Buffer::setBusy(bool on) const
4038 d->gui_->setBusy(on);
4042 void Buffer::updateTitles() const
4045 d->wa_->updateTitles();
4049 void Buffer::resetAutosaveTimers() const
4052 d->gui_->resetAutosaveTimers();
4056 bool Buffer::hasGuiDelegate() const
4062 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4071 class AutoSaveBuffer : public ForkedProcess {
4074 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4075 : buffer_(buffer), fname_(fname) {}
4077 virtual shared_ptr<ForkedProcess> clone() const
4079 return make_shared<AutoSaveBuffer>(*this);
4084 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4085 from_utf8(fname_.absFileName())));
4086 return run(DontWait);
4090 virtual int generateChild();
4092 Buffer const & buffer_;
4097 int AutoSaveBuffer::generateChild()
4099 #if defined(__APPLE__)
4100 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4101 * We should use something else like threads.
4103 * Since I do not know how to determine at run time what is the OS X
4104 * version, I just disable forking altogether for now (JMarc)
4106 pid_t const pid = -1;
4108 // tmp_ret will be located (usually) in /tmp
4109 // will that be a problem?
4110 // Note that this calls ForkedCalls::fork(), so it's
4111 // ok cross-platform.
4112 pid_t const pid = fork();
4113 // If you want to debug the autosave
4114 // you should set pid to -1, and comment out the fork.
4115 if (pid != 0 && pid != -1)
4119 // pid = -1 signifies that lyx was unable
4120 // to fork. But we will do the save
4122 bool failed = false;
4123 TempFile tempfile("lyxautoXXXXXX.lyx");
4124 tempfile.setAutoRemove(false);
4125 FileName const tmp_ret = tempfile.name();
4126 if (!tmp_ret.empty()) {
4127 if (!buffer_.writeFile(tmp_ret))
4129 else if (!tmp_ret.moveTo(fname_))
4135 // failed to write/rename tmp_ret so try writing direct
4136 if (!buffer_.writeFile(fname_)) {
4137 // It is dangerous to do this in the child,
4138 // but safe in the parent, so...
4139 if (pid == -1) // emit message signal.
4140 buffer_.message(_("Autosave failed!"));
4144 if (pid == 0) // we are the child so...
4153 FileName Buffer::getEmergencyFileName() const
4155 return FileName(d->filename.absFileName() + ".emergency");
4159 FileName Buffer::getAutosaveFileName() const
4161 // if the document is unnamed try to save in the backup dir, else
4162 // in the default document path, and as a last try in the filePath,
4163 // which will most often be the temporary directory
4166 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4167 : lyxrc.backupdir_path;
4168 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4171 string const fname = "#" + d->filename.onlyFileName() + "#";
4173 return makeAbsPath(fname, fpath);
4177 void Buffer::removeAutosaveFile() const
4179 FileName const f = getAutosaveFileName();
4185 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4187 FileName const newauto = getAutosaveFileName();
4189 if (newauto != oldauto && oldauto.exists())
4190 if (!oldauto.moveTo(newauto))
4191 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4195 bool Buffer::autoSave() const
4197 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4198 if (buf->d->bak_clean || hasReadonlyFlag())
4201 message(_("Autosaving current document..."));
4202 buf->d->bak_clean = true;
4204 FileName const fname = getAutosaveFileName();
4205 LASSERT(d->cloned_buffer_, return false);
4207 // If this buffer is cloned, we assume that
4208 // we are running in a separate thread already.
4209 TempFile tempfile("lyxautoXXXXXX.lyx");
4210 tempfile.setAutoRemove(false);
4211 FileName const tmp_ret = tempfile.name();
4212 if (!tmp_ret.empty()) {
4214 // assume successful write of tmp_ret
4215 if (tmp_ret.moveTo(fname))
4218 // failed to write/rename tmp_ret so try writing direct
4219 return writeFile(fname);
4223 void Buffer::setExportStatus(bool e) const
4225 d->doing_export = e;
4226 ListOfBuffers clist = getDescendents();
4227 for (auto const & bit : clist)
4228 bit->d->doing_export = e;
4232 bool Buffer::isExporting() const
4234 return d->doing_export;
4238 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4242 return doExport(target, put_in_tempdir, result_file);
4245 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4246 string & result_file) const
4248 bool const update_unincluded =
4249 params().maintain_unincluded_children
4250 && !params().getIncludedChildren().empty();
4252 // (1) export with all included children (omit \includeonly)
4253 if (update_unincluded) {
4254 ExportStatus const status =
4255 doExport(target, put_in_tempdir, true, result_file);
4256 if (status != ExportSuccess)
4259 // (2) export with included children only
4260 return doExport(target, put_in_tempdir, false, result_file);
4264 void Buffer::setMathFlavor(OutputParams & op) const
4266 switch (params().html_math_output) {
4267 case BufferParams::MathML:
4268 op.math_flavor = OutputParams::MathAsMathML;
4270 case BufferParams::HTML:
4271 op.math_flavor = OutputParams::MathAsHTML;
4273 case BufferParams::Images:
4274 op.math_flavor = OutputParams::MathAsImages;
4276 case BufferParams::LaTeX:
4277 op.math_flavor = OutputParams::MathAsLaTeX;
4283 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4284 bool includeall, string & result_file) const
4286 LYXERR(Debug::FILES, "target=" << target);
4287 OutputParams runparams(¶ms().encoding());
4288 string format = target;
4289 string dest_filename;
4290 size_t pos = target.find(' ');
4291 if (pos != string::npos) {
4292 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4293 format = target.substr(0, pos);
4294 if (format == "default")
4295 format = params().getDefaultOutputFormat();
4296 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4297 FileName(dest_filename).onlyPath().createPath();
4298 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4300 MarkAsExporting exporting(this);
4301 string backend_format;
4302 runparams.flavor = OutputParams::LATEX;
4303 runparams.linelen = lyxrc.plaintext_linelen;
4304 runparams.includeall = includeall;
4305 vector<string> backs = params().backends();
4306 Converters converters = theConverters();
4307 bool need_nice_file = false;
4308 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4309 // Get shortest path to format
4310 converters.buildGraph();
4311 Graph::EdgePath path;
4312 for (string const & sit : backs) {
4313 Graph::EdgePath p = converters.getPath(sit, format);
4314 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4315 backend_format = sit;
4320 if (!put_in_tempdir) {
4321 // Only show this alert if this is an export to a non-temporary
4322 // file (not for previewing).
4323 Alert::error(_("Couldn't export file"), bformat(
4324 _("No information for exporting the format %1$s."),
4325 theFormats().prettyName(format)));
4327 return ExportNoPathToFormat;
4329 runparams.flavor = converters.getFlavor(path, this);
4330 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4331 for (auto const & edge : path)
4332 if (theConverters().get(edge).nice()) {
4333 need_nice_file = true;
4338 backend_format = format;
4339 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4340 // FIXME: Don't hardcode format names here, but use a flag
4341 if (backend_format == "pdflatex")
4342 runparams.flavor = OutputParams::PDFLATEX;
4343 else if (backend_format == "luatex")
4344 runparams.flavor = OutputParams::LUATEX;
4345 else if (backend_format == "dviluatex")
4346 runparams.flavor = OutputParams::DVILUATEX;
4347 else if (backend_format == "xetex")
4348 runparams.flavor = OutputParams::XETEX;
4351 string filename = latexName(false);
4352 filename = addName(temppath(), filename);
4353 filename = changeExtension(filename,
4354 theFormats().extension(backend_format));
4355 LYXERR(Debug::FILES, "filename=" << filename);
4357 // Plain text backend
4358 if (backend_format == "text") {
4359 runparams.flavor = OutputParams::TEXT;
4361 writePlaintextFile(*this, FileName(filename), runparams);
4363 catch (ConversionException const &) { return ExportCancel; }
4366 else if (backend_format == "xhtml") {
4367 runparams.flavor = OutputParams::HTML;
4368 setMathFlavor(runparams);
4369 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4370 return ExportKilled;
4371 } else if (backend_format == "lyx")
4372 writeFile(FileName(filename));
4374 else if (params().isDocBook()) {
4375 runparams.nice = !put_in_tempdir;
4376 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4377 return ExportKilled;
4380 else if (backend_format == format || need_nice_file) {
4381 runparams.nice = true;
4382 ExportStatus const retval =
4383 makeLaTeXFile(FileName(filename), string(), runparams);
4384 if (retval == ExportKilled)
4385 return ExportKilled;
4386 if (d->cloned_buffer_)
4387 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4388 if (retval != ExportSuccess)
4390 } else if (!lyxrc.tex_allows_spaces
4391 && contains(filePath(), ' ')) {
4392 Alert::error(_("File name error"),
4393 bformat(_("The directory path to the document\n%1$s\n"
4394 "contains spaces, but your TeX installation does "
4395 "not allow them. You should save the file to a directory "
4396 "whose name does not contain spaces."), from_ascii(filePath())));
4397 return ExportTexPathHasSpaces;
4399 runparams.nice = false;
4400 ExportStatus const retval =
4401 makeLaTeXFile(FileName(filename), filePath(), runparams);
4402 if (retval == ExportKilled)
4403 return ExportKilled;
4404 if (d->cloned_buffer_)
4405 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4406 if (retval != ExportSuccess)
4410 string const error_type = (format == "program")
4411 ? "Build" : params().bufferFormat();
4412 ErrorList & error_list = d->errorLists[error_type];
4413 string const ext = theFormats().extension(format);
4414 FileName const tmp_result_file(changeExtension(filename, ext));
4415 Converters::RetVal const retval =
4416 converters.convert(this, FileName(filename), tmp_result_file,
4417 FileName(absFileName()), backend_format, format, error_list);
4418 if (retval == Converters::KILLED)
4419 return ExportCancel;
4420 bool success = (retval == Converters::SUCCESS);
4422 // Emit the signal to show the error list or copy it back to the
4423 // cloned Buffer so that it can be emitted afterwards.
4424 if (format != backend_format) {
4425 if (runparams.silent)
4427 else if (d->cloned_buffer_)
4428 d->cloned_buffer_->d->errorLists[error_type] =
4429 d->errorLists[error_type];
4432 // also to the children, in case of master-buffer-view
4433 ListOfBuffers clist = getDescendents();
4434 for (auto const & bit : clist) {
4435 if (runparams.silent)
4436 bit->d->errorLists[error_type].clear();
4437 else if (d->cloned_buffer_) {
4438 // Enable reverse search by copying back the
4439 // texrow object to the cloned buffer.
4440 // FIXME: this is not thread safe.
4441 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4442 bit->d->cloned_buffer_->d->errorLists[error_type] =
4443 bit->d->errorLists[error_type];
4445 bit->errors(error_type, true);
4449 if (d->cloned_buffer_) {
4450 // Enable reverse dvi or pdf to work by copying back the texrow
4451 // object to the cloned buffer.
4452 // FIXME: There is a possibility of concurrent access to texrow
4453 // here from the main GUI thread that should be securized.
4454 d->cloned_buffer_->d->texrow = d->texrow;
4455 string const err_type = params().bufferFormat();
4456 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4460 if (put_in_tempdir) {
4461 result_file = tmp_result_file.absFileName();
4462 return success ? ExportSuccess : ExportConverterError;
4465 if (dest_filename.empty())
4466 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4468 result_file = dest_filename;
4469 // We need to copy referenced files (e. g. included graphics
4470 // if format == "dvi") to the result dir.
4471 vector<ExportedFile> const files =
4472 runparams.exportdata->externalFiles(format);
4473 string const dest = runparams.export_folder.empty() ?
4474 onlyPath(result_file) : runparams.export_folder;
4475 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4476 : force_overwrite == ALL_FILES;
4477 CopyStatus status = use_force ? FORCE : SUCCESS;
4479 for (ExportedFile const & exp : files) {
4480 if (status == CANCEL) {
4481 message(_("Document export cancelled."));
4482 return ExportCancel;
4484 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4485 string fixedName = exp.exportName;
4486 if (!runparams.export_folder.empty()) {
4487 // Relative pathnames starting with ../ will be sanitized
4488 // if exporting to a different folder
4489 while (fixedName.substr(0, 3) == "../")
4490 fixedName = fixedName.substr(3, fixedName.length() - 3);
4492 FileName fixedFileName = makeAbsPath(fixedName, dest);
4493 fixedFileName.onlyPath().createPath();
4494 status = copyFile(fmt, exp.sourceName,
4496 exp.exportName, status == FORCE,
4497 runparams.export_folder.empty());
4501 if (tmp_result_file.exists()) {
4502 // Finally copy the main file
4503 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4504 : force_overwrite != NO_FILES;
4505 if (status == SUCCESS && use_force)
4507 status = copyFile(format, tmp_result_file,
4508 FileName(result_file), result_file,
4510 if (status == CANCEL) {
4511 message(_("Document export cancelled."));
4512 return ExportCancel;
4514 message(bformat(_("Document exported as %1$s "
4516 theFormats().prettyName(format),
4517 makeDisplayPath(result_file)));
4520 // This must be a dummy converter like fax (bug 1888)
4521 message(bformat(_("Document exported as %1$s"),
4522 theFormats().prettyName(format)));
4525 return success ? ExportSuccess : ExportConverterError;
4529 Buffer::ExportStatus Buffer::preview(string const & format) const
4531 bool const update_unincluded =
4532 params().maintain_unincluded_children
4533 && !params().getIncludedChildren().empty();
4534 return preview(format, update_unincluded);
4538 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4540 MarkAsExporting exporting(this);
4542 // (1) export with all included children (omit \includeonly)
4544 ExportStatus const status = doExport(format, true, true, result_file);
4545 if (status != ExportSuccess)
4548 // (2) export with included children only
4549 ExportStatus const status = doExport(format, true, false, result_file);
4550 FileName const previewFile(result_file);
4552 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4553 theimpl->preview_file_ = previewFile;
4554 theimpl->preview_format_ = format;
4555 theimpl->preview_error_ = (status != ExportSuccess);
4557 if (status != ExportSuccess)
4560 if (previewFile.exists())
4561 return theFormats().view(*this, previewFile, format) ?
4562 PreviewSuccess : PreviewError;
4564 // Successful export but no output file?
4565 // Probably a bug in error detection.
4566 LATTEST(status != ExportSuccess);
4571 Buffer::ReadStatus Buffer::extractFromVC()
4573 bool const found = LyXVC::file_not_found_hook(d->filename);
4575 return ReadFileNotFound;
4576 if (!d->filename.isReadableFile())
4582 Buffer::ReadStatus Buffer::loadEmergency()
4584 FileName const emergencyFile = getEmergencyFileName();
4585 if (!emergencyFile.exists()
4586 || emergencyFile.lastModified() <= d->filename.lastModified())
4587 return ReadFileNotFound;
4589 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4590 docstring const text = bformat(_("An emergency save of the document "
4591 "%1$s exists.\n\nRecover emergency save?"), file);
4593 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4594 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4600 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4601 bool const success = (ret_llf == ReadSuccess);
4603 if (hasReadonlyFlag()) {
4604 Alert::warning(_("File is read-only"),
4605 bformat(_("An emergency file is successfully loaded, "
4606 "but the original file %1$s is marked read-only. "
4607 "Please make sure to save the document as a different "
4608 "file."), from_utf8(d->filename.absFileName())));
4611 lyxvc().file_found_hook(d->filename);
4612 str = _("Document was successfully recovered.");
4614 str = _("Document was NOT successfully recovered.");
4615 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4616 makeDisplayPath(emergencyFile.absFileName()));
4618 int const del_emerg =
4619 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4620 _("&Remove"), _("&Keep"));
4621 if (del_emerg == 0) {
4622 emergencyFile.removeFile();
4624 Alert::warning(_("Emergency file deleted"),
4625 _("Do not forget to save your file now!"), true);
4627 return success ? ReadSuccess : ReadEmergencyFailure;
4630 int const del_emerg =
4631 Alert::prompt(_("Delete emergency file?"),
4632 _("Remove emergency file now?"), 1, 1,
4633 _("&Remove"), _("&Keep"));
4635 emergencyFile.removeFile();
4636 return ReadOriginal;
4646 Buffer::ReadStatus Buffer::loadAutosave()
4648 // Now check if autosave file is newer.
4649 FileName const autosaveFile = getAutosaveFileName();
4650 if (!autosaveFile.exists()
4651 || autosaveFile.lastModified() <= d->filename.lastModified())
4652 return ReadFileNotFound;
4654 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4655 docstring const text = bformat(_("The backup of the document %1$s "
4656 "is newer.\n\nLoad the backup instead?"), file);
4657 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4658 _("&Load backup"), _("Load &original"), _("&Cancel"));
4663 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4664 // the file is not saved if we load the autosave file.
4665 if (ret_llf == ReadSuccess) {
4666 if (hasReadonlyFlag()) {
4667 Alert::warning(_("File is read-only"),
4668 bformat(_("A backup file is successfully loaded, "
4669 "but the original file %1$s is marked read-only. "
4670 "Please make sure to save the document as a "
4672 from_utf8(d->filename.absFileName())));
4675 lyxvc().file_found_hook(d->filename);
4678 return ReadAutosaveFailure;
4681 // Here we delete the autosave
4682 autosaveFile.removeFile();
4683 return ReadOriginal;
4691 Buffer::ReadStatus Buffer::loadLyXFile()
4693 if (!d->filename.isReadableFile()) {
4694 ReadStatus const ret_rvc = extractFromVC();
4695 if (ret_rvc != ReadSuccess)
4699 ReadStatus const ret_re = loadEmergency();
4700 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4703 ReadStatus const ret_ra = loadAutosave();
4704 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4707 return loadThisLyXFile(d->filename);
4711 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4713 return readFile(fn);
4717 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4719 for (auto const & err : terr) {
4720 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4721 int errorRow = err.error_in_line;
4722 Buffer const * buf = 0;
4724 if (err.child_name.empty())
4725 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4727 // The error occurred in a child
4728 for (Buffer const * child : getDescendents()) {
4729 string const child_name =
4730 DocFileName(changeExtension(child->absFileName(), "tex")).
4732 if (err.child_name != child_name)
4734 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4735 if (!TexRow::isNone(start)) {
4736 buf = d->cloned_buffer_
4737 ? child->d->cloned_buffer_->d->owner_
4744 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4750 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4752 LBUFERR(!text().paragraphs().empty());
4754 // Use the master text class also for child documents
4755 Buffer const * const master = masterBuffer();
4756 DocumentClass const & textclass = master->params().documentClass();
4758 FileNamePairList old_bibfiles;
4759 // Do this only if we are the top-level Buffer. We also need to account
4760 // for the case of a previewed child with ignored parent here.
4761 if (master == this && !d->ignore_parent) {
4762 textclass.counters().reset(from_ascii("bibitem"));
4763 reloadBibInfoCache();
4764 // we will re-read this cache as we go through, but we need
4765 // to know whether it's changed to know whether we need to
4766 // update the bibinfo cache.
4767 old_bibfiles = d->bibfiles_cache_;
4768 d->bibfiles_cache_.clear();
4771 // keep the buffers to be children in this set. If the call from the
4772 // master comes back we can see which of them were actually seen (i.e.
4773 // via an InsetInclude). The remaining ones in the set need still be updated.
4774 static std::set<Buffer const *> bufToUpdate;
4775 if (scope == UpdateMaster) {
4776 // If this is a child document start with the master
4777 if (master != this) {
4778 bufToUpdate.insert(this);
4779 master->updateBuffer(UpdateMaster, utype);
4780 // If the master buffer has no gui associated with it, then the TocModel is
4781 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4782 // (bug 5699). The same happens if the master buffer is open in a different
4783 // window. This test catches both possibilities.
4784 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4785 // There remains a problem here: If there is another child open in yet a third
4786 // window, that TOC is not updated. So some more general solution is needed at
4788 if (master->d->gui_ != d->gui_)
4791 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4792 if (bufToUpdate.find(this) == bufToUpdate.end())
4796 // start over the counters in the master
4797 textclass.counters().reset();
4800 // update will be done below for this buffer
4801 bufToUpdate.erase(this);
4803 // update all caches
4804 clearReferenceCache();
4806 setChangesPresent(false);
4808 Buffer & cbuf = const_cast<Buffer &>(*this);
4811 ParIterator parit = cbuf.par_iterator_begin();
4812 updateBuffer(parit, utype);
4814 // If this document has siblings, then update the TocBackend later. The
4815 // reason is to ensure that later siblings are up to date when e.g. the
4816 // broken or not status of references is computed. The update is called
4817 // in InsetInclude::addToToc.
4821 // if the bibfiles changed, the cache of bibinfo is invalid
4822 FileNamePairList new_bibfiles = d->bibfiles_cache_;
4823 // this is a trick to determine whether the two vectors have
4824 // the same elements.
4825 sort(new_bibfiles.begin(), new_bibfiles.end());
4826 sort(old_bibfiles.begin(), old_bibfiles.end());
4827 if (old_bibfiles != new_bibfiles) {
4828 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4829 invalidateBibinfoCache();
4830 reloadBibInfoCache();
4831 // We relied upon the bibinfo cache when recalculating labels. But that
4832 // cache was invalid, although we didn't find that out until now. So we
4833 // have to do it all again.
4834 // That said, the only thing we really need to do is update the citation
4835 // labels. Nothing else will have changed. So we could create a new
4836 // UpdateType that would signal that fact, if we needed to do so.
4837 parit = cbuf.par_iterator_begin();
4838 // we will be re-doing the counters and references and such.
4839 textclass.counters().reset();
4840 clearReferenceCache();
4841 // we should not need to do this again?
4843 setChangesPresent(false);
4844 updateBuffer(parit, utype);
4845 // this will already have been done by reloadBibInfoCache();
4846 // d->bibinfo_cache_valid_ = true;
4849 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4850 // this is also set to true on the other path, by reloadBibInfoCache.
4851 d->bibinfo_cache_valid_ = true;
4853 d->cite_labels_valid_ = true;
4855 cbuf.tocBackend().update(true, utype);
4856 if (scope == UpdateMaster)
4857 cbuf.structureChanged();
4861 static depth_type getDepth(DocIterator const & it)
4863 depth_type depth = 0;
4864 for (size_t i = 0 ; i < it.depth() ; ++i)
4865 if (!it[i].inset().inMathed())
4866 depth += it[i].paragraph().getDepth() + 1;
4867 // remove 1 since the outer inset does not count
4868 // we should have at least one non-math inset, so
4869 // depth should nevery be 0. but maybe it is worth
4870 // marking this, just in case.
4872 // coverity[INTEGER_OVERFLOW]
4876 static depth_type getItemDepth(ParIterator const & it)
4878 Paragraph const & par = *it;
4879 LabelType const labeltype = par.layout().labeltype;
4881 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4884 // this will hold the lowest depth encountered up to now.
4885 depth_type min_depth = getDepth(it);
4886 ParIterator prev_it = it;
4889 --prev_it.top().pit();
4891 // start of nested inset: go to outer par
4893 if (prev_it.empty()) {
4894 // start of document: nothing to do
4899 // We search for the first paragraph with same label
4900 // that is not more deeply nested.
4901 Paragraph & prev_par = *prev_it;
4902 depth_type const prev_depth = getDepth(prev_it);
4903 if (labeltype == prev_par.layout().labeltype) {
4904 if (prev_depth < min_depth)
4905 return prev_par.itemdepth + 1;
4906 if (prev_depth == min_depth)
4907 return prev_par.itemdepth;
4909 min_depth = min(min_depth, prev_depth);
4910 // small optimization: if we are at depth 0, we won't
4911 // find anything else
4912 if (prev_depth == 0)
4918 static bool needEnumCounterReset(ParIterator const & it)
4920 Paragraph const & par = *it;
4921 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4922 depth_type const cur_depth = par.getDepth();
4923 ParIterator prev_it = it;
4924 while (prev_it.pit()) {
4925 --prev_it.top().pit();
4926 Paragraph const & prev_par = *prev_it;
4927 if (prev_par.getDepth() <= cur_depth)
4928 return prev_par.layout().name() != par.layout().name();
4930 // start of nested inset: reset
4935 // set the label of a paragraph. This includes the counters.
4936 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4938 BufferParams const & bp = owner_->masterBuffer()->params();
4939 DocumentClass const & textclass = bp.documentClass();
4940 Paragraph & par = it.paragraph();
4941 Layout const & layout = par.layout();
4942 Counters & counters = textclass.counters();
4944 if (par.params().startOfAppendix()) {
4945 // We want to reset the counter corresponding to toplevel sectioning
4946 Layout const & lay = textclass.getTOCLayout();
4947 docstring const cnt = lay.counter;
4949 counters.reset(cnt);
4950 counters.appendix(true);
4952 par.params().appendix(counters.appendix());
4954 // Compute the item depth of the paragraph
4955 par.itemdepth = getItemDepth(it);
4957 if (layout.margintype == MARGIN_MANUAL) {
4958 if (par.params().labelWidthString().empty())
4959 par.params().labelWidthString(par.expandLabel(layout, bp));
4960 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4961 // we do not need to do anything here, since the empty case is
4962 // handled during export.
4964 par.params().labelWidthString(docstring());
4967 switch(layout.labeltype) {
4968 case LABEL_ITEMIZE: {
4969 // At some point of time we should do something more
4970 // clever here, like:
4971 // par.params().labelString(
4972 // bp.user_defined_bullet(par.itemdepth).getText());
4973 // for now, use a simple hardcoded label
4974 docstring itemlabel;
4975 switch (par.itemdepth) {
4977 itemlabel = char_type(0x2022);
4980 itemlabel = char_type(0x2013);
4983 itemlabel = char_type(0x2217);
4986 itemlabel = char_type(0x2219); // or 0x00b7
4989 par.params().labelString(itemlabel);
4993 case LABEL_ENUMERATE: {
4994 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4996 switch (par.itemdepth) {
5007 enumcounter += "iv";
5010 // not a valid enumdepth...
5014 if (needEnumCounterReset(it)) {
5015 // Increase the master counter?
5016 if (layout.stepmastercounter)
5017 counters.stepMaster(enumcounter, utype);
5018 // Maybe we have to reset the enumeration counter.
5019 if (!layout.resumecounter)
5020 counters.reset(enumcounter);
5022 counters.step(enumcounter, utype);
5024 string const & lang = par.getParLanguage(bp)->code();
5025 par.params().labelString(counters.theCounter(enumcounter, lang));
5030 case LABEL_SENSITIVE: {
5031 string const & type = counters.current_float();
5032 docstring full_label;
5034 full_label = owner_->B_("Senseless!!! ");
5036 docstring name = owner_->B_(textclass.floats().getType(type).name());
5037 if (counters.hasCounter(from_utf8(type))) {
5038 string const & lang = par.getParLanguage(bp)->code();
5039 counters.step(from_utf8(type), utype);
5040 full_label = bformat(from_ascii("%1$s %2$s:"),
5042 counters.theCounter(from_utf8(type), lang));
5044 full_label = bformat(from_ascii("%1$s #:"), name);
5046 par.params().labelString(full_label);
5050 case LABEL_NO_LABEL:
5051 par.params().labelString(docstring());
5055 case LABEL_CENTERED:
5056 case LABEL_STATIC: {
5057 docstring const & lcounter = layout.counter;
5058 if (!lcounter.empty()) {
5059 if (layout.toclevel <= bp.secnumdepth
5060 && (layout.latextype != LATEX_ENVIRONMENT
5061 || it.text()->isFirstInSequence(it.pit()))) {
5062 if (counters.hasCounter(lcounter))
5063 counters.step(lcounter, utype);
5064 par.params().labelString(par.expandLabel(layout, bp));
5066 par.params().labelString(docstring());
5068 par.params().labelString(par.expandLabel(layout, bp));
5074 par.params().labelString(par.expandLabel(layout, bp));
5079 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5081 // LASSERT: Is it safe to continue here, or should we just return?
5082 LASSERT(parit.pit() == 0, /**/);
5084 // Set the position of the text in the buffer to be able
5085 // to resolve macros in it.
5086 parit.text()->setMacrocontextPosition(parit);
5088 depth_type maxdepth = 0;
5089 pit_type const lastpit = parit.lastpit();
5090 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5091 // reduce depth if necessary
5092 if (parit->params().depth() > maxdepth) {
5093 /** FIXME: this function is const, but
5094 * nevertheless it modifies the buffer. To be
5095 * cleaner, one should modify the buffer in
5096 * another function, which is actually
5097 * non-const. This would however be costly in
5098 * terms of code duplication.
5100 CursorData(parit).recordUndo();
5101 parit->params().depth(maxdepth);
5103 maxdepth = parit->getMaxDepthAfter();
5105 if (utype == OutputUpdate) {
5106 // track the active counters
5107 // we have to do this for the master buffer, since the local
5108 // buffer isn't tracking anything.
5109 masterBuffer()->params().documentClass().counters().
5110 setActiveLayout(parit->layout());
5113 // set the counter for this paragraph
5114 d->setLabel(parit, utype);
5116 // update change-tracking flag
5117 parit->addChangesToBuffer(*this);
5120 for (auto const & insit : parit->insetList()) {
5121 parit.pos() = insit.pos;
5122 insit.inset->updateBuffer(parit, utype);
5128 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5129 WordLangTuple & word_lang, docstring_list & suggestions) const
5133 suggestions.clear();
5134 word_lang = WordLangTuple();
5135 bool const to_end = to.empty();
5136 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5137 // OK, we start from here.
5138 for (; from != end; from.forwardPos()) {
5139 // This skips all insets with spell check disabled.
5140 while (!from.allowSpellCheck()) {
5144 // If from is at the end of the document (which is possible
5145 // when "from" was changed above) LyX will crash later otherwise.
5146 if (from.atEnd() || (!to_end && from >= end))
5149 from.paragraph().spellCheck();
5150 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5151 if (SpellChecker::misspelled(res)) {
5155 // Do not increase progress when from == to, otherwise the word
5156 // count will be wrong.
5166 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5168 bool inword = false;
5173 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5174 if (!dit.inTexted()) {
5179 Paragraph const & par = dit.paragraph();
5180 pos_type const pos = dit.pos();
5182 // Copied and adapted from isWordSeparator() in Paragraph
5183 if (pos == dit.lastpos()) {
5186 Inset const * ins = par.getInset(pos);
5187 if (ins && skipNoOutput && !ins->producesOutput()) {
5190 // stop if end of range was skipped
5191 if (!to.atEnd() && dit >= to)
5194 } else if (!par.isDeleted(pos)) {
5195 if (par.isWordSeparator(pos))
5201 if (ins && ins->isLetter())
5203 else if (ins && ins->isSpace())
5206 char_type const c = par.getChar(pos);
5207 if (isPrintableNonspace(c))
5209 else if (isSpace(c))
5219 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5221 d->updateStatistics(from, to, skipNoOutput);
5225 int Buffer::wordCount() const
5227 return d->wordCount();
5231 int Buffer::charCount(bool with_blanks) const
5233 return d->charCount(with_blanks);
5237 Buffer::ReadStatus Buffer::reload()
5240 // c.f. bug https://www.lyx.org/trac/ticket/6587
5241 removeAutosaveFile();
5242 // e.g., read-only status could have changed due to version control
5243 d->filename.refresh();
5244 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5246 // clear parent. this will get reset if need be.
5248 ReadStatus const status = loadLyXFile();
5249 if (status == ReadSuccess) {
5254 message(bformat(_("Document %1$s reloaded."), disp_fn));
5257 message(bformat(_("Could not reload document %1$s."), disp_fn));
5267 bool Buffer::saveAs(FileName const & fn)
5269 FileName const old_name = fileName();
5270 FileName const old_auto = getAutosaveFileName();
5271 bool const old_unnamed = isUnnamed();
5272 bool success = true;
5273 d->old_position = filePath();
5280 // bring the autosave file with us, just in case.
5281 moveAutosaveFile(old_auto);
5282 // validate version control data and
5283 // correct buffer title
5284 lyxvc().file_found_hook(fileName());
5286 // the file has now been saved to the new location.
5287 // we need to check that the locations of child buffers
5289 checkChildBuffers();
5290 checkMasterBuffer();
5293 // reset the old filename and unnamed state
5294 setFileName(old_name);
5295 setUnnamed(old_unnamed);
5299 d->old_position.clear();
5304 void Buffer::checkChildBuffers()
5306 for (auto const & bit : d->children_positions) {
5307 DocIterator dit = bit.second;
5308 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5309 if (!cbuf || !theBufferList().isLoaded(cbuf))
5311 Inset * inset = dit.nextInset();
5312 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5313 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5314 docstring const & incfile = inset_inc->getParam("filename");
5315 string oldloc = cbuf->absFileName();
5316 string newloc = makeAbsPath(to_utf8(incfile),
5317 onlyPath(absFileName())).absFileName();
5318 if (oldloc == newloc)
5320 // the location of the child file is incorrect.
5322 inset_inc->setChildBuffer(0);
5324 // invalidate cache of children
5325 d->children_positions.clear();
5326 d->position_to_children.clear();
5330 // If a child has been saved under a different name/path, it might have been
5331 // orphaned. Therefore the master needs to be reset (bug 8161).
5332 void Buffer::checkMasterBuffer()
5334 Buffer const * const master = masterBuffer();
5338 // necessary to re-register the child (bug 5873)
5339 // FIXME: clean up updateMacros (here, only
5340 // child registering is needed).
5341 master->updateMacros();
5342 // (re)set master as master buffer, but only
5343 // if we are a real child
5344 if (master->isChild(this))
5351 string Buffer::includedFilePath(string const & name, string const & ext) const
5353 if (d->old_position.empty() ||
5354 equivalent(FileName(d->old_position), FileName(filePath())))
5357 bool isabsolute = FileName::isAbsolute(name);
5358 // both old_position and filePath() end with a path separator
5359 string absname = isabsolute ? name : d->old_position + name;
5361 // if old_position is set to origin, we need to do the equivalent of
5362 // getReferencedFileName() (see readDocument())
5363 if (!isabsolute && d->old_position == params().origin) {
5364 FileName const test(addExtension(filePath() + name, ext));
5366 absname = filePath() + name;
5369 if (!FileName(addExtension(absname, ext)).exists())
5373 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5375 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5376 from_utf8(filePath())));
5380 void Buffer::setChangesPresent(bool b) const
5382 d->tracked_changes_present_ = b;
5386 bool Buffer::areChangesPresent() const
5388 return d->tracked_changes_present_;
5392 void Buffer::updateChangesPresent() const
5394 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5395 setChangesPresent(false);
5396 ParConstIterator it = par_iterator_begin();
5397 ParConstIterator const end = par_iterator_end();
5398 for (; !areChangesPresent() && it != end; ++it)
5399 it->addChangesToBuffer(*this);
5403 void Buffer::Impl::refreshFileMonitor()
5405 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5406 file_monitor_->refresh();
5410 // The previous file monitor is invalid
5411 // This also destroys the previous file monitor and all its connections
5412 file_monitor_ = FileSystemWatcher::monitor(filename);
5413 // file_monitor_ will be destroyed with *this, so it is not going to call a
5414 // destroyed object method.
5415 file_monitor_->connect([this](bool exists) {
5416 fileExternallyModified(exists);
5421 void Buffer::Impl::fileExternallyModified(bool const exists)
5423 // ignore notifications after our own saving operations
5424 if (checksum_ == filename.checksum()) {
5425 LYXERR(Debug::FILES, "External modification but "
5426 "checksum unchanged: " << filename);
5429 // If the file has been deleted, only mark the file as dirty since it is
5430 // pointless to prompt for reloading. If later a file is moved into this
5431 // location, then the externally modified warning will appear then.
5433 externally_modified_ = true;
5434 // Update external modification notification.
5435 // Dirty buffers must be visible at all times.
5436 if (wa_ && wa_->unhide(owner_))
5437 wa_->updateTitles();
5439 // Unable to unhide the buffer (e.g. no GUI or not current View)
5444 bool Buffer::notifiesExternalModification() const
5446 return d->externally_modified_;
5450 void Buffer::clearExternalModification() const
5452 d->externally_modified_ = false;
5454 d->wa_->updateTitles();