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.");
1044 // If the master has just been created, un-hide it (#11162)
1045 if (!master->fileName().exists())
1046 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1047 master->absFileName()));
1052 // assure we have a default index
1053 params().indiceslist().addDefault(B_("Index"));
1056 if (FileName::isAbsolute(params().origin))
1057 d->old_position = params().origin;
1059 d->old_position = filePath();
1060 bool const res = text().read(lex, errorList, d->inset);
1061 d->old_position.clear();
1063 // inform parent buffer about local macros
1065 Buffer const * pbuf = parent();
1066 for (auto const & m : usermacros)
1067 pbuf->usermacros.insert(m);
1071 updateMacroInstances(InternalUpdate);
1076 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1078 Format const * fmt = theFormats().getFormat(format);
1081 // It is important to use the correct extension here, since some
1082 // converters create a wrong output file otherwise (e.g. html2latex)
1083 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1084 ofdocstream os(name.toFilesystemEncoding().c_str());
1085 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1086 bool const success = !(os << contents).fail();
1089 bool converted = false;
1091 params().compressed = false;
1093 // remove dummy empty par
1094 paragraphs().clear();
1096 converted = importFile(format, name, errorList);
1099 removeTempFile(name);
1104 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1106 if (!theConverters().isReachable(format, "lyx"))
1109 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1110 Converters::RetVal const retval =
1111 theConverters().convert(0, name, lyx, name, format, "lyx", errorList);
1112 if (retval == Converters::SUCCESS) {
1113 bool const success = readFile(lyx) == ReadSuccess;
1114 removeTempFile(lyx);
1122 bool Buffer::readString(string const & s)
1124 params().compressed = false;
1127 istringstream is(s);
1129 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1130 FileName const fn = tempfile.name();
1133 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1135 if (success && file_format != LYX_FORMAT) {
1136 // We need to call lyx2lyx, so write the input to a file
1137 ofstream os(fn.toFilesystemEncoding().c_str());
1140 // lyxvc in readFile
1141 if (readFile(fn) != ReadSuccess)
1145 if (readDocument(lex))
1151 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1155 if (!lex.setFile(fname)) {
1156 Alert::error(_("File Not Found"),
1157 bformat(_("Unable to open file `%1$s'."),
1158 from_utf8(fn.absFileName())));
1159 return ReadFileNotFound;
1163 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1164 if (ret_plf != ReadSuccess)
1167 if (file_format != LYX_FORMAT) {
1169 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1170 if (ret_clf != ReadSuccess)
1172 ret_clf = readFile(tmpFile);
1173 if (ret_clf == ReadSuccess) {
1174 d->file_format = file_format;
1175 d->need_format_backup = true;
1180 // FIXME: InsetInfo needs to know whether the file is under VCS
1181 // during the parse process, so this has to be done before.
1182 lyxvc().file_found_hook(d->filename);
1184 if (readDocument(lex)) {
1185 Alert::error(_("Document format failure"),
1186 bformat(_("%1$s ended unexpectedly, which means"
1187 " that it is probably corrupted."),
1188 from_utf8(fn.absFileName())));
1189 return ReadDocumentFailure;
1192 d->file_fully_loaded = true;
1193 d->read_only = !d->filename.isWritable();
1194 params().compressed = theFormats().isZippedFile(d->filename);
1200 bool Buffer::isFullyLoaded() const
1202 return d->file_fully_loaded;
1206 void Buffer::setFullyLoaded(bool value)
1208 d->file_fully_loaded = value;
1212 bool Buffer::lastPreviewError() const
1214 return d->preview_error_;
1218 PreviewLoader * Buffer::loader() const
1220 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1222 if (!d->preview_loader_)
1223 d->preview_loader_ = new PreviewLoader(*this);
1224 return d->preview_loader_;
1228 void Buffer::removePreviews() const
1230 delete d->preview_loader_;
1231 d->preview_loader_ = 0;
1235 void Buffer::updatePreviews() const
1237 PreviewLoader * ploader = loader();
1241 InsetIterator it = inset_iterator_begin(*d->inset);
1242 InsetIterator const end = inset_iterator_end(*d->inset);
1243 for (; it != end; ++it)
1244 it->addPreview(it, *ploader);
1246 ploader->startLoading();
1250 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1251 FileName const & fn, int & file_format) const
1253 if(!lex.checkFor("\\lyxformat")) {
1254 Alert::error(_("Document format failure"),
1255 bformat(_("%1$s is not a readable LyX document."),
1256 from_utf8(fn.absFileName())));
1257 return ReadNoLyXFormat;
1263 // LyX formats 217 and earlier were written as 2.17. This corresponds
1264 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1265 // these cases. See also: www.lyx.org/trac/changeset/1313.
1266 size_t dot = tmp_format.find_first_of(".,");
1267 if (dot != string::npos)
1268 tmp_format.erase(dot, 1);
1270 file_format = convert<int>(tmp_format);
1275 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1276 FileName & tmpfile, int from_format)
1278 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1279 tempfile.setAutoRemove(false);
1280 tmpfile = tempfile.name();
1281 if(tmpfile.empty()) {
1282 Alert::error(_("Conversion failed"),
1283 bformat(_("%1$s is from a different"
1284 " version of LyX, but a temporary"
1285 " file for converting it could"
1286 " not be created."),
1287 from_utf8(fn.absFileName())));
1288 return LyX2LyXNoTempFile;
1291 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1292 if (lyx2lyx.empty()) {
1293 Alert::error(_("Conversion script not found"),
1294 bformat(_("%1$s is from a different"
1295 " version of LyX, but the"
1296 " conversion script lyx2lyx"
1297 " could not be found."),
1298 from_utf8(fn.absFileName())));
1299 return LyX2LyXNotFound;
1303 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1304 ostringstream command;
1305 command << os::python()
1306 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1307 << " -t " << convert<string>(LYX_FORMAT)
1308 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1309 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1310 string const command_str = command.str();
1312 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1314 cmd_ret const ret = runCommand(command_str);
1315 if (ret.first != 0) {
1316 if (from_format < LYX_FORMAT) {
1317 Alert::error(_("Conversion script failed"),
1318 bformat(_("%1$s is from an older version"
1319 " of LyX and the lyx2lyx script"
1320 " failed to convert it."),
1321 from_utf8(fn.absFileName())));
1322 return LyX2LyXOlderFormat;
1324 Alert::error(_("Conversion script failed"),
1325 bformat(_("%1$s is from a newer version"
1326 " of LyX and the lyx2lyx script"
1327 " failed to convert it."),
1328 from_utf8(fn.absFileName())));
1329 return LyX2LyXNewerFormat;
1336 FileName Buffer::getBackupName() const {
1337 map<int, string> const file_formats = {
1354 FileName const & fn = fileName();
1355 string const fname = fn.onlyFileNameWithoutExt();
1356 string const fext = fn.extension() + "~";
1357 string const fpath = lyxrc.backupdir_path.empty() ?
1358 fn.onlyPath().absFileName() :
1359 lyxrc.backupdir_path;
1360 string backup_suffix;
1361 // If file format is from a stable series use version instead of file format
1362 auto const it = file_formats.find(d->file_format);
1363 if (it != file_formats.end())
1364 backup_suffix = "-lyx" + it->second;
1366 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1367 string const backname = fname + backup_suffix;
1368 FileName backup(addName(fpath, addExtension(backname, fext)));
1370 // limit recursion, just in case
1372 unsigned long orig_checksum = 0;
1373 while (backup.exists() && v < 100) {
1374 if (orig_checksum == 0)
1375 orig_checksum = fn.checksum();
1376 unsigned long new_checksum = backup.checksum();
1377 if (orig_checksum == new_checksum) {
1378 LYXERR(Debug::FILES, "Not backing up " << fn <<
1379 "since " << backup << "has the same checksum.");
1380 // a bit of a hack, but we have to check this anyway
1381 // below, and setting this is simpler than introducing
1382 // a special boolean for this purpose.
1386 string const newbackname = backname + "-" + convert<string>(v);
1387 backup.set(addName(fpath, addExtension(newbackname, fext)));
1390 return v < 100 ? backup : FileName();
1394 // Should probably be moved to somewhere else: BufferView? GuiView?
1395 bool Buffer::save() const
1397 docstring const file = makeDisplayPath(absFileName(), 20);
1398 d->filename.refresh();
1400 // check the read-only status before moving the file as a backup
1401 if (d->filename.exists()) {
1402 bool const read_only = !d->filename.isWritable();
1404 Alert::warning(_("File is read-only"),
1405 bformat(_("The file %1$s cannot be written because it "
1406 "is marked as read-only."), file));
1411 // ask if the disk file has been externally modified (use checksum method)
1412 if (fileName().exists() && isChecksumModified()) {
1414 bformat(_("Document %1$s has been externally modified. "
1415 "Are you sure you want to overwrite this file?"), file);
1416 int const ret = Alert::prompt(_("Overwrite modified file?"),
1417 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1422 // We don't need autosaves in the immediate future. (Asger)
1423 resetAutosaveTimers();
1425 // if the file does not yet exist, none of the backup activity
1426 // that follows is necessary
1427 if (!fileName().exists()) {
1428 if (!writeFile(fileName()))
1434 // we first write the file to a new name, then move it to its
1435 // proper location once that has been done successfully. that
1436 // way we preserve the original file if something goes wrong.
1437 string const justname = fileName().onlyFileNameWithoutExt();
1438 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1439 justname + "-XXXXXX.lyx");
1440 bool const symlink = fileName().isSymLink();
1442 tempfile->setAutoRemove(false);
1444 FileName savefile(tempfile->name());
1445 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1446 if (!writeFile(savefile))
1449 // we will set this to false if we fail
1450 bool made_backup = true;
1452 FileName backupName;
1453 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1455 if (d->need_format_backup)
1456 backupName = getBackupName();
1458 // If we for some reason failed to find a backup name in case of
1459 // a format change, this will still set one. It's the best we can
1461 if (backupName.empty()) {
1462 backupName.set(fileName().absFileName() + "~");
1463 if (!lyxrc.backupdir_path.empty()) {
1464 string const mangledName =
1465 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1466 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1470 LYXERR(Debug::FILES, "Backing up original file to " <<
1471 backupName.absFileName());
1472 // Except file is symlink do not copy because of #6587.
1473 // Hard links have bad luck.
1474 made_backup = symlink ?
1475 fileName().copyTo(backupName):
1476 fileName().moveTo(backupName);
1479 Alert::error(_("Backup failure"),
1480 bformat(_("Cannot create backup file %1$s.\n"
1481 "Please check whether the directory exists and is writable."),
1482 from_utf8(backupName.absFileName())));
1483 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1484 } else if (d->need_format_backup) {
1485 // the original file has been backed up successfully, so we
1486 // will not need to do that again
1487 d->need_format_backup = false;
1491 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1492 // Only do this if tempfile is not in autoremove mode
1495 // If we have no symlink, we can simply rename the temp file.
1496 // Otherwise, we need to copy it so the symlink stays intact.
1497 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1498 savefile.moveTo(fileName()))
1500 // saveCheckSum() was already called by writeFile(), but the
1501 // time stamp is invalidated by copying/moving
1504 if (d->file_format != LYX_FORMAT)
1505 // the file associated with this buffer is now in the current format
1506 d->file_format = LYX_FORMAT;
1509 // else we saved the file, but failed to move it to the right location.
1511 if (needBackup && made_backup && !symlink) {
1512 // the original file was moved to some new location, so it will look
1513 // to the user as if it was deleted. (see bug #9234.) we could try
1514 // to restore it, but that would basically mean trying to do again
1515 // what we just failed to do. better to leave things as they are.
1516 Alert::error(_("Write failure"),
1517 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1518 "But LyX could not move it to:\n %2$s.\n"
1519 "Your original file has been backed up to:\n %3$s"),
1520 from_utf8(savefile.absFileName()),
1521 from_utf8(fileName().absFileName()),
1522 from_utf8(backupName.absFileName())));
1524 // either we did not try to make a backup, or else we tried and failed,
1525 // or else the original file was a symlink, in which case it was copied,
1526 // not moved. so the original file is intact.
1527 Alert::error(_("Write failure"),
1528 bformat(_("Cannot move saved file to:\n %1$s.\n"
1529 "But the file has successfully been saved as:\n %2$s."),
1530 from_utf8(fileName().absFileName()),
1531 from_utf8(savefile.absFileName())));
1537 bool Buffer::writeFile(FileName const & fname) const
1539 if (d->read_only && fname == d->filename)
1542 bool retval = false;
1544 docstring const str = bformat(_("Saving document %1$s..."),
1545 makeDisplayPath(fname.absFileName()));
1548 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1550 if (params().compressed) {
1551 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1552 retval = ofs && write(ofs);
1554 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1555 retval = ofs && write(ofs);
1559 message(str + _(" could not write file!"));
1564 // removeAutosaveFile();
1567 message(str + _(" done."));
1573 docstring Buffer::emergencyWrite()
1575 // No need to save if the buffer has not changed.
1579 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1581 docstring user_message = bformat(
1582 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1584 // We try to save three places:
1585 // 1) Same place as document. Unless it is an unnamed doc.
1587 string s = absFileName();
1590 if (writeFile(FileName(s))) {
1592 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1593 return user_message;
1595 user_message += " " + _("Save failed! Trying again...\n");
1599 // 2) In HOME directory.
1600 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1602 lyxerr << ' ' << s << endl;
1603 if (writeFile(FileName(s))) {
1605 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1606 return user_message;
1609 user_message += " " + _("Save failed! Trying yet again...\n");
1611 // 3) In "/tmp" directory.
1612 // MakeAbsPath to prepend the current
1613 // drive letter on OS/2
1614 s = addName(package().temp_dir().absFileName(), absFileName());
1616 lyxerr << ' ' << s << endl;
1617 if (writeFile(FileName(s))) {
1619 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1620 return user_message;
1623 user_message += " " + _("Save failed! Document is lost.");
1626 return user_message;
1630 bool Buffer::write(ostream & ofs) const
1633 // Use the standard "C" locale for file output.
1634 ofs.imbue(locale::classic());
1637 // The top of the file should not be written by params().
1639 // write out a comment in the top of the file
1640 // Important: Keep the version formatting in sync with lyx2lyx and
1641 // tex2lyx (bug 7951)
1642 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1643 << " created this file. For more info see https://www.lyx.org/\n"
1644 << "\\lyxformat " << LYX_FORMAT << "\n"
1645 << "\\begin_document\n";
1647 /// For each author, set 'used' to true if there is a change
1648 /// by this author in the document; otherwise set it to 'false'.
1649 for (Author const & a : params().authors())
1652 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1653 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1654 for ( ; it != end; ++it)
1655 it->checkAuthors(params().authors());
1657 // now write out the buffer parameters.
1658 ofs << "\\begin_header\n";
1659 params().writeFile(ofs, this);
1660 ofs << "\\end_header\n";
1663 ofs << "\n\\begin_body\n";
1665 ofs << "\n\\end_body\n";
1667 // Write marker that shows file is complete
1668 ofs << "\\end_document" << endl;
1670 // Shouldn't really be needed....
1673 // how to check if close went ok?
1674 // Following is an attempt... (BE 20001011)
1676 // good() returns false if any error occurred, including some
1677 // formatting error.
1678 // bad() returns true if something bad happened in the buffer,
1679 // which should include file system full errors.
1684 lyxerr << "File was not closed properly." << endl;
1691 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1692 string const & original_path,
1693 OutputParams const & runparams_in,
1694 OutputWhat output) const
1696 OutputParams runparams = runparams_in;
1698 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1699 // Check here, because the "flavor" is not known in BufferParams::encoding()
1700 // (power users can override this safety measure selecting "utf8-plain").
1701 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1702 && (runparams.encoding->name() != "utf8-plain"))
1703 runparams.encoding = encodings.fromLyXName("ascii");
1705 string const encoding = runparams.encoding->iconvName();
1706 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1709 try { ofs.reset(encoding); }
1710 catch (iconv_codecvt_facet_exception const & e) {
1711 lyxerr << "Caught iconv exception: " << e.what() << endl;
1712 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1713 "verify that the support software for your encoding (%1$s) is "
1714 "properly installed"), from_ascii(encoding)));
1717 if (!openFileWrite(ofs, fname))
1720 ErrorList & errorList = d->errorLists["Export"];
1722 ExportStatus status = ExportSuccess;
1725 // make sure we are ready to export
1726 // this needs to be done before we validate
1727 // FIXME Do we need to do this all the time? I.e., in children
1728 // of a master we are exporting?
1730 updateMacroInstances(OutputUpdate);
1732 ExportStatus retval;
1734 retval = writeLaTeXSource(os, original_path, runparams, output);
1735 if (retval == ExportKilled)
1736 return ExportKilled;
1738 catch (EncodingException const & e) {
1739 docstring const failed(1, e.failed_char);
1741 oss << "0x" << hex << e.failed_char << dec;
1742 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1743 docstring msg = bformat(_("Uncodable character '%1$s'"
1744 " (code point %2$s)"),
1745 failed, from_utf8(oss.str()));
1746 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1747 "representable in specific verbatim contexts.\n"
1748 "Changing the document encoding to utf8 could help."),
1749 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1751 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1752 " (code point %2$s)"),
1753 failed, from_utf8(oss.str()));
1754 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1755 "representable in the chosen encoding.\n"
1756 "Changing the document encoding to utf8 could help."),
1757 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1759 status = ExportError;
1761 catch (iconv_codecvt_facet_exception const & e) {
1762 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1764 status = ExportError;
1766 catch (exception const & e) {
1767 errorList.push_back(ErrorItem(_("conversion failed"),
1769 lyxerr << e.what() << endl;
1770 status = ExportError;
1773 lyxerr << "Caught some really weird exception..." << endl;
1777 d->texrow = move(os.texrow());
1781 status = ExportError;
1782 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1785 if (runparams_in.silent)
1793 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1794 string const & original_path,
1795 OutputParams const & runparams_in,
1796 OutputWhat output) const
1798 // The child documents, if any, shall be already loaded at this point.
1800 OutputParams runparams = runparams_in;
1802 // XeTeX with TeX fonts is only safe with ASCII encoding,
1803 // Check here, because the "flavor" is not known in BufferParams::encoding()
1804 // (power users can override this safety measure selecting "utf8-plain").
1805 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1806 && (runparams.encoding->name() != "utf8-plain"))
1807 runparams.encoding = encodings.fromLyXName("ascii");
1808 // FIXME: when only the current paragraph is shown, this is ignored
1809 // (or not reached) and characters encodable in the current
1810 // encoding are not converted to ASCII-representation.
1812 // Some macros rely on font encoding
1813 runparams.main_fontenc = params().main_font_encoding();
1815 // If we are compiling a file standalone, even if this is the
1816 // child of some other buffer, let's cut the link here, so the
1817 // file is really independent and no concurring settings from
1818 // the master (e.g. branch state) interfere (see #8100).
1819 if (!runparams.is_child)
1820 d->ignore_parent = true;
1822 // Classify the unicode characters appearing in math insets
1823 BufferEncodings::initUnicodeMath(*this);
1825 // validate the buffer.
1826 LYXERR(Debug::LATEX, " Validating buffer...");
1827 LaTeXFeatures features(*this, params(), runparams);
1829 // This is only set once per document (in master)
1830 if (!runparams.is_child)
1831 runparams.use_polyglossia = features.usePolyglossia();
1832 LYXERR(Debug::LATEX, " Buffer validation done.");
1834 bool const output_preamble =
1835 output == FullSource || output == OnlyPreamble;
1836 bool const output_body =
1837 output == FullSource || output == OnlyBody;
1839 // The starting paragraph of the coming rows is the
1840 // first paragraph of the document. (Asger)
1841 if (output_preamble && runparams.nice) {
1842 os << "%% LyX " << lyx_version << " created this file. "
1843 "For more info, see https://www.lyx.org/.\n"
1844 "%% Do not edit unless you really know what "
1847 LYXERR(Debug::INFO, "lyx document header finished");
1849 // There are a few differences between nice LaTeX and usual files:
1850 // usual files have \batchmode and special input@path to allow
1851 // inclusion of figures specified by an explicitly relative path
1852 // (i.e., a path starting with './' or '../') with either \input or
1853 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1854 // input@path is set when the actual parameter original_path is set.
1855 // This is done for usual tex-file, but not for nice-latex-file.
1856 // (Matthias 250696)
1857 // Note that input@path is only needed for something the user does
1858 // in the preamble, included .tex files or ERT, files included by
1859 // LyX work without it.
1860 if (output_preamble) {
1861 if (!runparams.nice) {
1862 // code for usual, NOT nice-latex-file
1863 os << "\\batchmode\n"; // changed from \nonstopmode
1865 if (!original_path.empty()) {
1867 // We don't know the encoding of inputpath
1868 docstring const inputpath = from_utf8(original_path);
1869 docstring uncodable_glyphs;
1870 Encoding const * const enc = runparams.encoding;
1872 for (size_t n = 0; n < inputpath.size(); ++n) {
1873 if (!enc->encodable(inputpath[n])) {
1874 docstring const glyph(1, inputpath[n]);
1875 LYXERR0("Uncodable character '"
1877 << "' in input path!");
1878 uncodable_glyphs += glyph;
1883 // warn user if we found uncodable glyphs.
1884 if (!uncodable_glyphs.empty()) {
1885 frontend::Alert::warning(
1886 _("Uncodable character in file path"),
1888 _("The path of your document\n"
1890 "contains glyphs that are unknown "
1891 "in the current document encoding "
1892 "(namely %2$s). This may result in "
1893 "incomplete output, unless "
1894 "TEXINPUTS contains the document "
1895 "directory and you don't use "
1896 "explicitly relative paths (i.e., "
1897 "paths starting with './' or "
1898 "'../') in the preamble or in ERT."
1899 "\n\nIn case of problems, choose "
1900 "an appropriate document encoding\n"
1901 "(such as utf8) or change the "
1903 inputpath, uncodable_glyphs));
1905 string docdir = os::latex_path(original_path);
1906 if (contains(docdir, '#')) {
1907 docdir = subst(docdir, "#", "\\#");
1908 os << "\\catcode`\\#=11"
1909 "\\def\\#{#}\\catcode`\\#=6\n";
1911 if (contains(docdir, '%')) {
1912 docdir = subst(docdir, "%", "\\%");
1913 os << "\\catcode`\\%=11"
1914 "\\def\\%{%}\\catcode`\\%=14\n";
1916 bool const detokenize = !isAscii(from_utf8(docdir));
1917 bool const quote = contains(docdir, ' ');
1918 os << "\\makeatletter\n"
1919 << "\\def\\input@path{{";
1921 os << "\\detokenize{";
1930 << "\\makeatother\n";
1934 // get parent macros (if this buffer has a parent) which will be
1935 // written at the document begin further down.
1936 MacroSet parentMacros;
1937 listParentMacros(parentMacros, features);
1939 // Write the preamble
1940 runparams.use_babel = params().writeLaTeX(os, features,
1941 d->filename.onlyPath());
1943 // Biblatex bibliographies are loaded here
1944 if (params().useBiblatex()) {
1945 vector<docstring> const bibfiles =
1946 prepareBibFilePaths(runparams, getBibfiles(), true);
1947 for (docstring const & file: bibfiles)
1948 os << "\\addbibresource{" << file << "}\n";
1951 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1952 && !features.hasOnlyPolyglossiaLanguages()) {
1955 vector<string> bll = features.getBabelExclusiveLanguages();
1956 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1959 for (string const & sit : bll) {
1964 blangs = bll.size() > 1 ?
1965 bformat(_("The languages %1$s are only supported by Babel."), langs)
1966 : bformat(_("The language %1$s is only supported by Babel."), langs);
1970 for (string const & pit : pll) {
1975 plangs = pll.size() > 1 ?
1976 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1977 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1978 if (!blangs.empty())
1982 frontend::Alert::warning(
1983 _("Incompatible Languages!"),
1985 _("You cannot use the following languages "
1986 "together in one LaTeX document because "
1987 "they require conflicting language packages:\n"
1992 // Japanese might be required only in some children of a document,
1993 // but once required, we must keep use_japanese true.
1994 runparams.use_japanese |= features.isRequired("japanese");
1997 // Restore the parenthood if needed
1998 if (!runparams.is_child)
1999 d->ignore_parent = false;
2000 return ExportSuccess;
2004 // mark the beginning of the body to separate it from InPreamble insets
2005 os.texrow().start(TexRow::beginDocument());
2006 os << "\\begin{document}\n";
2008 // mark the start of a new paragraph by simulating a newline,
2009 // so that os.afterParbreak() returns true at document start
2012 // output the parent macros
2013 for (auto const & mac : parentMacros) {
2014 int num_lines = mac->write(os.os(), true);
2015 os.texrow().newlines(num_lines);
2018 } // output_preamble
2020 LYXERR(Debug::INFO, "preamble finished, now the body.");
2024 latexParagraphs(*this, text(), os, runparams);
2026 catch (ConversionException const &) { return ExportKilled; }
2028 // Restore the parenthood if needed
2029 if (!runparams.is_child)
2030 d->ignore_parent = false;
2032 // add this just in case after all the paragraphs
2035 if (output_preamble) {
2036 os << "\\end{document}\n";
2037 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2039 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2041 runparams_in.encoding = runparams.encoding;
2043 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2044 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2045 return ExportSuccess;
2049 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2050 OutputParams const & runparams,
2051 OutputWhat output) const
2053 LYXERR(Debug::LATEX, "makeDocBookFile...");
2056 if (!openFileWrite(ofs, fname))
2059 // make sure we are ready to export
2060 // this needs to be done before we validate
2062 updateMacroInstances(OutputUpdate);
2064 ExportStatus const retval =
2065 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2066 if (retval == ExportKilled)
2067 return ExportKilled;
2071 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2072 return ExportSuccess;
2076 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os, string const & fname,
2077 OutputParams const & runparams,
2078 OutputWhat output) const
2080 LaTeXFeatures features(*this, params(), runparams);
2085 DocumentClass const & tclass = params().documentClass();
2086 string const & top_element = tclass.latexname();
2088 bool const output_preamble =
2089 output == FullSource || output == OnlyPreamble;
2090 bool const output_body =
2091 output == FullSource || output == OnlyBody;
2093 if (output_preamble) {
2094 if (runparams.flavor == OutputParams::XML)
2095 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2098 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2101 if (! tclass.class_header().empty())
2102 os << from_ascii(tclass.class_header());
2103 else if (runparams.flavor == OutputParams::XML)
2104 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2105 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2107 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2109 docstring preamble = params().preamble;
2110 if (runparams.flavor != OutputParams::XML ) {
2111 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2112 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2113 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2114 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2117 string const name = runparams.nice
2118 ? changeExtension(absFileName(), ".sgml") : fname;
2119 preamble += features.getIncludedFiles(name);
2120 preamble += features.getLyXSGMLEntities();
2122 if (!preamble.empty()) {
2123 os << "\n [ " << preamble << " ]";
2129 string top = top_element;
2131 if (runparams.flavor == OutputParams::XML)
2132 top += params().language->code();
2134 top += params().language->code().substr(0, 2);
2137 if (!params().options.empty()) {
2139 top += params().options;
2142 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2143 << " file was created by LyX " << lyx_version
2144 << "\n See https://www.lyx.org/ for more information -->\n";
2146 params().documentClass().counters().reset();
2148 sgml::openTag(os, top);
2151 docbookParagraphs(text(), *this, os, runparams);
2153 catch (ConversionException const &) { return ExportKilled; }
2154 sgml::closeTag(os, top_element);
2156 return ExportSuccess;
2160 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2161 OutputParams const & runparams) const
2163 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2166 if (!openFileWrite(ofs, fname))
2169 // make sure we are ready to export
2170 // this has to be done before we validate
2171 updateBuffer(UpdateMaster, OutputUpdate);
2172 updateMacroInstances(OutputUpdate);
2174 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2175 if (retval == ExportKilled)
2180 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2185 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2186 OutputParams const & runparams,
2187 OutputWhat output) const
2189 LaTeXFeatures features(*this, params(), runparams);
2191 d->bibinfo_.makeCitationLabels(*this);
2193 bool const output_preamble =
2194 output == FullSource || output == OnlyPreamble;
2195 bool const output_body =
2196 output == FullSource || output == OnlyBody || output == IncludedFile;
2198 if (output_preamble) {
2199 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2200 << "<!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"
2201 // FIXME Language should be set properly.
2202 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2204 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2205 // FIXME Presumably need to set this right
2206 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2208 docstring const & doctitle = features.htmlTitle();
2210 << (doctitle.empty() ?
2211 from_ascii("LyX Document") :
2212 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2215 docstring styles = features.getTClassHTMLPreamble();
2216 if (!styles.empty())
2217 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2219 styles = features.getPreambleSnippets().str;
2220 if (!styles.empty())
2221 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2223 // we will collect CSS information in a stream, and then output it
2224 // either here, as part of the header, or else in a separate file.
2225 odocstringstream css;
2226 styles = features.getCSSSnippets();
2227 if (!styles.empty())
2228 css << "/* LyX Provided Styles */\n" << styles << '\n';
2230 styles = features.getTClassHTMLStyles();
2231 if (!styles.empty())
2232 css << "/* Layout-provided Styles */\n" << styles << '\n';
2234 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2235 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2236 if (needfg || needbg) {
2237 css << "\nbody {\n";
2240 << from_ascii(X11hexname(params().fontcolor))
2243 css << " background-color: "
2244 << from_ascii(X11hexname(params().backgroundcolor))
2249 docstring const dstyles = css.str();
2250 if (!dstyles.empty()) {
2251 bool written = false;
2252 if (params().html_css_as_file) {
2253 // open a file for CSS info
2255 string const fcssname = addName(temppath(), "docstyle.css");
2256 FileName const fcssfile = FileName(fcssname);
2257 if (openFileWrite(ocss, fcssfile)) {
2261 // write link to header
2262 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2264 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2267 // we are here if the CSS is supposed to be written to the header
2268 // or if we failed to write it to an external file.
2270 os << "<style type='text/css'>\n"
2279 bool const output_body_tag = (output != IncludedFile);
2280 if (output_body_tag)
2281 os << "<body dir=\"auto\">\n";
2283 if (output != IncludedFile)
2284 // if we're an included file, the counters are in the master.
2285 params().documentClass().counters().reset();
2287 xhtmlParagraphs(text(), *this, xs, runparams);
2289 catch (ConversionException const &) { return ExportKilled; }
2290 if (output_body_tag)
2294 if (output_preamble)
2297 return ExportSuccess;
2301 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2302 // Other flags: -wall -v0 -x
2303 int Buffer::runChktex()
2307 // get LaTeX-Filename
2308 FileName const path(temppath());
2309 string const name = addName(path.absFileName(), latexName());
2310 string const org_path = filePath();
2312 PathChanger p(path); // path to LaTeX file
2313 message(_("Running chktex..."));
2315 // Generate the LaTeX file if neccessary
2316 OutputParams runparams(¶ms().encoding());
2317 runparams.flavor = OutputParams::LATEX;
2318 runparams.nice = false;
2319 runparams.linelen = lyxrc.plaintext_linelen;
2320 ExportStatus const retval =
2321 makeLaTeXFile(FileName(name), org_path, runparams);
2322 if (retval != ExportSuccess) {
2323 // error code on failure
2328 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2329 int const res = chktex.run(terr); // run chktex
2332 Alert::error(_("chktex failure"),
2333 _("Could not run chktex successfully."));
2335 ErrorList & errlist = d->errorLists["ChkTeX"];
2337 bufferErrors(terr, errlist);
2342 if (runparams.silent)
2343 d->errorLists["ChkTeX"].clear();
2351 void Buffer::validate(LaTeXFeatures & features) const
2353 // Validate the buffer params, but not for included
2354 // files, since they also use the parent buffer's
2356 if (!features.runparams().is_child)
2357 params().validate(features);
2359 for (Paragraph const & p : paragraphs())
2360 p.validate(features);
2362 if (lyxerr.debugging(Debug::LATEX)) {
2363 features.showStruct();
2368 void Buffer::getLabelList(vector<docstring> & list) const
2370 // If this is a child document, use the master's list instead.
2372 masterBuffer()->getLabelList(list);
2377 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2378 for (auto const & tocit : *toc) {
2379 if (tocit.depth() == 0)
2380 list.push_back(tocit.str());
2385 void Buffer::invalidateBibinfoCache() const
2387 d->bibinfo_cache_valid_ = false;
2388 d->cite_labels_valid_ = false;
2389 removeBiblioTempFiles();
2390 // also invalidate the cache for the parent buffer
2391 Buffer const * const pbuf = d->parent();
2393 pbuf->invalidateBibinfoCache();
2397 FileNamePairList const & Buffer::getBibfiles(UpdateScope scope) const
2399 // FIXME This is probably unnecessary, given where we call this.
2400 // If this is a child document, use the master instead.
2401 Buffer const * const pbuf = masterBuffer();
2402 if (pbuf != this && scope != UpdateChildOnly)
2403 return pbuf->getBibfiles();
2404 return d->bibfiles_cache_;
2408 BiblioInfo const & Buffer::masterBibInfo() const
2410 Buffer const * const tmp = masterBuffer();
2412 return tmp->masterBibInfo();
2417 BiblioInfo const & Buffer::bibInfo() const
2423 void Buffer::registerBibfiles(FileNamePairList const & bf) const
2425 // We register the bib files in the master buffer,
2426 // if there is one, but also in every single buffer,
2427 // in case a child is compiled alone.
2428 Buffer const * const tmp = masterBuffer();
2430 tmp->registerBibfiles(bf);
2432 for (auto const & p : bf) {
2433 FileNamePairList::const_iterator temp =
2434 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2435 if (temp == d->bibfiles_cache_.end())
2436 d->bibfiles_cache_.push_back(p);
2441 void Buffer::checkIfBibInfoCacheIsValid() const
2443 // use the master's cache
2444 Buffer const * const tmp = masterBuffer();
2446 tmp->checkIfBibInfoCacheIsValid();
2450 // if we already know the cache is invalid, no need to check
2452 if (!d->bibinfo_cache_valid_)
2455 // compare the cached timestamps with the actual ones.
2456 FileNamePairList const & bibfiles_cache = getBibfiles();
2457 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2458 FileNamePairList::const_iterator en = bibfiles_cache.end();
2459 for (; ei != en; ++ ei) {
2460 FileName const fn = ei->second;
2461 time_t lastw = fn.lastModified();
2462 time_t prevw = d->bibfile_status_[fn];
2463 if (lastw != prevw) {
2464 d->bibinfo_cache_valid_ = false;
2465 d->cite_labels_valid_ = false;
2466 d->bibfile_status_[fn] = lastw;
2472 void Buffer::reloadBibInfoCache(bool const force) const
2474 // use the master's cache
2475 Buffer const * const tmp = masterBuffer();
2477 tmp->reloadBibInfoCache(force);
2481 checkIfBibInfoCacheIsValid();
2482 if (d->bibinfo_cache_valid_ && !force)
2485 d->bibinfo_.clear();
2486 FileNameList checkedFiles;
2487 collectBibKeys(checkedFiles);
2488 d->bibinfo_cache_valid_ = true;
2492 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2494 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2495 it->collectBibKeys(it, checkedFiles);
2499 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2501 // We add the biblio 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_;
2505 bi.mergeBiblioInfo(bin);
2507 if (parent() != 0) {
2508 BiblioInfo & masterbi = parent()->d->bibinfo_;
2509 masterbi.mergeBiblioInfo(bin);
2514 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2516 // We add the bibtex info to the master buffer,
2517 // if there is one, but also to every single buffer,
2518 // in case a child is compiled alone.
2519 BiblioInfo & bi = d->bibinfo_;
2522 if (parent() != 0) {
2523 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2524 masterbi[key] = bin;
2529 void Buffer::makeCitationLabels() const
2531 Buffer const * const master = masterBuffer();
2532 return d->bibinfo_.makeCitationLabels(*master);
2536 void Buffer::invalidateCiteLabels() const
2538 masterBuffer()->d->cite_labels_valid_ = false;
2541 bool Buffer::citeLabelsValid() const
2543 return masterBuffer()->d->cite_labels_valid_;
2547 void Buffer::removeBiblioTempFiles() const
2549 // We remove files that contain LaTeX commands specific to the
2550 // particular bibliographic style being used, in order to avoid
2551 // LaTeX errors when we switch style.
2552 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2553 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2554 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2555 aux_file.removeFile();
2556 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2557 bbl_file.removeFile();
2558 // Also for the parent buffer
2559 Buffer const * const pbuf = parent();
2561 pbuf->removeBiblioTempFiles();
2565 bool Buffer::isDepClean(string const & name) const
2567 DepClean::const_iterator const it = d->dep_clean.find(name);
2568 if (it == d->dep_clean.end())
2574 void Buffer::markDepClean(string const & name)
2576 d->dep_clean[name] = true;
2580 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2583 // FIXME? if there is an Buffer LFUN that can be dispatched even
2584 // if internal, put a switch '(cmd.action)' here.
2590 switch (cmd.action()) {
2592 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2593 flag.setOnOff(hasReadonlyFlag());
2596 // FIXME: There is need for a command-line import.
2597 //case LFUN_BUFFER_IMPORT:
2599 case LFUN_BUFFER_AUTO_SAVE:
2602 case LFUN_BUFFER_EXPORT_CUSTOM:
2603 // FIXME: Nothing to check here?
2606 case LFUN_BUFFER_EXPORT: {
2607 docstring const arg = cmd.argument();
2608 if (arg == "custom") {
2612 string format = (arg.empty() || arg == "default") ?
2613 params().getDefaultOutputFormat() : to_utf8(arg);
2614 size_t pos = format.find(' ');
2615 if (pos != string::npos)
2616 format = format.substr(0, pos);
2617 enable = params().isExportable(format, false);
2619 flag.message(bformat(
2620 _("Don't know how to export to format: %1$s"), arg));
2624 case LFUN_BUILD_PROGRAM:
2625 enable = params().isExportable("program", false);
2628 case LFUN_BRANCH_ACTIVATE:
2629 case LFUN_BRANCH_DEACTIVATE:
2630 case LFUN_BRANCH_MASTER_ACTIVATE:
2631 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2632 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2633 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2634 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2635 : params().branchlist();
2636 docstring const branchName = cmd.argument();
2637 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2641 case LFUN_BRANCH_ADD:
2642 case LFUN_BRANCHES_RENAME:
2643 // if no Buffer is present, then of course we won't be called!
2646 case LFUN_BUFFER_LANGUAGE:
2647 enable = !isReadonly();
2650 case LFUN_BUFFER_VIEW_CACHE:
2651 (d->preview_file_).refresh();
2652 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2655 case LFUN_CHANGES_TRACK:
2656 flag.setEnabled(true);
2657 flag.setOnOff(params().track_changes);
2660 case LFUN_CHANGES_OUTPUT:
2661 flag.setEnabled(true);
2662 flag.setOnOff(params().output_changes);
2665 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2666 flag.setOnOff(params().compressed);
2669 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2670 flag.setOnOff(params().output_sync);
2673 case LFUN_BUFFER_ANONYMIZE:
2679 flag.setEnabled(enable);
2684 void Buffer::dispatch(string const & command, DispatchResult & result)
2686 return dispatch(lyxaction.lookupFunc(command), result);
2690 // NOTE We can end up here even if we have no GUI, because we are called
2691 // by LyX::exec to handled command-line requests. So we may need to check
2692 // whether we have a GUI or not. The boolean use_gui holds this information.
2693 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2696 // FIXME? if there is an Buffer LFUN that can be dispatched even
2697 // if internal, put a switch '(cmd.action())' here.
2698 dr.dispatched(false);
2701 string const argument = to_utf8(func.argument());
2702 // We'll set this back to false if need be.
2703 bool dispatched = true;
2704 // This handles undo groups automagically
2705 UndoGroupHelper ugh(this);
2707 switch (func.action()) {
2708 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2709 if (lyxvc().inUse()) {
2710 string log = lyxvc().toggleReadOnly();
2715 setReadonly(!hasReadonlyFlag());
2718 case LFUN_BUFFER_EXPORT: {
2719 string const format = (argument.empty() || argument == "default") ?
2720 params().getDefaultOutputFormat() : argument;
2721 ExportStatus const status = doExport(format, false);
2722 dr.setError(status != ExportSuccess);
2723 if (status != ExportSuccess)
2724 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2725 from_utf8(format)));
2729 case LFUN_BUILD_PROGRAM: {
2730 ExportStatus const status = doExport("program", true);
2731 dr.setError(status != ExportSuccess);
2732 if (status != ExportSuccess)
2733 dr.setMessage(_("Error generating literate programming code."));
2737 case LFUN_BUFFER_EXPORT_CUSTOM: {
2739 string command = split(argument, format_name, ' ');
2740 Format const * format = theFormats().getFormat(format_name);
2742 lyxerr << "Format \"" << format_name
2743 << "\" not recognized!"
2748 // The name of the file created by the conversion process
2751 // Output to filename
2752 if (format->name() == "lyx") {
2753 string const latexname = latexName(false);
2754 filename = changeExtension(latexname,
2755 format->extension());
2756 filename = addName(temppath(), filename);
2758 if (!writeFile(FileName(filename)))
2762 doExport(format_name, true, filename);
2765 // Substitute $$FName for filename
2766 if (!contains(command, "$$FName"))
2767 command = "( " + command + " ) < $$FName";
2768 command = subst(command, "$$FName", filename);
2770 // Execute the command in the background
2772 call.startscript(Systemcall::DontWait, command,
2773 filePath(), layoutPos());
2777 // FIXME: There is need for a command-line import.
2779 case LFUN_BUFFER_IMPORT:
2784 case LFUN_BUFFER_AUTO_SAVE:
2786 resetAutosaveTimers();
2789 case LFUN_BRANCH_ACTIVATE:
2790 case LFUN_BRANCH_DEACTIVATE:
2791 case LFUN_BRANCH_MASTER_ACTIVATE:
2792 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2793 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2794 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2795 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2798 docstring const branch_name = func.argument();
2799 // the case without a branch name is handled elsewhere
2800 if (branch_name.empty()) {
2804 Branch * branch = buf->params().branchlist().find(branch_name);
2806 LYXERR0("Branch " << branch_name << " does not exist.");
2808 docstring const msg =
2809 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2813 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2814 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2815 if (branch->isSelected() != activate) {
2816 buf->undo().recordUndoBufferParams(CursorData());
2817 branch->setSelected(activate);
2819 dr.screenUpdate(Update::Force);
2820 dr.forceBufferUpdate();
2825 case LFUN_BRANCH_ADD: {
2826 docstring branchnames = func.argument();
2827 if (branchnames.empty()) {
2831 BranchList & branch_list = params().branchlist();
2832 vector<docstring> const branches =
2833 getVectorFromString(branchnames, branch_list.separator());
2835 for (docstring const & branch_name : branches) {
2836 Branch * branch = branch_list.find(branch_name);
2838 LYXERR0("Branch " << branch_name << " already exists.");
2842 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2844 undo().recordUndoBufferParams(CursorData());
2845 branch_list.add(branch_name);
2846 branch = branch_list.find(branch_name);
2847 string const x11hexname = X11hexname(branch->color());
2848 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2849 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2851 dr.screenUpdate(Update::Force);
2859 case LFUN_BRANCHES_RENAME: {
2860 if (func.argument().empty())
2863 docstring const oldname = from_utf8(func.getArg(0));
2864 docstring const newname = from_utf8(func.getArg(1));
2865 InsetIterator it = inset_iterator_begin(inset());
2866 InsetIterator const end = inset_iterator_end(inset());
2867 bool success = false;
2868 for (; it != end; ++it) {
2869 if (it->lyxCode() == BRANCH_CODE) {
2870 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2871 if (ins.branch() == oldname) {
2872 undo().recordUndo(CursorData(it));
2873 ins.rename(newname);
2878 if (it->lyxCode() == INCLUDE_CODE) {
2879 // get buffer of external file
2880 InsetInclude const & ins =
2881 static_cast<InsetInclude const &>(*it);
2882 Buffer * child = ins.getChildBuffer();
2885 child->dispatch(func, dr);
2890 dr.screenUpdate(Update::Force);
2891 dr.forceBufferUpdate();
2896 case LFUN_BUFFER_VIEW_CACHE:
2897 if (!theFormats().view(*this, d->preview_file_,
2898 d->preview_format_))
2899 dr.setMessage(_("Error viewing the output file."));
2902 case LFUN_CHANGES_TRACK:
2903 if (params().save_transient_properties)
2904 undo().recordUndoBufferParams(CursorData());
2905 params().track_changes = !params().track_changes;
2906 if (!params().track_changes)
2907 dr.forceChangesUpdate();
2910 case LFUN_CHANGES_OUTPUT:
2911 if (params().save_transient_properties)
2912 undo().recordUndoBufferParams(CursorData());
2913 params().output_changes = !params().output_changes;
2914 if (params().output_changes) {
2915 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2916 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2917 LaTeXFeatures::isAvailable("xcolor");
2919 if (!dvipost && !xcolorulem) {
2920 Alert::warning(_("Changes not shown in LaTeX output"),
2921 _("Changes will not be highlighted in LaTeX output, "
2922 "because neither dvipost nor xcolor/ulem are installed.\n"
2923 "Please install these packages or redefine "
2924 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2925 } else if (!xcolorulem) {
2926 Alert::warning(_("Changes not shown in LaTeX output"),
2927 _("Changes will not be highlighted in LaTeX output "
2928 "when using pdflatex, because xcolor and ulem are not installed.\n"
2929 "Please install both packages or redefine "
2930 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2935 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2936 // turn compression on/off
2937 undo().recordUndoBufferParams(CursorData());
2938 params().compressed = !params().compressed;
2941 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2942 undo().recordUndoBufferParams(CursorData());
2943 params().output_sync = !params().output_sync;
2946 case LFUN_BUFFER_ANONYMIZE: {
2947 undo().recordUndoFullBuffer(CursorData());
2948 CursorData cur(doc_iterator_begin(this));
2949 for ( ; cur ; cur.forwardPar())
2950 cur.paragraph().anonymize();
2951 dr.forceBufferUpdate();
2959 dr.dispatched(dispatched);
2963 void Buffer::changeLanguage(Language const * from, Language const * to)
2965 LASSERT(from, return);
2966 LASSERT(to, return);
2968 for_each(par_iterator_begin(),
2970 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2974 bool Buffer::isMultiLingual() const
2976 ParConstIterator end = par_iterator_end();
2977 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2978 if (it->isMultiLingual(params()))
2985 std::set<Language const *> Buffer::getLanguages() const
2987 std::set<Language const *> langs;
2988 getLanguages(langs);
2993 void Buffer::getLanguages(std::set<Language const *> & langs) const
2995 ParConstIterator end = par_iterator_end();
2996 // add the buffer language, even if it's not actively used
2997 langs.insert(language());
2998 // iterate over the paragraphs
2999 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3000 it->getLanguages(langs);
3002 ListOfBuffers clist = getDescendents();
3003 for (auto const & cit : clist)
3004 cit->getLanguages(langs);
3008 DocIterator Buffer::getParFromID(int const id) const
3010 Buffer * buf = const_cast<Buffer *>(this);
3012 // This means non-existent
3013 return doc_iterator_end(buf);
3015 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3016 if (it.paragraph().id() == id)
3019 return doc_iterator_end(buf);
3023 bool Buffer::hasParWithID(int const id) const
3025 return !getParFromID(id).atEnd();
3029 ParIterator Buffer::par_iterator_begin()
3031 return ParIterator(doc_iterator_begin(this));
3035 ParIterator Buffer::par_iterator_end()
3037 return ParIterator(doc_iterator_end(this));
3041 ParConstIterator Buffer::par_iterator_begin() const
3043 return ParConstIterator(doc_iterator_begin(this));
3047 ParConstIterator Buffer::par_iterator_end() const
3049 return ParConstIterator(doc_iterator_end(this));
3053 Language const * Buffer::language() const
3055 return params().language;
3059 docstring const Buffer::B_(string const & l10n) const
3061 return params().B_(l10n);
3065 bool Buffer::isClean() const
3067 return d->lyx_clean;
3071 bool Buffer::isChecksumModified() const
3073 LASSERT(d->filename.exists(), return false);
3074 return d->checksum_ != d->filename.checksum();
3078 void Buffer::saveCheckSum() const
3080 FileName const & file = d->filename;
3082 d->checksum_ = file.exists() ? file.checksum()
3083 : 0; // in the case of save to a new file.
3087 void Buffer::markClean() const
3089 if (!d->lyx_clean) {
3090 d->lyx_clean = true;
3093 // if the .lyx file has been saved, we don't need an
3095 d->bak_clean = true;
3096 d->undo_.markDirty();
3097 clearExternalModification();
3101 void Buffer::setUnnamed(bool flag)
3107 bool Buffer::isUnnamed() const
3114 /// Don't check unnamed, here: isInternal() is used in
3115 /// newBuffer(), where the unnamed flag has not been set by anyone
3116 /// yet. Also, for an internal buffer, there should be no need for
3117 /// retrieving fileName() nor for checking if it is unnamed or not.
3118 bool Buffer::isInternal() const
3120 return d->internal_buffer;
3124 void Buffer::setInternal(bool flag)
3126 d->internal_buffer = flag;
3130 void Buffer::markDirty()
3133 d->lyx_clean = false;
3136 d->bak_clean = false;
3138 for (auto & depit : d->dep_clean)
3139 depit.second = false;
3143 FileName Buffer::fileName() const
3149 string Buffer::absFileName() const
3151 return d->filename.absFileName();
3155 string Buffer::filePath() const
3157 string const abs = d->filename.onlyPath().absFileName();
3160 int last = abs.length() - 1;
3162 return abs[last] == '/' ? abs : abs + '/';
3166 DocFileName Buffer::getReferencedFileName(string const & fn) const
3169 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3170 result.set(fn, filePath());
3172 // filePath() ends with a path separator
3173 FileName const test(filePath() + fn);
3175 result.set(fn, filePath());
3177 result.set(fn, params().origin);
3184 string const Buffer::prepareFileNameForLaTeX(string const & name,
3185 string const & ext, bool nice) const
3187 string const fname = makeAbsPath(name, filePath()).absFileName();
3188 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3194 return to_utf8(makeRelPath(from_utf8(fname),
3195 from_utf8(masterBuffer()->filePath())));
3199 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3200 FileNamePairList const bibfilelist,
3201 bool const add_extension) const
3203 // If we are processing the LaTeX file in a temp directory then
3204 // copy the .bib databases to this temp directory, mangling their
3205 // names in the process. Store this mangled name in the list of
3207 // (We need to do all this because BibTeX *really*, *really*
3208 // can't handle "files with spaces" and Windows users tend to
3209 // use such filenames.)
3210 // Otherwise, store the (maybe absolute) path to the original,
3211 // unmangled database name.
3213 vector<docstring> res;
3215 // determine the export format
3216 string const tex_format = flavor2format(runparams.flavor);
3218 // check for spaces in paths
3219 bool found_space = false;
3221 for (auto const & bit : bibfilelist) {
3222 string utf8input = to_utf8(bit.first);
3224 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3225 FileName try_in_file =
3226 makeAbsPath(database + ".bib", filePath());
3227 bool not_from_texmf = try_in_file.isReadableFile();
3228 // If the file has not been found, try with the real file name
3229 // (it might come from a child in a sub-directory)
3230 if (!not_from_texmf) {
3231 try_in_file = bit.second;
3232 if (try_in_file.isReadableFile()) {
3233 // Check if the file is in texmf
3234 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3235 not_from_texmf = kpsefile.empty()
3236 || kpsefile.absFileName() != try_in_file.absFileName();
3238 // If this exists, make path relative to the master
3241 removeExtension(prepareFileNameForLaTeX(
3242 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3243 from_utf8(filePath()))),
3244 ".bib", runparams.nice));
3248 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3250 // mangledFileName() needs the extension
3251 DocFileName const in_file = DocFileName(try_in_file);
3252 database = removeExtension(in_file.mangledFileName());
3253 FileName const out_file = makeAbsPath(database + ".bib",
3254 masterBuffer()->temppath());
3255 bool const success = in_file.copyTo(out_file);
3257 LYXERR0("Failed to copy '" << in_file
3258 << "' to '" << out_file << "'");
3260 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3261 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3262 if (!isValidLaTeXFileName(database)) {
3263 frontend::Alert::warning(_("Invalid filename"),
3264 _("The following filename will cause troubles "
3265 "when running the exported file through LaTeX: ") +
3266 from_utf8(database));
3268 if (!isValidDVIFileName(database)) {
3269 frontend::Alert::warning(_("Problematic filename for DVI"),
3270 _("The following filename can cause troubles "
3271 "when running the exported file through LaTeX "
3272 "and opening the resulting DVI: ") +
3273 from_utf8(database), true);
3281 docstring const path = from_utf8(latex_path(database));
3283 if (contains(path, ' '))
3286 if (find(res.begin(), res.end(), path) == res.end())
3287 res.push_back(path);
3290 // Check if there are spaces in the path and warn BibTeX users, if so.
3291 // (biber can cope with such paths)
3292 if (!prefixIs(runparams.bibtex_command, "biber")) {
3293 // Post this warning only once.
3294 static bool warned_about_spaces = false;
3295 if (!warned_about_spaces &&
3296 runparams.nice && found_space) {
3297 warned_about_spaces = true;
3298 Alert::warning(_("Export Warning!"),
3299 _("There are spaces in the paths to your BibTeX databases.\n"
3300 "BibTeX will be unable to find them."));
3309 string Buffer::layoutPos() const
3311 return d->layout_position;
3315 void Buffer::setLayoutPos(string const & path)
3318 d->layout_position.clear();
3322 LATTEST(FileName::isAbsolute(path));
3324 d->layout_position =
3325 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3327 if (d->layout_position.empty())
3328 d->layout_position = ".";
3332 bool Buffer::hasReadonlyFlag() const
3334 return d->read_only;
3338 bool Buffer::isReadonly() const
3340 return hasReadonlyFlag() || notifiesExternalModification();
3344 void Buffer::setParent(Buffer const * buffer)
3346 // Avoids recursive include.
3347 d->setParent(buffer == this ? 0 : buffer);
3352 Buffer const * Buffer::parent() const
3358 ListOfBuffers Buffer::allRelatives() const
3360 ListOfBuffers lb = masterBuffer()->getDescendents();
3361 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3366 Buffer const * Buffer::masterBuffer() const
3368 // FIXME Should be make sure we are not in some kind
3369 // of recursive include? A -> B -> A will crash this.
3370 Buffer const * const pbuf = d->parent();
3374 return pbuf->masterBuffer();
3378 bool Buffer::isChild(Buffer * child) const
3380 return d->children_positions.find(child) != d->children_positions.end();
3384 DocIterator Buffer::firstChildPosition(Buffer const * child)
3386 Impl::BufferPositionMap::iterator it;
3387 it = d->children_positions.find(child);
3388 if (it == d->children_positions.end())
3389 return DocIterator(this);
3394 bool Buffer::hasChildren() const
3396 return !d->children_positions.empty();
3400 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3402 // loop over children
3403 for (auto const & p : d->children_positions) {
3404 Buffer * child = const_cast<Buffer *>(p.first);
3406 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3407 if (bit != clist.end())
3409 clist.push_back(child);
3411 // there might be grandchildren
3412 child->collectChildren(clist, true);
3417 ListOfBuffers Buffer::getChildren() const
3420 collectChildren(v, false);
3421 // Make sure we have not included ourselves.
3422 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3423 if (bit != v.end()) {
3424 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3431 ListOfBuffers Buffer::getDescendents() const
3434 collectChildren(v, true);
3435 // Make sure we have not included ourselves.
3436 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3437 if (bit != v.end()) {
3438 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3445 template<typename M>
3446 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3451 typename M::const_iterator it = m.lower_bound(x);
3452 if (it == m.begin())
3460 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3461 DocIterator const & pos) const
3463 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3465 // if paragraphs have no macro context set, pos will be empty
3469 // we haven't found anything yet
3470 DocIterator bestPos = owner_->par_iterator_begin();
3471 MacroData const * bestData = 0;
3473 // find macro definitions for name
3474 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3475 if (nameIt != macros.end()) {
3476 // find last definition in front of pos or at pos itself
3477 PositionScopeMacroMap::const_iterator it
3478 = greatest_below(nameIt->second, pos);
3479 if (it != nameIt->second.end()) {
3481 // scope ends behind pos?
3482 if (pos < it->second.scope) {
3483 // Looks good, remember this. If there
3484 // is no external macro behind this,
3485 // we found the right one already.
3486 bestPos = it->first;
3487 bestData = &it->second.macro;
3491 // try previous macro if there is one
3492 if (it == nameIt->second.begin())
3499 // find macros in included files
3500 PositionScopeBufferMap::const_iterator it
3501 = greatest_below(position_to_children, pos);
3502 if (it == position_to_children.end())
3503 // no children before
3507 // do we know something better (i.e. later) already?
3508 if (it->first < bestPos )
3511 // scope ends behind pos?
3512 if (pos < it->second.scope
3513 && (cloned_buffer_ ||
3514 theBufferList().isLoaded(it->second.buffer))) {
3515 // look for macro in external file
3517 MacroData const * data
3518 = it->second.buffer->getMacro(name, false);
3521 bestPos = it->first;
3527 // try previous file if there is one
3528 if (it == position_to_children.begin())
3533 // return the best macro we have found
3538 MacroData const * Buffer::getMacro(docstring const & name,
3539 DocIterator const & pos, bool global) const
3544 // query buffer macros
3545 MacroData const * data = d->getBufferMacro(name, pos);
3549 // If there is a master buffer, query that
3550 Buffer const * const pbuf = d->parent();
3552 d->macro_lock = true;
3553 MacroData const * macro = pbuf->getMacro(
3554 name, *this, false);
3555 d->macro_lock = false;
3561 data = MacroTable::globalMacros().get(name);
3570 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3572 // set scope end behind the last paragraph
3573 DocIterator scope = par_iterator_begin();
3574 scope.pit() = scope.lastpit() + 1;
3576 return getMacro(name, scope, global);
3580 MacroData const * Buffer::getMacro(docstring const & name,
3581 Buffer const & child, bool global) const
3583 // look where the child buffer is included first
3584 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3585 if (it == d->children_positions.end())
3588 // check for macros at the inclusion position
3589 return getMacro(name, it->second, global);
3593 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3595 pit_type const lastpit = it.lastpit();
3597 // look for macros in each paragraph
3598 while (it.pit() <= lastpit) {
3599 Paragraph & par = it.paragraph();
3601 // FIXME Can this be done with the new-style iterators?
3602 // iterate over the insets of the current paragraph
3603 for (auto const & insit : par.insetList()) {
3604 it.pos() = insit.pos;
3606 // is it a nested text inset?
3607 if (insit.inset->asInsetText()) {
3608 // Inset needs its own scope?
3609 InsetText const * itext = insit.inset->asInsetText();
3610 bool newScope = itext->isMacroScope();
3612 // scope which ends just behind the inset
3613 DocIterator insetScope = it;
3616 // collect macros in inset
3617 it.push_back(CursorSlice(*insit.inset));
3618 updateMacros(it, newScope ? insetScope : scope);
3623 if (insit.inset->asInsetTabular()) {
3624 CursorSlice slice(*insit.inset);
3625 size_t const numcells = slice.nargs();
3626 for (; slice.idx() < numcells; slice.forwardIdx()) {
3627 it.push_back(slice);
3628 updateMacros(it, scope);
3634 // is it an external file?
3635 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3636 // get buffer of external file
3637 InsetInclude const & incinset =
3638 static_cast<InsetInclude const &>(*insit.inset);
3640 Buffer * child = incinset.getChildBuffer();
3645 // register its position, but only when it is
3646 // included first in the buffer
3647 if (children_positions.find(child) ==
3648 children_positions.end())
3649 children_positions[child] = it;
3651 // register child with its scope
3652 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3656 InsetMath * im = insit.inset->asInsetMath();
3657 if (doing_export && im) {
3658 InsetMathHull * hull = im->asHullInset();
3660 hull->recordLocation(it);
3663 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3667 InsetMathMacroTemplate & macroTemplate =
3668 *insit.inset->asInsetMath()->asMacroTemplate();
3669 MacroContext mc(owner_, it);
3670 macroTemplate.updateToContext(mc);
3673 bool valid = macroTemplate.validMacro();
3674 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3675 // then the BufferView's cursor will be invalid in
3676 // some cases which leads to crashes.
3681 // FIXME (Abdel), I don't understand why we pass 'it' here
3682 // instead of 'macroTemplate' defined above... is this correct?
3683 macros[macroTemplate.name()][it] =
3684 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3694 void Buffer::updateMacros() const
3699 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3701 // start with empty table
3703 d->children_positions.clear();
3704 d->position_to_children.clear();
3706 // Iterate over buffer, starting with first paragraph
3707 // The scope must be bigger than any lookup DocIterator
3708 // later. For the global lookup, lastpit+1 is used, hence
3709 // we use lastpit+2 here.
3710 DocIterator it = par_iterator_begin();
3711 DocIterator outerScope = it;
3712 outerScope.pit() = outerScope.lastpit() + 2;
3713 d->updateMacros(it, outerScope);
3717 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3719 InsetIterator it = inset_iterator_begin(inset());
3720 InsetIterator const end = inset_iterator_end(inset());
3721 for (; it != end; ++it) {
3722 if (it->lyxCode() == BRANCH_CODE) {
3723 InsetBranch & br = static_cast<InsetBranch &>(*it);
3724 docstring const name = br.branch();
3725 if (!from_master && !params().branchlist().find(name))
3726 result.push_back(name);
3727 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3728 result.push_back(name);
3731 if (it->lyxCode() == INCLUDE_CODE) {
3732 // get buffer of external file
3733 InsetInclude const & ins =
3734 static_cast<InsetInclude const &>(*it);
3735 Buffer * child = ins.getChildBuffer();
3738 child->getUsedBranches(result, true);
3741 // remove duplicates
3746 void Buffer::updateMacroInstances(UpdateType utype) const
3748 LYXERR(Debug::MACROS, "updateMacroInstances for "
3749 << d->filename.onlyFileName());
3750 DocIterator it = doc_iterator_begin(this);
3752 DocIterator const end = doc_iterator_end(this);
3753 for (; it != end; it.forwardInset()) {
3754 // look for MathData cells in InsetMathNest insets
3755 InsetMath * minset = it.nextInset()->asInsetMath();
3759 // update macro in all cells of the InsetMathNest
3760 DocIterator::idx_type n = minset->nargs();
3761 MacroContext mc = MacroContext(this, it);
3762 for (DocIterator::idx_type i = 0; i < n; ++i) {
3763 MathData & data = minset->cell(i);
3764 data.updateMacros(0, mc, utype, 0);
3770 void Buffer::listMacroNames(MacroNameSet & macros) const
3775 d->macro_lock = true;
3777 // loop over macro names
3778 for (auto const & nameit : d->macros)
3779 macros.insert(nameit.first);
3781 // loop over children
3782 for (auto const & p : d->children_positions) {
3783 Buffer * child = const_cast<Buffer *>(p.first);
3784 // The buffer might have been closed (see #10766).
3785 if (theBufferList().isLoaded(child))
3786 child->listMacroNames(macros);
3790 Buffer const * const pbuf = d->parent();
3792 pbuf->listMacroNames(macros);
3794 d->macro_lock = false;
3798 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3800 Buffer const * const pbuf = d->parent();
3805 pbuf->listMacroNames(names);
3808 for (auto const & mit : names) {
3810 MacroData const * data = pbuf->getMacro(mit, *this, false);
3812 macros.insert(data);
3814 // we cannot access the original InsetMathMacroTemplate anymore
3815 // here to calls validate method. So we do its work here manually.
3816 // FIXME: somehow make the template accessible here.
3817 if (data->optionals() > 0)
3818 features.require("xargs");
3824 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3827 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3829 RefCache::iterator it = d->ref_cache_.find(label);
3830 if (it != d->ref_cache_.end())
3831 return it->second.second;
3833 static InsetLabel const * dummy_il = 0;
3834 static References const dummy_refs = References();
3835 it = d->ref_cache_.insert(
3836 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3837 return it->second.second;
3841 Buffer::References const & Buffer::references(docstring const & label) const
3843 return const_cast<Buffer *>(this)->getReferenceCache(label);
3847 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3849 References & refs = getReferenceCache(label);
3850 refs.push_back(make_pair(inset, it));
3854 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3856 masterBuffer()->d->ref_cache_[label].first = il;
3860 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3862 return masterBuffer()->d->ref_cache_[label].first;
3866 void Buffer::clearReferenceCache() const
3869 d->ref_cache_.clear();
3873 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3875 //FIXME: This does not work for child documents yet.
3876 reloadBibInfoCache();
3878 // Check if the label 'from' appears more than once
3879 vector<docstring> labels;
3880 for (auto const & bibit : masterBibInfo())
3881 labels.push_back(bibit.first);
3883 if (count(labels.begin(), labels.end(), from) > 1)
3886 string const paramName = "key";
3887 InsetIterator it = inset_iterator_begin(inset());
3889 if (it->lyxCode() != CITE_CODE)
3891 InsetCommand * inset = it->asInsetCommand();
3892 docstring const oldValue = inset->getParam(paramName);
3893 if (oldValue == from)
3894 inset->setParam(paramName, to);
3898 // returns NULL if id-to-row conversion is unsupported
3899 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3900 pit_type par_begin, pit_type par_end,
3901 OutputWhat output, bool master) const
3903 unique_ptr<TexRow> texrow;
3904 OutputParams runparams(¶ms().encoding());
3905 runparams.nice = true;
3906 runparams.flavor = params().getOutputFlavor(format);
3907 runparams.linelen = lyxrc.plaintext_linelen;
3908 // No side effect of file copying and image conversion
3909 runparams.dryrun = true;
3911 // Some macros rely on font encoding
3912 runparams.main_fontenc = params().main_font_encoding();
3914 if (output == CurrentParagraph) {
3915 runparams.par_begin = par_begin;
3916 runparams.par_end = par_end;
3917 if (par_begin + 1 == par_end) {
3919 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3923 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3924 convert<docstring>(par_begin),
3925 convert<docstring>(par_end - 1))
3928 // output paragraphs
3929 if (runparams.flavor == OutputParams::LYX) {
3930 Paragraph const & par = text().paragraphs()[par_begin];
3932 depth_type dt = par.getDepth();
3933 par.write(ods, params(), dt);
3934 os << from_utf8(ods.str());
3935 } else if (runparams.flavor == OutputParams::HTML) {
3937 setMathFlavor(runparams);
3938 xhtmlParagraphs(text(), *this, xs, runparams);
3939 } else if (runparams.flavor == OutputParams::TEXT) {
3941 // FIXME Handles only one paragraph, unlike the others.
3942 // Probably should have some routine with a signature like them.
3943 writePlaintextParagraph(*this,
3944 text().paragraphs()[par_begin], os, runparams, dummy);
3945 } else if (params().isDocBook()) {
3946 docbookParagraphs(text(), *this, os, runparams);
3948 // If we are previewing a paragraph, even if this is the
3949 // child of some other buffer, let's cut the link here,
3950 // so that no concurring settings from the master
3951 // (e.g. branch state) interfere (see #8101).
3953 d->ignore_parent = true;
3954 // We need to validate the Buffer params' features here
3955 // in order to know if we should output polyglossia
3956 // macros (instead of babel macros)
3957 LaTeXFeatures features(*this, params(), runparams);
3959 runparams.use_polyglossia = features.usePolyglossia();
3960 // latex or literate
3963 ots.texrow().newlines(2);
3965 latexParagraphs(*this, text(), ots, runparams);
3966 texrow = ots.releaseTexRow();
3968 // Restore the parenthood
3970 d->ignore_parent = false;
3974 if (output == FullSource)
3975 os << _("Preview source code");
3976 else if (output == OnlyPreamble)
3977 os << _("Preview preamble");
3978 else if (output == OnlyBody)
3979 os << _("Preview body");
3981 if (runparams.flavor == OutputParams::LYX) {
3983 if (output == FullSource)
3985 else if (output == OnlyPreamble)
3986 params().writeFile(ods, this);
3987 else if (output == OnlyBody)
3989 os << from_utf8(ods.str());
3990 } else if (runparams.flavor == OutputParams::HTML) {
3991 writeLyXHTMLSource(os, runparams, output);
3992 } else if (runparams.flavor == OutputParams::TEXT) {
3993 if (output == OnlyPreamble) {
3994 os << "% "<< _("Plain text does not have a preamble.");
3996 writePlaintextFile(*this, os, runparams);
3997 } else if (params().isDocBook()) {
3998 writeDocBookSource(os, absFileName(), runparams, output);
4000 // latex or literate
4003 ots.texrow().newlines(2);
4005 runparams.is_child = true;
4007 writeLaTeXSource(ots, string(), runparams, output);
4008 texrow = ots.releaseTexRow();
4015 ErrorList & Buffer::errorList(string const & type) const
4017 return d->errorLists[type];
4021 void Buffer::updateTocItem(std::string const & type,
4022 DocIterator const & dit) const
4025 d->gui_->updateTocItem(type, dit);
4029 void Buffer::structureChanged() const
4032 d->gui_->structureChanged();
4036 void Buffer::errors(string const & err, bool from_master) const
4039 d->gui_->errors(err, from_master);
4043 void Buffer::message(docstring const & msg) const
4046 d->gui_->message(msg);
4050 void Buffer::setBusy(bool on) const
4053 d->gui_->setBusy(on);
4057 void Buffer::updateTitles() const
4060 d->wa_->updateTitles();
4064 void Buffer::resetAutosaveTimers() const
4067 d->gui_->resetAutosaveTimers();
4071 bool Buffer::hasGuiDelegate() const
4077 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4086 class AutoSaveBuffer : public ForkedProcess {
4089 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4090 : buffer_(buffer), fname_(fname) {}
4092 virtual shared_ptr<ForkedProcess> clone() const
4094 return make_shared<AutoSaveBuffer>(*this);
4099 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4100 from_utf8(fname_.absFileName())));
4101 return run(DontWait);
4105 virtual int generateChild();
4107 Buffer const & buffer_;
4112 int AutoSaveBuffer::generateChild()
4114 #if defined(__APPLE__)
4115 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4116 * We should use something else like threads.
4118 * Since I do not know how to determine at run time what is the OS X
4119 * version, I just disable forking altogether for now (JMarc)
4121 pid_t const pid = -1;
4123 // tmp_ret will be located (usually) in /tmp
4124 // will that be a problem?
4125 // Note that this calls ForkedCalls::fork(), so it's
4126 // ok cross-platform.
4127 pid_t const pid = fork();
4128 // If you want to debug the autosave
4129 // you should set pid to -1, and comment out the fork.
4130 if (pid != 0 && pid != -1)
4134 // pid = -1 signifies that lyx was unable
4135 // to fork. But we will do the save
4137 bool failed = false;
4138 TempFile tempfile("lyxautoXXXXXX.lyx");
4139 tempfile.setAutoRemove(false);
4140 FileName const tmp_ret = tempfile.name();
4141 if (!tmp_ret.empty()) {
4142 if (!buffer_.writeFile(tmp_ret))
4144 else if (!tmp_ret.moveTo(fname_))
4150 // failed to write/rename tmp_ret so try writing direct
4151 if (!buffer_.writeFile(fname_)) {
4152 // It is dangerous to do this in the child,
4153 // but safe in the parent, so...
4154 if (pid == -1) // emit message signal.
4155 buffer_.message(_("Autosave failed!"));
4159 if (pid == 0) // we are the child so...
4168 FileName Buffer::getEmergencyFileName() const
4170 return FileName(d->filename.absFileName() + ".emergency");
4174 FileName Buffer::getAutosaveFileName() const
4176 // if the document is unnamed try to save in the backup dir, else
4177 // in the default document path, and as a last try in the filePath,
4178 // which will most often be the temporary directory
4181 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4182 : lyxrc.backupdir_path;
4183 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4186 string const fname = "#" + d->filename.onlyFileName() + "#";
4188 return makeAbsPath(fname, fpath);
4192 void Buffer::removeAutosaveFile() const
4194 FileName const f = getAutosaveFileName();
4200 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4202 FileName const newauto = getAutosaveFileName();
4204 if (newauto != oldauto && oldauto.exists())
4205 if (!oldauto.moveTo(newauto))
4206 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4210 bool Buffer::autoSave() const
4212 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4213 if (buf->d->bak_clean || hasReadonlyFlag())
4216 message(_("Autosaving current document..."));
4217 buf->d->bak_clean = true;
4219 FileName const fname = getAutosaveFileName();
4220 LASSERT(d->cloned_buffer_, return false);
4222 // If this buffer is cloned, we assume that
4223 // we are running in a separate thread already.
4224 TempFile tempfile("lyxautoXXXXXX.lyx");
4225 tempfile.setAutoRemove(false);
4226 FileName const tmp_ret = tempfile.name();
4227 if (!tmp_ret.empty()) {
4229 // assume successful write of tmp_ret
4230 if (tmp_ret.moveTo(fname))
4233 // failed to write/rename tmp_ret so try writing direct
4234 return writeFile(fname);
4238 void Buffer::setExportStatus(bool e) const
4240 d->doing_export = e;
4241 ListOfBuffers clist = getDescendents();
4242 for (auto const & bit : clist)
4243 bit->d->doing_export = e;
4247 bool Buffer::isExporting() const
4249 return d->doing_export;
4253 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4257 return doExport(target, put_in_tempdir, result_file);
4260 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4261 string & result_file) const
4263 bool const update_unincluded =
4264 params().maintain_unincluded_children
4265 && !params().getIncludedChildren().empty();
4267 // (1) export with all included children (omit \includeonly)
4268 if (update_unincluded) {
4269 ExportStatus const status =
4270 doExport(target, put_in_tempdir, true, result_file);
4271 if (status != ExportSuccess)
4274 // (2) export with included children only
4275 return doExport(target, put_in_tempdir, false, result_file);
4279 void Buffer::setMathFlavor(OutputParams & op) const
4281 switch (params().html_math_output) {
4282 case BufferParams::MathML:
4283 op.math_flavor = OutputParams::MathAsMathML;
4285 case BufferParams::HTML:
4286 op.math_flavor = OutputParams::MathAsHTML;
4288 case BufferParams::Images:
4289 op.math_flavor = OutputParams::MathAsImages;
4291 case BufferParams::LaTeX:
4292 op.math_flavor = OutputParams::MathAsLaTeX;
4298 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4299 bool includeall, string & result_file) const
4301 LYXERR(Debug::FILES, "target=" << target);
4302 OutputParams runparams(¶ms().encoding());
4303 string format = target;
4304 string dest_filename;
4305 size_t pos = target.find(' ');
4306 if (pos != string::npos) {
4307 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4308 format = target.substr(0, pos);
4309 if (format == "default")
4310 format = params().getDefaultOutputFormat();
4311 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4312 FileName(dest_filename).onlyPath().createPath();
4313 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4315 MarkAsExporting exporting(this);
4316 string backend_format;
4317 runparams.flavor = OutputParams::LATEX;
4318 runparams.linelen = lyxrc.plaintext_linelen;
4319 runparams.includeall = includeall;
4320 vector<string> backs = params().backends();
4321 Converters converters = theConverters();
4322 bool need_nice_file = false;
4323 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4324 // Get shortest path to format
4325 converters.buildGraph();
4326 Graph::EdgePath path;
4327 for (string const & sit : backs) {
4328 Graph::EdgePath p = converters.getPath(sit, format);
4329 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4330 backend_format = sit;
4335 if (!put_in_tempdir) {
4336 // Only show this alert if this is an export to a non-temporary
4337 // file (not for previewing).
4338 Alert::error(_("Couldn't export file"), bformat(
4339 _("No information for exporting the format %1$s."),
4340 theFormats().prettyName(format)));
4342 return ExportNoPathToFormat;
4344 runparams.flavor = converters.getFlavor(path, this);
4345 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4346 for (auto const & edge : path)
4347 if (theConverters().get(edge).nice()) {
4348 need_nice_file = true;
4353 backend_format = format;
4354 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4355 // FIXME: Don't hardcode format names here, but use a flag
4356 if (backend_format == "pdflatex")
4357 runparams.flavor = OutputParams::PDFLATEX;
4358 else if (backend_format == "luatex")
4359 runparams.flavor = OutputParams::LUATEX;
4360 else if (backend_format == "dviluatex")
4361 runparams.flavor = OutputParams::DVILUATEX;
4362 else if (backend_format == "xetex")
4363 runparams.flavor = OutputParams::XETEX;
4366 string filename = latexName(false);
4367 filename = addName(temppath(), filename);
4368 filename = changeExtension(filename,
4369 theFormats().extension(backend_format));
4370 LYXERR(Debug::FILES, "filename=" << filename);
4372 // Plain text backend
4373 if (backend_format == "text") {
4374 runparams.flavor = OutputParams::TEXT;
4376 writePlaintextFile(*this, FileName(filename), runparams);
4378 catch (ConversionException const &) { return ExportCancel; }
4381 else if (backend_format == "xhtml") {
4382 runparams.flavor = OutputParams::HTML;
4383 setMathFlavor(runparams);
4384 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4385 return ExportKilled;
4386 } else if (backend_format == "lyx")
4387 writeFile(FileName(filename));
4389 else if (params().isDocBook()) {
4390 runparams.nice = !put_in_tempdir;
4391 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4392 return ExportKilled;
4395 else if (backend_format == format || need_nice_file) {
4396 runparams.nice = true;
4397 ExportStatus const retval =
4398 makeLaTeXFile(FileName(filename), string(), runparams);
4399 if (retval == ExportKilled)
4400 return ExportKilled;
4401 if (d->cloned_buffer_)
4402 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4403 if (retval != ExportSuccess)
4405 } else if (!lyxrc.tex_allows_spaces
4406 && contains(filePath(), ' ')) {
4407 Alert::error(_("File name error"),
4408 bformat(_("The directory path to the document\n%1$s\n"
4409 "contains spaces, but your TeX installation does "
4410 "not allow them. You should save the file to a directory "
4411 "whose name does not contain spaces."), from_ascii(filePath())));
4412 return ExportTexPathHasSpaces;
4414 runparams.nice = false;
4415 ExportStatus const retval =
4416 makeLaTeXFile(FileName(filename), filePath(), runparams);
4417 if (retval == ExportKilled)
4418 return ExportKilled;
4419 if (d->cloned_buffer_)
4420 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4421 if (retval != ExportSuccess)
4425 string const error_type = (format == "program")
4426 ? "Build" : params().bufferFormat();
4427 ErrorList & error_list = d->errorLists[error_type];
4428 string const ext = theFormats().extension(format);
4429 FileName const tmp_result_file(changeExtension(filename, ext));
4430 Converters::RetVal const retval =
4431 converters.convert(this, FileName(filename), tmp_result_file,
4432 FileName(absFileName()), backend_format, format, error_list);
4433 if (retval == Converters::KILLED)
4434 return ExportCancel;
4435 bool success = (retval == Converters::SUCCESS);
4437 // Emit the signal to show the error list or copy it back to the
4438 // cloned Buffer so that it can be emitted afterwards.
4439 if (format != backend_format) {
4440 if (runparams.silent)
4442 else if (d->cloned_buffer_)
4443 d->cloned_buffer_->d->errorLists[error_type] =
4444 d->errorLists[error_type];
4447 // also to the children, in case of master-buffer-view
4448 ListOfBuffers clist = getDescendents();
4449 for (auto const & bit : clist) {
4450 if (runparams.silent)
4451 bit->d->errorLists[error_type].clear();
4452 else if (d->cloned_buffer_) {
4453 // Enable reverse search by copying back the
4454 // texrow object to the cloned buffer.
4455 // FIXME: this is not thread safe.
4456 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4457 bit->d->cloned_buffer_->d->errorLists[error_type] =
4458 bit->d->errorLists[error_type];
4460 bit->errors(error_type, true);
4464 if (d->cloned_buffer_) {
4465 // Enable reverse dvi or pdf to work by copying back the texrow
4466 // object to the cloned buffer.
4467 // FIXME: There is a possibility of concurrent access to texrow
4468 // here from the main GUI thread that should be securized.
4469 d->cloned_buffer_->d->texrow = d->texrow;
4470 string const err_type = params().bufferFormat();
4471 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4475 if (put_in_tempdir) {
4476 result_file = tmp_result_file.absFileName();
4477 return success ? ExportSuccess : ExportConverterError;
4480 if (dest_filename.empty())
4481 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4483 result_file = dest_filename;
4484 // We need to copy referenced files (e. g. included graphics
4485 // if format == "dvi") to the result dir.
4486 vector<ExportedFile> const files =
4487 runparams.exportdata->externalFiles(format);
4488 string const dest = runparams.export_folder.empty() ?
4489 onlyPath(result_file) : runparams.export_folder;
4490 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4491 : force_overwrite == ALL_FILES;
4492 CopyStatus status = use_force ? FORCE : SUCCESS;
4494 for (ExportedFile const & exp : files) {
4495 if (status == CANCEL) {
4496 message(_("Document export cancelled."));
4497 return ExportCancel;
4499 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4500 string fixedName = exp.exportName;
4501 if (!runparams.export_folder.empty()) {
4502 // Relative pathnames starting with ../ will be sanitized
4503 // if exporting to a different folder
4504 while (fixedName.substr(0, 3) == "../")
4505 fixedName = fixedName.substr(3, fixedName.length() - 3);
4507 FileName fixedFileName = makeAbsPath(fixedName, dest);
4508 fixedFileName.onlyPath().createPath();
4509 status = copyFile(fmt, exp.sourceName,
4511 exp.exportName, status == FORCE,
4512 runparams.export_folder.empty());
4516 if (tmp_result_file.exists()) {
4517 // Finally copy the main file
4518 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4519 : force_overwrite != NO_FILES;
4520 if (status == SUCCESS && use_force)
4522 status = copyFile(format, tmp_result_file,
4523 FileName(result_file), result_file,
4525 if (status == CANCEL) {
4526 message(_("Document export cancelled."));
4527 return ExportCancel;
4529 message(bformat(_("Document exported as %1$s "
4531 theFormats().prettyName(format),
4532 makeDisplayPath(result_file)));
4535 // This must be a dummy converter like fax (bug 1888)
4536 message(bformat(_("Document exported as %1$s"),
4537 theFormats().prettyName(format)));
4540 return success ? ExportSuccess : ExportConverterError;
4544 Buffer::ExportStatus Buffer::preview(string const & format) const
4546 bool const update_unincluded =
4547 params().maintain_unincluded_children
4548 && !params().getIncludedChildren().empty();
4549 return preview(format, update_unincluded);
4553 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4555 MarkAsExporting exporting(this);
4557 // (1) export with all included children (omit \includeonly)
4559 ExportStatus const status = doExport(format, true, true, result_file);
4560 if (status != ExportSuccess)
4563 // (2) export with included children only
4564 ExportStatus const status = doExport(format, true, false, result_file);
4565 FileName const previewFile(result_file);
4567 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4568 theimpl->preview_file_ = previewFile;
4569 theimpl->preview_format_ = format;
4570 theimpl->preview_error_ = (status != ExportSuccess);
4572 if (status != ExportSuccess)
4575 if (previewFile.exists())
4576 return theFormats().view(*this, previewFile, format) ?
4577 PreviewSuccess : PreviewError;
4579 // Successful export but no output file?
4580 // Probably a bug in error detection.
4581 LATTEST(status != ExportSuccess);
4586 Buffer::ReadStatus Buffer::extractFromVC()
4588 bool const found = LyXVC::file_not_found_hook(d->filename);
4590 return ReadFileNotFound;
4591 if (!d->filename.isReadableFile())
4597 Buffer::ReadStatus Buffer::loadEmergency()
4599 FileName const emergencyFile = getEmergencyFileName();
4600 if (!emergencyFile.exists()
4601 || emergencyFile.lastModified() <= d->filename.lastModified())
4602 return ReadFileNotFound;
4604 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4605 docstring const text = bformat(_("An emergency save of the document "
4606 "%1$s exists.\n\nRecover emergency save?"), file);
4608 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4609 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4615 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4616 bool const success = (ret_llf == ReadSuccess);
4618 if (hasReadonlyFlag()) {
4619 Alert::warning(_("File is read-only"),
4620 bformat(_("An emergency file is successfully loaded, "
4621 "but the original file %1$s is marked read-only. "
4622 "Please make sure to save the document as a different "
4623 "file."), from_utf8(d->filename.absFileName())));
4626 lyxvc().file_found_hook(d->filename);
4627 str = _("Document was successfully recovered.");
4629 str = _("Document was NOT successfully recovered.");
4630 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4631 makeDisplayPath(emergencyFile.absFileName()));
4633 int const del_emerg =
4634 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4635 _("&Remove"), _("&Keep"));
4636 if (del_emerg == 0) {
4637 emergencyFile.removeFile();
4639 Alert::warning(_("Emergency file deleted"),
4640 _("Do not forget to save your file now!"), true);
4642 return success ? ReadSuccess : ReadEmergencyFailure;
4645 int const del_emerg =
4646 Alert::prompt(_("Delete emergency file?"),
4647 _("Remove emergency file now?"), 1, 1,
4648 _("&Remove"), _("&Keep"));
4650 emergencyFile.removeFile();
4651 return ReadOriginal;
4661 Buffer::ReadStatus Buffer::loadAutosave()
4663 // Now check if autosave file is newer.
4664 FileName const autosaveFile = getAutosaveFileName();
4665 if (!autosaveFile.exists()
4666 || autosaveFile.lastModified() <= d->filename.lastModified())
4667 return ReadFileNotFound;
4669 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4670 docstring const text = bformat(_("The backup of the document %1$s "
4671 "is newer.\n\nLoad the backup instead?"), file);
4672 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4673 _("&Load backup"), _("Load &original"), _("&Cancel"));
4678 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4679 // the file is not saved if we load the autosave file.
4680 if (ret_llf == ReadSuccess) {
4681 if (hasReadonlyFlag()) {
4682 Alert::warning(_("File is read-only"),
4683 bformat(_("A backup file is successfully loaded, "
4684 "but the original file %1$s is marked read-only. "
4685 "Please make sure to save the document as a "
4687 from_utf8(d->filename.absFileName())));
4690 lyxvc().file_found_hook(d->filename);
4693 return ReadAutosaveFailure;
4696 // Here we delete the autosave
4697 autosaveFile.removeFile();
4698 return ReadOriginal;
4706 Buffer::ReadStatus Buffer::loadLyXFile()
4708 if (!d->filename.isReadableFile()) {
4709 ReadStatus const ret_rvc = extractFromVC();
4710 if (ret_rvc != ReadSuccess)
4714 ReadStatus const ret_re = loadEmergency();
4715 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4718 ReadStatus const ret_ra = loadAutosave();
4719 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4722 return loadThisLyXFile(d->filename);
4726 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4728 return readFile(fn);
4732 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4734 for (auto const & err : terr) {
4735 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4736 int errorRow = err.error_in_line;
4737 Buffer const * buf = 0;
4739 if (err.child_name.empty())
4740 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4742 // The error occurred in a child
4743 for (Buffer const * child : getDescendents()) {
4744 string const child_name =
4745 DocFileName(changeExtension(child->absFileName(), "tex")).
4747 if (err.child_name != child_name)
4749 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4750 if (!TexRow::isNone(start)) {
4751 buf = d->cloned_buffer_
4752 ? child->d->cloned_buffer_->d->owner_
4759 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4765 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4767 LBUFERR(!text().paragraphs().empty());
4769 // Use the master text class also for child documents
4770 Buffer const * const master = masterBuffer();
4771 DocumentClass const & textclass = master->params().documentClass();
4773 FileNamePairList old_bibfiles;
4774 // Do this only if we are the top-level Buffer. We also need to account
4775 // for the case of a previewed child with ignored parent here.
4776 if (master == this && !d->ignore_parent) {
4777 textclass.counters().reset(from_ascii("bibitem"));
4778 reloadBibInfoCache();
4779 // we will re-read this cache as we go through, but we need
4780 // to know whether it's changed to know whether we need to
4781 // update the bibinfo cache.
4782 old_bibfiles = d->bibfiles_cache_;
4783 d->bibfiles_cache_.clear();
4786 // keep the buffers to be children in this set. If the call from the
4787 // master comes back we can see which of them were actually seen (i.e.
4788 // via an InsetInclude). The remaining ones in the set need still be updated.
4789 static std::set<Buffer const *> bufToUpdate;
4790 if (scope == UpdateMaster) {
4791 // If this is a child document start with the master
4792 if (master != this) {
4793 bufToUpdate.insert(this);
4794 master->updateBuffer(UpdateMaster, utype);
4795 // If the master buffer has no gui associated with it, then the TocModel is
4796 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4797 // (bug 5699). The same happens if the master buffer is open in a different
4798 // window. This test catches both possibilities.
4799 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4800 // There remains a problem here: If there is another child open in yet a third
4801 // window, that TOC is not updated. So some more general solution is needed at
4803 if (master->d->gui_ != d->gui_)
4806 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4807 if (bufToUpdate.find(this) == bufToUpdate.end())
4811 // start over the counters in the master
4812 textclass.counters().reset();
4815 // update will be done below for this buffer
4816 bufToUpdate.erase(this);
4818 // update all caches
4819 clearReferenceCache();
4821 setChangesPresent(false);
4823 Buffer & cbuf = const_cast<Buffer &>(*this);
4826 ParIterator parit = cbuf.par_iterator_begin();
4827 updateBuffer(parit, utype);
4829 // If this document has siblings, then update the TocBackend later. The
4830 // reason is to ensure that later siblings are up to date when e.g. the
4831 // broken or not status of references is computed. The update is called
4832 // in InsetInclude::addToToc.
4836 // if the bibfiles changed, the cache of bibinfo is invalid
4837 FileNamePairList new_bibfiles = d->bibfiles_cache_;
4838 // this is a trick to determine whether the two vectors have
4839 // the same elements.
4840 sort(new_bibfiles.begin(), new_bibfiles.end());
4841 sort(old_bibfiles.begin(), old_bibfiles.end());
4842 if (old_bibfiles != new_bibfiles) {
4843 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4844 invalidateBibinfoCache();
4845 reloadBibInfoCache();
4846 // We relied upon the bibinfo cache when recalculating labels. But that
4847 // cache was invalid, although we didn't find that out until now. So we
4848 // have to do it all again.
4849 // That said, the only thing we really need to do is update the citation
4850 // labels. Nothing else will have changed. So we could create a new
4851 // UpdateType that would signal that fact, if we needed to do so.
4852 parit = cbuf.par_iterator_begin();
4853 // we will be re-doing the counters and references and such.
4854 textclass.counters().reset();
4855 clearReferenceCache();
4856 // we should not need to do this again?
4858 setChangesPresent(false);
4859 updateBuffer(parit, utype);
4860 // this will already have been done by reloadBibInfoCache();
4861 // d->bibinfo_cache_valid_ = true;
4864 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4865 // this is also set to true on the other path, by reloadBibInfoCache.
4866 d->bibinfo_cache_valid_ = true;
4868 d->cite_labels_valid_ = true;
4870 cbuf.tocBackend().update(true, utype);
4871 if (scope == UpdateMaster)
4872 cbuf.structureChanged();
4876 static depth_type getDepth(DocIterator const & it)
4878 depth_type depth = 0;
4879 for (size_t i = 0 ; i < it.depth() ; ++i)
4880 if (!it[i].inset().inMathed())
4881 depth += it[i].paragraph().getDepth() + 1;
4882 // remove 1 since the outer inset does not count
4883 // we should have at least one non-math inset, so
4884 // depth should nevery be 0. but maybe it is worth
4885 // marking this, just in case.
4887 // coverity[INTEGER_OVERFLOW]
4891 static depth_type getItemDepth(ParIterator const & it)
4893 Paragraph const & par = *it;
4894 LabelType const labeltype = par.layout().labeltype;
4896 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4899 // this will hold the lowest depth encountered up to now.
4900 depth_type min_depth = getDepth(it);
4901 ParIterator prev_it = it;
4904 --prev_it.top().pit();
4906 // start of nested inset: go to outer par
4908 if (prev_it.empty()) {
4909 // start of document: nothing to do
4914 // We search for the first paragraph with same label
4915 // that is not more deeply nested.
4916 Paragraph & prev_par = *prev_it;
4917 depth_type const prev_depth = getDepth(prev_it);
4918 if (labeltype == prev_par.layout().labeltype) {
4919 if (prev_depth < min_depth)
4920 return prev_par.itemdepth + 1;
4921 if (prev_depth == min_depth)
4922 return prev_par.itemdepth;
4924 min_depth = min(min_depth, prev_depth);
4925 // small optimization: if we are at depth 0, we won't
4926 // find anything else
4927 if (prev_depth == 0)
4933 static bool needEnumCounterReset(ParIterator const & it)
4935 Paragraph const & par = *it;
4936 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4937 depth_type const cur_depth = par.getDepth();
4938 ParIterator prev_it = it;
4939 while (prev_it.pit()) {
4940 --prev_it.top().pit();
4941 Paragraph const & prev_par = *prev_it;
4942 if (prev_par.getDepth() <= cur_depth)
4943 return prev_par.layout().name() != par.layout().name();
4945 // start of nested inset: reset
4950 // set the label of a paragraph. This includes the counters.
4951 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4953 BufferParams const & bp = owner_->masterBuffer()->params();
4954 DocumentClass const & textclass = bp.documentClass();
4955 Paragraph & par = it.paragraph();
4956 Layout const & layout = par.layout();
4957 Counters & counters = textclass.counters();
4959 if (par.params().startOfAppendix()) {
4960 // We want to reset the counter corresponding to toplevel sectioning
4961 Layout const & lay = textclass.getTOCLayout();
4962 docstring const cnt = lay.counter;
4964 counters.reset(cnt);
4965 counters.appendix(true);
4967 par.params().appendix(counters.appendix());
4969 // Compute the item depth of the paragraph
4970 par.itemdepth = getItemDepth(it);
4972 if (layout.margintype == MARGIN_MANUAL) {
4973 if (par.params().labelWidthString().empty())
4974 par.params().labelWidthString(par.expandLabel(layout, bp));
4975 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4976 // we do not need to do anything here, since the empty case is
4977 // handled during export.
4979 par.params().labelWidthString(docstring());
4982 switch(layout.labeltype) {
4983 case LABEL_ITEMIZE: {
4984 // At some point of time we should do something more
4985 // clever here, like:
4986 // par.params().labelString(
4987 // bp.user_defined_bullet(par.itemdepth).getText());
4988 // for now, use a simple hardcoded label
4989 docstring itemlabel;
4990 switch (par.itemdepth) {
4992 itemlabel = char_type(0x2022);
4995 itemlabel = char_type(0x2013);
4998 itemlabel = char_type(0x2217);
5001 itemlabel = char_type(0x2219); // or 0x00b7
5004 par.params().labelString(itemlabel);
5008 case LABEL_ENUMERATE: {
5009 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5011 switch (par.itemdepth) {
5022 enumcounter += "iv";
5025 // not a valid enumdepth...
5029 if (needEnumCounterReset(it)) {
5030 // Increase the master counter?
5031 if (layout.stepmastercounter)
5032 counters.stepMaster(enumcounter, utype);
5033 // Maybe we have to reset the enumeration counter.
5034 if (!layout.resumecounter)
5035 counters.reset(enumcounter);
5037 counters.step(enumcounter, utype);
5039 string const & lang = par.getParLanguage(bp)->code();
5040 par.params().labelString(counters.theCounter(enumcounter, lang));
5045 case LABEL_SENSITIVE: {
5046 string const & type = counters.current_float();
5047 docstring full_label;
5049 full_label = owner_->B_("Senseless!!! ");
5051 docstring name = owner_->B_(textclass.floats().getType(type).name());
5052 if (counters.hasCounter(from_utf8(type))) {
5053 string const & lang = par.getParLanguage(bp)->code();
5054 counters.step(from_utf8(type), utype);
5055 full_label = bformat(from_ascii("%1$s %2$s:"),
5057 counters.theCounter(from_utf8(type), lang));
5059 full_label = bformat(from_ascii("%1$s #:"), name);
5061 par.params().labelString(full_label);
5065 case LABEL_NO_LABEL:
5066 par.params().labelString(docstring());
5070 case LABEL_CENTERED:
5071 case LABEL_STATIC: {
5072 docstring const & lcounter = layout.counter;
5073 if (!lcounter.empty()) {
5074 if (layout.toclevel <= bp.secnumdepth
5075 && (layout.latextype != LATEX_ENVIRONMENT
5076 || it.text()->isFirstInSequence(it.pit()))) {
5077 if (counters.hasCounter(lcounter))
5078 counters.step(lcounter, utype);
5079 par.params().labelString(par.expandLabel(layout, bp));
5081 par.params().labelString(docstring());
5083 par.params().labelString(par.expandLabel(layout, bp));
5089 par.params().labelString(par.expandLabel(layout, bp));
5094 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5096 // LASSERT: Is it safe to continue here, or should we just return?
5097 LASSERT(parit.pit() == 0, /**/);
5099 // Set the position of the text in the buffer to be able
5100 // to resolve macros in it.
5101 parit.text()->setMacrocontextPosition(parit);
5103 depth_type maxdepth = 0;
5104 pit_type const lastpit = parit.lastpit();
5105 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5106 // reduce depth if necessary
5107 if (parit->params().depth() > maxdepth) {
5108 /** FIXME: this function is const, but
5109 * nevertheless it modifies the buffer. To be
5110 * cleaner, one should modify the buffer in
5111 * another function, which is actually
5112 * non-const. This would however be costly in
5113 * terms of code duplication.
5115 CursorData(parit).recordUndo();
5116 parit->params().depth(maxdepth);
5118 maxdepth = parit->getMaxDepthAfter();
5120 if (utype == OutputUpdate) {
5121 // track the active counters
5122 // we have to do this for the master buffer, since the local
5123 // buffer isn't tracking anything.
5124 masterBuffer()->params().documentClass().counters().
5125 setActiveLayout(parit->layout());
5128 // set the counter for this paragraph
5129 d->setLabel(parit, utype);
5131 // update change-tracking flag
5132 parit->addChangesToBuffer(*this);
5135 for (auto const & insit : parit->insetList()) {
5136 parit.pos() = insit.pos;
5137 insit.inset->updateBuffer(parit, utype);
5143 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5144 WordLangTuple & word_lang, docstring_list & suggestions) const
5148 suggestions.clear();
5149 word_lang = WordLangTuple();
5150 bool const to_end = to.empty();
5151 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5152 // OK, we start from here.
5153 for (; from != end; from.forwardPos()) {
5154 // This skips all insets with spell check disabled.
5155 while (!from.allowSpellCheck()) {
5159 // If from is at the end of the document (which is possible
5160 // when "from" was changed above) LyX will crash later otherwise.
5161 if (from.atEnd() || (!to_end && from >= end))
5164 from.paragraph().spellCheck();
5165 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5166 if (SpellChecker::misspelled(res)) {
5170 // Do not increase progress when from == to, otherwise the word
5171 // count will be wrong.
5181 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5183 bool inword = false;
5188 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5189 if (!dit.inTexted()) {
5194 Paragraph const & par = dit.paragraph();
5195 pos_type const pos = dit.pos();
5197 // Copied and adapted from isWordSeparator() in Paragraph
5198 if (pos == dit.lastpos()) {
5201 Inset const * ins = par.getInset(pos);
5202 if (ins && skipNoOutput && !ins->producesOutput()) {
5205 // stop if end of range was skipped
5206 if (!to.atEnd() && dit >= to)
5209 } else if (!par.isDeleted(pos)) {
5210 if (par.isWordSeparator(pos))
5216 if (ins && ins->isLetter())
5218 else if (ins && ins->isSpace())
5221 char_type const c = par.getChar(pos);
5222 if (isPrintableNonspace(c))
5224 else if (isSpace(c))
5234 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5236 d->updateStatistics(from, to, skipNoOutput);
5240 int Buffer::wordCount() const
5242 return d->wordCount();
5246 int Buffer::charCount(bool with_blanks) const
5248 return d->charCount(with_blanks);
5252 Buffer::ReadStatus Buffer::reload()
5255 // c.f. bug https://www.lyx.org/trac/ticket/6587
5256 removeAutosaveFile();
5257 // e.g., read-only status could have changed due to version control
5258 d->filename.refresh();
5259 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5261 // clear parent. this will get reset if need be.
5263 ReadStatus const status = loadLyXFile();
5264 if (status == ReadSuccess) {
5269 message(bformat(_("Document %1$s reloaded."), disp_fn));
5272 message(bformat(_("Could not reload document %1$s."), disp_fn));
5282 bool Buffer::saveAs(FileName const & fn)
5284 FileName const old_name = fileName();
5285 FileName const old_auto = getAutosaveFileName();
5286 bool const old_unnamed = isUnnamed();
5287 bool success = true;
5288 d->old_position = filePath();
5295 // bring the autosave file with us, just in case.
5296 moveAutosaveFile(old_auto);
5297 // validate version control data and
5298 // correct buffer title
5299 lyxvc().file_found_hook(fileName());
5301 // the file has now been saved to the new location.
5302 // we need to check that the locations of child buffers
5304 checkChildBuffers();
5305 checkMasterBuffer();
5308 // reset the old filename and unnamed state
5309 setFileName(old_name);
5310 setUnnamed(old_unnamed);
5314 d->old_position.clear();
5319 void Buffer::checkChildBuffers()
5321 for (auto const & bit : d->children_positions) {
5322 DocIterator dit = bit.second;
5323 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5324 if (!cbuf || !theBufferList().isLoaded(cbuf))
5326 Inset * inset = dit.nextInset();
5327 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5328 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5329 docstring const & incfile = inset_inc->getParam("filename");
5330 string oldloc = cbuf->absFileName();
5331 string newloc = makeAbsPath(to_utf8(incfile),
5332 onlyPath(absFileName())).absFileName();
5333 if (oldloc == newloc)
5335 // the location of the child file is incorrect.
5337 inset_inc->setChildBuffer(0);
5339 // invalidate cache of children
5340 d->children_positions.clear();
5341 d->position_to_children.clear();
5345 // If a child has been saved under a different name/path, it might have been
5346 // orphaned. Therefore the master needs to be reset (bug 8161).
5347 void Buffer::checkMasterBuffer()
5349 Buffer const * const master = masterBuffer();
5353 // necessary to re-register the child (bug 5873)
5354 // FIXME: clean up updateMacros (here, only
5355 // child registering is needed).
5356 master->updateMacros();
5357 // (re)set master as master buffer, but only
5358 // if we are a real child
5359 if (master->isChild(this))
5366 string Buffer::includedFilePath(string const & name, string const & ext) const
5368 if (d->old_position.empty() ||
5369 equivalent(FileName(d->old_position), FileName(filePath())))
5372 bool isabsolute = FileName::isAbsolute(name);
5373 // both old_position and filePath() end with a path separator
5374 string absname = isabsolute ? name : d->old_position + name;
5376 // if old_position is set to origin, we need to do the equivalent of
5377 // getReferencedFileName() (see readDocument())
5378 if (!isabsolute && d->old_position == params().origin) {
5379 FileName const test(addExtension(filePath() + name, ext));
5381 absname = filePath() + name;
5384 if (!FileName(addExtension(absname, ext)).exists())
5388 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5390 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5391 from_utf8(filePath())));
5395 void Buffer::setChangesPresent(bool b) const
5397 d->tracked_changes_present_ = b;
5401 bool Buffer::areChangesPresent() const
5403 return d->tracked_changes_present_;
5407 void Buffer::updateChangesPresent() const
5409 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5410 setChangesPresent(false);
5411 ParConstIterator it = par_iterator_begin();
5412 ParConstIterator const end = par_iterator_end();
5413 for (; !areChangesPresent() && it != end; ++it)
5414 it->addChangesToBuffer(*this);
5418 void Buffer::Impl::refreshFileMonitor()
5420 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5421 file_monitor_->refresh();
5425 // The previous file monitor is invalid
5426 // This also destroys the previous file monitor and all its connections
5427 file_monitor_ = FileSystemWatcher::monitor(filename);
5428 // file_monitor_ will be destroyed with *this, so it is not going to call a
5429 // destroyed object method.
5430 file_monitor_->connect([this](bool exists) {
5431 fileExternallyModified(exists);
5436 void Buffer::Impl::fileExternallyModified(bool const exists)
5438 // ignore notifications after our own saving operations
5439 if (checksum_ == filename.checksum()) {
5440 LYXERR(Debug::FILES, "External modification but "
5441 "checksum unchanged: " << filename);
5444 // If the file has been deleted, only mark the file as dirty since it is
5445 // pointless to prompt for reloading. If later a file is moved into this
5446 // location, then the externally modified warning will appear then.
5448 externally_modified_ = true;
5449 // Update external modification notification.
5450 // Dirty buffers must be visible at all times.
5451 if (wa_ && wa_->unhide(owner_))
5452 wa_->updateTitles();
5454 // Unable to unhide the buffer (e.g. no GUI or not current View)
5459 bool Buffer::notifiesExternalModification() const
5461 return d->externally_modified_;
5465 void Buffer::clearExternalModification() const
5467 d->externally_modified_ = false;
5469 d->wa_->updateTitles();