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 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, no need to check
2502 if (!d->bibinfo_cache_valid_)
2505 // we'll assume it's ok and change this if it's not
2506 d->bibinfo_cache_valid_ = true;
2507 d->cite_labels_valid_ = true;
2509 // compare the cached timestamps with the actual ones.
2510 docstring_list const & bibfiles_cache = getBibfiles();
2511 for (auto const & bf : bibfiles_cache) {
2512 FileName const fn = getBibfilePath(bf);
2513 time_t lastw = fn.lastModified();
2514 time_t prevw = d->bibfile_status_[fn];
2515 if (lastw != prevw) {
2516 d->bibinfo_cache_valid_ = false;
2517 d->cite_labels_valid_ = false;
2518 d->bibfile_status_[fn] = lastw;
2524 void Buffer::clearBibFileCache() const
2526 bibfileCache.clear();
2530 void Buffer::reloadBibInfoCache(bool const force) const
2532 // we should not need to do this for internal buffers
2536 // use the master's cache
2537 Buffer const * const tmp = masterBuffer();
2539 tmp->reloadBibInfoCache(force);
2544 checkIfBibInfoCacheIsValid();
2545 if (d->bibinfo_cache_valid_)
2549 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2550 // re-read file locations when this info changes
2551 // FIXME Is this sufficient? Or should we also force that
2552 // in some other cases? If so, then it is easy enough to
2553 // add the following line in some other places.
2554 clearBibFileCache();
2555 d->bibinfo_.clear();
2556 FileNameList checkedFiles;
2557 collectBibKeys(checkedFiles);
2558 d->bibinfo_cache_valid_ = true;
2562 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2564 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2565 it->collectBibKeys(it, checkedFiles);
2569 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2571 // We add the biblio info to the master buffer,
2572 // if there is one, but also to every single buffer,
2573 // in case a child is compiled alone.
2574 BiblioInfo & bi = d->bibinfo_;
2575 bi.mergeBiblioInfo(bin);
2577 if (parent() != 0) {
2578 BiblioInfo & masterbi = parent()->d->bibinfo_;
2579 masterbi.mergeBiblioInfo(bin);
2584 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2586 // We add the bibtex info to the master buffer,
2587 // if there is one, but also to every single buffer,
2588 // in case a child is compiled alone.
2589 BiblioInfo & bi = d->bibinfo_;
2592 if (parent() != 0) {
2593 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2594 masterbi[key] = bin;
2599 void Buffer::makeCitationLabels() const
2601 Buffer const * const master = masterBuffer();
2602 return d->bibinfo_.makeCitationLabels(*master);
2606 void Buffer::invalidateCiteLabels() const
2608 masterBuffer()->d->cite_labels_valid_ = false;
2611 bool Buffer::citeLabelsValid() const
2613 return masterBuffer()->d->cite_labels_valid_;
2617 void Buffer::removeBiblioTempFiles() const
2619 // We remove files that contain LaTeX commands specific to the
2620 // particular bibliographic style being used, in order to avoid
2621 // LaTeX errors when we switch style.
2622 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2623 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2624 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2625 aux_file.removeFile();
2626 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2627 bbl_file.removeFile();
2628 // Also for the parent buffer
2629 Buffer const * const pbuf = parent();
2631 pbuf->removeBiblioTempFiles();
2635 bool Buffer::isDepClean(string const & name) const
2637 DepClean::const_iterator const it = d->dep_clean.find(name);
2638 if (it == d->dep_clean.end())
2644 void Buffer::markDepClean(string const & name)
2646 d->dep_clean[name] = true;
2650 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2653 // FIXME? if there is an Buffer LFUN that can be dispatched even
2654 // if internal, put a switch '(cmd.action)' here.
2660 switch (cmd.action()) {
2662 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2663 flag.setOnOff(hasReadonlyFlag());
2666 // FIXME: There is need for a command-line import.
2667 //case LFUN_BUFFER_IMPORT:
2669 case LFUN_BUFFER_AUTO_SAVE:
2672 case LFUN_BUFFER_EXPORT_CUSTOM:
2673 // FIXME: Nothing to check here?
2676 case LFUN_BUFFER_EXPORT: {
2677 docstring const arg = cmd.argument();
2678 if (arg == "custom") {
2682 string format = (arg.empty() || arg == "default") ?
2683 params().getDefaultOutputFormat() : to_utf8(arg);
2684 size_t pos = format.find(' ');
2685 if (pos != string::npos)
2686 format = format.substr(0, pos);
2687 enable = params().isExportable(format, false);
2689 flag.message(bformat(
2690 _("Don't know how to export to format: %1$s"), arg));
2694 case LFUN_BUILD_PROGRAM:
2695 enable = params().isExportable("program", false);
2698 case LFUN_BRANCH_ACTIVATE:
2699 case LFUN_BRANCH_DEACTIVATE:
2700 case LFUN_BRANCH_MASTER_ACTIVATE:
2701 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2702 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2703 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2704 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2705 : params().branchlist();
2706 docstring const branchName = cmd.argument();
2707 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2711 case LFUN_BRANCH_ADD:
2712 case LFUN_BRANCHES_RENAME:
2713 // if no Buffer is present, then of course we won't be called!
2716 case LFUN_BUFFER_LANGUAGE:
2717 enable = !isReadonly();
2720 case LFUN_BUFFER_VIEW_CACHE:
2721 (d->preview_file_).refresh();
2722 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2725 case LFUN_CHANGES_TRACK:
2726 flag.setEnabled(true);
2727 flag.setOnOff(params().track_changes);
2730 case LFUN_CHANGES_OUTPUT:
2731 flag.setEnabled(true);
2732 flag.setOnOff(params().output_changes);
2735 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2736 flag.setOnOff(params().compressed);
2739 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2740 flag.setOnOff(params().output_sync);
2743 case LFUN_BUFFER_ANONYMIZE:
2749 flag.setEnabled(enable);
2754 void Buffer::dispatch(string const & command, DispatchResult & result)
2756 return dispatch(lyxaction.lookupFunc(command), result);
2760 // NOTE We can end up here even if we have no GUI, because we are called
2761 // by LyX::exec to handled command-line requests. So we may need to check
2762 // whether we have a GUI or not. The boolean use_gui holds this information.
2763 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2766 // FIXME? if there is an Buffer LFUN that can be dispatched even
2767 // if internal, put a switch '(cmd.action())' here.
2768 dr.dispatched(false);
2771 string const argument = to_utf8(func.argument());
2772 // We'll set this back to false if need be.
2773 bool dispatched = true;
2774 // This handles undo groups automagically
2775 UndoGroupHelper ugh(this);
2777 switch (func.action()) {
2778 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2779 if (lyxvc().inUse()) {
2780 string log = lyxvc().toggleReadOnly();
2785 setReadonly(!hasReadonlyFlag());
2788 case LFUN_BUFFER_EXPORT: {
2789 string const format = (argument.empty() || argument == "default") ?
2790 params().getDefaultOutputFormat() : argument;
2791 ExportStatus const status = doExport(format, false);
2792 dr.setError(status != ExportSuccess);
2793 if (status != ExportSuccess)
2794 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2795 from_utf8(format)));
2799 case LFUN_BUILD_PROGRAM: {
2800 ExportStatus const status = doExport("program", true);
2801 dr.setError(status != ExportSuccess);
2802 if (status != ExportSuccess)
2803 dr.setMessage(_("Error generating literate programming code."));
2807 case LFUN_BUFFER_EXPORT_CUSTOM: {
2809 string command = split(argument, format_name, ' ');
2810 Format const * format = theFormats().getFormat(format_name);
2812 lyxerr << "Format \"" << format_name
2813 << "\" not recognized!"
2818 // The name of the file created by the conversion process
2821 // Output to filename
2822 if (format->name() == "lyx") {
2823 string const latexname = latexName(false);
2824 filename = changeExtension(latexname,
2825 format->extension());
2826 filename = addName(temppath(), filename);
2828 if (!writeFile(FileName(filename)))
2832 doExport(format_name, true, filename);
2835 // Substitute $$FName for filename
2836 if (!contains(command, "$$FName"))
2837 command = "( " + command + " ) < $$FName";
2838 command = subst(command, "$$FName", filename);
2840 // Execute the command in the background
2842 call.startscript(Systemcall::DontWait, command,
2843 filePath(), layoutPos());
2847 // FIXME: There is need for a command-line import.
2849 case LFUN_BUFFER_IMPORT:
2854 case LFUN_BUFFER_AUTO_SAVE:
2856 resetAutosaveTimers();
2859 case LFUN_BRANCH_ACTIVATE:
2860 case LFUN_BRANCH_DEACTIVATE:
2861 case LFUN_BRANCH_MASTER_ACTIVATE:
2862 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2863 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2864 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2865 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2868 docstring const branch_name = func.argument();
2869 // the case without a branch name is handled elsewhere
2870 if (branch_name.empty()) {
2874 Branch * branch = buf->params().branchlist().find(branch_name);
2876 LYXERR0("Branch " << branch_name << " does not exist.");
2878 docstring const msg =
2879 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2883 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2884 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2885 if (branch->isSelected() != activate) {
2886 buf->undo().recordUndoBufferParams(CursorData());
2887 branch->setSelected(activate);
2889 dr.screenUpdate(Update::Force);
2890 dr.forceBufferUpdate();
2895 case LFUN_BRANCH_ADD: {
2896 docstring branchnames = func.argument();
2897 if (branchnames.empty()) {
2901 BranchList & branch_list = params().branchlist();
2902 vector<docstring> const branches =
2903 getVectorFromString(branchnames, branch_list.separator());
2905 for (docstring const & branch_name : branches) {
2906 Branch * branch = branch_list.find(branch_name);
2908 LYXERR0("Branch " << branch_name << " already exists.");
2912 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2914 undo().recordUndoBufferParams(CursorData());
2915 branch_list.add(branch_name);
2916 branch = branch_list.find(branch_name);
2917 string const x11hexname = X11hexname(branch->color());
2918 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2919 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2921 dr.screenUpdate(Update::Force);
2929 case LFUN_BRANCHES_RENAME: {
2930 if (func.argument().empty())
2933 docstring const oldname = from_utf8(func.getArg(0));
2934 docstring const newname = from_utf8(func.getArg(1));
2935 InsetIterator it = inset_iterator_begin(inset());
2936 InsetIterator const end = inset_iterator_end(inset());
2937 bool success = false;
2938 for (; it != end; ++it) {
2939 if (it->lyxCode() == BRANCH_CODE) {
2940 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2941 if (ins.branch() == oldname) {
2942 undo().recordUndo(CursorData(it));
2943 ins.rename(newname);
2948 if (it->lyxCode() == INCLUDE_CODE) {
2949 // get buffer of external file
2950 InsetInclude const & ins =
2951 static_cast<InsetInclude const &>(*it);
2952 Buffer * child = ins.getChildBuffer();
2955 child->dispatch(func, dr);
2960 dr.screenUpdate(Update::Force);
2961 dr.forceBufferUpdate();
2966 case LFUN_BUFFER_VIEW_CACHE:
2967 if (!theFormats().view(*this, d->preview_file_,
2968 d->preview_format_))
2969 dr.setMessage(_("Error viewing the output file."));
2972 case LFUN_CHANGES_TRACK:
2973 if (params().save_transient_properties)
2974 undo().recordUndoBufferParams(CursorData());
2975 params().track_changes = !params().track_changes;
2976 if (!params().track_changes)
2977 dr.forceChangesUpdate();
2980 case LFUN_CHANGES_OUTPUT:
2981 if (params().save_transient_properties)
2982 undo().recordUndoBufferParams(CursorData());
2983 params().output_changes = !params().output_changes;
2984 if (params().output_changes) {
2985 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2986 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2987 LaTeXFeatures::isAvailable("xcolor");
2989 if (!dvipost && !xcolorulem) {
2990 Alert::warning(_("Changes not shown in LaTeX output"),
2991 _("Changes will not be highlighted in LaTeX output, "
2992 "because neither dvipost nor xcolor/ulem are installed.\n"
2993 "Please install these packages or redefine "
2994 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2995 } else if (!xcolorulem) {
2996 Alert::warning(_("Changes not shown in LaTeX output"),
2997 _("Changes will not be highlighted in LaTeX output "
2998 "when using pdflatex, because xcolor and ulem are not installed.\n"
2999 "Please install both packages or redefine "
3000 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3005 case LFUN_BUFFER_TOGGLE_COMPRESSION:
3006 // turn compression on/off
3007 undo().recordUndoBufferParams(CursorData());
3008 params().compressed = !params().compressed;
3011 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3012 undo().recordUndoBufferParams(CursorData());
3013 params().output_sync = !params().output_sync;
3016 case LFUN_BUFFER_ANONYMIZE: {
3017 undo().recordUndoFullBuffer(CursorData());
3018 CursorData cur(doc_iterator_begin(this));
3019 for ( ; cur ; cur.forwardPar())
3020 cur.paragraph().anonymize();
3021 dr.forceBufferUpdate();
3022 dr.screenUpdate(Update::Force);
3030 dr.dispatched(dispatched);
3034 void Buffer::changeLanguage(Language const * from, Language const * to)
3036 LASSERT(from, return);
3037 LASSERT(to, return);
3039 for_each(par_iterator_begin(),
3041 bind(&Paragraph::changeLanguage, _1, params(), from, to));
3045 bool Buffer::isMultiLingual() const
3047 ParConstIterator end = par_iterator_end();
3048 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3049 if (it->isMultiLingual(params()))
3056 std::set<Language const *> Buffer::getLanguages() const
3058 std::set<Language const *> langs;
3059 getLanguages(langs);
3064 void Buffer::getLanguages(std::set<Language const *> & langs) const
3066 ParConstIterator end = par_iterator_end();
3067 // add the buffer language, even if it's not actively used
3068 langs.insert(language());
3069 // iterate over the paragraphs
3070 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3071 it->getLanguages(langs);
3073 ListOfBuffers clist = getDescendents();
3074 for (auto const & cit : clist)
3075 cit->getLanguages(langs);
3079 DocIterator Buffer::getParFromID(int const id) const
3081 Buffer * buf = const_cast<Buffer *>(this);
3083 // This means non-existent
3084 return doc_iterator_end(buf);
3086 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3087 if (it.paragraph().id() == id)
3090 return doc_iterator_end(buf);
3094 bool Buffer::hasParWithID(int const id) const
3096 return !getParFromID(id).atEnd();
3100 ParIterator Buffer::par_iterator_begin()
3102 return ParIterator(doc_iterator_begin(this));
3106 ParIterator Buffer::par_iterator_end()
3108 return ParIterator(doc_iterator_end(this));
3112 ParConstIterator Buffer::par_iterator_begin() const
3114 return ParConstIterator(doc_iterator_begin(this));
3118 ParConstIterator Buffer::par_iterator_end() const
3120 return ParConstIterator(doc_iterator_end(this));
3124 Language const * Buffer::language() const
3126 return params().language;
3130 docstring const Buffer::B_(string const & l10n) const
3132 return params().B_(l10n);
3136 bool Buffer::isClean() const
3138 return d->lyx_clean;
3142 bool Buffer::isChecksumModified() const
3144 LASSERT(d->filename.exists(), return false);
3145 return d->checksum_ != d->filename.checksum();
3149 void Buffer::saveCheckSum() const
3151 FileName const & file = d->filename;
3153 d->checksum_ = file.exists() ? file.checksum()
3154 : 0; // in the case of save to a new file.
3158 void Buffer::markClean() const
3160 if (!d->lyx_clean) {
3161 d->lyx_clean = true;
3164 // if the .lyx file has been saved, we don't need an
3166 d->bak_clean = true;
3167 d->undo_.markDirty();
3168 clearExternalModification();
3172 void Buffer::setUnnamed(bool flag)
3178 bool Buffer::isUnnamed() const
3185 /// Don't check unnamed, here: isInternal() is used in
3186 /// newBuffer(), where the unnamed flag has not been set by anyone
3187 /// yet. Also, for an internal buffer, there should be no need for
3188 /// retrieving fileName() nor for checking if it is unnamed or not.
3189 bool Buffer::isInternal() const
3191 return d->internal_buffer;
3195 void Buffer::setInternal(bool flag)
3197 d->internal_buffer = flag;
3201 void Buffer::markDirty()
3204 d->lyx_clean = false;
3207 d->bak_clean = false;
3209 for (auto & depit : d->dep_clean)
3210 depit.second = false;
3214 FileName Buffer::fileName() const
3220 string Buffer::absFileName() const
3222 return d->filename.absFileName();
3226 string Buffer::filePath() const
3228 string const abs = d->filename.onlyPath().absFileName();
3231 int last = abs.length() - 1;
3233 return abs[last] == '/' ? abs : abs + '/';
3237 DocFileName Buffer::getReferencedFileName(string const & fn) const
3240 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3241 result.set(fn, filePath());
3243 // filePath() ends with a path separator
3244 FileName const test(filePath() + fn);
3246 result.set(fn, filePath());
3248 result.set(fn, params().origin);
3255 string const Buffer::prepareFileNameForLaTeX(string const & name,
3256 string const & ext, bool nice) const
3258 string const fname = makeAbsPath(name, filePath()).absFileName();
3259 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3265 return to_utf8(makeRelPath(from_utf8(fname),
3266 from_utf8(masterBuffer()->filePath())));
3270 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3271 docstring_list const & bibfilelist,
3272 bool const add_extension) const
3274 // If we are processing the LaTeX file in a temp directory then
3275 // copy the .bib databases to this temp directory, mangling their
3276 // names in the process. Store this mangled name in the list of
3278 // (We need to do all this because BibTeX *really*, *really*
3279 // can't handle "files with spaces" and Windows users tend to
3280 // use such filenames.)
3281 // Otherwise, store the (maybe absolute) path to the original,
3282 // unmangled database name.
3284 vector<docstring> res;
3286 // determine the export format
3287 string const tex_format = flavor2format(runparams.flavor);
3289 // check for spaces in paths
3290 bool found_space = false;
3292 for (auto const & bit : bibfilelist) {
3293 string utf8input = to_utf8(bit);
3295 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3296 FileName try_in_file =
3297 makeAbsPath(database + ".bib", filePath());
3298 bool not_from_texmf = try_in_file.isReadableFile();
3299 // If the file has not been found, try with the real file name
3300 // (it might come from a child in a sub-directory)
3301 if (!not_from_texmf) {
3302 try_in_file = getBibfilePath(bit);
3303 if (try_in_file.isReadableFile()) {
3304 // Check if the file is in texmf
3305 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3306 not_from_texmf = kpsefile.empty()
3307 || kpsefile.absFileName() != try_in_file.absFileName();
3309 // If this exists, make path relative to the master
3312 removeExtension(prepareFileNameForLaTeX(
3313 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3314 from_utf8(filePath()))),
3315 ".bib", runparams.nice));
3319 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3321 // mangledFileName() needs the extension
3322 DocFileName const in_file = DocFileName(try_in_file);
3323 database = removeExtension(in_file.mangledFileName());
3324 FileName const out_file = makeAbsPath(database + ".bib",
3325 masterBuffer()->temppath());
3326 bool const success = in_file.copyTo(out_file);
3328 LYXERR0("Failed to copy '" << in_file
3329 << "' to '" << out_file << "'");
3331 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3332 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3333 if (!isValidLaTeXFileName(database)) {
3334 frontend::Alert::warning(_("Invalid filename"),
3335 _("The following filename will cause troubles "
3336 "when running the exported file through LaTeX: ") +
3337 from_utf8(database));
3339 if (!isValidDVIFileName(database)) {
3340 frontend::Alert::warning(_("Problematic filename for DVI"),
3341 _("The following filename can cause troubles "
3342 "when running the exported file through LaTeX "
3343 "and opening the resulting DVI: ") +
3344 from_utf8(database), true);
3352 docstring const path = from_utf8(latex_path(database));
3354 if (contains(path, ' '))
3357 if (find(res.begin(), res.end(), path) == res.end())
3358 res.push_back(path);
3361 // Check if there are spaces in the path and warn BibTeX users, if so.
3362 // (biber can cope with such paths)
3363 if (!prefixIs(runparams.bibtex_command, "biber")) {
3364 // Post this warning only once.
3365 static bool warned_about_spaces = false;
3366 if (!warned_about_spaces &&
3367 runparams.nice && found_space) {
3368 warned_about_spaces = true;
3369 Alert::warning(_("Export Warning!"),
3370 _("There are spaces in the paths to your BibTeX databases.\n"
3371 "BibTeX will be unable to find them."));
3380 string Buffer::layoutPos() const
3382 return d->layout_position;
3386 void Buffer::setLayoutPos(string const & path)
3389 d->layout_position.clear();
3393 LATTEST(FileName::isAbsolute(path));
3395 d->layout_position =
3396 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3398 if (d->layout_position.empty())
3399 d->layout_position = ".";
3403 bool Buffer::hasReadonlyFlag() const
3405 return d->read_only;
3409 bool Buffer::isReadonly() const
3411 return hasReadonlyFlag() || notifiesExternalModification();
3415 void Buffer::setParent(Buffer const * buffer)
3417 // Avoids recursive include.
3418 d->setParent(buffer == this ? 0 : buffer);
3423 Buffer const * Buffer::parent() const
3429 ListOfBuffers Buffer::allRelatives() const
3431 ListOfBuffers lb = masterBuffer()->getDescendents();
3432 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3437 Buffer const * Buffer::masterBuffer() const
3439 // FIXME Should be make sure we are not in some kind
3440 // of recursive include? A -> B -> A will crash this.
3441 Buffer const * const pbuf = d->parent();
3445 return pbuf->masterBuffer();
3449 bool Buffer::isChild(Buffer * child) const
3451 return d->children_positions.find(child) != d->children_positions.end();
3455 DocIterator Buffer::firstChildPosition(Buffer const * child)
3457 Impl::BufferPositionMap::iterator it;
3458 it = d->children_positions.find(child);
3459 if (it == d->children_positions.end())
3460 return DocIterator(this);
3465 bool Buffer::hasChildren() const
3467 return !d->children_positions.empty();
3471 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3473 // loop over children
3474 for (auto const & p : d->children_positions) {
3475 Buffer * child = const_cast<Buffer *>(p.first);
3477 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3478 if (bit != clist.end())
3480 clist.push_back(child);
3482 // there might be grandchildren
3483 child->collectChildren(clist, true);
3488 ListOfBuffers Buffer::getChildren() const
3491 collectChildren(v, false);
3492 // Make sure we have not included ourselves.
3493 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3494 if (bit != v.end()) {
3495 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3502 ListOfBuffers Buffer::getDescendents() const
3505 collectChildren(v, true);
3506 // Make sure we have not included ourselves.
3507 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3508 if (bit != v.end()) {
3509 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3516 template<typename M>
3517 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3522 typename M::const_iterator it = m.lower_bound(x);
3523 if (it == m.begin())
3531 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3532 DocIterator const & pos) const
3534 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3536 // if paragraphs have no macro context set, pos will be empty
3540 // we haven't found anything yet
3541 DocIterator bestPos = owner_->par_iterator_begin();
3542 MacroData const * bestData = 0;
3544 // find macro definitions for name
3545 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3546 if (nameIt != macros.end()) {
3547 // find last definition in front of pos or at pos itself
3548 PositionScopeMacroMap::const_iterator it
3549 = greatest_below(nameIt->second, pos);
3550 if (it != nameIt->second.end()) {
3552 // scope ends behind pos?
3553 if (pos < it->second.scope) {
3554 // Looks good, remember this. If there
3555 // is no external macro behind this,
3556 // we found the right one already.
3557 bestPos = it->first;
3558 bestData = &it->second.macro;
3562 // try previous macro if there is one
3563 if (it == nameIt->second.begin())
3570 // find macros in included files
3571 PositionScopeBufferMap::const_iterator it
3572 = greatest_below(position_to_children, pos);
3573 if (it == position_to_children.end())
3574 // no children before
3578 // do we know something better (i.e. later) already?
3579 if (it->first < bestPos )
3582 // scope ends behind pos?
3583 if (pos < it->second.scope
3584 && (cloned_buffer_ ||
3585 theBufferList().isLoaded(it->second.buffer))) {
3586 // look for macro in external file
3588 MacroData const * data
3589 = it->second.buffer->getMacro(name, false);
3592 bestPos = it->first;
3598 // try previous file if there is one
3599 if (it == position_to_children.begin())
3604 // return the best macro we have found
3609 MacroData const * Buffer::getMacro(docstring const & name,
3610 DocIterator const & pos, bool global) const
3615 // query buffer macros
3616 MacroData const * data = d->getBufferMacro(name, pos);
3620 // If there is a master buffer, query that
3621 Buffer const * const pbuf = d->parent();
3623 d->macro_lock = true;
3624 MacroData const * macro = pbuf->getMacro(
3625 name, *this, false);
3626 d->macro_lock = false;
3632 data = MacroTable::globalMacros().get(name);
3641 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3643 // set scope end behind the last paragraph
3644 DocIterator scope = par_iterator_begin();
3645 scope.pit() = scope.lastpit() + 1;
3647 return getMacro(name, scope, global);
3651 MacroData const * Buffer::getMacro(docstring const & name,
3652 Buffer const & child, bool global) const
3654 // look where the child buffer is included first
3655 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3656 if (it == d->children_positions.end())
3659 // check for macros at the inclusion position
3660 return getMacro(name, it->second, global);
3664 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3666 pit_type const lastpit = it.lastpit();
3668 // look for macros in each paragraph
3669 while (it.pit() <= lastpit) {
3670 Paragraph & par = it.paragraph();
3672 // FIXME Can this be done with the new-style iterators?
3673 // iterate over the insets of the current paragraph
3674 for (auto const & insit : par.insetList()) {
3675 it.pos() = insit.pos;
3677 // is it a nested text inset?
3678 if (insit.inset->asInsetText()) {
3679 // Inset needs its own scope?
3680 InsetText const * itext = insit.inset->asInsetText();
3681 bool newScope = itext->isMacroScope();
3683 // scope which ends just behind the inset
3684 DocIterator insetScope = it;
3687 // collect macros in inset
3688 it.push_back(CursorSlice(*insit.inset));
3689 updateMacros(it, newScope ? insetScope : scope);
3694 if (insit.inset->asInsetTabular()) {
3695 CursorSlice slice(*insit.inset);
3696 size_t const numcells = slice.nargs();
3697 for (; slice.idx() < numcells; slice.forwardIdx()) {
3698 it.push_back(slice);
3699 updateMacros(it, scope);
3705 // is it an external file?
3706 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3707 // get buffer of external file
3708 InsetInclude const & incinset =
3709 static_cast<InsetInclude const &>(*insit.inset);
3711 Buffer * child = incinset.getChildBuffer();
3716 // register its position, but only when it is
3717 // included first in the buffer
3718 if (children_positions.find(child) ==
3719 children_positions.end())
3720 children_positions[child] = it;
3722 // register child with its scope
3723 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3727 InsetMath * im = insit.inset->asInsetMath();
3728 if (doing_export && im) {
3729 InsetMathHull * hull = im->asHullInset();
3731 hull->recordLocation(it);
3734 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3738 InsetMathMacroTemplate & macroTemplate =
3739 *insit.inset->asInsetMath()->asMacroTemplate();
3740 MacroContext mc(owner_, it);
3741 macroTemplate.updateToContext(mc);
3744 bool valid = macroTemplate.validMacro();
3745 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3746 // then the BufferView's cursor will be invalid in
3747 // some cases which leads to crashes.
3752 // FIXME (Abdel), I don't understand why we pass 'it' here
3753 // instead of 'macroTemplate' defined above... is this correct?
3754 macros[macroTemplate.name()][it] =
3755 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3765 void Buffer::updateMacros() const
3770 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3772 // start with empty table
3774 d->children_positions.clear();
3775 d->position_to_children.clear();
3777 // Iterate over buffer, starting with first paragraph
3778 // The scope must be bigger than any lookup DocIterator
3779 // later. For the global lookup, lastpit+1 is used, hence
3780 // we use lastpit+2 here.
3781 DocIterator it = par_iterator_begin();
3782 DocIterator outerScope = it;
3783 outerScope.pit() = outerScope.lastpit() + 2;
3784 d->updateMacros(it, outerScope);
3788 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3790 InsetIterator it = inset_iterator_begin(inset());
3791 InsetIterator const end = inset_iterator_end(inset());
3792 for (; it != end; ++it) {
3793 if (it->lyxCode() == BRANCH_CODE) {
3794 InsetBranch & br = static_cast<InsetBranch &>(*it);
3795 docstring const name = br.branch();
3796 if (!from_master && !params().branchlist().find(name))
3797 result.push_back(name);
3798 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3799 result.push_back(name);
3802 if (it->lyxCode() == INCLUDE_CODE) {
3803 // get buffer of external file
3804 InsetInclude const & ins =
3805 static_cast<InsetInclude const &>(*it);
3806 Buffer * child = ins.getChildBuffer();
3809 child->getUsedBranches(result, true);
3812 // remove duplicates
3817 void Buffer::updateMacroInstances(UpdateType utype) const
3819 LYXERR(Debug::MACROS, "updateMacroInstances for "
3820 << d->filename.onlyFileName());
3821 DocIterator it = doc_iterator_begin(this);
3823 DocIterator const end = doc_iterator_end(this);
3824 for (; it != end; it.forwardInset()) {
3825 // look for MathData cells in InsetMathNest insets
3826 InsetMath * minset = it.nextInset()->asInsetMath();
3830 // update macro in all cells of the InsetMathNest
3831 DocIterator::idx_type n = minset->nargs();
3832 MacroContext mc = MacroContext(this, it);
3833 for (DocIterator::idx_type i = 0; i < n; ++i) {
3834 MathData & data = minset->cell(i);
3835 data.updateMacros(0, mc, utype, 0);
3841 void Buffer::listMacroNames(MacroNameSet & macros) const
3846 d->macro_lock = true;
3848 // loop over macro names
3849 for (auto const & nameit : d->macros)
3850 macros.insert(nameit.first);
3852 // loop over children
3853 for (auto const & p : d->children_positions) {
3854 Buffer * child = const_cast<Buffer *>(p.first);
3855 // The buffer might have been closed (see #10766).
3856 if (theBufferList().isLoaded(child))
3857 child->listMacroNames(macros);
3861 Buffer const * const pbuf = d->parent();
3863 pbuf->listMacroNames(macros);
3865 d->macro_lock = false;
3869 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3871 Buffer const * const pbuf = d->parent();
3876 pbuf->listMacroNames(names);
3879 for (auto const & mit : names) {
3881 MacroData const * data = pbuf->getMacro(mit, *this, false);
3883 macros.insert(data);
3885 // we cannot access the original InsetMathMacroTemplate anymore
3886 // here to calls validate method. So we do its work here manually.
3887 // FIXME: somehow make the template accessible here.
3888 if (data->optionals() > 0)
3889 features.require("xargs");
3895 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3898 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3900 // In what follows, we look whether we find an active label
3901 // with the given string in the cache. If so, return its
3902 // references cache. If we only find an inactive one, return
3903 // that (the last we find, coincidentally). If we find noting,
3904 // return an empty references cache.
3905 static LabelInfo linfo;
3906 linfo.inset = nullptr;
3907 linfo.references = References();
3908 linfo.active = false;
3909 bool have_inactive = false;
3910 for (auto & rc : d->ref_cache_) {
3911 if (rc.label == label) {
3913 return rc.references;
3916 have_inactive = true;
3922 // We found nothing, so insert the empty one to the cache
3923 // for further processing
3924 d->ref_cache_.push_back(linfo);
3926 return linfo.references;
3930 Buffer::References const & Buffer::references(docstring const & label) const
3932 return const_cast<Buffer *>(this)->getReferenceCache(label);
3936 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3938 References & refs = getReferenceCache(label);
3939 refs.push_back(make_pair(inset, it));
3943 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3946 static LabelInfo linfo;
3947 linfo.label = label;
3949 linfo.references = References();
3950 linfo.active = active;
3951 masterBuffer()->d->ref_cache_.push_back(linfo);
3955 InsetLabel const * Buffer::insetLabel(docstring const & label,
3956 bool const active) const
3958 for (auto & rc : masterBuffer()->d->ref_cache_) {
3959 if (rc.label == label && (rc.active || !active))
3966 bool Buffer::activeLabel(docstring const & label) const
3968 if (!insetLabel(label))
3971 for (auto & rc : masterBuffer()->d->ref_cache_) {
3972 if (rc.label == label && rc.active)
3979 void Buffer::clearReferenceCache() const
3982 d->ref_cache_.clear();
3986 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3988 //FIXME: This does not work for child documents yet.
3989 reloadBibInfoCache();
3991 // Check if the label 'from' appears more than once
3992 vector<docstring> labels;
3993 for (auto const & bibit : masterBibInfo())
3994 labels.push_back(bibit.first);
3996 if (count(labels.begin(), labels.end(), from) > 1)
3999 string const paramName = "key";
4000 InsetIterator it = inset_iterator_begin(inset());
4002 if (it->lyxCode() != CITE_CODE)
4004 InsetCommand * inset = it->asInsetCommand();
4005 docstring const oldValue = inset->getParam(paramName);
4006 if (oldValue == from)
4007 inset->setParam(paramName, to);
4011 // returns NULL if id-to-row conversion is unsupported
4012 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4013 pit_type par_begin, pit_type par_end,
4014 OutputWhat output, bool master) const
4016 unique_ptr<TexRow> texrow;
4017 OutputParams runparams(¶ms().encoding());
4018 runparams.nice = true;
4019 runparams.flavor = params().getOutputFlavor(format);
4020 runparams.linelen = lyxrc.plaintext_linelen;
4021 // No side effect of file copying and image conversion
4022 runparams.dryrun = true;
4024 // Some macros rely on font encoding
4025 runparams.main_fontenc = params().main_font_encoding();
4027 if (output == CurrentParagraph) {
4028 runparams.par_begin = par_begin;
4029 runparams.par_end = par_end;
4030 if (par_begin + 1 == par_end) {
4032 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4036 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4037 convert<docstring>(par_begin),
4038 convert<docstring>(par_end - 1))
4041 // output paragraphs
4042 if (runparams.flavor == OutputParams::LYX) {
4043 Paragraph const & par = text().paragraphs()[par_begin];
4045 depth_type dt = par.getDepth();
4046 par.write(ods, params(), dt);
4047 os << from_utf8(ods.str());
4048 } else if (runparams.flavor == OutputParams::HTML) {
4050 setMathFlavor(runparams);
4051 xhtmlParagraphs(text(), *this, xs, runparams);
4052 } else if (runparams.flavor == OutputParams::TEXT) {
4054 // FIXME Handles only one paragraph, unlike the others.
4055 // Probably should have some routine with a signature like them.
4056 writePlaintextParagraph(*this,
4057 text().paragraphs()[par_begin], os, runparams, dummy);
4058 } else if (params().isDocBook()) {
4059 docbookParagraphs(text(), *this, os, runparams);
4061 // If we are previewing a paragraph, even if this is the
4062 // child of some other buffer, let's cut the link here,
4063 // so that no concurring settings from the master
4064 // (e.g. branch state) interfere (see #8101).
4066 d->ignore_parent = true;
4067 // We need to validate the Buffer params' features here
4068 // in order to know if we should output polyglossia
4069 // macros (instead of babel macros)
4070 LaTeXFeatures features(*this, params(), runparams);
4072 runparams.use_polyglossia = features.usePolyglossia();
4073 // latex or literate
4076 ots.texrow().newlines(2);
4078 latexParagraphs(*this, text(), ots, runparams);
4079 texrow = ots.releaseTexRow();
4081 // Restore the parenthood
4083 d->ignore_parent = false;
4087 if (output == FullSource)
4088 os << _("Preview source code");
4089 else if (output == OnlyPreamble)
4090 os << _("Preview preamble");
4091 else if (output == OnlyBody)
4092 os << _("Preview body");
4094 if (runparams.flavor == OutputParams::LYX) {
4096 if (output == FullSource)
4098 else if (output == OnlyPreamble)
4099 params().writeFile(ods, this);
4100 else if (output == OnlyBody)
4102 os << from_utf8(ods.str());
4103 } else if (runparams.flavor == OutputParams::HTML) {
4104 writeLyXHTMLSource(os, runparams, output);
4105 } else if (runparams.flavor == OutputParams::TEXT) {
4106 if (output == OnlyPreamble) {
4107 os << "% "<< _("Plain text does not have a preamble.");
4109 writePlaintextFile(*this, os, runparams);
4110 } else if (params().isDocBook()) {
4111 writeDocBookSource(os, absFileName(), runparams, output);
4113 // latex or literate
4116 ots.texrow().newlines(2);
4118 runparams.is_child = true;
4120 writeLaTeXSource(ots, string(), runparams, output);
4121 texrow = ots.releaseTexRow();
4128 ErrorList & Buffer::errorList(string const & type) const
4130 return d->errorLists[type];
4134 void Buffer::updateTocItem(std::string const & type,
4135 DocIterator const & dit) const
4138 d->gui_->updateTocItem(type, dit);
4142 void Buffer::structureChanged() const
4145 d->gui_->structureChanged();
4149 void Buffer::errors(string const & err, bool from_master) const
4152 d->gui_->errors(err, from_master);
4156 void Buffer::message(docstring const & msg) const
4159 d->gui_->message(msg);
4163 void Buffer::setBusy(bool on) const
4166 d->gui_->setBusy(on);
4170 void Buffer::updateTitles() const
4173 d->wa_->updateTitles();
4177 void Buffer::resetAutosaveTimers() const
4180 d->gui_->resetAutosaveTimers();
4184 bool Buffer::hasGuiDelegate() const
4190 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4199 class AutoSaveBuffer : public ForkedProcess {
4202 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4203 : buffer_(buffer), fname_(fname) {}
4205 virtual shared_ptr<ForkedProcess> clone() const
4207 return make_shared<AutoSaveBuffer>(*this);
4212 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4213 from_utf8(fname_.absFileName())));
4214 return run(DontWait);
4218 virtual int generateChild();
4220 Buffer const & buffer_;
4225 int AutoSaveBuffer::generateChild()
4227 #if defined(__APPLE__)
4228 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4229 * We should use something else like threads.
4231 * Since I do not know how to determine at run time what is the OS X
4232 * version, I just disable forking altogether for now (JMarc)
4234 pid_t const pid = -1;
4236 // tmp_ret will be located (usually) in /tmp
4237 // will that be a problem?
4238 // Note that this calls ForkedCalls::fork(), so it's
4239 // ok cross-platform.
4240 pid_t const pid = fork();
4241 // If you want to debug the autosave
4242 // you should set pid to -1, and comment out the fork.
4243 if (pid != 0 && pid != -1)
4247 // pid = -1 signifies that lyx was unable
4248 // to fork. But we will do the save
4250 bool failed = false;
4251 TempFile tempfile("lyxautoXXXXXX.lyx");
4252 tempfile.setAutoRemove(false);
4253 FileName const tmp_ret = tempfile.name();
4254 if (!tmp_ret.empty()) {
4255 if (!buffer_.writeFile(tmp_ret))
4257 else if (!tmp_ret.moveTo(fname_))
4263 // failed to write/rename tmp_ret so try writing direct
4264 if (!buffer_.writeFile(fname_)) {
4265 // It is dangerous to do this in the child,
4266 // but safe in the parent, so...
4267 if (pid == -1) // emit message signal.
4268 buffer_.message(_("Autosave failed!"));
4272 if (pid == 0) // we are the child so...
4281 FileName Buffer::getEmergencyFileName() const
4283 return FileName(d->filename.absFileName() + ".emergency");
4287 FileName Buffer::getAutosaveFileName() const
4289 // if the document is unnamed try to save in the backup dir, else
4290 // in the default document path, and as a last try in the filePath,
4291 // which will most often be the temporary directory
4294 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4295 : lyxrc.backupdir_path;
4296 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4299 string const fname = "#" + d->filename.onlyFileName() + "#";
4301 return makeAbsPath(fname, fpath);
4305 void Buffer::removeAutosaveFile() const
4307 FileName const f = getAutosaveFileName();
4313 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4315 FileName const newauto = getAutosaveFileName();
4317 if (newauto != oldauto && oldauto.exists())
4318 if (!oldauto.moveTo(newauto))
4319 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4323 bool Buffer::autoSave() const
4325 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4326 if (buf->d->bak_clean || hasReadonlyFlag())
4329 message(_("Autosaving current document..."));
4330 buf->d->bak_clean = true;
4332 FileName const fname = getAutosaveFileName();
4333 LASSERT(d->cloned_buffer_, return false);
4335 // If this buffer is cloned, we assume that
4336 // we are running in a separate thread already.
4337 TempFile tempfile("lyxautoXXXXXX.lyx");
4338 tempfile.setAutoRemove(false);
4339 FileName const tmp_ret = tempfile.name();
4340 if (!tmp_ret.empty()) {
4342 // assume successful write of tmp_ret
4343 if (tmp_ret.moveTo(fname))
4346 // failed to write/rename tmp_ret so try writing direct
4347 return writeFile(fname);
4351 void Buffer::setExportStatus(bool e) const
4353 d->doing_export = e;
4354 ListOfBuffers clist = getDescendents();
4355 for (auto const & bit : clist)
4356 bit->d->doing_export = e;
4360 bool Buffer::isExporting() const
4362 return d->doing_export;
4366 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4370 return doExport(target, put_in_tempdir, result_file);
4373 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4374 string & result_file) const
4376 bool const update_unincluded =
4377 params().maintain_unincluded_children
4378 && !params().getIncludedChildren().empty();
4380 // (1) export with all included children (omit \includeonly)
4381 if (update_unincluded) {
4382 ExportStatus const status =
4383 doExport(target, put_in_tempdir, true, result_file);
4384 if (status != ExportSuccess)
4387 // (2) export with included children only
4388 return doExport(target, put_in_tempdir, false, result_file);
4392 void Buffer::setMathFlavor(OutputParams & op) const
4394 switch (params().html_math_output) {
4395 case BufferParams::MathML:
4396 op.math_flavor = OutputParams::MathAsMathML;
4398 case BufferParams::HTML:
4399 op.math_flavor = OutputParams::MathAsHTML;
4401 case BufferParams::Images:
4402 op.math_flavor = OutputParams::MathAsImages;
4404 case BufferParams::LaTeX:
4405 op.math_flavor = OutputParams::MathAsLaTeX;
4411 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4412 bool includeall, string & result_file) const
4414 LYXERR(Debug::FILES, "target=" << target);
4415 OutputParams runparams(¶ms().encoding());
4416 string format = target;
4417 string dest_filename;
4418 size_t pos = target.find(' ');
4419 if (pos != string::npos) {
4420 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4421 format = target.substr(0, pos);
4422 if (format == "default")
4423 format = params().getDefaultOutputFormat();
4424 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4425 FileName(dest_filename).onlyPath().createPath();
4426 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4428 MarkAsExporting exporting(this);
4429 string backend_format;
4430 runparams.flavor = OutputParams::LATEX;
4431 runparams.linelen = lyxrc.plaintext_linelen;
4432 runparams.includeall = includeall;
4433 vector<string> backs = params().backends();
4434 Converters converters = theConverters();
4435 bool need_nice_file = false;
4436 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4437 // Get shortest path to format
4438 converters.buildGraph();
4439 Graph::EdgePath path;
4440 for (string const & sit : backs) {
4441 Graph::EdgePath p = converters.getPath(sit, format);
4442 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4443 backend_format = sit;
4448 if (!put_in_tempdir) {
4449 // Only show this alert if this is an export to a non-temporary
4450 // file (not for previewing).
4451 Alert::error(_("Couldn't export file"), bformat(
4452 _("No information for exporting the format %1$s."),
4453 theFormats().prettyName(format)));
4455 return ExportNoPathToFormat;
4457 runparams.flavor = converters.getFlavor(path, this);
4458 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4459 for (auto const & edge : path)
4460 if (theConverters().get(edge).nice()) {
4461 need_nice_file = true;
4466 backend_format = format;
4467 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4468 // FIXME: Don't hardcode format names here, but use a flag
4469 if (backend_format == "pdflatex")
4470 runparams.flavor = OutputParams::PDFLATEX;
4471 else if (backend_format == "luatex")
4472 runparams.flavor = OutputParams::LUATEX;
4473 else if (backend_format == "dviluatex")
4474 runparams.flavor = OutputParams::DVILUATEX;
4475 else if (backend_format == "xetex")
4476 runparams.flavor = OutputParams::XETEX;
4479 string filename = latexName(false);
4480 filename = addName(temppath(), filename);
4481 filename = changeExtension(filename,
4482 theFormats().extension(backend_format));
4483 LYXERR(Debug::FILES, "filename=" << filename);
4485 // Plain text backend
4486 if (backend_format == "text") {
4487 runparams.flavor = OutputParams::TEXT;
4489 writePlaintextFile(*this, FileName(filename), runparams);
4491 catch (ConversionException const &) { return ExportCancel; }
4494 else if (backend_format == "xhtml") {
4495 runparams.flavor = OutputParams::HTML;
4496 setMathFlavor(runparams);
4497 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4498 return ExportKilled;
4499 } else if (backend_format == "lyx")
4500 writeFile(FileName(filename));
4502 else if (params().isDocBook()) {
4503 runparams.nice = !put_in_tempdir;
4504 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4505 return ExportKilled;
4508 else if (backend_format == format || need_nice_file) {
4509 runparams.nice = true;
4510 ExportStatus const retval =
4511 makeLaTeXFile(FileName(filename), string(), runparams);
4512 if (retval == ExportKilled)
4513 return ExportKilled;
4514 if (d->cloned_buffer_)
4515 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4516 if (retval != ExportSuccess)
4518 } else if (!lyxrc.tex_allows_spaces
4519 && contains(filePath(), ' ')) {
4520 Alert::error(_("File name error"),
4521 bformat(_("The directory path to the document\n%1$s\n"
4522 "contains spaces, but your TeX installation does "
4523 "not allow them. You should save the file to a directory "
4524 "whose name does not contain spaces."), from_ascii(filePath())));
4525 return ExportTexPathHasSpaces;
4527 runparams.nice = false;
4528 ExportStatus const retval =
4529 makeLaTeXFile(FileName(filename), filePath(), runparams);
4530 if (retval == ExportKilled)
4531 return ExportKilled;
4532 if (d->cloned_buffer_)
4533 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4534 if (retval != ExportSuccess)
4538 string const error_type = (format == "program")
4539 ? "Build" : params().bufferFormat();
4540 ErrorList & error_list = d->errorLists[error_type];
4541 string const ext = theFormats().extension(format);
4542 FileName const tmp_result_file(changeExtension(filename, ext));
4543 Converters::RetVal const retval =
4544 converters.convert(this, FileName(filename), tmp_result_file,
4545 FileName(absFileName()), backend_format, format, error_list);
4546 if (retval == Converters::KILLED)
4547 return ExportCancel;
4548 bool success = (retval == Converters::SUCCESS);
4550 // Emit the signal to show the error list or copy it back to the
4551 // cloned Buffer so that it can be emitted afterwards.
4552 if (format != backend_format) {
4553 if (runparams.silent)
4555 else if (d->cloned_buffer_)
4556 d->cloned_buffer_->d->errorLists[error_type] =
4557 d->errorLists[error_type];
4560 // also to the children, in case of master-buffer-view
4561 ListOfBuffers clist = getDescendents();
4562 for (auto const & bit : clist) {
4563 if (runparams.silent)
4564 bit->d->errorLists[error_type].clear();
4565 else if (d->cloned_buffer_) {
4566 // Enable reverse search by copying back the
4567 // texrow object to the cloned buffer.
4568 // FIXME: this is not thread safe.
4569 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4570 bit->d->cloned_buffer_->d->errorLists[error_type] =
4571 bit->d->errorLists[error_type];
4573 bit->errors(error_type, true);
4577 if (d->cloned_buffer_) {
4578 // Enable reverse dvi or pdf to work by copying back the texrow
4579 // object to the cloned buffer.
4580 // FIXME: There is a possibility of concurrent access to texrow
4581 // here from the main GUI thread that should be securized.
4582 d->cloned_buffer_->d->texrow = d->texrow;
4583 string const err_type = params().bufferFormat();
4584 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4588 if (put_in_tempdir) {
4589 result_file = tmp_result_file.absFileName();
4590 return success ? ExportSuccess : ExportConverterError;
4593 if (dest_filename.empty())
4594 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4596 result_file = dest_filename;
4597 // We need to copy referenced files (e. g. included graphics
4598 // if format == "dvi") to the result dir.
4599 vector<ExportedFile> const files =
4600 runparams.exportdata->externalFiles(format);
4601 string const dest = runparams.export_folder.empty() ?
4602 onlyPath(result_file) : runparams.export_folder;
4603 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4604 : force_overwrite == ALL_FILES;
4605 CopyStatus status = use_force ? FORCE : SUCCESS;
4607 for (ExportedFile const & exp : files) {
4608 if (status == CANCEL) {
4609 message(_("Document export cancelled."));
4610 return ExportCancel;
4612 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4613 string fixedName = exp.exportName;
4614 if (!runparams.export_folder.empty()) {
4615 // Relative pathnames starting with ../ will be sanitized
4616 // if exporting to a different folder
4617 while (fixedName.substr(0, 3) == "../")
4618 fixedName = fixedName.substr(3, fixedName.length() - 3);
4620 FileName fixedFileName = makeAbsPath(fixedName, dest);
4621 fixedFileName.onlyPath().createPath();
4622 status = copyFile(fmt, exp.sourceName,
4624 exp.exportName, status == FORCE,
4625 runparams.export_folder.empty());
4629 if (tmp_result_file.exists()) {
4630 // Finally copy the main file
4631 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4632 : force_overwrite != NO_FILES;
4633 if (status == SUCCESS && use_force)
4635 status = copyFile(format, tmp_result_file,
4636 FileName(result_file), result_file,
4638 if (status == CANCEL) {
4639 message(_("Document export cancelled."));
4640 return ExportCancel;
4642 message(bformat(_("Document exported as %1$s "
4644 theFormats().prettyName(format),
4645 makeDisplayPath(result_file)));
4648 // This must be a dummy converter like fax (bug 1888)
4649 message(bformat(_("Document exported as %1$s"),
4650 theFormats().prettyName(format)));
4653 return success ? ExportSuccess : ExportConverterError;
4657 Buffer::ExportStatus Buffer::preview(string const & format) const
4659 bool const update_unincluded =
4660 params().maintain_unincluded_children
4661 && !params().getIncludedChildren().empty();
4662 return preview(format, update_unincluded);
4666 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4668 MarkAsExporting exporting(this);
4670 // (1) export with all included children (omit \includeonly)
4672 ExportStatus const status = doExport(format, true, true, result_file);
4673 if (status != ExportSuccess)
4676 // (2) export with included children only
4677 ExportStatus const status = doExport(format, true, false, result_file);
4678 FileName const previewFile(result_file);
4680 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4681 theimpl->preview_file_ = previewFile;
4682 theimpl->preview_format_ = format;
4683 theimpl->preview_error_ = (status != ExportSuccess);
4685 if (status != ExportSuccess)
4688 if (previewFile.exists())
4689 return theFormats().view(*this, previewFile, format) ?
4690 PreviewSuccess : PreviewError;
4692 // Successful export but no output file?
4693 // Probably a bug in error detection.
4694 LATTEST(status != ExportSuccess);
4699 Buffer::ReadStatus Buffer::extractFromVC()
4701 bool const found = LyXVC::file_not_found_hook(d->filename);
4703 return ReadFileNotFound;
4704 if (!d->filename.isReadableFile())
4710 Buffer::ReadStatus Buffer::loadEmergency()
4712 FileName const emergencyFile = getEmergencyFileName();
4713 if (!emergencyFile.exists()
4714 || emergencyFile.lastModified() <= d->filename.lastModified())
4715 return ReadFileNotFound;
4717 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4718 docstring const text = bformat(_("An emergency save of the document "
4719 "%1$s exists.\n\nRecover emergency save?"), file);
4721 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4722 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4728 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4729 bool const success = (ret_llf == ReadSuccess);
4731 if (hasReadonlyFlag()) {
4732 Alert::warning(_("File is read-only"),
4733 bformat(_("An emergency file is successfully loaded, "
4734 "but the original file %1$s is marked read-only. "
4735 "Please make sure to save the document as a different "
4736 "file."), from_utf8(d->filename.absFileName())));
4739 lyxvc().file_found_hook(d->filename);
4740 str = _("Document was successfully recovered.");
4742 str = _("Document was NOT successfully recovered.");
4743 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4744 makeDisplayPath(emergencyFile.absFileName()));
4746 int const del_emerg =
4747 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4748 _("&Remove"), _("&Keep"));
4749 if (del_emerg == 0) {
4750 emergencyFile.removeFile();
4752 Alert::warning(_("Emergency file deleted"),
4753 _("Do not forget to save your file now!"), true);
4755 return success ? ReadSuccess : ReadEmergencyFailure;
4758 int const del_emerg =
4759 Alert::prompt(_("Delete emergency file?"),
4760 _("Remove emergency file now?"), 1, 1,
4761 _("&Remove"), _("&Keep"));
4763 emergencyFile.removeFile();
4764 return ReadOriginal;
4774 Buffer::ReadStatus Buffer::loadAutosave()
4776 // Now check if autosave file is newer.
4777 FileName const autosaveFile = getAutosaveFileName();
4778 if (!autosaveFile.exists()
4779 || autosaveFile.lastModified() <= d->filename.lastModified())
4780 return ReadFileNotFound;
4782 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4783 docstring const text = bformat(_("The backup of the document %1$s "
4784 "is newer.\n\nLoad the backup instead?"), file);
4785 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4786 _("&Load backup"), _("Load &original"), _("&Cancel"));
4791 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4792 // the file is not saved if we load the autosave file.
4793 if (ret_llf == ReadSuccess) {
4794 if (hasReadonlyFlag()) {
4795 Alert::warning(_("File is read-only"),
4796 bformat(_("A backup file is successfully loaded, "
4797 "but the original file %1$s is marked read-only. "
4798 "Please make sure to save the document as a "
4800 from_utf8(d->filename.absFileName())));
4803 lyxvc().file_found_hook(d->filename);
4806 return ReadAutosaveFailure;
4809 // Here we delete the autosave
4810 autosaveFile.removeFile();
4811 return ReadOriginal;
4819 Buffer::ReadStatus Buffer::loadLyXFile()
4821 if (!d->filename.isReadableFile()) {
4822 ReadStatus const ret_rvc = extractFromVC();
4823 if (ret_rvc != ReadSuccess)
4827 ReadStatus const ret_re = loadEmergency();
4828 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4831 ReadStatus const ret_ra = loadAutosave();
4832 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4835 return loadThisLyXFile(d->filename);
4839 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4841 return readFile(fn);
4845 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4847 for (auto const & err : terr) {
4848 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4849 int errorRow = err.error_in_line;
4850 Buffer const * buf = 0;
4852 if (err.child_name.empty())
4853 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4855 // The error occurred in a child
4856 for (Buffer const * child : getDescendents()) {
4857 string const child_name =
4858 DocFileName(changeExtension(child->absFileName(), "tex")).
4860 if (err.child_name != child_name)
4862 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4863 if (!TexRow::isNone(start)) {
4864 buf = d->cloned_buffer_
4865 ? child->d->cloned_buffer_->d->owner_
4872 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4878 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4880 LBUFERR(!text().paragraphs().empty());
4882 // Use the master text class also for child documents
4883 Buffer const * const master = masterBuffer();
4884 DocumentClass const & textclass = master->params().documentClass();
4886 docstring_list old_bibfiles;
4887 // Do this only if we are the top-level Buffer. We also need to account
4888 // for the case of a previewed child with ignored parent here.
4889 if (master == this && !d->ignore_parent) {
4890 textclass.counters().reset(from_ascii("bibitem"));
4891 reloadBibInfoCache();
4892 // we will re-read this cache as we go through, but we need
4893 // to know whether it's changed to know whether we need to
4894 // update the bibinfo cache.
4895 old_bibfiles = d->bibfiles_cache_;
4896 d->bibfiles_cache_.clear();
4899 // keep the buffers to be children in this set. If the call from the
4900 // master comes back we can see which of them were actually seen (i.e.
4901 // via an InsetInclude). The remaining ones in the set need still be updated.
4902 static std::set<Buffer const *> bufToUpdate;
4903 if (scope == UpdateMaster) {
4904 // If this is a child document start with the master
4905 if (master != this) {
4906 bufToUpdate.insert(this);
4907 master->updateBuffer(UpdateMaster, utype);
4908 // If the master buffer has no gui associated with it, then the TocModel is
4909 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4910 // (bug 5699). The same happens if the master buffer is open in a different
4911 // window. This test catches both possibilities.
4912 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4913 // There remains a problem here: If there is another child open in yet a third
4914 // window, that TOC is not updated. So some more general solution is needed at
4916 if (master->d->gui_ != d->gui_)
4919 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4920 if (bufToUpdate.find(this) == bufToUpdate.end())
4924 // start over the counters in the master
4925 textclass.counters().reset();
4928 // update will be done below for this buffer
4929 bufToUpdate.erase(this);
4931 // update all caches
4932 clearReferenceCache();
4934 setChangesPresent(false);
4936 Buffer & cbuf = const_cast<Buffer &>(*this);
4939 ParIterator parit = cbuf.par_iterator_begin();
4940 updateBuffer(parit, utype);
4942 // If this document has siblings, then update the TocBackend later. The
4943 // reason is to ensure that later siblings are up to date when e.g. the
4944 // broken or not status of references is computed. The update is called
4945 // in InsetInclude::addToToc.
4949 // if the bibfiles changed, the cache of bibinfo is invalid
4950 docstring_list new_bibfiles = d->bibfiles_cache_;
4951 // this is a trick to determine whether the two vectors have
4952 // the same elements.
4953 sort(new_bibfiles.begin(), new_bibfiles.end());
4954 sort(old_bibfiles.begin(), old_bibfiles.end());
4955 if (old_bibfiles != new_bibfiles) {
4956 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4957 invalidateBibinfoCache();
4958 reloadBibInfoCache();
4959 // We relied upon the bibinfo cache when recalculating labels. But that
4960 // cache was invalid, although we didn't find that out until now. So we
4961 // have to do it all again.
4962 // That said, the only thing we really need to do is update the citation
4963 // labels. Nothing else will have changed. So we could create a new
4964 // UpdateType that would signal that fact, if we needed to do so.
4965 parit = cbuf.par_iterator_begin();
4966 // we will be re-doing the counters and references and such.
4967 textclass.counters().reset();
4968 clearReferenceCache();
4969 // we should not need to do this again?
4971 setChangesPresent(false);
4972 updateBuffer(parit, utype);
4973 // this will already have been done by reloadBibInfoCache();
4974 // d->bibinfo_cache_valid_ = true;
4977 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4978 // this is also set to true on the other path, by reloadBibInfoCache.
4979 d->bibinfo_cache_valid_ = true;
4981 d->cite_labels_valid_ = true;
4983 cbuf.tocBackend().update(true, utype);
4984 if (scope == UpdateMaster)
4985 cbuf.structureChanged();
4989 static depth_type getDepth(DocIterator const & it)
4991 depth_type depth = 0;
4992 for (size_t i = 0 ; i < it.depth() ; ++i)
4993 if (!it[i].inset().inMathed())
4994 depth += it[i].paragraph().getDepth() + 1;
4995 // remove 1 since the outer inset does not count
4996 // we should have at least one non-math inset, so
4997 // depth should nevery be 0. but maybe it is worth
4998 // marking this, just in case.
5000 // coverity[INTEGER_OVERFLOW]
5004 static depth_type getItemDepth(ParIterator const & it)
5006 Paragraph const & par = *it;
5007 LabelType const labeltype = par.layout().labeltype;
5009 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5012 // this will hold the lowest depth encountered up to now.
5013 depth_type min_depth = getDepth(it);
5014 ParIterator prev_it = it;
5017 --prev_it.top().pit();
5019 // start of nested inset: go to outer par
5021 if (prev_it.empty()) {
5022 // start of document: nothing to do
5027 // We search for the first paragraph with same label
5028 // that is not more deeply nested.
5029 Paragraph & prev_par = *prev_it;
5030 depth_type const prev_depth = getDepth(prev_it);
5031 if (labeltype == prev_par.layout().labeltype) {
5032 if (prev_depth < min_depth)
5033 return prev_par.itemdepth + 1;
5034 if (prev_depth == min_depth)
5035 return prev_par.itemdepth;
5037 min_depth = min(min_depth, prev_depth);
5038 // small optimization: if we are at depth 0, we won't
5039 // find anything else
5040 if (prev_depth == 0)
5046 static bool needEnumCounterReset(ParIterator const & it)
5048 Paragraph const & par = *it;
5049 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5050 depth_type const cur_depth = par.getDepth();
5051 ParIterator prev_it = it;
5052 while (prev_it.pit()) {
5053 --prev_it.top().pit();
5054 Paragraph const & prev_par = *prev_it;
5055 if (prev_par.getDepth() <= cur_depth)
5056 return prev_par.layout().name() != par.layout().name();
5058 // start of nested inset: reset
5063 // set the label of a paragraph. This includes the counters.
5064 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5066 BufferParams const & bp = owner_->masterBuffer()->params();
5067 DocumentClass const & textclass = bp.documentClass();
5068 Paragraph & par = it.paragraph();
5069 Layout const & layout = par.layout();
5070 Counters & counters = textclass.counters();
5072 if (par.params().startOfAppendix()) {
5073 // We want to reset the counter corresponding to toplevel sectioning
5074 Layout const & lay = textclass.getTOCLayout();
5075 docstring const cnt = lay.counter;
5077 counters.reset(cnt);
5078 counters.appendix(true);
5080 par.params().appendix(counters.appendix());
5082 // Compute the item depth of the paragraph
5083 par.itemdepth = getItemDepth(it);
5085 if (layout.margintype == MARGIN_MANUAL) {
5086 if (par.params().labelWidthString().empty())
5087 par.params().labelWidthString(par.expandLabel(layout, bp));
5088 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5089 // we do not need to do anything here, since the empty case is
5090 // handled during export.
5092 par.params().labelWidthString(docstring());
5095 switch(layout.labeltype) {
5096 case LABEL_ITEMIZE: {
5097 // At some point of time we should do something more
5098 // clever here, like:
5099 // par.params().labelString(
5100 // bp.user_defined_bullet(par.itemdepth).getText());
5101 // for now, use a simple hardcoded label
5102 docstring itemlabel;
5103 switch (par.itemdepth) {
5105 itemlabel = char_type(0x2022);
5108 itemlabel = char_type(0x2013);
5111 itemlabel = char_type(0x2217);
5114 itemlabel = char_type(0x2219); // or 0x00b7
5117 par.params().labelString(itemlabel);
5121 case LABEL_ENUMERATE: {
5122 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5124 switch (par.itemdepth) {
5135 enumcounter += "iv";
5138 // not a valid enumdepth...
5142 if (needEnumCounterReset(it)) {
5143 // Increase the master counter?
5144 if (layout.stepmastercounter)
5145 counters.stepMaster(enumcounter, utype);
5146 // Maybe we have to reset the enumeration counter.
5147 if (!layout.resumecounter)
5148 counters.reset(enumcounter);
5150 counters.step(enumcounter, utype);
5152 string const & lang = par.getParLanguage(bp)->code();
5153 par.params().labelString(counters.theCounter(enumcounter, lang));
5158 case LABEL_SENSITIVE: {
5159 string const & type = counters.current_float();
5160 docstring full_label;
5162 full_label = owner_->B_("Senseless!!! ");
5164 docstring name = owner_->B_(textclass.floats().getType(type).name());
5165 if (counters.hasCounter(from_utf8(type))) {
5166 string const & lang = par.getParLanguage(bp)->code();
5167 counters.step(from_utf8(type), utype);
5168 full_label = bformat(from_ascii("%1$s %2$s:"),
5170 counters.theCounter(from_utf8(type), lang));
5172 full_label = bformat(from_ascii("%1$s #:"), name);
5174 par.params().labelString(full_label);
5178 case LABEL_NO_LABEL:
5179 par.params().labelString(docstring());
5183 case LABEL_CENTERED:
5184 case LABEL_STATIC: {
5185 docstring const & lcounter = layout.counter;
5186 if (!lcounter.empty()) {
5187 if (layout.toclevel <= bp.secnumdepth
5188 && (layout.latextype != LATEX_ENVIRONMENT
5189 || it.text()->isFirstInSequence(it.pit()))) {
5190 if (counters.hasCounter(lcounter))
5191 counters.step(lcounter, utype);
5192 par.params().labelString(par.expandLabel(layout, bp));
5194 par.params().labelString(docstring());
5196 par.params().labelString(par.expandLabel(layout, bp));
5202 par.params().labelString(par.expandLabel(layout, bp));
5207 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5209 // LASSERT: Is it safe to continue here, or should we just return?
5210 LASSERT(parit.pit() == 0, /**/);
5212 // Set the position of the text in the buffer to be able
5213 // to resolve macros in it.
5214 parit.text()->setMacrocontextPosition(parit);
5216 depth_type maxdepth = 0;
5217 pit_type const lastpit = parit.lastpit();
5218 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5219 // reduce depth if necessary
5220 if (parit->params().depth() > maxdepth) {
5221 /** FIXME: this function is const, but
5222 * nevertheless it modifies the buffer. To be
5223 * cleaner, one should modify the buffer in
5224 * another function, which is actually
5225 * non-const. This would however be costly in
5226 * terms of code duplication.
5228 CursorData(parit).recordUndo();
5229 parit->params().depth(maxdepth);
5231 maxdepth = parit->getMaxDepthAfter();
5233 if (utype == OutputUpdate) {
5234 // track the active counters
5235 // we have to do this for the master buffer, since the local
5236 // buffer isn't tracking anything.
5237 masterBuffer()->params().documentClass().counters().
5238 setActiveLayout(parit->layout());
5241 // set the counter for this paragraph
5242 d->setLabel(parit, utype);
5244 // update change-tracking flag
5245 parit->addChangesToBuffer(*this);
5248 for (auto const & insit : parit->insetList()) {
5249 parit.pos() = insit.pos;
5250 insit.inset->updateBuffer(parit, utype);
5256 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5257 WordLangTuple & word_lang, docstring_list & suggestions) const
5261 suggestions.clear();
5262 word_lang = WordLangTuple();
5263 bool const to_end = to.empty();
5264 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5265 // OK, we start from here.
5266 for (; from != end; from.forwardPos()) {
5267 // This skips all insets with spell check disabled.
5268 while (!from.allowSpellCheck()) {
5272 // If from is at the end of the document (which is possible
5273 // when "from" was changed above) LyX will crash later otherwise.
5274 if (from.atEnd() || (!to_end && from >= end))
5277 from.paragraph().spellCheck();
5278 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5279 if (SpellChecker::misspelled(res)) {
5283 // Do not increase progress when from == to, otherwise the word
5284 // count will be wrong.
5294 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5296 bool inword = false;
5301 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5302 if (!dit.inTexted()) {
5307 Paragraph const & par = dit.paragraph();
5308 pos_type const pos = dit.pos();
5310 // Copied and adapted from isWordSeparator() in Paragraph
5311 if (pos == dit.lastpos()) {
5314 Inset const * ins = par.getInset(pos);
5315 if (ins && skipNoOutput && !ins->producesOutput()) {
5318 // stop if end of range was skipped
5319 if (!to.atEnd() && dit >= to)
5322 } else if (!par.isDeleted(pos)) {
5323 if (par.isWordSeparator(pos))
5329 if (ins && ins->isLetter())
5331 else if (ins && ins->isSpace())
5334 char_type const c = par.getChar(pos);
5335 if (isPrintableNonspace(c))
5337 else if (isSpace(c))
5347 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5349 d->updateStatistics(from, to, skipNoOutput);
5353 int Buffer::wordCount() const
5355 return d->wordCount();
5359 int Buffer::charCount(bool with_blanks) const
5361 return d->charCount(with_blanks);
5365 Buffer::ReadStatus Buffer::reload()
5368 // c.f. bug https://www.lyx.org/trac/ticket/6587
5369 removeAutosaveFile();
5370 // e.g., read-only status could have changed due to version control
5371 d->filename.refresh();
5372 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5374 // clear parent. this will get reset if need be.
5376 ReadStatus const status = loadLyXFile();
5377 if (status == ReadSuccess) {
5382 message(bformat(_("Document %1$s reloaded."), disp_fn));
5385 message(bformat(_("Could not reload document %1$s."), disp_fn));
5395 bool Buffer::saveAs(FileName const & fn)
5397 FileName const old_name = fileName();
5398 FileName const old_auto = getAutosaveFileName();
5399 bool const old_unnamed = isUnnamed();
5400 bool success = true;
5401 d->old_position = filePath();
5408 // bring the autosave file with us, just in case.
5409 moveAutosaveFile(old_auto);
5410 // validate version control data and
5411 // correct buffer title
5412 lyxvc().file_found_hook(fileName());
5414 // the file has now been saved to the new location.
5415 // we need to check that the locations of child buffers
5417 checkChildBuffers();
5418 checkMasterBuffer();
5421 // reset the old filename and unnamed state
5422 setFileName(old_name);
5423 setUnnamed(old_unnamed);
5427 d->old_position.clear();
5432 void Buffer::checkChildBuffers()
5434 for (auto const & bit : d->children_positions) {
5435 DocIterator dit = bit.second;
5436 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5437 if (!cbuf || !theBufferList().isLoaded(cbuf))
5439 Inset * inset = dit.nextInset();
5440 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5441 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5442 docstring const & incfile = inset_inc->getParam("filename");
5443 string oldloc = cbuf->absFileName();
5444 string newloc = makeAbsPath(to_utf8(incfile),
5445 onlyPath(absFileName())).absFileName();
5446 if (oldloc == newloc)
5448 // the location of the child file is incorrect.
5450 inset_inc->setChildBuffer(0);
5452 // invalidate cache of children
5453 d->children_positions.clear();
5454 d->position_to_children.clear();
5458 // If a child has been saved under a different name/path, it might have been
5459 // orphaned. Therefore the master needs to be reset (bug 8161).
5460 void Buffer::checkMasterBuffer()
5462 Buffer const * const master = masterBuffer();
5466 // necessary to re-register the child (bug 5873)
5467 // FIXME: clean up updateMacros (here, only
5468 // child registering is needed).
5469 master->updateMacros();
5470 // (re)set master as master buffer, but only
5471 // if we are a real child
5472 if (master->isChild(this))
5479 string Buffer::includedFilePath(string const & name, string const & ext) const
5481 if (d->old_position.empty() ||
5482 equivalent(FileName(d->old_position), FileName(filePath())))
5485 bool isabsolute = FileName::isAbsolute(name);
5486 // both old_position and filePath() end with a path separator
5487 string absname = isabsolute ? name : d->old_position + name;
5489 // if old_position is set to origin, we need to do the equivalent of
5490 // getReferencedFileName() (see readDocument())
5491 if (!isabsolute && d->old_position == params().origin) {
5492 FileName const test(addExtension(filePath() + name, ext));
5494 absname = filePath() + name;
5497 if (!FileName(addExtension(absname, ext)).exists())
5501 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5503 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5504 from_utf8(filePath())));
5508 void Buffer::setChangesPresent(bool b) const
5510 d->tracked_changes_present_ = b;
5514 bool Buffer::areChangesPresent() const
5516 return d->tracked_changes_present_;
5520 void Buffer::updateChangesPresent() const
5522 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5523 setChangesPresent(false);
5524 ParConstIterator it = par_iterator_begin();
5525 ParConstIterator const end = par_iterator_end();
5526 for (; !areChangesPresent() && it != end; ++it)
5527 it->addChangesToBuffer(*this);
5531 void Buffer::Impl::refreshFileMonitor()
5533 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5534 file_monitor_->refresh();
5538 // The previous file monitor is invalid
5539 // This also destroys the previous file monitor and all its connections
5540 file_monitor_ = FileSystemWatcher::monitor(filename);
5541 // file_monitor_ will be destroyed with *this, so it is not going to call a
5542 // destroyed object method.
5543 file_monitor_->connect([this](bool exists) {
5544 fileExternallyModified(exists);
5549 void Buffer::Impl::fileExternallyModified(bool const exists)
5551 // ignore notifications after our own saving operations
5552 if (checksum_ == filename.checksum()) {
5553 LYXERR(Debug::FILES, "External modification but "
5554 "checksum unchanged: " << filename);
5557 // If the file has been deleted, only mark the file as dirty since it is
5558 // pointless to prompt for reloading. If later a file is moved into this
5559 // location, then the externally modified warning will appear then.
5561 externally_modified_ = true;
5562 // Update external modification notification.
5563 // Dirty buffers must be visible at all times.
5564 if (wa_ && wa_->unhide(owner_))
5565 wa_->updateTitles();
5567 // Unable to unhide the buffer (e.g. no GUI or not current View)
5572 bool Buffer::notifiesExternalModification() const
5574 return d->externally_modified_;
5578 void Buffer::clearExternalModification() const
5580 d->externally_modified_ = false;
5582 d->wa_->updateTitles();