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;
139 // Information about labels and their associated refs
144 InsetLabel const * inset;
145 /// associated references cache
146 Buffer::References references;
147 /// whether this label is active (i.e., not deleted)
151 typedef vector<LabelInfo> RefCache;
156 // A storehouse for the cloned buffers.
157 list<CloneList *> cloned_buffers;
163 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
167 delete preview_loader_;
175 /// search for macro in local (buffer) table or in children
176 MacroData const * getBufferMacro(docstring const & name,
177 DocIterator const & pos) const;
179 /// Update macro table starting with position of it \param it in some
181 void updateMacros(DocIterator & it, DocIterator & scope);
183 void setLabel(ParIterator & it, UpdateType utype) const;
185 /** If we have branches that use the file suffix
186 feature, return the file name with suffix appended.
188 FileName exportFileName() const;
195 mutable TexRow texrow;
197 /// need to regenerate .tex?
201 mutable bool lyx_clean;
203 /// is autosave needed?
204 mutable bool bak_clean;
206 /// is this an unnamed file (New...)?
209 /// is this an internal bufffer?
210 bool internal_buffer;
215 /// name of the file the buffer is associated with.
218 /** Set to true only when the file is fully loaded.
219 * Used to prevent the premature generation of previews
220 * and by the citation inset.
222 bool file_fully_loaded;
224 /// original format of loaded file
227 /// if the file was originally loaded from an older format, do
228 /// we need to back it up still?
229 bool need_format_backup;
231 /// Ignore the parent (e.g. when exporting a child standalone)?
235 mutable TocBackend toc_backend;
240 ScopeMacro(DocIterator const & s, MacroData const & m)
241 : scope(s), macro(m) {}
245 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
246 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
247 /// map from the macro name to the position map,
248 /// which maps the macro definition position to the scope and the MacroData.
249 NamePositionScopeMacroMap macros;
250 /// This seem to change the way Buffer::getMacro() works
251 mutable bool macro_lock;
253 /// positions of child buffers in the buffer
254 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
256 ScopeBuffer() : buffer(0) {}
257 ScopeBuffer(DocIterator const & s, Buffer const * b)
258 : scope(s), buffer(b) {}
260 Buffer const * buffer;
262 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
263 /// position of children buffers in this buffer
264 BufferPositionMap children_positions;
265 /// map from children inclusion positions to their scope and their buffer
266 PositionScopeBufferMap position_to_children;
268 /// Contains the old buffer filePath() while saving-as, or the
269 /// directory where the document was last saved while loading.
272 /** Keeps track of the path of local layout files.
273 * If possible, it is always relative to the buffer path.
274 * Empty for layouts in system or user directory.
276 string layout_position;
278 /// Container for all sort of Buffer dependant errors.
279 map<string, ErrorList> errorLists;
281 /// checksum used to test if the file has been externally modified. Used to
282 /// double check whether the file had been externally modified when saving.
283 unsigned long checksum_;
286 frontend::WorkAreaManager * wa_;
288 frontend::GuiBufferDelegate * gui_;
293 /// A cache for the bibfiles (including bibfiles of loaded child
294 /// documents), needed for appropriate update of natbib labels.
295 mutable docstring_list bibfiles_cache_;
297 // FIXME The caching mechanism could be improved. At present, we have a
298 // cache for each Buffer, that caches all the bibliography info for that
299 // Buffer. A more efficient solution would be to have a global cache per
300 // file, and then to construct the Buffer's bibinfo from that.
301 /// A cache for bibliography info
302 mutable BiblioInfo bibinfo_;
303 /// whether the bibinfo cache is valid
304 mutable bool bibinfo_cache_valid_;
305 /// Cache of timestamps of .bib files
306 map<FileName, time_t> bibfile_status_;
307 /// Indicates whether the bibinfo has changed since the last time
308 /// we ran updateBuffer(), i.e., whether citation labels may need
310 mutable bool cite_labels_valid_;
312 /// These two hold the file name and format, written to by
313 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
314 FileName preview_file_;
315 string preview_format_;
316 /// If there was an error when previewing, on the next preview we do
317 /// a fresh compile (e.g. in case the user installed a package that
321 /// Cache the label insets, their associated refs (with positions),
322 /// and whether the insets are active.
323 mutable RefCache ref_cache_;
325 /// our Text that should be wrapped in an InsetText
329 PreviewLoader * preview_loader_;
331 /// This is here to force the test to be done whenever parent_buffer
333 Buffer const * parent() const
335 // ignore_parent temporarily "orphans" a buffer
336 // (e.g. if a child is compiled standalone)
339 // if parent_buffer is not loaded, then it has been unloaded,
340 // which means that parent_buffer is an invalid pointer. So we
341 // set it to null in that case.
342 // however, the BufferList doesn't know about cloned buffers, so
343 // they will always be regarded as unloaded. in that case, we hope
345 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
347 return parent_buffer;
351 void setParent(Buffer const * pb)
353 if (parent_buffer == pb)
356 if (!cloned_buffer_ && parent_buffer && pb)
357 LYXERR0("Warning: a buffer should not have two parents!");
359 if (!cloned_buffer_ && parent_buffer)
360 parent_buffer->invalidateBibinfoCache();
363 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
364 /// This one is useful for preview detached in a thread.
365 Buffer const * cloned_buffer_;
367 CloneList * clone_list_;
368 /// are we in the process of exporting this buffer?
369 mutable bool doing_export;
371 /// compute statistics
372 /// \p from initial position
373 /// \p to points to the end position
374 void updateStatistics(DocIterator & from, DocIterator & to,
375 bool skipNoOutput = true);
376 /// statistics accessor functions
377 int wordCount() const
381 int charCount(bool with_blanks) const
384 + (with_blanks ? blank_count_ : 0);
387 // does the buffer contain tracked changes? (if so, we automatically
388 // display the review toolbar, for instance)
389 mutable bool tracked_changes_present_;
391 // Make sure the file monitor monitors the good file.
392 void refreshFileMonitor();
394 /// Notify or clear of external modification
395 void fileExternallyModified(bool exists);
397 /// has been externally modified? Can be reset by the user.
398 mutable bool externally_modified_;
401 /// So we can force access via the accessors.
402 mutable Buffer const * parent_buffer;
408 FileMonitorPtr file_monitor_;
412 /// Creates the per buffer temporary directory
413 static FileName createBufferTmpDir()
415 // FIXME This would be the ideal application for a TempDir class (like
416 // TempFile but for directories)
421 Mutex::Locker locker(&mutex);
422 counter = convert<string>(count++);
424 // We are in our own directory. Why bother to mangle name?
425 // In fact I wrote this code to circumvent a problematic behaviour
426 // (bug?) of EMX mkstemp().
427 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
430 if (!tmpfl.createDirectory(0777)) {
431 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
432 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
433 from_utf8(tmpfl.absFileName())));
439 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
440 Buffer const * cloned_buffer)
441 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
442 internal_buffer(false), read_only(readonly_), filename(file),
443 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
444 ignore_parent(false), toc_backend(owner), macro_lock(false),
445 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
446 cite_labels_valid_(false), preview_error_(false),
447 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
448 clone_list_(0), doing_export(false),
449 tracked_changes_present_(0), externally_modified_(false), parent_buffer(0),
450 word_count_(0), char_count_(0), blank_count_(0)
452 refreshFileMonitor();
453 if (!cloned_buffer_) {
454 temppath = createBufferTmpDir();
455 lyxvc.setBuffer(owner_);
457 wa_ = new frontend::WorkAreaManager;
460 temppath = cloned_buffer_->d->temppath;
461 file_fully_loaded = true;
462 params = cloned_buffer_->d->params;
463 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
464 bibinfo_ = cloned_buffer_->d->bibinfo_;
465 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
466 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
467 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
468 unnamed = cloned_buffer_->d->unnamed;
469 internal_buffer = cloned_buffer_->d->internal_buffer;
470 layout_position = cloned_buffer_->d->layout_position;
471 preview_file_ = cloned_buffer_->d->preview_file_;
472 preview_format_ = cloned_buffer_->d->preview_format_;
473 preview_error_ = cloned_buffer_->d->preview_error_;
474 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
478 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
479 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
481 LYXERR(Debug::INFO, "Buffer::Buffer()");
483 d->inset = new InsetText(*cloned_buffer->d->inset);
484 d->inset->setBuffer(*this);
485 // FIXME: optimize this loop somewhat, maybe by creating a new
486 // general recursive Inset::setId().
487 DocIterator it = doc_iterator_begin(this);
488 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
489 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
490 it.paragraph().setId(cloned_it.paragraph().id());
492 d->inset = new InsetText(this);
493 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
499 LYXERR(Debug::INFO, "Buffer::~Buffer()");
500 // here the buffer should take care that it is
501 // saved properly, before it goes into the void.
503 // GuiView already destroyed
507 // No need to do additional cleanups for internal buffer.
513 // this is in case of recursive includes: we won't try to delete
514 // ourselves as a child.
515 d->clone_list_->erase(this);
516 // loop over children
517 for (auto const & p : d->children_positions) {
518 Buffer * child = const_cast<Buffer *>(p.first);
519 if (d->clone_list_->erase(child))
522 // if we're the master buffer, then we should get rid of the list
525 // If this is not empty, we have leaked something. Worse, one of the
526 // children still has a reference to this list. But we will try to
527 // continue, rather than shut down.
528 LATTEST(d->clone_list_->empty());
529 list<CloneList *>::iterator it =
530 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
531 if (it == cloned_buffers.end()) {
532 // We will leak in this case, but it is safe to continue.
535 cloned_buffers.erase(it);
536 delete d->clone_list_;
538 // FIXME Do we really need to do this right before we delete d?
539 // clear references to children in macro tables
540 d->children_positions.clear();
541 d->position_to_children.clear();
543 // loop over children
544 for (auto const & p : d->children_positions) {
545 Buffer * child = const_cast<Buffer *>(p.first);
546 if (theBufferList().isLoaded(child)) {
547 if (theBufferList().isOthersChild(this, child))
550 theBufferList().release(child);
555 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
557 msg += emergencyWrite();
559 msg += " " + _("Save failed! Document is lost.");
561 Alert::warning(_("Attempting to close changed document!"), msg);
564 // FIXME Do we really need to do this right before we delete d?
565 // clear references to children in macro tables
566 d->children_positions.clear();
567 d->position_to_children.clear();
569 if (!d->temppath.destroyDirectory()) {
570 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
571 from_utf8(d->temppath.absFileName())));
580 Buffer * Buffer::cloneWithChildren() const
583 cloned_buffers.push_back(new CloneList);
584 CloneList * clones = cloned_buffers.back();
586 cloneWithChildren(bufmap, clones);
588 // make sure we got cloned
589 BufferMap::const_iterator bit = bufmap.find(this);
590 LASSERT(bit != bufmap.end(), return 0);
591 Buffer * cloned_buffer = bit->second;
593 return cloned_buffer;
597 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
599 // have we already been cloned?
600 if (bufmap.find(this) != bufmap.end())
603 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
605 // The clone needs its own DocumentClass, since running updateBuffer() will
606 // modify it, and we would otherwise be sharing it with the original Buffer.
607 buffer_clone->params().makeDocumentClass(true);
609 cap::switchBetweenClasses(
610 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
611 static_cast<InsetText &>(buffer_clone->inset()), el);
613 bufmap[this] = buffer_clone;
614 clones->insert(buffer_clone);
615 buffer_clone->d->clone_list_ = clones;
616 buffer_clone->d->macro_lock = true;
617 buffer_clone->d->children_positions.clear();
619 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
620 // math macro caches need to be rethought and simplified.
621 // I am not sure wether we should handle Buffer cloning here or in BufferList.
622 // Right now BufferList knows nothing about buffer clones.
623 for (auto const & p : d->position_to_children) {
624 DocIterator dit = p.first.clone(buffer_clone);
625 dit.setBuffer(buffer_clone);
626 Buffer * child = const_cast<Buffer *>(p.second.buffer);
628 child->cloneWithChildren(bufmap, clones);
629 BufferMap::iterator const bit = bufmap.find(child);
630 LASSERT(bit != bufmap.end(), continue);
631 Buffer * child_clone = bit->second;
633 Inset * inset = dit.nextInset();
634 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
635 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
636 inset_inc->setChildBuffer(child_clone);
637 child_clone->d->setParent(buffer_clone);
638 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
639 buffer_clone->setChild(dit, child_clone);
641 buffer_clone->d->macro_lock = false;
646 Buffer * Buffer::cloneBufferOnly() const {
647 cloned_buffers.push_back(new CloneList);
648 CloneList * clones = cloned_buffers.back();
649 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
651 // The clone needs its own DocumentClass, since running updateBuffer() will
652 // modify it, and we would otherwise be sharing it with the original Buffer.
653 buffer_clone->params().makeDocumentClass(true);
655 cap::switchBetweenClasses(
656 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
657 static_cast<InsetText &>(buffer_clone->inset()), el);
659 clones->insert(buffer_clone);
660 buffer_clone->d->clone_list_ = clones;
662 // we won't be cloning the children
663 buffer_clone->d->children_positions.clear();
668 bool Buffer::isClone() const
670 return d->cloned_buffer_;
674 void Buffer::changed(bool update_metrics) const
677 d->wa_->redrawAll(update_metrics);
681 frontend::WorkAreaManager & Buffer::workAreaManager() const
688 Text & Buffer::text() const
690 return d->inset->text();
694 Inset & Buffer::inset() const
700 BufferParams & Buffer::params()
706 BufferParams const & Buffer::params() const
712 BufferParams const & Buffer::masterParams() const
714 if (masterBuffer() == this)
717 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
718 // Copy child authors to the params. We need those pointers.
719 for (Author const & a : params().authors())
720 mparams.authors().record(a);
725 double Buffer::fontScalingFactor() const
727 return isExporting() ? 75.0 * params().html_math_img_scale
728 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
732 ParagraphList & Buffer::paragraphs()
734 return text().paragraphs();
738 ParagraphList const & Buffer::paragraphs() const
740 return text().paragraphs();
744 LyXVC & Buffer::lyxvc()
750 LyXVC const & Buffer::lyxvc() const
756 string const Buffer::temppath() const
758 return d->temppath.absFileName();
762 TexRow & Buffer::texrow()
768 TexRow const & Buffer::texrow() const
774 TocBackend & Buffer::tocBackend() const
776 return d->toc_backend;
780 Undo & Buffer::undo()
786 void Buffer::setChild(DocIterator const & dit, Buffer * child)
788 d->children_positions[child] = dit;
792 string Buffer::latexName(bool const no_path) const
794 FileName latex_name =
795 makeLatexName(d->exportFileName());
796 return no_path ? latex_name.onlyFileName()
797 : latex_name.absFileName();
801 FileName Buffer::Impl::exportFileName() const
803 docstring const branch_suffix =
804 params.branchlist().getFileNameSuffix();
805 if (branch_suffix.empty())
808 string const name = filename.onlyFileNameWithoutExt()
809 + to_utf8(branch_suffix);
810 FileName res(filename.onlyPath().absFileName() + "/" + name);
811 res.changeExtension(filename.extension());
817 string Buffer::logName(LogType * type) const
819 string const filename = latexName(false);
821 if (filename.empty()) {
827 string const path = temppath();
829 FileName const fname(addName(temppath(),
830 onlyFileName(changeExtension(filename,
833 // FIXME: how do we know this is the name of the build log?
834 FileName const bname(
835 addName(path, onlyFileName(
836 changeExtension(filename,
837 theFormats().extension(params().bufferFormat()) + ".out"))));
839 // Also consider the master buffer log file
840 FileName masterfname = fname;
841 LogType mtype = latexlog;
842 if (masterBuffer() != this) {
843 string const mlogfile = masterBuffer()->logName(&mtype);
844 masterfname = FileName(mlogfile);
847 // If no Latex log or Build log is newer, show Build log
848 if (bname.exists() &&
849 ((!fname.exists() && !masterfname.exists())
850 || (fname.lastModified() < bname.lastModified()
851 && masterfname.lastModified() < bname.lastModified()))) {
852 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
855 return bname.absFileName();
856 // If we have a newer master file log or only a master log, show this
857 } else if (fname != masterfname
858 && (!fname.exists() && (masterfname.exists()
859 || fname.lastModified() < masterfname.lastModified()))) {
860 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
863 return masterfname.absFileName();
865 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
868 return fname.absFileName();
872 void Buffer::setReadonly(bool const flag)
874 if (d->read_only != flag) {
881 void Buffer::setFileName(FileName const & fname)
883 bool const changed = fname != d->filename;
885 d->refreshFileMonitor();
887 lyxvc().file_found_hook(fname);
888 setReadonly(d->filename.isReadOnly());
894 int Buffer::readHeader(Lexer & lex)
896 int unknown_tokens = 0;
898 int begin_header_line = -1;
900 // Initialize parameters that may be/go lacking in header:
901 params().branchlist().clear();
902 params().preamble.erase();
903 params().options.erase();
904 params().master.erase();
905 params().float_placement.erase();
906 params().float_alignment.erase();
907 params().paperwidth.erase();
908 params().paperheight.erase();
909 params().leftmargin.erase();
910 params().rightmargin.erase();
911 params().topmargin.erase();
912 params().bottommargin.erase();
913 params().headheight.erase();
914 params().headsep.erase();
915 params().footskip.erase();
916 params().columnsep.erase();
917 params().fonts_cjk.erase();
918 params().listings_params.clear();
919 params().clearLayoutModules();
920 params().clearRemovedModules();
921 params().clearIncludedChildren();
922 params().pdfoptions().clear();
923 params().indiceslist().clear();
924 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
925 params().isbackgroundcolor = false;
926 params().fontcolor = RGBColor(0, 0, 0);
927 params().isfontcolor = false;
928 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
929 params().boxbgcolor = RGBColor(0xFF, 0, 0);
930 params().html_latex_start.clear();
931 params().html_latex_end.clear();
932 params().html_math_img_scale = 1.0;
933 params().output_sync_macro.erase();
934 params().setLocalLayout(docstring(), false);
935 params().setLocalLayout(docstring(), true);
936 params().biblio_opts.erase();
937 params().biblatex_bibstyle.erase();
938 params().biblatex_citestyle.erase();
939 params().multibib.erase();
941 for (int i = 0; i < 4; ++i) {
942 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
943 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
946 ErrorList & errorList = d->errorLists["Parse"];
955 if (token == "\\end_header")
959 if (token == "\\begin_header") {
960 begin_header_line = line;
964 LYXERR(Debug::PARSER, "Handling document header token: `"
967 string const result =
968 params().readToken(lex, token, d->filename.onlyPath());
969 if (!result.empty()) {
970 if (token == "\\textclass") {
971 d->layout_position = result;
974 docstring const s = bformat(_("Unknown token: "
978 errorList.push_back(ErrorItem(_("Document header error"), s));
982 if (begin_header_line) {
983 docstring const s = _("\\begin_header is missing");
984 errorList.push_back(ErrorItem(_("Document header error"), s));
987 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
989 params().makeDocumentClass();
991 return unknown_tokens;
996 // changed to be public and have one parameter
997 // Returns true if "\end_document" is not read (Asger)
998 bool Buffer::readDocument(Lexer & lex)
1000 ErrorList & errorList = d->errorLists["Parse"];
1003 // remove dummy empty par
1004 paragraphs().clear();
1006 if (!lex.checkFor("\\begin_document")) {
1007 docstring const s = _("\\begin_document is missing");
1008 errorList.push_back(ErrorItem(_("Document header error"), s));
1013 if (params().output_changes) {
1014 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1015 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1016 LaTeXFeatures::isAvailable("xcolor");
1018 if (!dvipost && !xcolorulem) {
1019 Alert::warning(_("Changes not shown in LaTeX output"),
1020 _("Changes will not be highlighted in LaTeX output, "
1021 "because neither dvipost nor xcolor/ulem are installed.\n"
1022 "Please install these packages or redefine "
1023 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1024 } else if (!xcolorulem) {
1025 Alert::warning(_("Changes not shown in LaTeX output"),
1026 _("Changes will not be highlighted in LaTeX output "
1027 "when using pdflatex, because xcolor and ulem are not installed.\n"
1028 "Please install both packages or redefine "
1029 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1033 if (!parent() && !params().master.empty()) {
1034 FileName const master_file = makeAbsPath(params().master,
1035 onlyPath(absFileName()));
1036 if (isLyXFileName(master_file.absFileName())) {
1038 checkAndLoadLyXFile(master_file, true);
1040 // necessary e.g. after a reload
1041 // to re-register the child (bug 5873)
1042 // FIXME: clean up updateMacros (here, only
1043 // child registering is needed).
1044 master->updateMacros();
1045 // set master as master buffer, but only
1046 // if we are a real child
1047 if (master->isChild(this))
1049 // if the master is not fully loaded
1050 // it is probably just loading this
1051 // child. No warning needed then.
1052 else if (master->isFullyLoaded())
1053 LYXERR0("The master '"
1055 << "' assigned to this document ("
1057 << ") does not include "
1058 "this document. Ignoring the master assignment.");
1059 // If the master has just been created, un-hide it (#11162)
1060 if (!master->fileName().exists())
1061 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1062 master->absFileName()));
1067 // assure we have a default index
1068 params().indiceslist().addDefault(B_("Index"));
1071 if (FileName::isAbsolute(params().origin))
1072 d->old_position = params().origin;
1074 d->old_position = filePath();
1075 bool const res = text().read(lex, errorList, d->inset);
1076 d->old_position.clear();
1078 // inform parent buffer about local macros
1080 Buffer const * pbuf = parent();
1081 for (auto const & m : usermacros)
1082 pbuf->usermacros.insert(m);
1086 updateMacroInstances(InternalUpdate);
1091 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1093 Format const * fmt = theFormats().getFormat(format);
1096 // It is important to use the correct extension here, since some
1097 // converters create a wrong output file otherwise (e.g. html2latex)
1098 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1099 ofdocstream os(name.toFilesystemEncoding().c_str());
1100 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1101 bool const success = !(os << contents).fail();
1104 bool converted = false;
1106 params().compressed = false;
1108 // remove dummy empty par
1109 paragraphs().clear();
1111 converted = importFile(format, name, errorList);
1114 removeTempFile(name);
1119 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1121 if (!theConverters().isReachable(format, "lyx"))
1124 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1125 Converters::RetVal const retval =
1126 theConverters().convert(0, name, lyx, name, format, "lyx", errorList);
1127 if (retval == Converters::SUCCESS) {
1128 bool const success = readFile(lyx) == ReadSuccess;
1129 removeTempFile(lyx);
1137 bool Buffer::readString(string const & s)
1139 params().compressed = false;
1142 istringstream is(s);
1144 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1145 FileName const fn = tempfile.name();
1148 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1150 if (success && file_format != LYX_FORMAT) {
1151 // We need to call lyx2lyx, so write the input to a file
1152 ofstream os(fn.toFilesystemEncoding().c_str());
1155 // lyxvc in readFile
1156 if (readFile(fn) != ReadSuccess)
1160 if (readDocument(lex))
1166 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1170 if (!lex.setFile(fname)) {
1171 Alert::error(_("File Not Found"),
1172 bformat(_("Unable to open file `%1$s'."),
1173 from_utf8(fn.absFileName())));
1174 return ReadFileNotFound;
1178 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1179 if (ret_plf != ReadSuccess)
1182 if (file_format != LYX_FORMAT) {
1184 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1185 if (ret_clf != ReadSuccess)
1187 ret_clf = readFile(tmpFile);
1188 if (ret_clf == ReadSuccess) {
1189 d->file_format = file_format;
1190 d->need_format_backup = true;
1195 // FIXME: InsetInfo needs to know whether the file is under VCS
1196 // during the parse process, so this has to be done before.
1197 lyxvc().file_found_hook(d->filename);
1199 if (readDocument(lex)) {
1200 Alert::error(_("Document format failure"),
1201 bformat(_("%1$s ended unexpectedly, which means"
1202 " that it is probably corrupted."),
1203 from_utf8(fn.absFileName())));
1204 return ReadDocumentFailure;
1207 d->file_fully_loaded = true;
1208 d->read_only = !d->filename.isWritable();
1209 params().compressed = theFormats().isZippedFile(d->filename);
1215 bool Buffer::isFullyLoaded() const
1217 return d->file_fully_loaded;
1221 void Buffer::setFullyLoaded(bool value)
1223 d->file_fully_loaded = value;
1227 bool Buffer::lastPreviewError() const
1229 return d->preview_error_;
1233 PreviewLoader * Buffer::loader() const
1235 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1237 if (!d->preview_loader_)
1238 d->preview_loader_ = new PreviewLoader(*this);
1239 return d->preview_loader_;
1243 void Buffer::removePreviews() const
1245 delete d->preview_loader_;
1246 d->preview_loader_ = 0;
1250 void Buffer::updatePreviews() const
1252 PreviewLoader * ploader = loader();
1256 InsetIterator it = inset_iterator_begin(*d->inset);
1257 InsetIterator const end = inset_iterator_end(*d->inset);
1258 for (; it != end; ++it)
1259 it->addPreview(it, *ploader);
1261 ploader->startLoading();
1265 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1266 FileName const & fn, int & file_format) const
1268 if(!lex.checkFor("\\lyxformat")) {
1269 Alert::error(_("Document format failure"),
1270 bformat(_("%1$s is not a readable LyX document."),
1271 from_utf8(fn.absFileName())));
1272 return ReadNoLyXFormat;
1278 // LyX formats 217 and earlier were written as 2.17. This corresponds
1279 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1280 // these cases. See also: www.lyx.org/trac/changeset/1313.
1281 size_t dot = tmp_format.find_first_of(".,");
1282 if (dot != string::npos)
1283 tmp_format.erase(dot, 1);
1285 file_format = convert<int>(tmp_format);
1290 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1291 FileName & tmpfile, int from_format)
1293 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1294 tempfile.setAutoRemove(false);
1295 tmpfile = tempfile.name();
1296 if(tmpfile.empty()) {
1297 Alert::error(_("Conversion failed"),
1298 bformat(_("%1$s is from a different"
1299 " version of LyX, but a temporary"
1300 " file for converting it could"
1301 " not be created."),
1302 from_utf8(fn.absFileName())));
1303 return LyX2LyXNoTempFile;
1306 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1307 if (lyx2lyx.empty()) {
1308 Alert::error(_("Conversion script not found"),
1309 bformat(_("%1$s is from a different"
1310 " version of LyX, but the"
1311 " conversion script lyx2lyx"
1312 " could not be found."),
1313 from_utf8(fn.absFileName())));
1314 return LyX2LyXNotFound;
1318 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1319 ostringstream command;
1320 command << os::python()
1321 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1322 << " -t " << convert<string>(LYX_FORMAT)
1323 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1324 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1325 string const command_str = command.str();
1327 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1329 cmd_ret const ret = runCommand(command_str);
1330 if (ret.first != 0) {
1331 if (from_format < LYX_FORMAT) {
1332 Alert::error(_("Conversion script failed"),
1333 bformat(_("%1$s is from an older version"
1334 " of LyX and the lyx2lyx script"
1335 " failed to convert it."),
1336 from_utf8(fn.absFileName())));
1337 return LyX2LyXOlderFormat;
1339 Alert::error(_("Conversion script failed"),
1340 bformat(_("%1$s is from a newer version"
1341 " of LyX and the lyx2lyx script"
1342 " failed to convert it."),
1343 from_utf8(fn.absFileName())));
1344 return LyX2LyXNewerFormat;
1351 FileName Buffer::getBackupName() const {
1352 map<int, string> const file_formats = {
1369 FileName const & fn = fileName();
1370 string const fname = fn.onlyFileNameWithoutExt();
1371 string const fext = fn.extension() + "~";
1372 string const fpath = lyxrc.backupdir_path.empty() ?
1373 fn.onlyPath().absFileName() :
1374 lyxrc.backupdir_path;
1375 string backup_suffix;
1376 // If file format is from a stable series use version instead of file format
1377 auto const it = file_formats.find(d->file_format);
1378 if (it != file_formats.end())
1379 backup_suffix = "-lyx" + it->second;
1381 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1382 string const backname = fname + backup_suffix;
1383 FileName backup(addName(fpath, addExtension(backname, fext)));
1385 // limit recursion, just in case
1387 unsigned long orig_checksum = 0;
1388 while (backup.exists() && v < 100) {
1389 if (orig_checksum == 0)
1390 orig_checksum = fn.checksum();
1391 unsigned long new_checksum = backup.checksum();
1392 if (orig_checksum == new_checksum) {
1393 LYXERR(Debug::FILES, "Not backing up " << fn <<
1394 "since " << backup << "has the same checksum.");
1395 // a bit of a hack, but we have to check this anyway
1396 // below, and setting this is simpler than introducing
1397 // a special boolean for this purpose.
1401 string const newbackname = backname + "-" + convert<string>(v);
1402 backup.set(addName(fpath, addExtension(newbackname, fext)));
1405 return v < 100 ? backup : FileName();
1409 // Should probably be moved to somewhere else: BufferView? GuiView?
1410 bool Buffer::save() const
1412 docstring const file = makeDisplayPath(absFileName(), 20);
1413 d->filename.refresh();
1415 // check the read-only status before moving the file as a backup
1416 if (d->filename.exists()) {
1417 bool const read_only = !d->filename.isWritable();
1419 Alert::warning(_("File is read-only"),
1420 bformat(_("The file %1$s cannot be written because it "
1421 "is marked as read-only."), file));
1426 // ask if the disk file has been externally modified (use checksum method)
1427 if (fileName().exists() && isChecksumModified()) {
1429 bformat(_("Document %1$s has been externally modified. "
1430 "Are you sure you want to overwrite this file?"), file);
1431 int const ret = Alert::prompt(_("Overwrite modified file?"),
1432 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1437 // We don't need autosaves in the immediate future. (Asger)
1438 resetAutosaveTimers();
1440 // if the file does not yet exist, none of the backup activity
1441 // that follows is necessary
1442 if (!fileName().exists()) {
1443 if (!writeFile(fileName()))
1449 // we first write the file to a new name, then move it to its
1450 // proper location once that has been done successfully. that
1451 // way we preserve the original file if something goes wrong.
1452 string const justname = fileName().onlyFileNameWithoutExt();
1453 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1454 justname + "-XXXXXX.lyx");
1455 bool const symlink = fileName().isSymLink();
1457 tempfile->setAutoRemove(false);
1459 FileName savefile(tempfile->name());
1460 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1461 if (!savefile.clonePermissions(fileName()))
1462 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1464 if (!writeFile(savefile))
1467 // we will set this to false if we fail
1468 bool made_backup = true;
1470 FileName backupName;
1471 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1473 if (d->need_format_backup)
1474 backupName = getBackupName();
1476 // If we for some reason failed to find a backup name in case of
1477 // a format change, this will still set one. It's the best we can
1479 if (backupName.empty()) {
1480 backupName.set(fileName().absFileName() + "~");
1481 if (!lyxrc.backupdir_path.empty()) {
1482 string const mangledName =
1483 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1484 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1488 LYXERR(Debug::FILES, "Backing up original file to " <<
1489 backupName.absFileName());
1490 // Except file is symlink do not copy because of #6587.
1491 // Hard links have bad luck.
1492 made_backup = symlink ?
1493 fileName().copyTo(backupName):
1494 fileName().moveTo(backupName);
1497 Alert::error(_("Backup failure"),
1498 bformat(_("Cannot create backup file %1$s.\n"
1499 "Please check whether the directory exists and is writable."),
1500 from_utf8(backupName.absFileName())));
1501 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1502 } else if (d->need_format_backup) {
1503 // the original file has been backed up successfully, so we
1504 // will not need to do that again
1505 d->need_format_backup = false;
1509 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1510 // Only do this if tempfile is not in autoremove mode
1513 // If we have no symlink, we can simply rename the temp file.
1514 // Otherwise, we need to copy it so the symlink stays intact.
1515 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1516 savefile.moveTo(fileName()))
1518 // saveCheckSum() was already called by writeFile(), but the
1519 // time stamp is invalidated by copying/moving
1522 if (d->file_format != LYX_FORMAT)
1523 // the file associated with this buffer is now in the current format
1524 d->file_format = LYX_FORMAT;
1527 // else we saved the file, but failed to move it to the right location.
1529 if (needBackup && made_backup && !symlink) {
1530 // the original file was moved to some new location, so it will look
1531 // to the user as if it was deleted. (see bug #9234.) we could try
1532 // to restore it, but that would basically mean trying to do again
1533 // what we just failed to do. better to leave things as they are.
1534 Alert::error(_("Write failure"),
1535 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1536 "But LyX could not move it to:\n %2$s.\n"
1537 "Your original file has been backed up to:\n %3$s"),
1538 from_utf8(savefile.absFileName()),
1539 from_utf8(fileName().absFileName()),
1540 from_utf8(backupName.absFileName())));
1542 // either we did not try to make a backup, or else we tried and failed,
1543 // or else the original file was a symlink, in which case it was copied,
1544 // not moved. so the original file is intact.
1545 Alert::error(_("Write failure"),
1546 bformat(_("Cannot move saved file to:\n %1$s.\n"
1547 "But the file has successfully been saved as:\n %2$s."),
1548 from_utf8(fileName().absFileName()),
1549 from_utf8(savefile.absFileName())));
1555 bool Buffer::writeFile(FileName const & fname) const
1557 if (d->read_only && fname == d->filename)
1560 bool retval = false;
1562 docstring const str = bformat(_("Saving document %1$s..."),
1563 makeDisplayPath(fname.absFileName()));
1566 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1568 if (params().compressed) {
1569 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1570 retval = ofs && write(ofs);
1572 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1573 retval = ofs && write(ofs);
1577 message(str + _(" could not write file!"));
1582 // removeAutosaveFile();
1585 message(str + _(" done."));
1591 docstring Buffer::emergencyWrite()
1593 // No need to save if the buffer has not changed.
1597 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1599 docstring user_message = bformat(
1600 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1602 // We try to save three places:
1603 // 1) Same place as document. Unless it is an unnamed doc.
1605 string s = absFileName();
1608 if (writeFile(FileName(s))) {
1610 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1611 return user_message;
1613 user_message += " " + _("Save failed! Trying again...\n");
1617 // 2) In HOME directory.
1618 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1620 lyxerr << ' ' << s << endl;
1621 if (writeFile(FileName(s))) {
1623 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1624 return user_message;
1627 user_message += " " + _("Save failed! Trying yet again...\n");
1629 // 3) In "/tmp" directory.
1630 // MakeAbsPath to prepend the current
1631 // drive letter on OS/2
1632 s = addName(package().temp_dir().absFileName(), absFileName());
1634 lyxerr << ' ' << s << endl;
1635 if (writeFile(FileName(s))) {
1637 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1638 return user_message;
1641 user_message += " " + _("Save failed! Document is lost.");
1644 return user_message;
1648 bool Buffer::write(ostream & ofs) const
1651 // Use the standard "C" locale for file output.
1652 ofs.imbue(locale::classic());
1655 // The top of the file should not be written by params().
1657 // write out a comment in the top of the file
1658 // Important: Keep the version formatting in sync with lyx2lyx and
1659 // tex2lyx (bug 7951)
1660 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1661 << " created this file. For more info see https://www.lyx.org/\n"
1662 << "\\lyxformat " << LYX_FORMAT << "\n"
1663 << "\\begin_document\n";
1665 /// For each author, set 'used' to true if there is a change
1666 /// by this author in the document; otherwise set it to 'false'.
1667 for (Author const & a : params().authors())
1670 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1671 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1672 for ( ; it != end; ++it)
1673 it->checkAuthors(params().authors());
1675 // now write out the buffer parameters.
1676 ofs << "\\begin_header\n";
1677 params().writeFile(ofs, this);
1678 ofs << "\\end_header\n";
1681 ofs << "\n\\begin_body\n";
1683 ofs << "\n\\end_body\n";
1685 // Write marker that shows file is complete
1686 ofs << "\\end_document" << endl;
1688 // Shouldn't really be needed....
1691 // how to check if close went ok?
1692 // Following is an attempt... (BE 20001011)
1694 // good() returns false if any error occurred, including some
1695 // formatting error.
1696 // bad() returns true if something bad happened in the buffer,
1697 // which should include file system full errors.
1702 lyxerr << "File was not closed properly." << endl;
1709 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1710 string const & original_path,
1711 OutputParams const & runparams_in,
1712 OutputWhat output) const
1714 OutputParams runparams = runparams_in;
1716 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1717 // Check here, because the "flavor" is not known in BufferParams::encoding()
1718 // (power users can override this safety measure selecting "utf8-plain").
1719 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1720 && (runparams.encoding->name() != "utf8-plain"))
1721 runparams.encoding = encodings.fromLyXName("ascii");
1723 string const encoding = runparams.encoding->iconvName();
1724 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1727 try { ofs.reset(encoding); }
1728 catch (iconv_codecvt_facet_exception const & e) {
1729 lyxerr << "Caught iconv exception: " << e.what() << endl;
1730 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1731 "verify that the support software for your encoding (%1$s) is "
1732 "properly installed"), from_ascii(encoding)));
1735 if (!openFileWrite(ofs, fname))
1738 ErrorList & errorList = d->errorLists["Export"];
1740 ExportStatus status = ExportSuccess;
1743 // make sure we are ready to export
1744 // this needs to be done before we validate
1745 // FIXME Do we need to do this all the time? I.e., in children
1746 // of a master we are exporting?
1748 updateMacroInstances(OutputUpdate);
1750 ExportStatus retval;
1752 retval = writeLaTeXSource(os, original_path, runparams, output);
1753 if (retval == ExportKilled)
1754 return ExportKilled;
1756 catch (EncodingException const & e) {
1757 docstring const failed(1, e.failed_char);
1759 oss << "0x" << hex << e.failed_char << dec;
1760 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1761 docstring msg = bformat(_("Uncodable character '%1$s'"
1762 " (code point %2$s)"),
1763 failed, from_utf8(oss.str()));
1764 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1765 "representable in specific verbatim contexts.\n"
1766 "Changing the document encoding to utf8 could help."),
1767 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1769 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1770 " (code point %2$s)"),
1771 failed, from_utf8(oss.str()));
1772 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1773 "representable in the chosen encoding.\n"
1774 "Changing the document encoding to utf8 could help."),
1775 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1777 status = ExportError;
1779 catch (iconv_codecvt_facet_exception const & e) {
1780 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1782 status = ExportError;
1784 catch (exception const & e) {
1785 errorList.push_back(ErrorItem(_("conversion failed"),
1787 lyxerr << e.what() << endl;
1788 status = ExportError;
1791 lyxerr << "Caught some really weird exception..." << endl;
1795 d->texrow = move(os.texrow());
1799 status = ExportError;
1800 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1803 if (runparams_in.silent)
1811 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1812 string const & original_path,
1813 OutputParams const & runparams_in,
1814 OutputWhat output) const
1816 // The child documents, if any, shall be already loaded at this point.
1818 OutputParams runparams = runparams_in;
1820 // XeTeX with TeX fonts is only safe with ASCII encoding,
1821 // Check here, because the "flavor" is not known in BufferParams::encoding()
1822 // (power users can override this safety measure selecting "utf8-plain").
1823 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1824 && (runparams.encoding->name() != "utf8-plain"))
1825 runparams.encoding = encodings.fromLyXName("ascii");
1826 // FIXME: when only the current paragraph is shown, this is ignored
1827 // (or not reached) and characters encodable in the current
1828 // encoding are not converted to ASCII-representation.
1830 // Some macros rely on font encoding
1831 runparams.main_fontenc = params().main_font_encoding();
1833 // If we are compiling a file standalone, even if this is the
1834 // child of some other buffer, let's cut the link here, so the
1835 // file is really independent and no concurring settings from
1836 // the master (e.g. branch state) interfere (see #8100).
1837 if (!runparams.is_child)
1838 d->ignore_parent = true;
1840 // Classify the unicode characters appearing in math insets
1841 BufferEncodings::initUnicodeMath(*this);
1843 // validate the buffer.
1844 LYXERR(Debug::LATEX, " Validating buffer...");
1845 LaTeXFeatures features(*this, params(), runparams);
1847 // This is only set once per document (in master)
1848 if (!runparams.is_child)
1849 runparams.use_polyglossia = features.usePolyglossia();
1850 LYXERR(Debug::LATEX, " Buffer validation done.");
1852 bool const output_preamble =
1853 output == FullSource || output == OnlyPreamble;
1854 bool const output_body =
1855 output == FullSource || output == OnlyBody;
1857 // The starting paragraph of the coming rows is the
1858 // first paragraph of the document. (Asger)
1859 if (output_preamble && runparams.nice) {
1860 os << "%% LyX " << lyx_version << " created this file. "
1861 "For more info, see https://www.lyx.org/.\n"
1862 "%% Do not edit unless you really know what "
1865 LYXERR(Debug::INFO, "lyx document header finished");
1867 // There are a few differences between nice LaTeX and usual files:
1868 // usual files have \batchmode and special input@path to allow
1869 // inclusion of figures specified by an explicitly relative path
1870 // (i.e., a path starting with './' or '../') with either \input or
1871 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1872 // input@path is set when the actual parameter original_path is set.
1873 // This is done for usual tex-file, but not for nice-latex-file.
1874 // (Matthias 250696)
1875 // Note that input@path is only needed for something the user does
1876 // in the preamble, included .tex files or ERT, files included by
1877 // LyX work without it.
1878 if (output_preamble) {
1879 if (!runparams.nice) {
1880 // code for usual, NOT nice-latex-file
1881 os << "\\batchmode\n"; // changed from \nonstopmode
1883 if (!original_path.empty()) {
1885 // We don't know the encoding of inputpath
1886 docstring const inputpath = from_utf8(original_path);
1887 docstring uncodable_glyphs;
1888 Encoding const * const enc = runparams.encoding;
1890 for (size_t n = 0; n < inputpath.size(); ++n) {
1891 if (!enc->encodable(inputpath[n])) {
1892 docstring const glyph(1, inputpath[n]);
1893 LYXERR0("Uncodable character '"
1895 << "' in input path!");
1896 uncodable_glyphs += glyph;
1901 // warn user if we found uncodable glyphs.
1902 if (!uncodable_glyphs.empty()) {
1903 frontend::Alert::warning(
1904 _("Uncodable character in file path"),
1906 _("The path of your document\n"
1908 "contains glyphs that are unknown "
1909 "in the current document encoding "
1910 "(namely %2$s). This may result in "
1911 "incomplete output, unless "
1912 "TEXINPUTS contains the document "
1913 "directory and you don't use "
1914 "explicitly relative paths (i.e., "
1915 "paths starting with './' or "
1916 "'../') in the preamble or in ERT."
1917 "\n\nIn case of problems, choose "
1918 "an appropriate document encoding\n"
1919 "(such as utf8) or change the "
1921 inputpath, uncodable_glyphs));
1923 string docdir = os::latex_path(original_path);
1924 if (contains(docdir, '#')) {
1925 docdir = subst(docdir, "#", "\\#");
1926 os << "\\catcode`\\#=11"
1927 "\\def\\#{#}\\catcode`\\#=6\n";
1929 if (contains(docdir, '%')) {
1930 docdir = subst(docdir, "%", "\\%");
1931 os << "\\catcode`\\%=11"
1932 "\\def\\%{%}\\catcode`\\%=14\n";
1934 bool const detokenize = !isAscii(from_utf8(docdir));
1935 bool const quote = contains(docdir, ' ');
1936 os << "\\makeatletter\n"
1937 << "\\def\\input@path{{";
1939 os << "\\detokenize{";
1948 << "\\makeatother\n";
1952 // get parent macros (if this buffer has a parent) which will be
1953 // written at the document begin further down.
1954 MacroSet parentMacros;
1955 listParentMacros(parentMacros, features);
1957 // Write the preamble
1958 runparams.use_babel = params().writeLaTeX(os, features,
1959 d->filename.onlyPath());
1961 // Biblatex bibliographies are loaded here
1962 if (params().useBiblatex()) {
1963 vector<docstring> const bibfiles =
1964 prepareBibFilePaths(runparams, getBibfiles(), true);
1965 for (docstring const & file: bibfiles)
1966 os << "\\addbibresource{" << file << "}\n";
1969 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1970 && !features.hasOnlyPolyglossiaLanguages()) {
1973 vector<string> bll = features.getBabelExclusiveLanguages();
1974 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1977 for (string const & sit : bll) {
1982 blangs = bll.size() > 1 ?
1983 bformat(_("The languages %1$s are only supported by Babel."), langs)
1984 : bformat(_("The language %1$s is only supported by Babel."), langs);
1988 for (string const & pit : pll) {
1993 plangs = pll.size() > 1 ?
1994 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1995 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1996 if (!blangs.empty())
2000 frontend::Alert::warning(
2001 _("Incompatible Languages!"),
2003 _("You cannot use the following languages "
2004 "together in one LaTeX document because "
2005 "they require conflicting language packages:\n"
2010 // Japanese might be required only in some children of a document,
2011 // but once required, we must keep use_japanese true.
2012 runparams.use_japanese |= features.isRequired("japanese");
2015 // Restore the parenthood if needed
2016 if (!runparams.is_child)
2017 d->ignore_parent = false;
2018 return ExportSuccess;
2022 // mark the beginning of the body to separate it from InPreamble insets
2023 os.texrow().start(TexRow::beginDocument());
2024 os << "\\begin{document}\n";
2026 // mark the start of a new paragraph by simulating a newline,
2027 // so that os.afterParbreak() returns true at document start
2030 // output the parent macros
2031 for (auto const & mac : parentMacros) {
2032 int num_lines = mac->write(os.os(), true);
2033 os.texrow().newlines(num_lines);
2036 } // output_preamble
2038 LYXERR(Debug::INFO, "preamble finished, now the body.");
2042 latexParagraphs(*this, text(), os, runparams);
2044 catch (ConversionException const &) { return ExportKilled; }
2046 // Restore the parenthood if needed
2047 if (!runparams.is_child)
2048 d->ignore_parent = false;
2050 // add this just in case after all the paragraphs
2053 if (output_preamble) {
2054 os << "\\end{document}\n";
2055 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2057 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2059 runparams_in.encoding = runparams.encoding;
2061 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2062 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2063 return ExportSuccess;
2067 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2068 OutputParams const & runparams,
2069 OutputWhat output) const
2071 LYXERR(Debug::LATEX, "makeDocBookFile...");
2074 if (!openFileWrite(ofs, fname))
2077 // make sure we are ready to export
2078 // this needs to be done before we validate
2080 updateMacroInstances(OutputUpdate);
2082 ExportStatus const retval =
2083 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2084 if (retval == ExportKilled)
2085 return ExportKilled;
2089 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2090 return ExportSuccess;
2094 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os, string const & fname,
2095 OutputParams const & runparams,
2096 OutputWhat output) const
2098 LaTeXFeatures features(*this, params(), runparams);
2103 DocumentClass const & tclass = params().documentClass();
2104 string const & top_element = tclass.latexname();
2106 bool const output_preamble =
2107 output == FullSource || output == OnlyPreamble;
2108 bool const output_body =
2109 output == FullSource || output == OnlyBody;
2111 if (output_preamble) {
2112 if (runparams.flavor == OutputParams::XML)
2113 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2116 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2119 if (! tclass.class_header().empty())
2120 os << from_ascii(tclass.class_header());
2121 else if (runparams.flavor == OutputParams::XML)
2122 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2123 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2125 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2127 docstring preamble = params().preamble;
2128 if (runparams.flavor != OutputParams::XML ) {
2129 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2130 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2131 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2132 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2135 string const name = runparams.nice
2136 ? changeExtension(absFileName(), ".sgml") : fname;
2137 preamble += features.getIncludedFiles(name);
2138 preamble += features.getLyXSGMLEntities();
2140 if (!preamble.empty()) {
2141 os << "\n [ " << preamble << " ]";
2147 string top = top_element;
2149 if (runparams.flavor == OutputParams::XML)
2150 top += params().language->code();
2152 top += params().language->code().substr(0, 2);
2155 if (!params().options.empty()) {
2157 top += params().options;
2160 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2161 << " file was created by LyX " << lyx_version
2162 << "\n See https://www.lyx.org/ for more information -->\n";
2164 params().documentClass().counters().reset();
2166 sgml::openTag(os, top);
2169 docbookParagraphs(text(), *this, os, runparams);
2171 catch (ConversionException const &) { return ExportKilled; }
2172 sgml::closeTag(os, top_element);
2174 return ExportSuccess;
2178 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2179 OutputParams const & runparams) const
2181 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2184 if (!openFileWrite(ofs, fname))
2187 // make sure we are ready to export
2188 // this has to be done before we validate
2189 updateBuffer(UpdateMaster, OutputUpdate);
2190 updateMacroInstances(OutputUpdate);
2192 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2193 if (retval == ExportKilled)
2198 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2203 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2204 OutputParams const & runparams,
2205 OutputWhat output) const
2207 LaTeXFeatures features(*this, params(), runparams);
2209 d->bibinfo_.makeCitationLabels(*this);
2211 bool const output_preamble =
2212 output == FullSource || output == OnlyPreamble;
2213 bool const output_body =
2214 output == FullSource || output == OnlyBody || output == IncludedFile;
2216 if (output_preamble) {
2217 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2218 << "<!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"
2219 // FIXME Language should be set properly.
2220 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2222 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2223 // FIXME Presumably need to set this right
2224 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2226 docstring const & doctitle = features.htmlTitle();
2228 << (doctitle.empty() ?
2229 from_ascii("LyX Document") :
2230 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2233 docstring styles = features.getTClassHTMLPreamble();
2234 if (!styles.empty())
2235 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2237 styles = features.getPreambleSnippets().str;
2238 if (!styles.empty())
2239 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2241 // we will collect CSS information in a stream, and then output it
2242 // either here, as part of the header, or else in a separate file.
2243 odocstringstream css;
2244 styles = features.getCSSSnippets();
2245 if (!styles.empty())
2246 css << "/* LyX Provided Styles */\n" << styles << '\n';
2248 styles = features.getTClassHTMLStyles();
2249 if (!styles.empty())
2250 css << "/* Layout-provided Styles */\n" << styles << '\n';
2252 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2253 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2254 if (needfg || needbg) {
2255 css << "\nbody {\n";
2258 << from_ascii(X11hexname(params().fontcolor))
2261 css << " background-color: "
2262 << from_ascii(X11hexname(params().backgroundcolor))
2267 docstring const dstyles = css.str();
2268 if (!dstyles.empty()) {
2269 bool written = false;
2270 if (params().html_css_as_file) {
2271 // open a file for CSS info
2273 string const fcssname = addName(temppath(), "docstyle.css");
2274 FileName const fcssfile = FileName(fcssname);
2275 if (openFileWrite(ocss, fcssfile)) {
2279 // write link to header
2280 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2282 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2285 // we are here if the CSS is supposed to be written to the header
2286 // or if we failed to write it to an external file.
2288 os << "<style type='text/css'>\n"
2297 bool const output_body_tag = (output != IncludedFile);
2298 if (output_body_tag)
2299 os << "<body dir=\"auto\">\n";
2301 if (output != IncludedFile)
2302 // if we're an included file, the counters are in the master.
2303 params().documentClass().counters().reset();
2305 xhtmlParagraphs(text(), *this, xs, runparams);
2307 catch (ConversionException const &) { return ExportKilled; }
2308 if (output_body_tag)
2312 if (output_preamble)
2315 return ExportSuccess;
2319 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2320 // Other flags: -wall -v0 -x
2321 int Buffer::runChktex()
2325 // get LaTeX-Filename
2326 FileName const path(temppath());
2327 string const name = addName(path.absFileName(), latexName());
2328 string const org_path = filePath();
2330 PathChanger p(path); // path to LaTeX file
2331 message(_("Running chktex..."));
2333 // Generate the LaTeX file if neccessary
2334 OutputParams runparams(¶ms().encoding());
2335 runparams.flavor = OutputParams::LATEX;
2336 runparams.nice = false;
2337 runparams.linelen = lyxrc.plaintext_linelen;
2338 ExportStatus const retval =
2339 makeLaTeXFile(FileName(name), org_path, runparams);
2340 if (retval != ExportSuccess) {
2341 // error code on failure
2346 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2347 int const res = chktex.run(terr); // run chktex
2350 Alert::error(_("chktex failure"),
2351 _("Could not run chktex successfully."));
2353 ErrorList & errlist = d->errorLists["ChkTeX"];
2355 bufferErrors(terr, errlist);
2360 if (runparams.silent)
2361 d->errorLists["ChkTeX"].clear();
2369 void Buffer::validate(LaTeXFeatures & features) const
2371 // Validate the buffer params, but not for included
2372 // files, since they also use the parent buffer's
2374 if (!features.runparams().is_child)
2375 params().validate(features);
2377 for (Paragraph const & p : paragraphs())
2378 p.validate(features);
2380 if (lyxerr.debugging(Debug::LATEX)) {
2381 features.showStruct();
2386 void Buffer::getLabelList(vector<docstring> & list) const
2388 // If this is a child document, use the master's list instead.
2390 masterBuffer()->getLabelList(list);
2395 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2396 for (auto const & tocit : *toc) {
2397 if (tocit.depth() == 0)
2398 list.push_back(tocit.str());
2403 void Buffer::invalidateBibinfoCache() const
2405 d->bibinfo_cache_valid_ = false;
2406 d->cite_labels_valid_ = false;
2407 removeBiblioTempFiles();
2408 // also invalidate the cache for the parent buffer
2409 Buffer const * const pbuf = d->parent();
2411 pbuf->invalidateBibinfoCache();
2415 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2417 // FIXME This is probably unnecessary, given where we call this.
2418 // If this is a child document, use the master instead.
2419 Buffer const * const pbuf = masterBuffer();
2420 if (pbuf != this && scope != UpdateChildOnly)
2421 return pbuf->getBibfiles();
2423 // In 2.3.x, we have:
2424 //if (!d->bibfile_cache_valid_)
2425 // this->updateBibfilesCache(scope);
2426 // I think that is a leftover, but there have been so many back-
2427 // and-forths with this, due to Windows issues, that I am not sure.
2429 return d->bibfiles_cache_;
2433 BiblioInfo const & Buffer::masterBibInfo() const
2435 Buffer const * const tmp = masterBuffer();
2437 return tmp->masterBibInfo();
2442 BiblioInfo const & Buffer::bibInfo() const
2448 void Buffer::registerBibfiles(const docstring_list & bf) const
2450 // We register the bib files in the master buffer,
2451 // if there is one, but also in every single buffer,
2452 // in case a child is compiled alone.
2453 Buffer const * const tmp = masterBuffer();
2455 tmp->registerBibfiles(bf);
2457 for (auto const & p : bf) {
2458 docstring_list::const_iterator temp =
2459 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2460 if (temp == d->bibfiles_cache_.end())
2461 d->bibfiles_cache_.push_back(p);
2466 static map<docstring, FileName> bibfileCache;
2468 FileName Buffer::getBibfilePath(docstring const & bibid) const
2470 map<docstring, FileName>::const_iterator it =
2471 bibfileCache.find(bibid);
2472 if (it != bibfileCache.end()) {
2473 // i.e., bibfileCache[bibid]
2477 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2478 string texfile = changeExtension(to_utf8(bibid), "bib");
2479 // note that, if the filename can be found directly from the path,
2480 // findtexfile will just return a FileName object for that path.
2481 FileName file(findtexfile(texfile, "bib"));
2483 file = FileName(makeAbsPath(texfile, filePath()));
2484 LYXERR(Debug::FILES, "Found at: " << file);
2486 bibfileCache[bibid] = file;
2487 return bibfileCache[bibid];
2491 void Buffer::checkIfBibInfoCacheIsValid() const
2493 // use the master's cache
2494 Buffer const * const tmp = masterBuffer();
2496 tmp->checkIfBibInfoCacheIsValid();
2500 // If we already know the cache is invalid, stop here.
2501 // This is important in the case when the bibliography
2502 // environment (rather than Bib[la]TeX) is used.
2503 // In that case, the timestamp check below gives no
2504 // sensible result. Rather than that, the cache will
2505 // be invalidated explicitly via invalidateBibInfoCache()
2506 // by the Bibitem inset.
2507 // Same applies for bib encoding changes, which trigger
2508 // invalidateBibInfoCache() by InsetBibtex.
2509 if (!d->bibinfo_cache_valid_)
2512 // we'll assume it's ok and change this if it's not
2513 d->bibinfo_cache_valid_ = true;
2514 d->cite_labels_valid_ = true;
2516 // compare the cached timestamps with the actual ones.
2517 docstring_list const & bibfiles_cache = getBibfiles();
2518 for (auto const & bf : bibfiles_cache) {
2519 FileName const fn = getBibfilePath(bf);
2520 time_t lastw = fn.lastModified();
2521 time_t prevw = d->bibfile_status_[fn];
2522 if (lastw != prevw) {
2523 d->bibinfo_cache_valid_ = false;
2524 d->cite_labels_valid_ = false;
2525 d->bibfile_status_[fn] = lastw;
2531 void Buffer::clearBibFileCache() const
2533 bibfileCache.clear();
2537 void Buffer::reloadBibInfoCache(bool const force) const
2539 // we should not need to do this for internal buffers
2543 // use the master's cache
2544 Buffer const * const tmp = masterBuffer();
2546 tmp->reloadBibInfoCache(force);
2551 checkIfBibInfoCacheIsValid();
2552 if (d->bibinfo_cache_valid_)
2556 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2557 // re-read file locations when this info changes
2558 // FIXME Is this sufficient? Or should we also force that
2559 // in some other cases? If so, then it is easy enough to
2560 // add the following line in some other places.
2561 clearBibFileCache();
2562 d->bibinfo_.clear();
2563 FileNameList checkedFiles;
2564 collectBibKeys(checkedFiles);
2565 d->bibinfo_cache_valid_ = true;
2569 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2571 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2572 it->collectBibKeys(it, checkedFiles);
2576 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2578 // We add the biblio info to the master buffer,
2579 // if there is one, but also to every single buffer,
2580 // in case a child is compiled alone.
2581 BiblioInfo & bi = d->bibinfo_;
2582 bi.mergeBiblioInfo(bin);
2584 if (parent() != 0) {
2585 BiblioInfo & masterbi = parent()->d->bibinfo_;
2586 masterbi.mergeBiblioInfo(bin);
2591 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2593 // We add the bibtex info to the master buffer,
2594 // if there is one, but also to every single buffer,
2595 // in case a child is compiled alone.
2596 BiblioInfo & bi = d->bibinfo_;
2599 if (parent() != 0) {
2600 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2601 masterbi[key] = bin;
2606 void Buffer::makeCitationLabels() const
2608 Buffer const * const master = masterBuffer();
2609 return d->bibinfo_.makeCitationLabels(*master);
2613 void Buffer::invalidateCiteLabels() const
2615 masterBuffer()->d->cite_labels_valid_ = false;
2618 bool Buffer::citeLabelsValid() const
2620 return masterBuffer()->d->cite_labels_valid_;
2624 void Buffer::removeBiblioTempFiles() const
2626 // We remove files that contain LaTeX commands specific to the
2627 // particular bibliographic style being used, in order to avoid
2628 // LaTeX errors when we switch style.
2629 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2630 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2631 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2632 aux_file.removeFile();
2633 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2634 bbl_file.removeFile();
2635 // Also for the parent buffer
2636 Buffer const * const pbuf = parent();
2638 pbuf->removeBiblioTempFiles();
2642 bool Buffer::isDepClean(string const & name) const
2644 DepClean::const_iterator const it = d->dep_clean.find(name);
2645 if (it == d->dep_clean.end())
2651 void Buffer::markDepClean(string const & name)
2653 d->dep_clean[name] = true;
2657 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2660 // FIXME? if there is an Buffer LFUN that can be dispatched even
2661 // if internal, put a switch '(cmd.action)' here.
2667 switch (cmd.action()) {
2669 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2670 flag.setOnOff(hasReadonlyFlag());
2673 // FIXME: There is need for a command-line import.
2674 //case LFUN_BUFFER_IMPORT:
2676 case LFUN_BUFFER_AUTO_SAVE:
2679 case LFUN_BUFFER_EXPORT_CUSTOM:
2680 // FIXME: Nothing to check here?
2683 case LFUN_BUFFER_EXPORT: {
2684 docstring const arg = cmd.argument();
2685 if (arg == "custom") {
2689 string format = (arg.empty() || arg == "default") ?
2690 params().getDefaultOutputFormat() : to_utf8(arg);
2691 size_t pos = format.find(' ');
2692 if (pos != string::npos)
2693 format = format.substr(0, pos);
2694 enable = params().isExportable(format, false);
2696 flag.message(bformat(
2697 _("Don't know how to export to format: %1$s"), arg));
2701 case LFUN_BUILD_PROGRAM:
2702 enable = params().isExportable("program", false);
2705 case LFUN_BRANCH_ACTIVATE:
2706 case LFUN_BRANCH_DEACTIVATE:
2707 case LFUN_BRANCH_MASTER_ACTIVATE:
2708 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2709 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2710 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2711 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2712 : params().branchlist();
2713 docstring const branchName = cmd.argument();
2714 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2718 case LFUN_BRANCH_ADD:
2719 case LFUN_BRANCHES_RENAME:
2720 // if no Buffer is present, then of course we won't be called!
2723 case LFUN_BUFFER_LANGUAGE:
2724 enable = !isReadonly();
2727 case LFUN_BUFFER_VIEW_CACHE:
2728 (d->preview_file_).refresh();
2729 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2732 case LFUN_CHANGES_TRACK:
2733 flag.setEnabled(true);
2734 flag.setOnOff(params().track_changes);
2737 case LFUN_CHANGES_OUTPUT:
2738 flag.setEnabled(true);
2739 flag.setOnOff(params().output_changes);
2742 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2743 flag.setOnOff(params().compressed);
2746 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2747 flag.setOnOff(params().output_sync);
2750 case LFUN_BUFFER_ANONYMIZE:
2756 flag.setEnabled(enable);
2761 void Buffer::dispatch(string const & command, DispatchResult & result)
2763 return dispatch(lyxaction.lookupFunc(command), result);
2767 // NOTE We can end up here even if we have no GUI, because we are called
2768 // by LyX::exec to handled command-line requests. So we may need to check
2769 // whether we have a GUI or not. The boolean use_gui holds this information.
2770 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2773 // FIXME? if there is an Buffer LFUN that can be dispatched even
2774 // if internal, put a switch '(cmd.action())' here.
2775 dr.dispatched(false);
2778 string const argument = to_utf8(func.argument());
2779 // We'll set this back to false if need be.
2780 bool dispatched = true;
2781 // This handles undo groups automagically
2782 UndoGroupHelper ugh(this);
2784 switch (func.action()) {
2785 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2786 if (lyxvc().inUse()) {
2787 string log = lyxvc().toggleReadOnly();
2792 setReadonly(!hasReadonlyFlag());
2795 case LFUN_BUFFER_EXPORT: {
2796 string const format = (argument.empty() || argument == "default") ?
2797 params().getDefaultOutputFormat() : argument;
2798 ExportStatus const status = doExport(format, false);
2799 dr.setError(status != ExportSuccess);
2800 if (status != ExportSuccess)
2801 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2802 from_utf8(format)));
2806 case LFUN_BUILD_PROGRAM: {
2807 ExportStatus const status = doExport("program", true);
2808 dr.setError(status != ExportSuccess);
2809 if (status != ExportSuccess)
2810 dr.setMessage(_("Error generating literate programming code."));
2814 case LFUN_BUFFER_EXPORT_CUSTOM: {
2816 string command = split(argument, format_name, ' ');
2817 Format const * format = theFormats().getFormat(format_name);
2819 lyxerr << "Format \"" << format_name
2820 << "\" not recognized!"
2825 // The name of the file created by the conversion process
2828 // Output to filename
2829 if (format->name() == "lyx") {
2830 string const latexname = latexName(false);
2831 filename = changeExtension(latexname,
2832 format->extension());
2833 filename = addName(temppath(), filename);
2835 if (!writeFile(FileName(filename)))
2839 doExport(format_name, true, filename);
2842 // Substitute $$FName for filename
2843 if (!contains(command, "$$FName"))
2844 command = "( " + command + " ) < $$FName";
2845 command = subst(command, "$$FName", filename);
2847 // Execute the command in the background
2849 call.startscript(Systemcall::DontWait, command,
2850 filePath(), layoutPos());
2854 // FIXME: There is need for a command-line import.
2856 case LFUN_BUFFER_IMPORT:
2861 case LFUN_BUFFER_AUTO_SAVE:
2863 resetAutosaveTimers();
2866 case LFUN_BRANCH_ACTIVATE:
2867 case LFUN_BRANCH_DEACTIVATE:
2868 case LFUN_BRANCH_MASTER_ACTIVATE:
2869 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2870 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2871 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2872 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2875 docstring const branch_name = func.argument();
2876 // the case without a branch name is handled elsewhere
2877 if (branch_name.empty()) {
2881 Branch * branch = buf->params().branchlist().find(branch_name);
2883 LYXERR0("Branch " << branch_name << " does not exist.");
2885 docstring const msg =
2886 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2890 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2891 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2892 if (branch->isSelected() != activate) {
2893 buf->undo().recordUndoBufferParams(CursorData());
2894 branch->setSelected(activate);
2896 dr.screenUpdate(Update::Force);
2897 dr.forceBufferUpdate();
2902 case LFUN_BRANCH_ADD: {
2903 docstring branchnames = func.argument();
2904 if (branchnames.empty()) {
2908 BranchList & branch_list = params().branchlist();
2909 vector<docstring> const branches =
2910 getVectorFromString(branchnames, branch_list.separator());
2912 for (docstring const & branch_name : branches) {
2913 Branch * branch = branch_list.find(branch_name);
2915 LYXERR0("Branch " << branch_name << " already exists.");
2919 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2921 undo().recordUndoBufferParams(CursorData());
2922 branch_list.add(branch_name);
2923 branch = branch_list.find(branch_name);
2924 string const x11hexname = X11hexname(branch->color());
2925 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2926 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2928 dr.screenUpdate(Update::Force);
2936 case LFUN_BRANCHES_RENAME: {
2937 if (func.argument().empty())
2940 docstring const oldname = from_utf8(func.getArg(0));
2941 docstring const newname = from_utf8(func.getArg(1));
2942 InsetIterator it = inset_iterator_begin(inset());
2943 InsetIterator const end = inset_iterator_end(inset());
2944 bool success = false;
2945 for (; it != end; ++it) {
2946 if (it->lyxCode() == BRANCH_CODE) {
2947 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2948 if (ins.branch() == oldname) {
2949 undo().recordUndo(CursorData(it));
2950 ins.rename(newname);
2955 if (it->lyxCode() == INCLUDE_CODE) {
2956 // get buffer of external file
2957 InsetInclude const & ins =
2958 static_cast<InsetInclude const &>(*it);
2959 Buffer * child = ins.getChildBuffer();
2962 child->dispatch(func, dr);
2967 dr.screenUpdate(Update::Force);
2968 dr.forceBufferUpdate();
2973 case LFUN_BUFFER_VIEW_CACHE:
2974 if (!theFormats().view(*this, d->preview_file_,
2975 d->preview_format_))
2976 dr.setMessage(_("Error viewing the output file."));
2979 case LFUN_CHANGES_TRACK:
2980 if (params().save_transient_properties)
2981 undo().recordUndoBufferParams(CursorData());
2982 params().track_changes = !params().track_changes;
2983 if (!params().track_changes)
2984 dr.forceChangesUpdate();
2987 case LFUN_CHANGES_OUTPUT:
2988 if (params().save_transient_properties)
2989 undo().recordUndoBufferParams(CursorData());
2990 params().output_changes = !params().output_changes;
2991 if (params().output_changes) {
2992 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2993 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2994 LaTeXFeatures::isAvailable("xcolor");
2996 if (!dvipost && !xcolorulem) {
2997 Alert::warning(_("Changes not shown in LaTeX output"),
2998 _("Changes will not be highlighted in LaTeX output, "
2999 "because neither dvipost nor xcolor/ulem are installed.\n"
3000 "Please install these packages or redefine "
3001 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3002 } else if (!xcolorulem) {
3003 Alert::warning(_("Changes not shown in LaTeX output"),
3004 _("Changes will not be highlighted in LaTeX output "
3005 "when using pdflatex, because xcolor and ulem are not installed.\n"
3006 "Please install both packages or redefine "
3007 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3012 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3013 // turn compression on/off
3014 undo().recordUndoBufferParams(CursorData());
3015 params().compressed = !params().compressed;
3018 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3019 undo().recordUndoBufferParams(CursorData());
3020 params().output_sync = !params().output_sync;
3023 case LFUN_BUFFER_ANONYMIZE: {
3024 undo().recordUndoFullBuffer(CursorData());
3025 CursorData cur(doc_iterator_begin(this));
3026 for ( ; cur ; cur.forwardPar())
3027 cur.paragraph().anonymize();
3028 dr.forceBufferUpdate();
3029 dr.screenUpdate(Update::Force);
3037 dr.dispatched(dispatched);
3041 void Buffer::changeLanguage(Language const * from, Language const * to)
3043 LASSERT(from, return);
3044 LASSERT(to, return);
3046 for_each(par_iterator_begin(),
3048 bind(&Paragraph::changeLanguage, _1, params(), from, to));
3052 bool Buffer::isMultiLingual() const
3054 ParConstIterator end = par_iterator_end();
3055 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3056 if (it->isMultiLingual(params()))
3063 std::set<Language const *> Buffer::getLanguages() const
3065 std::set<Language const *> langs;
3066 getLanguages(langs);
3071 void Buffer::getLanguages(std::set<Language const *> & langs) const
3073 ParConstIterator end = par_iterator_end();
3074 // add the buffer language, even if it's not actively used
3075 langs.insert(language());
3076 // iterate over the paragraphs
3077 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3078 it->getLanguages(langs);
3080 ListOfBuffers clist = getDescendents();
3081 for (auto const & cit : clist)
3082 cit->getLanguages(langs);
3086 DocIterator Buffer::getParFromID(int const id) const
3088 Buffer * buf = const_cast<Buffer *>(this);
3090 // This means non-existent
3091 return doc_iterator_end(buf);
3093 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3094 if (it.paragraph().id() == id)
3097 return doc_iterator_end(buf);
3101 bool Buffer::hasParWithID(int const id) const
3103 return !getParFromID(id).atEnd();
3107 ParIterator Buffer::par_iterator_begin()
3109 return ParIterator(doc_iterator_begin(this));
3113 ParIterator Buffer::par_iterator_end()
3115 return ParIterator(doc_iterator_end(this));
3119 ParConstIterator Buffer::par_iterator_begin() const
3121 return ParConstIterator(doc_iterator_begin(this));
3125 ParConstIterator Buffer::par_iterator_end() const
3127 return ParConstIterator(doc_iterator_end(this));
3131 Language const * Buffer::language() const
3133 return params().language;
3137 docstring const Buffer::B_(string const & l10n) const
3139 return params().B_(l10n);
3143 bool Buffer::isClean() const
3145 return d->lyx_clean;
3149 bool Buffer::isChecksumModified() const
3151 LASSERT(d->filename.exists(), return false);
3152 return d->checksum_ != d->filename.checksum();
3156 void Buffer::saveCheckSum() const
3158 FileName const & file = d->filename;
3160 d->checksum_ = file.exists() ? file.checksum()
3161 : 0; // in the case of save to a new file.
3165 void Buffer::markClean() const
3167 if (!d->lyx_clean) {
3168 d->lyx_clean = true;
3171 // if the .lyx file has been saved, we don't need an
3173 d->bak_clean = true;
3174 d->undo_.markDirty();
3175 clearExternalModification();
3179 void Buffer::setUnnamed(bool flag)
3185 bool Buffer::isUnnamed() const
3192 /// Don't check unnamed, here: isInternal() is used in
3193 /// newBuffer(), where the unnamed flag has not been set by anyone
3194 /// yet. Also, for an internal buffer, there should be no need for
3195 /// retrieving fileName() nor for checking if it is unnamed or not.
3196 bool Buffer::isInternal() const
3198 return d->internal_buffer;
3202 void Buffer::setInternal(bool flag)
3204 d->internal_buffer = flag;
3208 void Buffer::markDirty()
3211 d->lyx_clean = false;
3214 d->bak_clean = false;
3216 for (auto & depit : d->dep_clean)
3217 depit.second = false;
3221 FileName Buffer::fileName() const
3227 string Buffer::absFileName() const
3229 return d->filename.absFileName();
3233 string Buffer::filePath() const
3235 string const abs = d->filename.onlyPath().absFileName();
3238 int last = abs.length() - 1;
3240 return abs[last] == '/' ? abs : abs + '/';
3244 DocFileName Buffer::getReferencedFileName(string const & fn) const
3247 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3248 result.set(fn, filePath());
3250 // filePath() ends with a path separator
3251 FileName const test(filePath() + fn);
3253 result.set(fn, filePath());
3255 result.set(fn, params().origin);
3262 string const Buffer::prepareFileNameForLaTeX(string const & name,
3263 string const & ext, bool nice) const
3265 string const fname = makeAbsPath(name, filePath()).absFileName();
3266 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3272 return to_utf8(makeRelPath(from_utf8(fname),
3273 from_utf8(masterBuffer()->filePath())));
3277 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3278 docstring_list const & bibfilelist,
3279 bool const add_extension) const
3281 // If we are processing the LaTeX file in a temp directory then
3282 // copy the .bib databases to this temp directory, mangling their
3283 // names in the process. Store this mangled name in the list of
3285 // (We need to do all this because BibTeX *really*, *really*
3286 // can't handle "files with spaces" and Windows users tend to
3287 // use such filenames.)
3288 // Otherwise, store the (maybe absolute) path to the original,
3289 // unmangled database name.
3291 vector<docstring> res;
3293 // determine the export format
3294 string const tex_format = flavor2format(runparams.flavor);
3296 // check for spaces in paths
3297 bool found_space = false;
3299 for (auto const & bit : bibfilelist) {
3300 string utf8input = to_utf8(bit);
3302 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3303 FileName try_in_file =
3304 makeAbsPath(database + ".bib", filePath());
3305 bool not_from_texmf = try_in_file.isReadableFile();
3306 // If the file has not been found, try with the real file name
3307 // (it might come from a child in a sub-directory)
3308 if (!not_from_texmf) {
3309 try_in_file = getBibfilePath(bit);
3310 if (try_in_file.isReadableFile()) {
3311 // Check if the file is in texmf
3312 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3313 not_from_texmf = kpsefile.empty()
3314 || kpsefile.absFileName() != try_in_file.absFileName();
3316 // If this exists, make path relative to the master
3319 removeExtension(prepareFileNameForLaTeX(
3320 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3321 from_utf8(filePath()))),
3322 ".bib", runparams.nice));
3326 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3328 // mangledFileName() needs the extension
3329 DocFileName const in_file = DocFileName(try_in_file);
3330 database = removeExtension(in_file.mangledFileName());
3331 FileName const out_file = makeAbsPath(database + ".bib",
3332 masterBuffer()->temppath());
3333 bool const success = in_file.copyTo(out_file);
3335 LYXERR0("Failed to copy '" << in_file
3336 << "' to '" << out_file << "'");
3338 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3339 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3340 if (!isValidLaTeXFileName(database)) {
3341 frontend::Alert::warning(_("Invalid filename"),
3342 _("The following filename will cause troubles "
3343 "when running the exported file through LaTeX: ") +
3344 from_utf8(database));
3346 if (!isValidDVIFileName(database)) {
3347 frontend::Alert::warning(_("Problematic filename for DVI"),
3348 _("The following filename can cause troubles "
3349 "when running the exported file through LaTeX "
3350 "and opening the resulting DVI: ") +
3351 from_utf8(database), true);
3359 docstring const path = from_utf8(latex_path(database));
3361 if (contains(path, ' '))
3364 if (find(res.begin(), res.end(), path) == res.end())
3365 res.push_back(path);
3368 // Check if there are spaces in the path and warn BibTeX users, if so.
3369 // (biber can cope with such paths)
3370 if (!prefixIs(runparams.bibtex_command, "biber")) {
3371 // Post this warning only once.
3372 static bool warned_about_spaces = false;
3373 if (!warned_about_spaces &&
3374 runparams.nice && found_space) {
3375 warned_about_spaces = true;
3376 Alert::warning(_("Export Warning!"),
3377 _("There are spaces in the paths to your BibTeX databases.\n"
3378 "BibTeX will be unable to find them."));
3387 string Buffer::layoutPos() const
3389 return d->layout_position;
3393 void Buffer::setLayoutPos(string const & path)
3396 d->layout_position.clear();
3400 LATTEST(FileName::isAbsolute(path));
3402 d->layout_position =
3403 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3405 if (d->layout_position.empty())
3406 d->layout_position = ".";
3410 bool Buffer::hasReadonlyFlag() const
3412 return d->read_only;
3416 bool Buffer::isReadonly() const
3418 return hasReadonlyFlag() || notifiesExternalModification();
3422 void Buffer::setParent(Buffer const * buffer)
3424 // Avoids recursive include.
3425 d->setParent(buffer == this ? 0 : buffer);
3430 Buffer const * Buffer::parent() const
3436 ListOfBuffers Buffer::allRelatives() const
3438 ListOfBuffers lb = masterBuffer()->getDescendents();
3439 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3444 Buffer const * Buffer::masterBuffer() const
3446 // FIXME Should be make sure we are not in some kind
3447 // of recursive include? A -> B -> A will crash this.
3448 Buffer const * const pbuf = d->parent();
3452 return pbuf->masterBuffer();
3456 bool Buffer::isChild(Buffer * child) const
3458 return d->children_positions.find(child) != d->children_positions.end();
3462 DocIterator Buffer::firstChildPosition(Buffer const * child)
3464 Impl::BufferPositionMap::iterator it;
3465 it = d->children_positions.find(child);
3466 if (it == d->children_positions.end())
3467 return DocIterator(this);
3472 bool Buffer::hasChildren() const
3474 return !d->children_positions.empty();
3478 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3480 // loop over children
3481 for (auto const & p : d->children_positions) {
3482 Buffer * child = const_cast<Buffer *>(p.first);
3484 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3485 if (bit != clist.end())
3487 clist.push_back(child);
3489 // there might be grandchildren
3490 child->collectChildren(clist, true);
3495 ListOfBuffers Buffer::getChildren() const
3498 collectChildren(v, false);
3499 // Make sure we have not included ourselves.
3500 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3501 if (bit != v.end()) {
3502 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3509 ListOfBuffers Buffer::getDescendents() const
3512 collectChildren(v, true);
3513 // Make sure we have not included ourselves.
3514 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3515 if (bit != v.end()) {
3516 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3523 template<typename M>
3524 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3529 typename M::const_iterator it = m.lower_bound(x);
3530 if (it == m.begin())
3538 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3539 DocIterator const & pos) const
3541 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3543 // if paragraphs have no macro context set, pos will be empty
3547 // we haven't found anything yet
3548 DocIterator bestPos = owner_->par_iterator_begin();
3549 MacroData const * bestData = 0;
3551 // find macro definitions for name
3552 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3553 if (nameIt != macros.end()) {
3554 // find last definition in front of pos or at pos itself
3555 PositionScopeMacroMap::const_iterator it
3556 = greatest_below(nameIt->second, pos);
3557 if (it != nameIt->second.end()) {
3559 // scope ends behind pos?
3560 if (pos < it->second.scope) {
3561 // Looks good, remember this. If there
3562 // is no external macro behind this,
3563 // we found the right one already.
3564 bestPos = it->first;
3565 bestData = &it->second.macro;
3569 // try previous macro if there is one
3570 if (it == nameIt->second.begin())
3577 // find macros in included files
3578 PositionScopeBufferMap::const_iterator it
3579 = greatest_below(position_to_children, pos);
3580 if (it == position_to_children.end())
3581 // no children before
3585 // do we know something better (i.e. later) already?
3586 if (it->first < bestPos )
3589 // scope ends behind pos?
3590 if (pos < it->second.scope
3591 && (cloned_buffer_ ||
3592 theBufferList().isLoaded(it->second.buffer))) {
3593 // look for macro in external file
3595 MacroData const * data
3596 = it->second.buffer->getMacro(name, false);
3599 bestPos = it->first;
3605 // try previous file if there is one
3606 if (it == position_to_children.begin())
3611 // return the best macro we have found
3616 MacroData const * Buffer::getMacro(docstring const & name,
3617 DocIterator const & pos, bool global) const
3622 // query buffer macros
3623 MacroData const * data = d->getBufferMacro(name, pos);
3627 // If there is a master buffer, query that
3628 Buffer const * const pbuf = d->parent();
3630 d->macro_lock = true;
3631 MacroData const * macro = pbuf->getMacro(
3632 name, *this, false);
3633 d->macro_lock = false;
3639 data = MacroTable::globalMacros().get(name);
3648 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3650 // set scope end behind the last paragraph
3651 DocIterator scope = par_iterator_begin();
3652 scope.pit() = scope.lastpit() + 1;
3654 return getMacro(name, scope, global);
3658 MacroData const * Buffer::getMacro(docstring const & name,
3659 Buffer const & child, bool global) const
3661 // look where the child buffer is included first
3662 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3663 if (it == d->children_positions.end())
3666 // check for macros at the inclusion position
3667 return getMacro(name, it->second, global);
3671 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3673 pit_type const lastpit = it.lastpit();
3675 // look for macros in each paragraph
3676 while (it.pit() <= lastpit) {
3677 Paragraph & par = it.paragraph();
3679 // FIXME Can this be done with the new-style iterators?
3680 // iterate over the insets of the current paragraph
3681 for (auto const & insit : par.insetList()) {
3682 it.pos() = insit.pos;
3684 // is it a nested text inset?
3685 if (insit.inset->asInsetText()) {
3686 // Inset needs its own scope?
3687 InsetText const * itext = insit.inset->asInsetText();
3688 bool newScope = itext->isMacroScope();
3690 // scope which ends just behind the inset
3691 DocIterator insetScope = it;
3694 // collect macros in inset
3695 it.push_back(CursorSlice(*insit.inset));
3696 updateMacros(it, newScope ? insetScope : scope);
3701 if (insit.inset->asInsetTabular()) {
3702 CursorSlice slice(*insit.inset);
3703 size_t const numcells = slice.nargs();
3704 for (; slice.idx() < numcells; slice.forwardIdx()) {
3705 it.push_back(slice);
3706 updateMacros(it, scope);
3712 // is it an external file?
3713 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3714 // get buffer of external file
3715 InsetInclude const & incinset =
3716 static_cast<InsetInclude const &>(*insit.inset);
3718 Buffer * child = incinset.getChildBuffer();
3723 // register its position, but only when it is
3724 // included first in the buffer
3725 if (children_positions.find(child) ==
3726 children_positions.end())
3727 children_positions[child] = it;
3729 // register child with its scope
3730 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3734 InsetMath * im = insit.inset->asInsetMath();
3735 if (doing_export && im) {
3736 InsetMathHull * hull = im->asHullInset();
3738 hull->recordLocation(it);
3741 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3745 InsetMathMacroTemplate & macroTemplate =
3746 *insit.inset->asInsetMath()->asMacroTemplate();
3747 MacroContext mc(owner_, it);
3748 macroTemplate.updateToContext(mc);
3751 bool valid = macroTemplate.validMacro();
3752 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3753 // then the BufferView's cursor will be invalid in
3754 // some cases which leads to crashes.
3759 // FIXME (Abdel), I don't understand why we pass 'it' here
3760 // instead of 'macroTemplate' defined above... is this correct?
3761 macros[macroTemplate.name()][it] =
3762 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3772 void Buffer::updateMacros() const
3777 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3779 // start with empty table
3781 d->children_positions.clear();
3782 d->position_to_children.clear();
3784 // Iterate over buffer, starting with first paragraph
3785 // The scope must be bigger than any lookup DocIterator
3786 // later. For the global lookup, lastpit+1 is used, hence
3787 // we use lastpit+2 here.
3788 DocIterator it = par_iterator_begin();
3789 DocIterator outerScope = it;
3790 outerScope.pit() = outerScope.lastpit() + 2;
3791 d->updateMacros(it, outerScope);
3795 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3797 InsetIterator it = inset_iterator_begin(inset());
3798 InsetIterator const end = inset_iterator_end(inset());
3799 for (; it != end; ++it) {
3800 if (it->lyxCode() == BRANCH_CODE) {
3801 InsetBranch & br = static_cast<InsetBranch &>(*it);
3802 docstring const name = br.branch();
3803 if (!from_master && !params().branchlist().find(name))
3804 result.push_back(name);
3805 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3806 result.push_back(name);
3809 if (it->lyxCode() == INCLUDE_CODE) {
3810 // get buffer of external file
3811 InsetInclude const & ins =
3812 static_cast<InsetInclude const &>(*it);
3813 Buffer * child = ins.getChildBuffer();
3816 child->getUsedBranches(result, true);
3819 // remove duplicates
3824 void Buffer::updateMacroInstances(UpdateType utype) const
3826 LYXERR(Debug::MACROS, "updateMacroInstances for "
3827 << d->filename.onlyFileName());
3828 DocIterator it = doc_iterator_begin(this);
3830 DocIterator const end = doc_iterator_end(this);
3831 for (; it != end; it.forwardInset()) {
3832 // look for MathData cells in InsetMathNest insets
3833 InsetMath * minset = it.nextInset()->asInsetMath();
3837 // update macro in all cells of the InsetMathNest
3838 DocIterator::idx_type n = minset->nargs();
3839 MacroContext mc = MacroContext(this, it);
3840 for (DocIterator::idx_type i = 0; i < n; ++i) {
3841 MathData & data = minset->cell(i);
3842 data.updateMacros(0, mc, utype, 0);
3848 void Buffer::listMacroNames(MacroNameSet & macros) const
3853 d->macro_lock = true;
3855 // loop over macro names
3856 for (auto const & nameit : d->macros)
3857 macros.insert(nameit.first);
3859 // loop over children
3860 for (auto const & p : d->children_positions) {
3861 Buffer * child = const_cast<Buffer *>(p.first);
3862 // The buffer might have been closed (see #10766).
3863 if (theBufferList().isLoaded(child))
3864 child->listMacroNames(macros);
3868 Buffer const * const pbuf = d->parent();
3870 pbuf->listMacroNames(macros);
3872 d->macro_lock = false;
3876 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3878 Buffer const * const pbuf = d->parent();
3883 pbuf->listMacroNames(names);
3886 for (auto const & mit : names) {
3888 MacroData const * data = pbuf->getMacro(mit, *this, false);
3890 macros.insert(data);
3892 // we cannot access the original InsetMathMacroTemplate anymore
3893 // here to calls validate method. So we do its work here manually.
3894 // FIXME: somehow make the template accessible here.
3895 if (data->optionals() > 0)
3896 features.require("xargs");
3902 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3905 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3907 // In what follows, we look whether we find an active label
3908 // with the given string in the cache. If so, return its
3909 // references cache. If we only find an inactive one, return
3910 // that (the last we find, coincidentally). If we find nothing,
3911 // return an empty references cache.
3912 static LabelInfo linfo;
3913 linfo.inset = nullptr;
3914 linfo.references = References();
3915 linfo.active = false;
3916 bool have_inactive = false;
3917 for (auto & rc : d->ref_cache_) {
3918 if (rc.label == label) {
3920 return rc.references;
3923 have_inactive = true;
3929 // We found nothing, so insert the empty one to the cache
3930 // for further processing
3931 d->ref_cache_.push_back(linfo);
3933 return linfo.references;
3937 Buffer::References const & Buffer::references(docstring const & label) const
3939 return const_cast<Buffer *>(this)->getReferenceCache(label);
3943 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3945 References & refs = getReferenceCache(label);
3946 refs.push_back(make_pair(inset, it));
3950 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3954 linfo.label = label;
3956 linfo.active = active;
3957 masterBuffer()->d->ref_cache_.push_back(linfo);
3961 InsetLabel const * Buffer::insetLabel(docstring const & label,
3962 bool const active) const
3964 for (auto & rc : masterBuffer()->d->ref_cache_) {
3965 if (rc.label == label && (rc.active || !active))
3972 bool Buffer::activeLabel(docstring const & label) const
3974 if (!insetLabel(label, true))
3981 void Buffer::clearReferenceCache() const
3984 d->ref_cache_.clear();
3988 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3990 //FIXME: This does not work for child documents yet.
3991 reloadBibInfoCache();
3993 // Check if the label 'from' appears more than once
3994 vector<docstring> labels;
3995 for (auto const & bibit : masterBibInfo())
3996 labels.push_back(bibit.first);
3998 if (count(labels.begin(), labels.end(), from) > 1)
4001 string const paramName = "key";
4002 InsetIterator it = inset_iterator_begin(inset());
4004 if (it->lyxCode() != CITE_CODE)
4006 InsetCommand * inset = it->asInsetCommand();
4007 docstring const oldValue = inset->getParam(paramName);
4008 if (oldValue == from)
4009 inset->setParam(paramName, to);
4013 // returns NULL if id-to-row conversion is unsupported
4014 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4015 pit_type par_begin, pit_type par_end,
4016 OutputWhat output, bool master) const
4018 unique_ptr<TexRow> texrow;
4019 OutputParams runparams(¶ms().encoding());
4020 runparams.nice = true;
4021 runparams.flavor = params().getOutputFlavor(format);
4022 runparams.linelen = lyxrc.plaintext_linelen;
4023 // No side effect of file copying and image conversion
4024 runparams.dryrun = true;
4026 // Some macros rely on font encoding
4027 runparams.main_fontenc = params().main_font_encoding();
4029 if (output == CurrentParagraph) {
4030 runparams.par_begin = par_begin;
4031 runparams.par_end = par_end;
4032 if (par_begin + 1 == par_end) {
4034 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4038 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4039 convert<docstring>(par_begin),
4040 convert<docstring>(par_end - 1))
4043 // output paragraphs
4044 if (runparams.flavor == OutputParams::LYX) {
4045 Paragraph const & par = text().paragraphs()[par_begin];
4047 depth_type dt = par.getDepth();
4048 par.write(ods, params(), dt);
4049 os << from_utf8(ods.str());
4050 } else if (runparams.flavor == OutputParams::HTML) {
4052 setMathFlavor(runparams);
4053 xhtmlParagraphs(text(), *this, xs, runparams);
4054 } else if (runparams.flavor == OutputParams::TEXT) {
4056 // FIXME Handles only one paragraph, unlike the others.
4057 // Probably should have some routine with a signature like them.
4058 writePlaintextParagraph(*this,
4059 text().paragraphs()[par_begin], os, runparams, dummy);
4060 } else if (params().isDocBook()) {
4061 docbookParagraphs(text(), *this, os, runparams);
4063 // If we are previewing a paragraph, even if this is the
4064 // child of some other buffer, let's cut the link here,
4065 // so that no concurring settings from the master
4066 // (e.g. branch state) interfere (see #8101).
4068 d->ignore_parent = true;
4069 // We need to validate the Buffer params' features here
4070 // in order to know if we should output polyglossia
4071 // macros (instead of babel macros)
4072 LaTeXFeatures features(*this, params(), runparams);
4074 runparams.use_polyglossia = features.usePolyglossia();
4075 // latex or literate
4078 ots.texrow().newlines(2);
4080 latexParagraphs(*this, text(), ots, runparams);
4081 texrow = ots.releaseTexRow();
4083 // Restore the parenthood
4085 d->ignore_parent = false;
4089 if (output == FullSource)
4090 os << _("Preview source code");
4091 else if (output == OnlyPreamble)
4092 os << _("Preview preamble");
4093 else if (output == OnlyBody)
4094 os << _("Preview body");
4096 if (runparams.flavor == OutputParams::LYX) {
4098 if (output == FullSource)
4100 else if (output == OnlyPreamble)
4101 params().writeFile(ods, this);
4102 else if (output == OnlyBody)
4104 os << from_utf8(ods.str());
4105 } else if (runparams.flavor == OutputParams::HTML) {
4106 writeLyXHTMLSource(os, runparams, output);
4107 } else if (runparams.flavor == OutputParams::TEXT) {
4108 if (output == OnlyPreamble) {
4109 os << "% "<< _("Plain text does not have a preamble.");
4111 writePlaintextFile(*this, os, runparams);
4112 } else if (params().isDocBook()) {
4113 writeDocBookSource(os, absFileName(), runparams, output);
4115 // latex or literate
4118 ots.texrow().newlines(2);
4120 runparams.is_child = true;
4122 writeLaTeXSource(ots, string(), runparams, output);
4123 texrow = ots.releaseTexRow();
4130 ErrorList & Buffer::errorList(string const & type) const
4132 return d->errorLists[type];
4136 void Buffer::updateTocItem(std::string const & type,
4137 DocIterator const & dit) const
4140 d->gui_->updateTocItem(type, dit);
4144 void Buffer::structureChanged() const
4147 d->gui_->structureChanged();
4151 void Buffer::errors(string const & err, bool from_master) const
4154 d->gui_->errors(err, from_master);
4158 void Buffer::message(docstring const & msg) const
4161 d->gui_->message(msg);
4165 void Buffer::setBusy(bool on) const
4168 d->gui_->setBusy(on);
4172 void Buffer::updateTitles() const
4175 d->wa_->updateTitles();
4179 void Buffer::resetAutosaveTimers() const
4182 d->gui_->resetAutosaveTimers();
4186 bool Buffer::hasGuiDelegate() const
4192 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4201 class AutoSaveBuffer : public ForkedProcess {
4204 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4205 : buffer_(buffer), fname_(fname) {}
4207 virtual shared_ptr<ForkedProcess> clone() const
4209 return make_shared<AutoSaveBuffer>(*this);
4214 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4215 from_utf8(fname_.absFileName())));
4216 return run(DontWait);
4220 virtual int generateChild();
4222 Buffer const & buffer_;
4227 int AutoSaveBuffer::generateChild()
4229 #if defined(__APPLE__)
4230 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4231 * We should use something else like threads.
4233 * Since I do not know how to determine at run time what is the OS X
4234 * version, I just disable forking altogether for now (JMarc)
4236 pid_t const pid = -1;
4238 // tmp_ret will be located (usually) in /tmp
4239 // will that be a problem?
4240 // Note that this calls ForkedCalls::fork(), so it's
4241 // ok cross-platform.
4242 pid_t const pid = fork();
4243 // If you want to debug the autosave
4244 // you should set pid to -1, and comment out the fork.
4245 if (pid != 0 && pid != -1)
4249 // pid = -1 signifies that lyx was unable
4250 // to fork. But we will do the save
4252 bool failed = false;
4253 TempFile tempfile("lyxautoXXXXXX.lyx");
4254 tempfile.setAutoRemove(false);
4255 FileName const tmp_ret = tempfile.name();
4256 if (!tmp_ret.empty()) {
4257 if (!buffer_.writeFile(tmp_ret))
4259 else if (!tmp_ret.moveTo(fname_))
4265 // failed to write/rename tmp_ret so try writing direct
4266 if (!buffer_.writeFile(fname_)) {
4267 // It is dangerous to do this in the child,
4268 // but safe in the parent, so...
4269 if (pid == -1) // emit message signal.
4270 buffer_.message(_("Autosave failed!"));
4274 if (pid == 0) // we are the child so...
4283 FileName Buffer::getEmergencyFileName() const
4285 return FileName(d->filename.absFileName() + ".emergency");
4289 FileName Buffer::getAutosaveFileName() const
4291 // if the document is unnamed try to save in the backup dir, else
4292 // in the default document path, and as a last try in the filePath,
4293 // which will most often be the temporary directory
4296 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4297 : lyxrc.backupdir_path;
4298 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4301 string const fname = "#" + d->filename.onlyFileName() + "#";
4303 return makeAbsPath(fname, fpath);
4307 void Buffer::removeAutosaveFile() const
4309 FileName const f = getAutosaveFileName();
4315 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4317 FileName const newauto = getAutosaveFileName();
4319 if (newauto != oldauto && oldauto.exists())
4320 if (!oldauto.moveTo(newauto))
4321 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4325 bool Buffer::autoSave() const
4327 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4328 if (buf->d->bak_clean || hasReadonlyFlag())
4331 message(_("Autosaving current document..."));
4332 buf->d->bak_clean = true;
4334 FileName const fname = getAutosaveFileName();
4335 LASSERT(d->cloned_buffer_, return false);
4337 // If this buffer is cloned, we assume that
4338 // we are running in a separate thread already.
4339 TempFile tempfile("lyxautoXXXXXX.lyx");
4340 tempfile.setAutoRemove(false);
4341 FileName const tmp_ret = tempfile.name();
4342 if (!tmp_ret.empty()) {
4344 // assume successful write of tmp_ret
4345 if (tmp_ret.moveTo(fname))
4348 // failed to write/rename tmp_ret so try writing direct
4349 return writeFile(fname);
4353 void Buffer::setExportStatus(bool e) const
4355 d->doing_export = e;
4356 ListOfBuffers clist = getDescendents();
4357 for (auto const & bit : clist)
4358 bit->d->doing_export = e;
4362 bool Buffer::isExporting() const
4364 return d->doing_export;
4368 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4372 return doExport(target, put_in_tempdir, result_file);
4375 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4376 string & result_file) const
4378 bool const update_unincluded =
4379 params().maintain_unincluded_children
4380 && !params().getIncludedChildren().empty();
4382 // (1) export with all included children (omit \includeonly)
4383 if (update_unincluded) {
4384 ExportStatus const status =
4385 doExport(target, put_in_tempdir, true, result_file);
4386 if (status != ExportSuccess)
4389 // (2) export with included children only
4390 return doExport(target, put_in_tempdir, false, result_file);
4394 void Buffer::setMathFlavor(OutputParams & op) const
4396 switch (params().html_math_output) {
4397 case BufferParams::MathML:
4398 op.math_flavor = OutputParams::MathAsMathML;
4400 case BufferParams::HTML:
4401 op.math_flavor = OutputParams::MathAsHTML;
4403 case BufferParams::Images:
4404 op.math_flavor = OutputParams::MathAsImages;
4406 case BufferParams::LaTeX:
4407 op.math_flavor = OutputParams::MathAsLaTeX;
4413 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4414 bool includeall, string & result_file) const
4416 LYXERR(Debug::FILES, "target=" << target);
4417 OutputParams runparams(¶ms().encoding());
4418 string format = target;
4419 string dest_filename;
4420 size_t pos = target.find(' ');
4421 if (pos != string::npos) {
4422 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4423 format = target.substr(0, pos);
4424 if (format == "default")
4425 format = params().getDefaultOutputFormat();
4426 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4427 FileName(dest_filename).onlyPath().createPath();
4428 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4430 MarkAsExporting exporting(this);
4431 string backend_format;
4432 runparams.flavor = OutputParams::LATEX;
4433 runparams.linelen = lyxrc.plaintext_linelen;
4434 runparams.includeall = includeall;
4435 vector<string> backs = params().backends();
4436 Converters converters = theConverters();
4437 bool need_nice_file = false;
4438 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4439 // Get shortest path to format
4440 converters.buildGraph();
4441 Graph::EdgePath path;
4442 for (string const & sit : backs) {
4443 Graph::EdgePath p = converters.getPath(sit, format);
4444 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4445 backend_format = sit;
4450 if (!put_in_tempdir) {
4451 // Only show this alert if this is an export to a non-temporary
4452 // file (not for previewing).
4453 Alert::error(_("Couldn't export file"), bformat(
4454 _("No information for exporting the format %1$s."),
4455 theFormats().prettyName(format)));
4457 return ExportNoPathToFormat;
4459 runparams.flavor = converters.getFlavor(path, this);
4460 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4461 for (auto const & edge : path)
4462 if (theConverters().get(edge).nice()) {
4463 need_nice_file = true;
4468 backend_format = format;
4469 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4470 // FIXME: Don't hardcode format names here, but use a flag
4471 if (backend_format == "pdflatex")
4472 runparams.flavor = OutputParams::PDFLATEX;
4473 else if (backend_format == "luatex")
4474 runparams.flavor = OutputParams::LUATEX;
4475 else if (backend_format == "dviluatex")
4476 runparams.flavor = OutputParams::DVILUATEX;
4477 else if (backend_format == "xetex")
4478 runparams.flavor = OutputParams::XETEX;
4481 string filename = latexName(false);
4482 filename = addName(temppath(), filename);
4483 filename = changeExtension(filename,
4484 theFormats().extension(backend_format));
4485 LYXERR(Debug::FILES, "filename=" << filename);
4487 // Plain text backend
4488 if (backend_format == "text") {
4489 runparams.flavor = OutputParams::TEXT;
4491 writePlaintextFile(*this, FileName(filename), runparams);
4493 catch (ConversionException const &) { return ExportCancel; }
4496 else if (backend_format == "xhtml") {
4497 runparams.flavor = OutputParams::HTML;
4498 setMathFlavor(runparams);
4499 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4500 return ExportKilled;
4501 } else if (backend_format == "lyx")
4502 writeFile(FileName(filename));
4504 else if (params().isDocBook()) {
4505 runparams.nice = !put_in_tempdir;
4506 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4507 return ExportKilled;
4510 else if (backend_format == format || need_nice_file) {
4511 runparams.nice = true;
4512 ExportStatus const retval =
4513 makeLaTeXFile(FileName(filename), string(), runparams);
4514 if (retval == ExportKilled)
4515 return ExportKilled;
4516 if (d->cloned_buffer_)
4517 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4518 if (retval != ExportSuccess)
4520 } else if (!lyxrc.tex_allows_spaces
4521 && contains(filePath(), ' ')) {
4522 Alert::error(_("File name error"),
4523 bformat(_("The directory path to the document\n%1$s\n"
4524 "contains spaces, but your TeX installation does "
4525 "not allow them. You should save the file to a directory "
4526 "whose name does not contain spaces."), from_ascii(filePath())));
4527 return ExportTexPathHasSpaces;
4529 runparams.nice = false;
4530 ExportStatus const retval =
4531 makeLaTeXFile(FileName(filename), filePath(), runparams);
4532 if (retval == ExportKilled)
4533 return ExportKilled;
4534 if (d->cloned_buffer_)
4535 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4536 if (retval != ExportSuccess)
4540 string const error_type = (format == "program")
4541 ? "Build" : params().bufferFormat();
4542 ErrorList & error_list = d->errorLists[error_type];
4543 string const ext = theFormats().extension(format);
4544 FileName const tmp_result_file(changeExtension(filename, ext));
4545 Converters::RetVal const retval =
4546 converters.convert(this, FileName(filename), tmp_result_file,
4547 FileName(absFileName()), backend_format, format, error_list);
4548 if (retval == Converters::KILLED)
4549 return ExportCancel;
4550 bool success = (retval == Converters::SUCCESS);
4552 // Emit the signal to show the error list or copy it back to the
4553 // cloned Buffer so that it can be emitted afterwards.
4554 if (format != backend_format) {
4555 if (runparams.silent)
4557 else if (d->cloned_buffer_)
4558 d->cloned_buffer_->d->errorLists[error_type] =
4559 d->errorLists[error_type];
4562 // also to the children, in case of master-buffer-view
4563 ListOfBuffers clist = getDescendents();
4564 for (auto const & bit : clist) {
4565 if (runparams.silent)
4566 bit->d->errorLists[error_type].clear();
4567 else if (d->cloned_buffer_) {
4568 // Enable reverse search by copying back the
4569 // texrow object to the cloned buffer.
4570 // FIXME: this is not thread safe.
4571 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4572 bit->d->cloned_buffer_->d->errorLists[error_type] =
4573 bit->d->errorLists[error_type];
4575 bit->errors(error_type, true);
4579 if (d->cloned_buffer_) {
4580 // Enable reverse dvi or pdf to work by copying back the texrow
4581 // object to the cloned buffer.
4582 // FIXME: There is a possibility of concurrent access to texrow
4583 // here from the main GUI thread that should be securized.
4584 d->cloned_buffer_->d->texrow = d->texrow;
4585 string const err_type = params().bufferFormat();
4586 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4590 if (put_in_tempdir) {
4591 result_file = tmp_result_file.absFileName();
4592 return success ? ExportSuccess : ExportConverterError;
4595 if (dest_filename.empty())
4596 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4598 result_file = dest_filename;
4599 // We need to copy referenced files (e. g. included graphics
4600 // if format == "dvi") to the result dir.
4601 vector<ExportedFile> const files =
4602 runparams.exportdata->externalFiles(format);
4603 string const dest = runparams.export_folder.empty() ?
4604 onlyPath(result_file) : runparams.export_folder;
4605 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4606 : force_overwrite == ALL_FILES;
4607 CopyStatus status = use_force ? FORCE : SUCCESS;
4609 for (ExportedFile const & exp : files) {
4610 if (status == CANCEL) {
4611 message(_("Document export cancelled."));
4612 return ExportCancel;
4614 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4615 string fixedName = exp.exportName;
4616 if (!runparams.export_folder.empty()) {
4617 // Relative pathnames starting with ../ will be sanitized
4618 // if exporting to a different folder
4619 while (fixedName.substr(0, 3) == "../")
4620 fixedName = fixedName.substr(3, fixedName.length() - 3);
4622 FileName fixedFileName = makeAbsPath(fixedName, dest);
4623 fixedFileName.onlyPath().createPath();
4624 status = copyFile(fmt, exp.sourceName,
4626 exp.exportName, status == FORCE,
4627 runparams.export_folder.empty());
4631 if (tmp_result_file.exists()) {
4632 // Finally copy the main file
4633 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4634 : force_overwrite != NO_FILES;
4635 if (status == SUCCESS && use_force)
4637 status = copyFile(format, tmp_result_file,
4638 FileName(result_file), result_file,
4640 if (status == CANCEL) {
4641 message(_("Document export cancelled."));
4642 return ExportCancel;
4644 message(bformat(_("Document exported as %1$s "
4646 theFormats().prettyName(format),
4647 makeDisplayPath(result_file)));
4650 // This must be a dummy converter like fax (bug 1888)
4651 message(bformat(_("Document exported as %1$s"),
4652 theFormats().prettyName(format)));
4655 return success ? ExportSuccess : ExportConverterError;
4659 Buffer::ExportStatus Buffer::preview(string const & format) const
4661 bool const update_unincluded =
4662 params().maintain_unincluded_children
4663 && !params().getIncludedChildren().empty();
4664 return preview(format, update_unincluded);
4668 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4670 MarkAsExporting exporting(this);
4672 // (1) export with all included children (omit \includeonly)
4674 ExportStatus const status = doExport(format, true, true, result_file);
4675 if (status != ExportSuccess)
4678 // (2) export with included children only
4679 ExportStatus const status = doExport(format, true, false, result_file);
4680 FileName const previewFile(result_file);
4682 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4683 theimpl->preview_file_ = previewFile;
4684 theimpl->preview_format_ = format;
4685 theimpl->preview_error_ = (status != ExportSuccess);
4687 if (status != ExportSuccess)
4690 if (previewFile.exists())
4691 return theFormats().view(*this, previewFile, format) ?
4692 PreviewSuccess : PreviewError;
4694 // Successful export but no output file?
4695 // Probably a bug in error detection.
4696 LATTEST(status != ExportSuccess);
4701 Buffer::ReadStatus Buffer::extractFromVC()
4703 bool const found = LyXVC::file_not_found_hook(d->filename);
4705 return ReadFileNotFound;
4706 if (!d->filename.isReadableFile())
4712 Buffer::ReadStatus Buffer::loadEmergency()
4714 FileName const emergencyFile = getEmergencyFileName();
4715 if (!emergencyFile.exists()
4716 || emergencyFile.lastModified() <= d->filename.lastModified())
4717 return ReadFileNotFound;
4719 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4720 docstring const text = bformat(_("An emergency save of the document "
4721 "%1$s exists.\n\nRecover emergency save?"), file);
4723 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4724 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4730 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4731 bool const success = (ret_llf == ReadSuccess);
4733 if (hasReadonlyFlag()) {
4734 Alert::warning(_("File is read-only"),
4735 bformat(_("An emergency file is successfully loaded, "
4736 "but the original file %1$s is marked read-only. "
4737 "Please make sure to save the document as a different "
4738 "file."), from_utf8(d->filename.absFileName())));
4741 lyxvc().file_found_hook(d->filename);
4742 str = _("Document was successfully recovered.");
4744 str = _("Document was NOT successfully recovered.");
4745 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4746 makeDisplayPath(emergencyFile.absFileName()));
4748 int const del_emerg =
4749 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4750 _("&Remove"), _("&Keep"));
4751 if (del_emerg == 0) {
4752 emergencyFile.removeFile();
4754 Alert::warning(_("Emergency file deleted"),
4755 _("Do not forget to save your file now!"), true);
4757 return success ? ReadSuccess : ReadEmergencyFailure;
4760 int const del_emerg =
4761 Alert::prompt(_("Delete emergency file?"),
4762 _("Remove emergency file now?"), 1, 1,
4763 _("&Remove"), _("&Keep"));
4765 emergencyFile.removeFile();
4766 return ReadOriginal;
4776 Buffer::ReadStatus Buffer::loadAutosave()
4778 // Now check if autosave file is newer.
4779 FileName const autosaveFile = getAutosaveFileName();
4780 if (!autosaveFile.exists()
4781 || autosaveFile.lastModified() <= d->filename.lastModified())
4782 return ReadFileNotFound;
4784 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4785 docstring const text = bformat(_("The backup of the document %1$s "
4786 "is newer.\n\nLoad the backup instead?"), file);
4787 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4788 _("&Load backup"), _("Load &original"), _("&Cancel"));
4793 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4794 // the file is not saved if we load the autosave file.
4795 if (ret_llf == ReadSuccess) {
4796 if (hasReadonlyFlag()) {
4797 Alert::warning(_("File is read-only"),
4798 bformat(_("A backup file is successfully loaded, "
4799 "but the original file %1$s is marked read-only. "
4800 "Please make sure to save the document as a "
4802 from_utf8(d->filename.absFileName())));
4805 lyxvc().file_found_hook(d->filename);
4808 return ReadAutosaveFailure;
4811 // Here we delete the autosave
4812 autosaveFile.removeFile();
4813 return ReadOriginal;
4821 Buffer::ReadStatus Buffer::loadLyXFile()
4823 if (!d->filename.isReadableFile()) {
4824 ReadStatus const ret_rvc = extractFromVC();
4825 if (ret_rvc != ReadSuccess)
4829 ReadStatus const ret_re = loadEmergency();
4830 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4833 ReadStatus const ret_ra = loadAutosave();
4834 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4837 return loadThisLyXFile(d->filename);
4841 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4843 return readFile(fn);
4847 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4849 for (auto const & err : terr) {
4850 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4851 int errorRow = err.error_in_line;
4852 Buffer const * buf = 0;
4854 if (err.child_name.empty())
4855 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4857 // The error occurred in a child
4858 for (Buffer const * child : getDescendents()) {
4859 string const child_name =
4860 DocFileName(changeExtension(child->absFileName(), "tex")).
4862 if (err.child_name != child_name)
4864 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4865 if (!TexRow::isNone(start)) {
4866 buf = d->cloned_buffer_
4867 ? child->d->cloned_buffer_->d->owner_
4874 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4880 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4882 LBUFERR(!text().paragraphs().empty());
4884 // Use the master text class also for child documents
4885 Buffer const * const master = masterBuffer();
4886 DocumentClass const & textclass = master->params().documentClass();
4888 docstring_list old_bibfiles;
4889 // Do this only if we are the top-level Buffer. We also need to account
4890 // for the case of a previewed child with ignored parent here.
4891 if (master == this && !d->ignore_parent) {
4892 textclass.counters().reset(from_ascii("bibitem"));
4893 reloadBibInfoCache();
4894 // we will re-read this cache as we go through, but we need
4895 // to know whether it's changed to know whether we need to
4896 // update the bibinfo cache.
4897 old_bibfiles = d->bibfiles_cache_;
4898 d->bibfiles_cache_.clear();
4901 // keep the buffers to be children in this set. If the call from the
4902 // master comes back we can see which of them were actually seen (i.e.
4903 // via an InsetInclude). The remaining ones in the set need still be updated.
4904 static std::set<Buffer const *> bufToUpdate;
4905 if (scope == UpdateMaster) {
4906 // If this is a child document start with the master
4907 if (master != this) {
4908 bufToUpdate.insert(this);
4909 master->updateBuffer(UpdateMaster, utype);
4910 // If the master buffer has no gui associated with it, then the TocModel is
4911 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4912 // (bug 5699). The same happens if the master buffer is open in a different
4913 // window. This test catches both possibilities.
4914 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4915 // There remains a problem here: If there is another child open in yet a third
4916 // window, that TOC is not updated. So some more general solution is needed at
4918 if (master->d->gui_ != d->gui_)
4921 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4922 if (bufToUpdate.find(this) == bufToUpdate.end())
4926 // start over the counters in the master
4927 textclass.counters().reset();
4930 // update will be done below for this buffer
4931 bufToUpdate.erase(this);
4933 // update all caches
4934 clearReferenceCache();
4936 setChangesPresent(false);
4938 Buffer & cbuf = const_cast<Buffer &>(*this);
4941 ParIterator parit = cbuf.par_iterator_begin();
4942 updateBuffer(parit, utype);
4944 // If this document has siblings, then update the TocBackend later. The
4945 // reason is to ensure that later siblings are up to date when e.g. the
4946 // broken or not status of references is computed. The update is called
4947 // in InsetInclude::addToToc.
4951 // if the bibfiles changed, the cache of bibinfo is invalid
4952 docstring_list new_bibfiles = d->bibfiles_cache_;
4953 // this is a trick to determine whether the two vectors have
4954 // the same elements.
4955 sort(new_bibfiles.begin(), new_bibfiles.end());
4956 sort(old_bibfiles.begin(), old_bibfiles.end());
4957 if (old_bibfiles != new_bibfiles) {
4958 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4959 invalidateBibinfoCache();
4960 reloadBibInfoCache();
4961 // We relied upon the bibinfo cache when recalculating labels. But that
4962 // cache was invalid, although we didn't find that out until now. So we
4963 // have to do it all again.
4964 // That said, the only thing we really need to do is update the citation
4965 // labels. Nothing else will have changed. So we could create a new
4966 // UpdateType that would signal that fact, if we needed to do so.
4967 parit = cbuf.par_iterator_begin();
4968 // we will be re-doing the counters and references and such.
4969 textclass.counters().reset();
4970 clearReferenceCache();
4971 // we should not need to do this again?
4973 setChangesPresent(false);
4974 updateBuffer(parit, utype);
4975 // this will already have been done by reloadBibInfoCache();
4976 // d->bibinfo_cache_valid_ = true;
4979 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4980 // this is also set to true on the other path, by reloadBibInfoCache.
4981 d->bibinfo_cache_valid_ = true;
4983 d->cite_labels_valid_ = true;
4985 cbuf.tocBackend().update(true, utype);
4986 if (scope == UpdateMaster)
4987 cbuf.structureChanged();
4991 static depth_type getDepth(DocIterator const & it)
4993 depth_type depth = 0;
4994 for (size_t i = 0 ; i < it.depth() ; ++i)
4995 if (!it[i].inset().inMathed())
4996 depth += it[i].paragraph().getDepth() + 1;
4997 // remove 1 since the outer inset does not count
4998 // we should have at least one non-math inset, so
4999 // depth should nevery be 0. but maybe it is worth
5000 // marking this, just in case.
5002 // coverity[INTEGER_OVERFLOW]
5006 static depth_type getItemDepth(ParIterator const & it)
5008 Paragraph const & par = *it;
5009 LabelType const labeltype = par.layout().labeltype;
5011 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5014 // this will hold the lowest depth encountered up to now.
5015 depth_type min_depth = getDepth(it);
5016 ParIterator prev_it = it;
5019 --prev_it.top().pit();
5021 // start of nested inset: go to outer par
5023 if (prev_it.empty()) {
5024 // start of document: nothing to do
5029 // We search for the first paragraph with same label
5030 // that is not more deeply nested.
5031 Paragraph & prev_par = *prev_it;
5032 depth_type const prev_depth = getDepth(prev_it);
5033 if (labeltype == prev_par.layout().labeltype) {
5034 if (prev_depth < min_depth)
5035 return prev_par.itemdepth + 1;
5036 if (prev_depth == min_depth)
5037 return prev_par.itemdepth;
5039 min_depth = min(min_depth, prev_depth);
5040 // small optimization: if we are at depth 0, we won't
5041 // find anything else
5042 if (prev_depth == 0)
5048 static bool needEnumCounterReset(ParIterator const & it)
5050 Paragraph const & par = *it;
5051 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5052 depth_type const cur_depth = par.getDepth();
5053 ParIterator prev_it = it;
5054 while (prev_it.pit()) {
5055 --prev_it.top().pit();
5056 Paragraph const & prev_par = *prev_it;
5057 if (prev_par.getDepth() <= cur_depth)
5058 return prev_par.layout().name() != par.layout().name();
5060 // start of nested inset: reset
5065 // set the label of a paragraph. This includes the counters.
5066 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5068 BufferParams const & bp = owner_->masterBuffer()->params();
5069 DocumentClass const & textclass = bp.documentClass();
5070 Paragraph & par = it.paragraph();
5071 Layout const & layout = par.layout();
5072 Counters & counters = textclass.counters();
5074 if (par.params().startOfAppendix()) {
5075 // We want to reset the counter corresponding to toplevel sectioning
5076 Layout const & lay = textclass.getTOCLayout();
5077 docstring const cnt = lay.counter;
5079 counters.reset(cnt);
5080 counters.appendix(true);
5082 par.params().appendix(counters.appendix());
5084 // Compute the item depth of the paragraph
5085 par.itemdepth = getItemDepth(it);
5087 if (layout.margintype == MARGIN_MANUAL) {
5088 if (par.params().labelWidthString().empty())
5089 par.params().labelWidthString(par.expandLabel(layout, bp));
5090 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5091 // we do not need to do anything here, since the empty case is
5092 // handled during export.
5094 par.params().labelWidthString(docstring());
5097 switch(layout.labeltype) {
5098 case LABEL_ITEMIZE: {
5099 // At some point of time we should do something more
5100 // clever here, like:
5101 // par.params().labelString(
5102 // bp.user_defined_bullet(par.itemdepth).getText());
5103 // for now, use a simple hardcoded label
5104 docstring itemlabel;
5105 switch (par.itemdepth) {
5107 itemlabel = char_type(0x2022);
5110 itemlabel = char_type(0x2013);
5113 itemlabel = char_type(0x2217);
5116 itemlabel = char_type(0x2219); // or 0x00b7
5119 par.params().labelString(itemlabel);
5123 case LABEL_ENUMERATE: {
5124 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5126 switch (par.itemdepth) {
5137 enumcounter += "iv";
5140 // not a valid enumdepth...
5144 if (needEnumCounterReset(it)) {
5145 // Increase the master counter?
5146 if (layout.stepmastercounter)
5147 counters.stepMaster(enumcounter, utype);
5148 // Maybe we have to reset the enumeration counter.
5149 if (!layout.resumecounter)
5150 counters.reset(enumcounter);
5152 counters.step(enumcounter, utype);
5154 string const & lang = par.getParLanguage(bp)->code();
5155 par.params().labelString(counters.theCounter(enumcounter, lang));
5160 case LABEL_SENSITIVE: {
5161 string const & type = counters.current_float();
5162 docstring full_label;
5164 full_label = owner_->B_("Senseless!!! ");
5166 docstring name = owner_->B_(textclass.floats().getType(type).name());
5167 if (counters.hasCounter(from_utf8(type))) {
5168 string const & lang = par.getParLanguage(bp)->code();
5169 counters.step(from_utf8(type), utype);
5170 full_label = bformat(from_ascii("%1$s %2$s:"),
5172 counters.theCounter(from_utf8(type), lang));
5174 full_label = bformat(from_ascii("%1$s #:"), name);
5176 par.params().labelString(full_label);
5180 case LABEL_NO_LABEL:
5181 par.params().labelString(docstring());
5185 case LABEL_CENTERED:
5186 case LABEL_STATIC: {
5187 docstring const & lcounter = layout.counter;
5188 if (!lcounter.empty()) {
5189 if (layout.toclevel <= bp.secnumdepth
5190 && (layout.latextype != LATEX_ENVIRONMENT
5191 || it.text()->isFirstInSequence(it.pit()))) {
5192 if (counters.hasCounter(lcounter))
5193 counters.step(lcounter, utype);
5194 par.params().labelString(par.expandLabel(layout, bp));
5196 par.params().labelString(docstring());
5198 par.params().labelString(par.expandLabel(layout, bp));
5204 par.params().labelString(par.expandLabel(layout, bp));
5209 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5211 // LASSERT: Is it safe to continue here, or should we just return?
5212 LASSERT(parit.pit() == 0, /**/);
5214 // Set the position of the text in the buffer to be able
5215 // to resolve macros in it.
5216 parit.text()->setMacrocontextPosition(parit);
5218 depth_type maxdepth = 0;
5219 pit_type const lastpit = parit.lastpit();
5220 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5221 // reduce depth if necessary
5222 if (parit->params().depth() > maxdepth) {
5223 /** FIXME: this function is const, but
5224 * nevertheless it modifies the buffer. To be
5225 * cleaner, one should modify the buffer in
5226 * another function, which is actually
5227 * non-const. This would however be costly in
5228 * terms of code duplication.
5230 CursorData(parit).recordUndo();
5231 parit->params().depth(maxdepth);
5233 maxdepth = parit->getMaxDepthAfter();
5235 if (utype == OutputUpdate) {
5236 // track the active counters
5237 // we have to do this for the master buffer, since the local
5238 // buffer isn't tracking anything.
5239 masterBuffer()->params().documentClass().counters().
5240 setActiveLayout(parit->layout());
5243 // set the counter for this paragraph
5244 d->setLabel(parit, utype);
5246 // update change-tracking flag
5247 parit->addChangesToBuffer(*this);
5250 for (auto const & insit : parit->insetList()) {
5251 parit.pos() = insit.pos;
5252 insit.inset->updateBuffer(parit, utype);
5258 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5259 WordLangTuple & word_lang, docstring_list & suggestions) const
5263 suggestions.clear();
5264 word_lang = WordLangTuple();
5265 bool const to_end = to.empty();
5266 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5267 // OK, we start from here.
5268 for (; from != end; from.forwardPos()) {
5269 // This skips all insets with spell check disabled.
5270 while (!from.allowSpellCheck()) {
5274 // If from is at the end of the document (which is possible
5275 // when "from" was changed above) LyX will crash later otherwise.
5276 if (from.atEnd() || (!to_end && from >= end))
5279 from.paragraph().spellCheck();
5280 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5281 if (SpellChecker::misspelled(res)) {
5285 // Do not increase progress when from == to, otherwise the word
5286 // count will be wrong.
5296 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5298 bool inword = false;
5303 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5304 if (!dit.inTexted()) {
5309 Paragraph const & par = dit.paragraph();
5310 pos_type const pos = dit.pos();
5312 // Copied and adapted from isWordSeparator() in Paragraph
5313 if (pos == dit.lastpos()) {
5316 Inset const * ins = par.getInset(pos);
5317 if (ins && skipNoOutput && !ins->producesOutput()) {
5320 // stop if end of range was skipped
5321 if (!to.atEnd() && dit >= to)
5324 } else if (!par.isDeleted(pos)) {
5325 if (par.isWordSeparator(pos))
5331 if (ins && ins->isLetter())
5333 else if (ins && ins->isSpace())
5336 char_type const c = par.getChar(pos);
5337 if (isPrintableNonspace(c))
5339 else if (isSpace(c))
5349 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5351 d->updateStatistics(from, to, skipNoOutput);
5355 int Buffer::wordCount() const
5357 return d->wordCount();
5361 int Buffer::charCount(bool with_blanks) const
5363 return d->charCount(with_blanks);
5367 Buffer::ReadStatus Buffer::reload()
5370 // c.f. bug https://www.lyx.org/trac/ticket/6587
5371 removeAutosaveFile();
5372 // e.g., read-only status could have changed due to version control
5373 d->filename.refresh();
5374 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5376 // clear parent. this will get reset if need be.
5378 ReadStatus const status = loadLyXFile();
5379 if (status == ReadSuccess) {
5384 message(bformat(_("Document %1$s reloaded."), disp_fn));
5387 message(bformat(_("Could not reload document %1$s."), disp_fn));
5397 bool Buffer::saveAs(FileName const & fn)
5399 FileName const old_name = fileName();
5400 FileName const old_auto = getAutosaveFileName();
5401 bool const old_unnamed = isUnnamed();
5402 bool success = true;
5403 d->old_position = filePath();
5410 // bring the autosave file with us, just in case.
5411 moveAutosaveFile(old_auto);
5412 // validate version control data and
5413 // correct buffer title
5414 lyxvc().file_found_hook(fileName());
5416 // the file has now been saved to the new location.
5417 // we need to check that the locations of child buffers
5419 checkChildBuffers();
5420 checkMasterBuffer();
5423 // reset the old filename and unnamed state
5424 setFileName(old_name);
5425 setUnnamed(old_unnamed);
5429 d->old_position.clear();
5434 void Buffer::checkChildBuffers()
5436 for (auto const & bit : d->children_positions) {
5437 DocIterator dit = bit.second;
5438 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5439 if (!cbuf || !theBufferList().isLoaded(cbuf))
5441 Inset * inset = dit.nextInset();
5442 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5443 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5444 docstring const & incfile = inset_inc->getParam("filename");
5445 string oldloc = cbuf->absFileName();
5446 string newloc = makeAbsPath(to_utf8(incfile),
5447 onlyPath(absFileName())).absFileName();
5448 if (oldloc == newloc)
5450 // the location of the child file is incorrect.
5452 inset_inc->setChildBuffer(0);
5454 // invalidate cache of children
5455 d->children_positions.clear();
5456 d->position_to_children.clear();
5460 // If a child has been saved under a different name/path, it might have been
5461 // orphaned. Therefore the master needs to be reset (bug 8161).
5462 void Buffer::checkMasterBuffer()
5464 Buffer const * const master = masterBuffer();
5468 // necessary to re-register the child (bug 5873)
5469 // FIXME: clean up updateMacros (here, only
5470 // child registering is needed).
5471 master->updateMacros();
5472 // (re)set master as master buffer, but only
5473 // if we are a real child
5474 if (master->isChild(this))
5481 string Buffer::includedFilePath(string const & name, string const & ext) const
5483 if (d->old_position.empty() ||
5484 equivalent(FileName(d->old_position), FileName(filePath())))
5487 bool isabsolute = FileName::isAbsolute(name);
5488 // both old_position and filePath() end with a path separator
5489 string absname = isabsolute ? name : d->old_position + name;
5491 // if old_position is set to origin, we need to do the equivalent of
5492 // getReferencedFileName() (see readDocument())
5493 if (!isabsolute && d->old_position == params().origin) {
5494 FileName const test(addExtension(filePath() + name, ext));
5496 absname = filePath() + name;
5499 if (!FileName(addExtension(absname, ext)).exists())
5503 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5505 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5506 from_utf8(filePath())));
5510 void Buffer::setChangesPresent(bool b) const
5512 d->tracked_changes_present_ = b;
5516 bool Buffer::areChangesPresent() const
5518 return d->tracked_changes_present_;
5522 void Buffer::updateChangesPresent() const
5524 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5525 setChangesPresent(false);
5526 ParConstIterator it = par_iterator_begin();
5527 ParConstIterator const end = par_iterator_end();
5528 for (; !areChangesPresent() && it != end; ++it)
5529 it->addChangesToBuffer(*this);
5533 void Buffer::Impl::refreshFileMonitor()
5535 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5536 file_monitor_->refresh();
5540 // The previous file monitor is invalid
5541 // This also destroys the previous file monitor and all its connections
5542 file_monitor_ = FileSystemWatcher::monitor(filename);
5543 // file_monitor_ will be destroyed with *this, so it is not going to call a
5544 // destroyed object method.
5545 file_monitor_->connect([this](bool exists) {
5546 fileExternallyModified(exists);
5551 void Buffer::Impl::fileExternallyModified(bool const exists)
5553 // ignore notifications after our own saving operations
5554 if (checksum_ == filename.checksum()) {
5555 LYXERR(Debug::FILES, "External modification but "
5556 "checksum unchanged: " << filename);
5559 // If the file has been deleted, only mark the file as dirty since it is
5560 // pointless to prompt for reloading. If later a file is moved into this
5561 // location, then the externally modified warning will appear then.
5563 externally_modified_ = true;
5564 // Update external modification notification.
5565 // Dirty buffers must be visible at all times.
5566 if (wa_ && wa_->unhide(owner_))
5567 wa_->updateTitles();
5569 // Unable to unhide the buffer (e.g. no GUI or not current View)
5574 bool Buffer::notifiesExternalModification() const
5576 return d->externally_modified_;
5580 void Buffer::clearExternalModification() const
5582 d->externally_modified_ = false;
5584 d->wa_->updateTitles();