3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
59 #include "SpellChecker.h"
61 #include "texstream.h"
64 #include "TextClass.h"
65 #include "TocBackend.h"
67 #include "VCBackend.h"
69 #include "WordLangTuple.h"
72 #include "insets/InsetBibtex.h"
73 #include "insets/InsetBranch.h"
74 #include "insets/InsetInclude.h"
75 #include "insets/InsetTabular.h"
76 #include "insets/InsetText.h"
78 #include "mathed/InsetMathHull.h"
79 #include "mathed/MacroTable.h"
80 #include "mathed/InsetMathMacroTemplate.h"
81 #include "mathed/MathSupport.h"
83 #include "graphics/GraphicsCache.h"
84 #include "graphics/PreviewLoader.h"
86 #include "frontends/alert.h"
87 #include "frontends/Delegates.h"
88 #include "frontends/WorkAreaManager.h"
90 #include "support/lassert.h"
91 #include "support/convert.h"
92 #include "support/debug.h"
93 #include "support/docstring_list.h"
94 #include "support/ExceptionMessage.h"
95 #include "support/FileMonitor.h"
96 #include "support/FileName.h"
97 #include "support/FileNameList.h"
98 #include "support/filetools.h"
99 #include "support/ForkedCalls.h"
100 #include "support/gettext.h"
101 #include "support/gzstream.h"
102 #include "support/lstrings.h"
103 #include "support/lyxalgo.h"
104 #include "support/mutex.h"
105 #include "support/os.h"
106 #include "support/Package.h"
107 #include "support/PathChanger.h"
108 #include "support/Systemcall.h"
109 #include "support/TempFile.h"
110 #include "support/textutils.h"
111 #include "support/types.h"
113 #include "support/bind.h"
125 using namespace lyx::support;
126 using namespace lyx::graphics;
130 namespace Alert = frontend::Alert;
131 namespace os = support::os;
135 int const LYX_FORMAT = LYX_FORMAT_LYX;
137 typedef map<string, bool> DepClean;
138 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
143 // A storehouse for the cloned buffers.
144 list<CloneList *> cloned_buffers;
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
154 delete preview_loader_;
162 /// search for macro in local (buffer) table or in children
163 MacroData const * getBufferMacro(docstring const & name,
164 DocIterator const & pos) const;
166 /// Update macro table starting with position of it \param it in some
168 void updateMacros(DocIterator & it, DocIterator & scope);
170 void setLabel(ParIterator & it, UpdateType utype) const;
172 /** If we have branches that use the file suffix
173 feature, return the file name with suffix appended.
175 FileName exportFileName() const;
182 mutable TexRow texrow;
184 /// need to regenerate .tex?
188 mutable bool lyx_clean;
190 /// is autosave needed?
191 mutable bool bak_clean;
193 /// is this an unnamed file (New...)?
196 /// is this an internal bufffer?
197 bool internal_buffer;
202 /// name of the file the buffer is associated with.
205 /** Set to true only when the file is fully loaded.
206 * Used to prevent the premature generation of previews
207 * and by the citation inset.
209 bool file_fully_loaded;
211 /// original format of loaded file
214 /// if the file was originally loaded from an older format, do
215 /// we need to back it up still?
216 bool need_format_backup;
218 /// Ignore the parent (e.g. when exporting a child standalone)?
222 mutable TocBackend toc_backend;
227 ScopeMacro(DocIterator const & s, MacroData const & m)
228 : scope(s), macro(m) {}
232 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
233 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
234 /// map from the macro name to the position map,
235 /// which maps the macro definition position to the scope and the MacroData.
236 NamePositionScopeMacroMap macros;
237 /// This seem to change the way Buffer::getMacro() works
238 mutable bool macro_lock;
240 /// positions of child buffers in the buffer
241 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
243 ScopeBuffer() : buffer(0) {}
244 ScopeBuffer(DocIterator const & s, Buffer const * b)
245 : scope(s), buffer(b) {}
247 Buffer const * buffer;
249 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
250 /// position of children buffers in this buffer
251 BufferPositionMap children_positions;
252 /// map from children inclusion positions to their scope and their buffer
253 PositionScopeBufferMap position_to_children;
255 /// Contains the old buffer filePath() while saving-as, or the
256 /// directory where the document was last saved while loading.
259 /** Keeps track of the path of local layout files.
260 * If possible, it is always relative to the buffer path.
261 * Empty for layouts in system or user directory.
263 string layout_position;
265 /// Container for all sort of Buffer dependant errors.
266 map<string, ErrorList> errorLists;
268 /// checksum used to test if the file has been externally modified. Used to
269 /// double check whether the file had been externally modified when saving.
270 unsigned long checksum_;
273 frontend::WorkAreaManager * wa_;
275 frontend::GuiBufferDelegate * gui_;
280 /// A cache for the bibfiles (including bibfiles of loaded child
281 /// documents), needed for appropriate update of natbib labels.
282 mutable docstring_list bibfiles_cache_;
284 // FIXME The caching mechanism could be improved. At present, we have a
285 // cache for each Buffer, that caches all the bibliography info for that
286 // Buffer. A more efficient solution would be to have a global cache per
287 // file, and then to construct the Buffer's bibinfo from that.
288 /// A cache for bibliography info
289 mutable BiblioInfo bibinfo_;
290 /// whether the bibinfo cache is valid
291 mutable bool bibinfo_cache_valid_;
292 /// Cache of timestamps of .bib files
293 map<FileName, time_t> bibfile_status_;
294 /// Indicates whether the bibinfo has changed since the last time
295 /// we ran updateBuffer(), i.e., whether citation labels may need
297 mutable bool cite_labels_valid_;
299 /// These two hold the file name and format, written to by
300 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
301 FileName preview_file_;
302 string preview_format_;
303 /// If there was an error when previewing, on the next preview we do
304 /// a fresh compile (e.g. in case the user installed a package that
308 mutable RefCache ref_cache_;
310 /// our Text that should be wrapped in an InsetText
314 PreviewLoader * preview_loader_;
316 /// This is here to force the test to be done whenever parent_buffer
318 Buffer const * parent() const
320 // ignore_parent temporarily "orphans" a buffer
321 // (e.g. if a child is compiled standalone)
324 // if parent_buffer is not loaded, then it has been unloaded,
325 // which means that parent_buffer is an invalid pointer. So we
326 // set it to null in that case.
327 // however, the BufferList doesn't know about cloned buffers, so
328 // they will always be regarded as unloaded. in that case, we hope
330 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
332 return parent_buffer;
336 void setParent(Buffer const * pb)
338 if (parent_buffer == pb)
341 if (!cloned_buffer_ && parent_buffer && pb)
342 LYXERR0("Warning: a buffer should not have two parents!");
344 if (!cloned_buffer_ && parent_buffer)
345 parent_buffer->invalidateBibinfoCache();
348 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
349 /// This one is useful for preview detached in a thread.
350 Buffer const * cloned_buffer_;
352 CloneList * clone_list_;
353 /// are we in the process of exporting this buffer?
354 mutable bool doing_export;
356 /// compute statistics
357 /// \p from initial position
358 /// \p to points to the end position
359 void updateStatistics(DocIterator & from, DocIterator & to,
360 bool skipNoOutput = true);
361 /// statistics accessor functions
362 int wordCount() const
366 int charCount(bool with_blanks) const
369 + (with_blanks ? blank_count_ : 0);
372 // does the buffer contain tracked changes? (if so, we automatically
373 // display the review toolbar, for instance)
374 mutable bool tracked_changes_present_;
376 // Make sure the file monitor monitors the good file.
377 void refreshFileMonitor();
379 /// Notify or clear of external modification
380 void fileExternallyModified(bool exists);
382 /// has been externally modified? Can be reset by the user.
383 mutable bool externally_modified_;
386 /// So we can force access via the accessors.
387 mutable Buffer const * parent_buffer;
393 FileMonitorPtr file_monitor_;
397 /// Creates the per buffer temporary directory
398 static FileName createBufferTmpDir()
400 // FIXME This would be the ideal application for a TempDir class (like
401 // TempFile but for directories)
406 Mutex::Locker locker(&mutex);
407 counter = convert<string>(count++);
409 // We are in our own directory. Why bother to mangle name?
410 // In fact I wrote this code to circumvent a problematic behaviour
411 // (bug?) of EMX mkstemp().
412 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
415 if (!tmpfl.createDirectory(0777)) {
416 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
417 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
418 from_utf8(tmpfl.absFileName())));
424 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
425 Buffer const * cloned_buffer)
426 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
427 internal_buffer(false), read_only(readonly_), filename(file),
428 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
429 ignore_parent(false), toc_backend(owner), macro_lock(false),
430 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
431 cite_labels_valid_(false), preview_error_(false),
432 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
433 clone_list_(0), doing_export(false),
434 tracked_changes_present_(0), externally_modified_(false), parent_buffer(0),
435 word_count_(0), char_count_(0), blank_count_(0)
437 refreshFileMonitor();
438 if (!cloned_buffer_) {
439 temppath = createBufferTmpDir();
440 lyxvc.setBuffer(owner_);
442 wa_ = new frontend::WorkAreaManager;
445 temppath = cloned_buffer_->d->temppath;
446 file_fully_loaded = true;
447 params = cloned_buffer_->d->params;
448 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
449 bibinfo_ = cloned_buffer_->d->bibinfo_;
450 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
451 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
452 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
453 unnamed = cloned_buffer_->d->unnamed;
454 internal_buffer = cloned_buffer_->d->internal_buffer;
455 layout_position = cloned_buffer_->d->layout_position;
456 preview_file_ = cloned_buffer_->d->preview_file_;
457 preview_format_ = cloned_buffer_->d->preview_format_;
458 preview_error_ = cloned_buffer_->d->preview_error_;
459 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
463 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
464 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
466 LYXERR(Debug::INFO, "Buffer::Buffer()");
468 d->inset = new InsetText(*cloned_buffer->d->inset);
469 d->inset->setBuffer(*this);
470 // FIXME: optimize this loop somewhat, maybe by creating a new
471 // general recursive Inset::setId().
472 DocIterator it = doc_iterator_begin(this);
473 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
474 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
475 it.paragraph().setId(cloned_it.paragraph().id());
477 d->inset = new InsetText(this);
478 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
484 LYXERR(Debug::INFO, "Buffer::~Buffer()");
485 // here the buffer should take care that it is
486 // saved properly, before it goes into the void.
488 // GuiView already destroyed
492 // No need to do additional cleanups for internal buffer.
498 // this is in case of recursive includes: we won't try to delete
499 // ourselves as a child.
500 d->clone_list_->erase(this);
501 // loop over children
502 for (auto const & p : d->children_positions) {
503 Buffer * child = const_cast<Buffer *>(p.first);
504 if (d->clone_list_->erase(child))
507 // if we're the master buffer, then we should get rid of the list
510 // If this is not empty, we have leaked something. Worse, one of the
511 // children still has a reference to this list. But we will try to
512 // continue, rather than shut down.
513 LATTEST(d->clone_list_->empty());
514 list<CloneList *>::iterator it =
515 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
516 if (it == cloned_buffers.end()) {
517 // We will leak in this case, but it is safe to continue.
520 cloned_buffers.erase(it);
521 delete d->clone_list_;
523 // FIXME Do we really need to do this right before we delete d?
524 // clear references to children in macro tables
525 d->children_positions.clear();
526 d->position_to_children.clear();
528 // loop over children
529 for (auto const & p : d->children_positions) {
530 Buffer * child = const_cast<Buffer *>(p.first);
531 if (theBufferList().isLoaded(child)) {
532 if (theBufferList().isOthersChild(this, child))
535 theBufferList().release(child);
540 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
542 msg += emergencyWrite();
544 msg += " " + _("Save failed! Document is lost.");
546 Alert::warning(_("Attempting to close changed document!"), msg);
549 // FIXME Do we really need to do this right before we delete d?
550 // clear references to children in macro tables
551 d->children_positions.clear();
552 d->position_to_children.clear();
554 if (!d->temppath.destroyDirectory()) {
555 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
556 from_utf8(d->temppath.absFileName())));
565 Buffer * Buffer::cloneWithChildren() const
568 cloned_buffers.push_back(new CloneList);
569 CloneList * clones = cloned_buffers.back();
571 cloneWithChildren(bufmap, clones);
573 // make sure we got cloned
574 BufferMap::const_iterator bit = bufmap.find(this);
575 LASSERT(bit != bufmap.end(), return 0);
576 Buffer * cloned_buffer = bit->second;
578 return cloned_buffer;
582 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
584 // have we already been cloned?
585 if (bufmap.find(this) != bufmap.end())
588 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
590 // The clone needs its own DocumentClass, since running updateBuffer() will
591 // modify it, and we would otherwise be sharing it with the original Buffer.
592 buffer_clone->params().makeDocumentClass(true);
594 cap::switchBetweenClasses(
595 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
596 static_cast<InsetText &>(buffer_clone->inset()), el);
598 bufmap[this] = buffer_clone;
599 clones->insert(buffer_clone);
600 buffer_clone->d->clone_list_ = clones;
601 buffer_clone->d->macro_lock = true;
602 buffer_clone->d->children_positions.clear();
604 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
605 // math macro caches need to be rethought and simplified.
606 // I am not sure wether we should handle Buffer cloning here or in BufferList.
607 // Right now BufferList knows nothing about buffer clones.
608 for (auto const & p : d->position_to_children) {
609 DocIterator dit = p.first.clone(buffer_clone);
610 dit.setBuffer(buffer_clone);
611 Buffer * child = const_cast<Buffer *>(p.second.buffer);
613 child->cloneWithChildren(bufmap, clones);
614 BufferMap::iterator const bit = bufmap.find(child);
615 LASSERT(bit != bufmap.end(), continue);
616 Buffer * child_clone = bit->second;
618 Inset * inset = dit.nextInset();
619 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
620 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
621 inset_inc->setChildBuffer(child_clone);
622 child_clone->d->setParent(buffer_clone);
623 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
624 buffer_clone->setChild(dit, child_clone);
626 buffer_clone->d->macro_lock = false;
631 Buffer * Buffer::cloneBufferOnly() const {
632 cloned_buffers.push_back(new CloneList);
633 CloneList * clones = cloned_buffers.back();
634 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
636 // The clone needs its own DocumentClass, since running updateBuffer() will
637 // modify it, and we would otherwise be sharing it with the original Buffer.
638 buffer_clone->params().makeDocumentClass(true);
640 cap::switchBetweenClasses(
641 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
642 static_cast<InsetText &>(buffer_clone->inset()), el);
644 clones->insert(buffer_clone);
645 buffer_clone->d->clone_list_ = clones;
647 // we won't be cloning the children
648 buffer_clone->d->children_positions.clear();
653 bool Buffer::isClone() const
655 return d->cloned_buffer_;
659 void Buffer::changed(bool update_metrics) const
662 d->wa_->redrawAll(update_metrics);
666 frontend::WorkAreaManager & Buffer::workAreaManager() const
673 Text & Buffer::text() const
675 return d->inset->text();
679 Inset & Buffer::inset() const
685 BufferParams & Buffer::params()
691 BufferParams const & Buffer::params() const
697 BufferParams const & Buffer::masterParams() const
699 if (masterBuffer() == this)
702 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
703 // Copy child authors to the params. We need those pointers.
704 for (Author const & a : params().authors())
705 mparams.authors().record(a);
710 double Buffer::fontScalingFactor() const
712 return isExporting() ? 75.0 * params().html_math_img_scale
713 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
717 ParagraphList & Buffer::paragraphs()
719 return text().paragraphs();
723 ParagraphList const & Buffer::paragraphs() const
725 return text().paragraphs();
729 LyXVC & Buffer::lyxvc()
735 LyXVC const & Buffer::lyxvc() const
741 string const Buffer::temppath() const
743 return d->temppath.absFileName();
747 TexRow & Buffer::texrow()
753 TexRow const & Buffer::texrow() const
759 TocBackend & Buffer::tocBackend() const
761 return d->toc_backend;
765 Undo & Buffer::undo()
771 void Buffer::setChild(DocIterator const & dit, Buffer * child)
773 d->children_positions[child] = dit;
777 string Buffer::latexName(bool const no_path) const
779 FileName latex_name =
780 makeLatexName(d->exportFileName());
781 return no_path ? latex_name.onlyFileName()
782 : latex_name.absFileName();
786 FileName Buffer::Impl::exportFileName() const
788 docstring const branch_suffix =
789 params.branchlist().getFileNameSuffix();
790 if (branch_suffix.empty())
793 string const name = filename.onlyFileNameWithoutExt()
794 + to_utf8(branch_suffix);
795 FileName res(filename.onlyPath().absFileName() + "/" + name);
796 res.changeExtension(filename.extension());
802 string Buffer::logName(LogType * type) const
804 string const filename = latexName(false);
806 if (filename.empty()) {
812 string const path = temppath();
814 FileName const fname(addName(temppath(),
815 onlyFileName(changeExtension(filename,
818 // FIXME: how do we know this is the name of the build log?
819 FileName const bname(
820 addName(path, onlyFileName(
821 changeExtension(filename,
822 theFormats().extension(params().bufferFormat()) + ".out"))));
824 // Also consider the master buffer log file
825 FileName masterfname = fname;
826 LogType mtype = latexlog;
827 if (masterBuffer() != this) {
828 string const mlogfile = masterBuffer()->logName(&mtype);
829 masterfname = FileName(mlogfile);
832 // If no Latex log or Build log is newer, show Build log
833 if (bname.exists() &&
834 ((!fname.exists() && !masterfname.exists())
835 || (fname.lastModified() < bname.lastModified()
836 && masterfname.lastModified() < bname.lastModified()))) {
837 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
840 return bname.absFileName();
841 // If we have a newer master file log or only a master log, show this
842 } else if (fname != masterfname
843 && (!fname.exists() && (masterfname.exists()
844 || fname.lastModified() < masterfname.lastModified()))) {
845 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
848 return masterfname.absFileName();
850 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
853 return fname.absFileName();
857 void Buffer::setReadonly(bool const flag)
859 if (d->read_only != flag) {
866 void Buffer::setFileName(FileName const & fname)
868 bool const changed = fname != d->filename;
870 d->refreshFileMonitor();
872 lyxvc().file_found_hook(fname);
873 setReadonly(d->filename.isReadOnly());
879 int Buffer::readHeader(Lexer & lex)
881 int unknown_tokens = 0;
883 int begin_header_line = -1;
885 // Initialize parameters that may be/go lacking in header:
886 params().branchlist().clear();
887 params().preamble.erase();
888 params().options.erase();
889 params().master.erase();
890 params().float_placement.erase();
891 params().float_alignment.erase();
892 params().paperwidth.erase();
893 params().paperheight.erase();
894 params().leftmargin.erase();
895 params().rightmargin.erase();
896 params().topmargin.erase();
897 params().bottommargin.erase();
898 params().headheight.erase();
899 params().headsep.erase();
900 params().footskip.erase();
901 params().columnsep.erase();
902 params().fonts_cjk.erase();
903 params().listings_params.clear();
904 params().clearLayoutModules();
905 params().clearRemovedModules();
906 params().clearIncludedChildren();
907 params().pdfoptions().clear();
908 params().indiceslist().clear();
909 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
910 params().isbackgroundcolor = false;
911 params().fontcolor = RGBColor(0, 0, 0);
912 params().isfontcolor = false;
913 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
914 params().boxbgcolor = RGBColor(0xFF, 0, 0);
915 params().html_latex_start.clear();
916 params().html_latex_end.clear();
917 params().html_math_img_scale = 1.0;
918 params().output_sync_macro.erase();
919 params().setLocalLayout(docstring(), false);
920 params().setLocalLayout(docstring(), true);
921 params().biblio_opts.erase();
922 params().biblatex_bibstyle.erase();
923 params().biblatex_citestyle.erase();
924 params().multibib.erase();
926 for (int i = 0; i < 4; ++i) {
927 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
928 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
931 ErrorList & errorList = d->errorLists["Parse"];
940 if (token == "\\end_header")
944 if (token == "\\begin_header") {
945 begin_header_line = line;
949 LYXERR(Debug::PARSER, "Handling document header token: `"
952 string const result =
953 params().readToken(lex, token, d->filename.onlyPath());
954 if (!result.empty()) {
955 if (token == "\\textclass") {
956 d->layout_position = result;
959 docstring const s = bformat(_("Unknown token: "
963 errorList.push_back(ErrorItem(_("Document header error"), s));
967 if (begin_header_line) {
968 docstring const s = _("\\begin_header is missing");
969 errorList.push_back(ErrorItem(_("Document header error"), s));
972 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
974 params().makeDocumentClass();
976 return unknown_tokens;
981 // changed to be public and have one parameter
982 // Returns true if "\end_document" is not read (Asger)
983 bool Buffer::readDocument(Lexer & lex)
985 ErrorList & errorList = d->errorLists["Parse"];
988 // remove dummy empty par
989 paragraphs().clear();
991 if (!lex.checkFor("\\begin_document")) {
992 docstring const s = _("\\begin_document is missing");
993 errorList.push_back(ErrorItem(_("Document header error"), s));
998 if (params().output_changes) {
999 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1000 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1001 LaTeXFeatures::isAvailable("xcolor");
1003 if (!dvipost && !xcolorulem) {
1004 Alert::warning(_("Changes not shown in LaTeX output"),
1005 _("Changes will not be highlighted in LaTeX output, "
1006 "because neither dvipost nor xcolor/ulem are installed.\n"
1007 "Please install these packages or redefine "
1008 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1009 } else if (!xcolorulem) {
1010 Alert::warning(_("Changes not shown in LaTeX output"),
1011 _("Changes will not be highlighted in LaTeX output "
1012 "when using pdflatex, because xcolor and ulem are not installed.\n"
1013 "Please install both packages or redefine "
1014 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1018 if (!parent() && !params().master.empty()) {
1019 FileName const master_file = makeAbsPath(params().master,
1020 onlyPath(absFileName()));
1021 if (isLyXFileName(master_file.absFileName())) {
1023 checkAndLoadLyXFile(master_file, true);
1025 // necessary e.g. after a reload
1026 // to re-register the child (bug 5873)
1027 // FIXME: clean up updateMacros (here, only
1028 // child registering is needed).
1029 master->updateMacros();
1030 // set master as master buffer, but only
1031 // if we are a real child
1032 if (master->isChild(this))
1034 // if the master is not fully loaded
1035 // it is probably just loading this
1036 // child. No warning needed then.
1037 else if (master->isFullyLoaded())
1038 LYXERR0("The master '"
1040 << "' assigned to this document ("
1042 << ") does not include "
1043 "this document. Ignoring the master assignment.");
1044 // If the master has just been created, un-hide it (#11162)
1045 if (!master->fileName().exists())
1046 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1047 master->absFileName()));
1052 // assure we have a default index
1053 params().indiceslist().addDefault(B_("Index"));
1056 if (FileName::isAbsolute(params().origin))
1057 d->old_position = params().origin;
1059 d->old_position = filePath();
1060 bool const res = text().read(lex, errorList, d->inset);
1061 d->old_position.clear();
1063 // inform parent buffer about local macros
1065 Buffer const * pbuf = parent();
1066 for (auto const & m : usermacros)
1067 pbuf->usermacros.insert(m);
1071 updateMacroInstances(InternalUpdate);
1076 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1078 Format const * fmt = theFormats().getFormat(format);
1081 // It is important to use the correct extension here, since some
1082 // converters create a wrong output file otherwise (e.g. html2latex)
1083 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1084 ofdocstream os(name.toFilesystemEncoding().c_str());
1085 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1086 bool const success = !(os << contents).fail();
1089 bool converted = false;
1091 params().compressed = false;
1093 // remove dummy empty par
1094 paragraphs().clear();
1096 converted = importFile(format, name, errorList);
1099 removeTempFile(name);
1104 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1106 if (!theConverters().isReachable(format, "lyx"))
1109 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1110 Converters::RetVal const retval =
1111 theConverters().convert(0, name, lyx, name, format, "lyx", errorList);
1112 if (retval == Converters::SUCCESS) {
1113 bool const success = readFile(lyx) == ReadSuccess;
1114 removeTempFile(lyx);
1122 bool Buffer::readString(string const & s)
1124 params().compressed = false;
1127 istringstream is(s);
1129 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1130 FileName const fn = tempfile.name();
1133 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1135 if (success && file_format != LYX_FORMAT) {
1136 // We need to call lyx2lyx, so write the input to a file
1137 ofstream os(fn.toFilesystemEncoding().c_str());
1140 // lyxvc in readFile
1141 if (readFile(fn) != ReadSuccess)
1145 if (readDocument(lex))
1151 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1155 if (!lex.setFile(fname)) {
1156 Alert::error(_("File Not Found"),
1157 bformat(_("Unable to open file `%1$s'."),
1158 from_utf8(fn.absFileName())));
1159 return ReadFileNotFound;
1163 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1164 if (ret_plf != ReadSuccess)
1167 if (file_format != LYX_FORMAT) {
1169 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1170 if (ret_clf != ReadSuccess)
1172 ret_clf = readFile(tmpFile);
1173 if (ret_clf == ReadSuccess) {
1174 d->file_format = file_format;
1175 d->need_format_backup = true;
1180 // FIXME: InsetInfo needs to know whether the file is under VCS
1181 // during the parse process, so this has to be done before.
1182 lyxvc().file_found_hook(d->filename);
1184 if (readDocument(lex)) {
1185 Alert::error(_("Document format failure"),
1186 bformat(_("%1$s ended unexpectedly, which means"
1187 " that it is probably corrupted."),
1188 from_utf8(fn.absFileName())));
1189 return ReadDocumentFailure;
1192 d->file_fully_loaded = true;
1193 d->read_only = !d->filename.isWritable();
1194 params().compressed = theFormats().isZippedFile(d->filename);
1200 bool Buffer::isFullyLoaded() const
1202 return d->file_fully_loaded;
1206 void Buffer::setFullyLoaded(bool value)
1208 d->file_fully_loaded = value;
1212 bool Buffer::lastPreviewError() const
1214 return d->preview_error_;
1218 PreviewLoader * Buffer::loader() const
1220 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1222 if (!d->preview_loader_)
1223 d->preview_loader_ = new PreviewLoader(*this);
1224 return d->preview_loader_;
1228 void Buffer::removePreviews() const
1230 delete d->preview_loader_;
1231 d->preview_loader_ = 0;
1235 void Buffer::updatePreviews() const
1237 PreviewLoader * ploader = loader();
1241 InsetIterator it = inset_iterator_begin(*d->inset);
1242 InsetIterator const end = inset_iterator_end(*d->inset);
1243 for (; it != end; ++it)
1244 it->addPreview(it, *ploader);
1246 ploader->startLoading();
1250 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1251 FileName const & fn, int & file_format) const
1253 if(!lex.checkFor("\\lyxformat")) {
1254 Alert::error(_("Document format failure"),
1255 bformat(_("%1$s is not a readable LyX document."),
1256 from_utf8(fn.absFileName())));
1257 return ReadNoLyXFormat;
1263 // LyX formats 217 and earlier were written as 2.17. This corresponds
1264 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1265 // these cases. See also: www.lyx.org/trac/changeset/1313.
1266 size_t dot = tmp_format.find_first_of(".,");
1267 if (dot != string::npos)
1268 tmp_format.erase(dot, 1);
1270 file_format = convert<int>(tmp_format);
1275 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1276 FileName & tmpfile, int from_format)
1278 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1279 tempfile.setAutoRemove(false);
1280 tmpfile = tempfile.name();
1281 if(tmpfile.empty()) {
1282 Alert::error(_("Conversion failed"),
1283 bformat(_("%1$s is from a different"
1284 " version of LyX, but a temporary"
1285 " file for converting it could"
1286 " not be created."),
1287 from_utf8(fn.absFileName())));
1288 return LyX2LyXNoTempFile;
1291 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1292 if (lyx2lyx.empty()) {
1293 Alert::error(_("Conversion script not found"),
1294 bformat(_("%1$s is from a different"
1295 " version of LyX, but the"
1296 " conversion script lyx2lyx"
1297 " could not be found."),
1298 from_utf8(fn.absFileName())));
1299 return LyX2LyXNotFound;
1303 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1304 ostringstream command;
1305 command << os::python()
1306 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1307 << " -t " << convert<string>(LYX_FORMAT)
1308 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1309 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1310 string const command_str = command.str();
1312 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1314 cmd_ret const ret = runCommand(command_str);
1315 if (ret.first != 0) {
1316 if (from_format < LYX_FORMAT) {
1317 Alert::error(_("Conversion script failed"),
1318 bformat(_("%1$s is from an older version"
1319 " of LyX and the lyx2lyx script"
1320 " failed to convert it."),
1321 from_utf8(fn.absFileName())));
1322 return LyX2LyXOlderFormat;
1324 Alert::error(_("Conversion script failed"),
1325 bformat(_("%1$s is from a newer version"
1326 " of LyX and the lyx2lyx script"
1327 " failed to convert it."),
1328 from_utf8(fn.absFileName())));
1329 return LyX2LyXNewerFormat;
1336 FileName Buffer::getBackupName() const {
1337 map<int, string> const file_formats = {
1354 FileName const & fn = fileName();
1355 string const fname = fn.onlyFileNameWithoutExt();
1356 string const fext = fn.extension() + "~";
1357 string const fpath = lyxrc.backupdir_path.empty() ?
1358 fn.onlyPath().absFileName() :
1359 lyxrc.backupdir_path;
1360 string backup_suffix;
1361 // If file format is from a stable series use version instead of file format
1362 auto const it = file_formats.find(d->file_format);
1363 if (it != file_formats.end())
1364 backup_suffix = "-lyx" + it->second;
1366 backup_suffix = "-lyxformat-" + convert<string>(d->file_format);
1367 string const backname = fname + backup_suffix;
1368 FileName backup(addName(fpath, addExtension(backname, fext)));
1370 // limit recursion, just in case
1372 unsigned long orig_checksum = 0;
1373 while (backup.exists() && v < 100) {
1374 if (orig_checksum == 0)
1375 orig_checksum = fn.checksum();
1376 unsigned long new_checksum = backup.checksum();
1377 if (orig_checksum == new_checksum) {
1378 LYXERR(Debug::FILES, "Not backing up " << fn <<
1379 "since " << backup << "has the same checksum.");
1380 // a bit of a hack, but we have to check this anyway
1381 // below, and setting this is simpler than introducing
1382 // a special boolean for this purpose.
1386 string const newbackname = backname + "-" + convert<string>(v);
1387 backup.set(addName(fpath, addExtension(newbackname, fext)));
1390 return v < 100 ? backup : FileName();
1394 // Should probably be moved to somewhere else: BufferView? GuiView?
1395 bool Buffer::save() const
1397 docstring const file = makeDisplayPath(absFileName(), 20);
1398 d->filename.refresh();
1400 // check the read-only status before moving the file as a backup
1401 if (d->filename.exists()) {
1402 bool const read_only = !d->filename.isWritable();
1404 Alert::warning(_("File is read-only"),
1405 bformat(_("The file %1$s cannot be written because it "
1406 "is marked as read-only."), file));
1411 // ask if the disk file has been externally modified (use checksum method)
1412 if (fileName().exists() && isChecksumModified()) {
1414 bformat(_("Document %1$s has been externally modified. "
1415 "Are you sure you want to overwrite this file?"), file);
1416 int const ret = Alert::prompt(_("Overwrite modified file?"),
1417 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1422 // We don't need autosaves in the immediate future. (Asger)
1423 resetAutosaveTimers();
1425 // if the file does not yet exist, none of the backup activity
1426 // that follows is necessary
1427 if (!fileName().exists()) {
1428 if (!writeFile(fileName()))
1434 // we first write the file to a new name, then move it to its
1435 // proper location once that has been done successfully. that
1436 // way we preserve the original file if something goes wrong.
1437 string const justname = fileName().onlyFileNameWithoutExt();
1438 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1439 justname + "-XXXXXX.lyx");
1440 bool const symlink = fileName().isSymLink();
1442 tempfile->setAutoRemove(false);
1444 FileName savefile(tempfile->name());
1445 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1446 if (!savefile.clonePermissions(fileName()))
1447 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1449 if (!writeFile(savefile))
1452 // we will set this to false if we fail
1453 bool made_backup = true;
1455 FileName backupName;
1456 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1458 if (d->need_format_backup)
1459 backupName = getBackupName();
1461 // If we for some reason failed to find a backup name in case of
1462 // a format change, this will still set one. It's the best we can
1464 if (backupName.empty()) {
1465 backupName.set(fileName().absFileName() + "~");
1466 if (!lyxrc.backupdir_path.empty()) {
1467 string const mangledName =
1468 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1469 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1473 LYXERR(Debug::FILES, "Backing up original file to " <<
1474 backupName.absFileName());
1475 // Except file is symlink do not copy because of #6587.
1476 // Hard links have bad luck.
1477 made_backup = symlink ?
1478 fileName().copyTo(backupName):
1479 fileName().moveTo(backupName);
1482 Alert::error(_("Backup failure"),
1483 bformat(_("Cannot create backup file %1$s.\n"
1484 "Please check whether the directory exists and is writable."),
1485 from_utf8(backupName.absFileName())));
1486 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1487 } else if (d->need_format_backup) {
1488 // the original file has been backed up successfully, so we
1489 // will not need to do that again
1490 d->need_format_backup = false;
1494 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1495 // Only do this if tempfile is not in autoremove mode
1498 // If we have no symlink, we can simply rename the temp file.
1499 // Otherwise, we need to copy it so the symlink stays intact.
1500 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1501 savefile.moveTo(fileName()))
1503 // saveCheckSum() was already called by writeFile(), but the
1504 // time stamp is invalidated by copying/moving
1507 if (d->file_format != LYX_FORMAT)
1508 // the file associated with this buffer is now in the current format
1509 d->file_format = LYX_FORMAT;
1512 // else we saved the file, but failed to move it to the right location.
1514 if (needBackup && made_backup && !symlink) {
1515 // the original file was moved to some new location, so it will look
1516 // to the user as if it was deleted. (see bug #9234.) we could try
1517 // to restore it, but that would basically mean trying to do again
1518 // what we just failed to do. better to leave things as they are.
1519 Alert::error(_("Write failure"),
1520 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1521 "But LyX could not move it to:\n %2$s.\n"
1522 "Your original file has been backed up to:\n %3$s"),
1523 from_utf8(savefile.absFileName()),
1524 from_utf8(fileName().absFileName()),
1525 from_utf8(backupName.absFileName())));
1527 // either we did not try to make a backup, or else we tried and failed,
1528 // or else the original file was a symlink, in which case it was copied,
1529 // not moved. so the original file is intact.
1530 Alert::error(_("Write failure"),
1531 bformat(_("Cannot move saved file to:\n %1$s.\n"
1532 "But the file has successfully been saved as:\n %2$s."),
1533 from_utf8(fileName().absFileName()),
1534 from_utf8(savefile.absFileName())));
1540 bool Buffer::writeFile(FileName const & fname) const
1542 if (d->read_only && fname == d->filename)
1545 bool retval = false;
1547 docstring const str = bformat(_("Saving document %1$s..."),
1548 makeDisplayPath(fname.absFileName()));
1551 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1553 if (params().compressed) {
1554 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1555 retval = ofs && write(ofs);
1557 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1558 retval = ofs && write(ofs);
1562 message(str + _(" could not write file!"));
1567 // removeAutosaveFile();
1570 message(str + _(" done."));
1576 docstring Buffer::emergencyWrite()
1578 // No need to save if the buffer has not changed.
1582 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1584 docstring user_message = bformat(
1585 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1587 // We try to save three places:
1588 // 1) Same place as document. Unless it is an unnamed doc.
1590 string s = absFileName();
1593 if (writeFile(FileName(s))) {
1595 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1596 return user_message;
1598 user_message += " " + _("Save failed! Trying again...\n");
1602 // 2) In HOME directory.
1603 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1605 lyxerr << ' ' << s << endl;
1606 if (writeFile(FileName(s))) {
1608 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1609 return user_message;
1612 user_message += " " + _("Save failed! Trying yet again...\n");
1614 // 3) In "/tmp" directory.
1615 // MakeAbsPath to prepend the current
1616 // drive letter on OS/2
1617 s = addName(package().temp_dir().absFileName(), absFileName());
1619 lyxerr << ' ' << s << endl;
1620 if (writeFile(FileName(s))) {
1622 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1623 return user_message;
1626 user_message += " " + _("Save failed! Document is lost.");
1629 return user_message;
1633 bool Buffer::write(ostream & ofs) const
1636 // Use the standard "C" locale for file output.
1637 ofs.imbue(locale::classic());
1640 // The top of the file should not be written by params().
1642 // write out a comment in the top of the file
1643 // Important: Keep the version formatting in sync with lyx2lyx and
1644 // tex2lyx (bug 7951)
1645 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1646 << " created this file. For more info see https://www.lyx.org/\n"
1647 << "\\lyxformat " << LYX_FORMAT << "\n"
1648 << "\\begin_document\n";
1650 /// For each author, set 'used' to true if there is a change
1651 /// by this author in the document; otherwise set it to 'false'.
1652 for (Author const & a : params().authors())
1655 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1656 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1657 for ( ; it != end; ++it)
1658 it->checkAuthors(params().authors());
1660 // now write out the buffer parameters.
1661 ofs << "\\begin_header\n";
1662 params().writeFile(ofs, this);
1663 ofs << "\\end_header\n";
1666 ofs << "\n\\begin_body\n";
1668 ofs << "\n\\end_body\n";
1670 // Write marker that shows file is complete
1671 ofs << "\\end_document" << endl;
1673 // Shouldn't really be needed....
1676 // how to check if close went ok?
1677 // Following is an attempt... (BE 20001011)
1679 // good() returns false if any error occurred, including some
1680 // formatting error.
1681 // bad() returns true if something bad happened in the buffer,
1682 // which should include file system full errors.
1687 lyxerr << "File was not closed properly." << endl;
1694 Buffer::ExportStatus Buffer::makeLaTeXFile(FileName const & fname,
1695 string const & original_path,
1696 OutputParams const & runparams_in,
1697 OutputWhat output) const
1699 OutputParams runparams = runparams_in;
1701 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1702 // Check here, because the "flavor" is not known in BufferParams::encoding()
1703 // (power users can override this safety measure selecting "utf8-plain").
1704 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1705 && (runparams.encoding->name() != "utf8-plain"))
1706 runparams.encoding = encodings.fromLyXName("ascii");
1708 string const encoding = runparams.encoding->iconvName();
1709 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1712 try { ofs.reset(encoding); }
1713 catch (iconv_codecvt_facet_exception const & e) {
1714 lyxerr << "Caught iconv exception: " << e.what() << endl;
1715 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1716 "verify that the support software for your encoding (%1$s) is "
1717 "properly installed"), from_ascii(encoding)));
1720 if (!openFileWrite(ofs, fname))
1723 ErrorList & errorList = d->errorLists["Export"];
1725 ExportStatus status = ExportSuccess;
1728 // make sure we are ready to export
1729 // this needs to be done before we validate
1730 // FIXME Do we need to do this all the time? I.e., in children
1731 // of a master we are exporting?
1733 updateMacroInstances(OutputUpdate);
1735 ExportStatus retval;
1737 retval = writeLaTeXSource(os, original_path, runparams, output);
1738 if (retval == ExportKilled)
1739 return ExportKilled;
1741 catch (EncodingException const & e) {
1742 docstring const failed(1, e.failed_char);
1744 oss << "0x" << hex << e.failed_char << dec;
1745 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1746 docstring msg = bformat(_("Uncodable character '%1$s'"
1747 " (code point %2$s)"),
1748 failed, from_utf8(oss.str()));
1749 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1750 "representable in specific verbatim contexts.\n"
1751 "Changing the document encoding to utf8 could help."),
1752 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1754 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1755 " (code point %2$s)"),
1756 failed, from_utf8(oss.str()));
1757 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1758 "representable in the chosen encoding.\n"
1759 "Changing the document encoding to utf8 could help."),
1760 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1762 status = ExportError;
1764 catch (iconv_codecvt_facet_exception const & e) {
1765 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1767 status = ExportError;
1769 catch (exception const & e) {
1770 errorList.push_back(ErrorItem(_("conversion failed"),
1772 lyxerr << e.what() << endl;
1773 status = ExportError;
1776 lyxerr << "Caught some really weird exception..." << endl;
1780 d->texrow = move(os.texrow());
1784 status = ExportError;
1785 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1788 if (runparams_in.silent)
1796 Buffer::ExportStatus Buffer::writeLaTeXSource(otexstream & os,
1797 string const & original_path,
1798 OutputParams const & runparams_in,
1799 OutputWhat output) const
1801 // The child documents, if any, shall be already loaded at this point.
1803 OutputParams runparams = runparams_in;
1805 // XeTeX with TeX fonts is only safe with ASCII encoding,
1806 // Check here, because the "flavor" is not known in BufferParams::encoding()
1807 // (power users can override this safety measure selecting "utf8-plain").
1808 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1809 && (runparams.encoding->name() != "utf8-plain"))
1810 runparams.encoding = encodings.fromLyXName("ascii");
1811 // FIXME: when only the current paragraph is shown, this is ignored
1812 // (or not reached) and characters encodable in the current
1813 // encoding are not converted to ASCII-representation.
1815 // Some macros rely on font encoding
1816 runparams.main_fontenc = params().main_font_encoding();
1818 // If we are compiling a file standalone, even if this is the
1819 // child of some other buffer, let's cut the link here, so the
1820 // file is really independent and no concurring settings from
1821 // the master (e.g. branch state) interfere (see #8100).
1822 if (!runparams.is_child)
1823 d->ignore_parent = true;
1825 // Classify the unicode characters appearing in math insets
1826 BufferEncodings::initUnicodeMath(*this);
1828 // validate the buffer.
1829 LYXERR(Debug::LATEX, " Validating buffer...");
1830 LaTeXFeatures features(*this, params(), runparams);
1832 // This is only set once per document (in master)
1833 if (!runparams.is_child)
1834 runparams.use_polyglossia = features.usePolyglossia();
1835 LYXERR(Debug::LATEX, " Buffer validation done.");
1837 bool const output_preamble =
1838 output == FullSource || output == OnlyPreamble;
1839 bool const output_body =
1840 output == FullSource || output == OnlyBody;
1842 // The starting paragraph of the coming rows is the
1843 // first paragraph of the document. (Asger)
1844 if (output_preamble && runparams.nice) {
1845 os << "%% LyX " << lyx_version << " created this file. "
1846 "For more info, see https://www.lyx.org/.\n"
1847 "%% Do not edit unless you really know what "
1850 LYXERR(Debug::INFO, "lyx document header finished");
1852 // There are a few differences between nice LaTeX and usual files:
1853 // usual files have \batchmode and special input@path to allow
1854 // inclusion of figures specified by an explicitly relative path
1855 // (i.e., a path starting with './' or '../') with either \input or
1856 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1857 // input@path is set when the actual parameter original_path is set.
1858 // This is done for usual tex-file, but not for nice-latex-file.
1859 // (Matthias 250696)
1860 // Note that input@path is only needed for something the user does
1861 // in the preamble, included .tex files or ERT, files included by
1862 // LyX work without it.
1863 if (output_preamble) {
1864 if (!runparams.nice) {
1865 // code for usual, NOT nice-latex-file
1866 os << "\\batchmode\n"; // changed from \nonstopmode
1868 if (!original_path.empty()) {
1870 // We don't know the encoding of inputpath
1871 docstring const inputpath = from_utf8(original_path);
1872 docstring uncodable_glyphs;
1873 Encoding const * const enc = runparams.encoding;
1875 for (size_t n = 0; n < inputpath.size(); ++n) {
1876 if (!enc->encodable(inputpath[n])) {
1877 docstring const glyph(1, inputpath[n]);
1878 LYXERR0("Uncodable character '"
1880 << "' in input path!");
1881 uncodable_glyphs += glyph;
1886 // warn user if we found uncodable glyphs.
1887 if (!uncodable_glyphs.empty()) {
1888 frontend::Alert::warning(
1889 _("Uncodable character in file path"),
1891 _("The path of your document\n"
1893 "contains glyphs that are unknown "
1894 "in the current document encoding "
1895 "(namely %2$s). This may result in "
1896 "incomplete output, unless "
1897 "TEXINPUTS contains the document "
1898 "directory and you don't use "
1899 "explicitly relative paths (i.e., "
1900 "paths starting with './' or "
1901 "'../') in the preamble or in ERT."
1902 "\n\nIn case of problems, choose "
1903 "an appropriate document encoding\n"
1904 "(such as utf8) or change the "
1906 inputpath, uncodable_glyphs));
1908 string docdir = os::latex_path(original_path);
1909 if (contains(docdir, '#')) {
1910 docdir = subst(docdir, "#", "\\#");
1911 os << "\\catcode`\\#=11"
1912 "\\def\\#{#}\\catcode`\\#=6\n";
1914 if (contains(docdir, '%')) {
1915 docdir = subst(docdir, "%", "\\%");
1916 os << "\\catcode`\\%=11"
1917 "\\def\\%{%}\\catcode`\\%=14\n";
1919 bool const detokenize = !isAscii(from_utf8(docdir));
1920 bool const quote = contains(docdir, ' ');
1921 os << "\\makeatletter\n"
1922 << "\\def\\input@path{{";
1924 os << "\\detokenize{";
1933 << "\\makeatother\n";
1937 // get parent macros (if this buffer has a parent) which will be
1938 // written at the document begin further down.
1939 MacroSet parentMacros;
1940 listParentMacros(parentMacros, features);
1942 // Write the preamble
1943 runparams.use_babel = params().writeLaTeX(os, features,
1944 d->filename.onlyPath());
1946 // Biblatex bibliographies are loaded here
1947 if (params().useBiblatex()) {
1948 vector<docstring> const bibfiles =
1949 prepareBibFilePaths(runparams, getBibfiles(), true);
1950 for (docstring const & file: bibfiles)
1951 os << "\\addbibresource{" << file << "}\n";
1954 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1955 && !features.hasOnlyPolyglossiaLanguages()) {
1958 vector<string> bll = features.getBabelExclusiveLanguages();
1959 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1962 for (string const & sit : bll) {
1967 blangs = bll.size() > 1 ?
1968 bformat(_("The languages %1$s are only supported by Babel."), langs)
1969 : bformat(_("The language %1$s is only supported by Babel."), langs);
1973 for (string const & pit : pll) {
1978 plangs = pll.size() > 1 ?
1979 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1980 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1981 if (!blangs.empty())
1985 frontend::Alert::warning(
1986 _("Incompatible Languages!"),
1988 _("You cannot use the following languages "
1989 "together in one LaTeX document because "
1990 "they require conflicting language packages:\n"
1995 // Japanese might be required only in some children of a document,
1996 // but once required, we must keep use_japanese true.
1997 runparams.use_japanese |= features.isRequired("japanese");
2000 // Restore the parenthood if needed
2001 if (!runparams.is_child)
2002 d->ignore_parent = false;
2003 return ExportSuccess;
2007 // mark the beginning of the body to separate it from InPreamble insets
2008 os.texrow().start(TexRow::beginDocument());
2009 os << "\\begin{document}\n";
2011 // mark the start of a new paragraph by simulating a newline,
2012 // so that os.afterParbreak() returns true at document start
2015 // output the parent macros
2016 for (auto const & mac : parentMacros) {
2017 int num_lines = mac->write(os.os(), true);
2018 os.texrow().newlines(num_lines);
2021 } // output_preamble
2023 LYXERR(Debug::INFO, "preamble finished, now the body.");
2027 latexParagraphs(*this, text(), os, runparams);
2029 catch (ConversionException const &) { return ExportKilled; }
2031 // Restore the parenthood if needed
2032 if (!runparams.is_child)
2033 d->ignore_parent = false;
2035 // add this just in case after all the paragraphs
2038 if (output_preamble) {
2039 os << "\\end{document}\n";
2040 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2042 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2044 runparams_in.encoding = runparams.encoding;
2046 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2047 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2048 return ExportSuccess;
2052 Buffer::ExportStatus Buffer::makeDocBookFile(FileName const & fname,
2053 OutputParams const & runparams,
2054 OutputWhat output) const
2056 LYXERR(Debug::LATEX, "makeDocBookFile...");
2059 if (!openFileWrite(ofs, fname))
2062 // make sure we are ready to export
2063 // this needs to be done before we validate
2065 updateMacroInstances(OutputUpdate);
2067 ExportStatus const retval =
2068 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2069 if (retval == ExportKilled)
2070 return ExportKilled;
2074 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2075 return ExportSuccess;
2079 Buffer::ExportStatus Buffer::writeDocBookSource(odocstream & os, string const & fname,
2080 OutputParams const & runparams,
2081 OutputWhat output) const
2083 LaTeXFeatures features(*this, params(), runparams);
2088 DocumentClass const & tclass = params().documentClass();
2089 string const & top_element = tclass.latexname();
2091 bool const output_preamble =
2092 output == FullSource || output == OnlyPreamble;
2093 bool const output_body =
2094 output == FullSource || output == OnlyBody;
2096 if (output_preamble) {
2097 if (runparams.flavor == OutputParams::XML)
2098 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2101 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2104 if (! tclass.class_header().empty())
2105 os << from_ascii(tclass.class_header());
2106 else if (runparams.flavor == OutputParams::XML)
2107 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2108 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2110 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2112 docstring preamble = params().preamble;
2113 if (runparams.flavor != OutputParams::XML ) {
2114 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2115 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2116 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2117 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2120 string const name = runparams.nice
2121 ? changeExtension(absFileName(), ".sgml") : fname;
2122 preamble += features.getIncludedFiles(name);
2123 preamble += features.getLyXSGMLEntities();
2125 if (!preamble.empty()) {
2126 os << "\n [ " << preamble << " ]";
2132 string top = top_element;
2134 if (runparams.flavor == OutputParams::XML)
2135 top += params().language->code();
2137 top += params().language->code().substr(0, 2);
2140 if (!params().options.empty()) {
2142 top += params().options;
2145 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2146 << " file was created by LyX " << lyx_version
2147 << "\n See https://www.lyx.org/ for more information -->\n";
2149 params().documentClass().counters().reset();
2151 sgml::openTag(os, top);
2154 docbookParagraphs(text(), *this, os, runparams);
2156 catch (ConversionException const &) { return ExportKilled; }
2157 sgml::closeTag(os, top_element);
2159 return ExportSuccess;
2163 Buffer::ExportStatus Buffer::makeLyXHTMLFile(FileName const & fname,
2164 OutputParams const & runparams) const
2166 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2169 if (!openFileWrite(ofs, fname))
2172 // make sure we are ready to export
2173 // this has to be done before we validate
2174 updateBuffer(UpdateMaster, OutputUpdate);
2175 updateMacroInstances(OutputUpdate);
2177 ExportStatus const retval = writeLyXHTMLSource(ofs, runparams, FullSource);
2178 if (retval == ExportKilled)
2183 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2188 Buffer::ExportStatus Buffer::writeLyXHTMLSource(odocstream & os,
2189 OutputParams const & runparams,
2190 OutputWhat output) const
2192 LaTeXFeatures features(*this, params(), runparams);
2194 d->bibinfo_.makeCitationLabels(*this);
2196 bool const output_preamble =
2197 output == FullSource || output == OnlyPreamble;
2198 bool const output_body =
2199 output == FullSource || output == OnlyBody || output == IncludedFile;
2201 if (output_preamble) {
2202 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2203 << "<!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"
2204 // FIXME Language should be set properly.
2205 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2207 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2208 // FIXME Presumably need to set this right
2209 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2211 docstring const & doctitle = features.htmlTitle();
2213 << (doctitle.empty() ?
2214 from_ascii("LyX Document") :
2215 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2218 docstring styles = features.getTClassHTMLPreamble();
2219 if (!styles.empty())
2220 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2222 styles = features.getPreambleSnippets().str;
2223 if (!styles.empty())
2224 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2226 // we will collect CSS information in a stream, and then output it
2227 // either here, as part of the header, or else in a separate file.
2228 odocstringstream css;
2229 styles = features.getCSSSnippets();
2230 if (!styles.empty())
2231 css << "/* LyX Provided Styles */\n" << styles << '\n';
2233 styles = features.getTClassHTMLStyles();
2234 if (!styles.empty())
2235 css << "/* Layout-provided Styles */\n" << styles << '\n';
2237 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2238 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2239 if (needfg || needbg) {
2240 css << "\nbody {\n";
2243 << from_ascii(X11hexname(params().fontcolor))
2246 css << " background-color: "
2247 << from_ascii(X11hexname(params().backgroundcolor))
2252 docstring const dstyles = css.str();
2253 if (!dstyles.empty()) {
2254 bool written = false;
2255 if (params().html_css_as_file) {
2256 // open a file for CSS info
2258 string const fcssname = addName(temppath(), "docstyle.css");
2259 FileName const fcssfile = FileName(fcssname);
2260 if (openFileWrite(ocss, fcssfile)) {
2264 // write link to header
2265 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2267 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2270 // we are here if the CSS is supposed to be written to the header
2271 // or if we failed to write it to an external file.
2273 os << "<style type='text/css'>\n"
2282 bool const output_body_tag = (output != IncludedFile);
2283 if (output_body_tag)
2284 os << "<body dir=\"auto\">\n";
2286 if (output != IncludedFile)
2287 // if we're an included file, the counters are in the master.
2288 params().documentClass().counters().reset();
2290 xhtmlParagraphs(text(), *this, xs, runparams);
2292 catch (ConversionException const &) { return ExportKilled; }
2293 if (output_body_tag)
2297 if (output_preamble)
2300 return ExportSuccess;
2304 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2305 // Other flags: -wall -v0 -x
2306 int Buffer::runChktex()
2310 // get LaTeX-Filename
2311 FileName const path(temppath());
2312 string const name = addName(path.absFileName(), latexName());
2313 string const org_path = filePath();
2315 PathChanger p(path); // path to LaTeX file
2316 message(_("Running chktex..."));
2318 // Generate the LaTeX file if neccessary
2319 OutputParams runparams(¶ms().encoding());
2320 runparams.flavor = OutputParams::LATEX;
2321 runparams.nice = false;
2322 runparams.linelen = lyxrc.plaintext_linelen;
2323 ExportStatus const retval =
2324 makeLaTeXFile(FileName(name), org_path, runparams);
2325 if (retval != ExportSuccess) {
2326 // error code on failure
2331 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2332 int const res = chktex.run(terr); // run chktex
2335 Alert::error(_("chktex failure"),
2336 _("Could not run chktex successfully."));
2338 ErrorList & errlist = d->errorLists["ChkTeX"];
2340 bufferErrors(terr, errlist);
2345 if (runparams.silent)
2346 d->errorLists["ChkTeX"].clear();
2354 void Buffer::validate(LaTeXFeatures & features) const
2356 // Validate the buffer params, but not for included
2357 // files, since they also use the parent buffer's
2359 if (!features.runparams().is_child)
2360 params().validate(features);
2362 for (Paragraph const & p : paragraphs())
2363 p.validate(features);
2365 if (lyxerr.debugging(Debug::LATEX)) {
2366 features.showStruct();
2371 void Buffer::getLabelList(vector<docstring> & list) const
2373 // If this is a child document, use the master's list instead.
2375 masterBuffer()->getLabelList(list);
2380 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2381 for (auto const & tocit : *toc) {
2382 if (tocit.depth() == 0)
2383 list.push_back(tocit.str());
2388 void Buffer::invalidateBibinfoCache() const
2390 d->bibinfo_cache_valid_ = false;
2391 d->cite_labels_valid_ = false;
2392 removeBiblioTempFiles();
2393 // also invalidate the cache for the parent buffer
2394 Buffer const * const pbuf = d->parent();
2396 pbuf->invalidateBibinfoCache();
2400 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2402 // FIXME This is probably unnecessary, given where we call this.
2403 // If this is a child document, use the master instead.
2404 Buffer const * const pbuf = masterBuffer();
2405 if (pbuf != this && scope != UpdateChildOnly)
2406 return pbuf->getBibfiles();
2407 return d->bibfiles_cache_;
2411 BiblioInfo const & Buffer::masterBibInfo() const
2413 Buffer const * const tmp = masterBuffer();
2415 return tmp->masterBibInfo();
2420 BiblioInfo const & Buffer::bibInfo() const
2426 void Buffer::registerBibfiles(const docstring_list & bf) const
2428 // We register the bib files in the master buffer,
2429 // if there is one, but also in every single buffer,
2430 // in case a child is compiled alone.
2431 Buffer const * const tmp = masterBuffer();
2433 tmp->registerBibfiles(bf);
2435 for (auto const & p : bf) {
2436 docstring_list::const_iterator temp =
2437 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2438 if (temp == d->bibfiles_cache_.end())
2439 d->bibfiles_cache_.push_back(p);
2444 static map<docstring, FileName> bibfileCache;
2446 FileName Buffer::getBibfilePath(docstring const & bibid) const
2448 map<docstring, FileName>::const_iterator it =
2449 bibfileCache.find(bibid);
2450 if (it != bibfileCache.end()) {
2451 // i.e., bibfileCache[bibid]
2455 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2456 string texfile = changeExtension(to_utf8(bibid), "bib");
2457 // note that, if the filename can be found directly from the path,
2458 // findtexfile will just return a FileName object for that path.
2459 FileName file(findtexfile(texfile, "bib"));
2461 file = FileName(makeAbsPath(texfile, filePath()));
2462 LYXERR(Debug::FILES, "Found at: " << file);
2464 bibfileCache[bibid] = file;
2465 return bibfileCache[bibid];
2469 void Buffer::checkIfBibInfoCacheIsValid() const
2471 // use the master's cache
2472 Buffer const * const tmp = masterBuffer();
2474 tmp->checkIfBibInfoCacheIsValid();
2478 // if we already know the cache is invalid, no need to check
2480 if (!d->bibinfo_cache_valid_)
2483 // we'll assume it's ok and change this if it's not
2484 d->bibinfo_cache_valid_ = true;
2485 d->cite_labels_valid_ = true;
2487 // compare the cached timestamps with the actual ones.
2488 docstring_list const & bibfiles_cache = getBibfiles();
2489 for (auto const & bf : bibfiles_cache) {
2490 FileName const fn = getBibfilePath(bf);
2491 time_t lastw = fn.lastModified();
2492 time_t prevw = d->bibfile_status_[fn];
2493 if (lastw != prevw) {
2494 d->bibinfo_cache_valid_ = false;
2495 d->cite_labels_valid_ = false;
2496 d->bibfile_status_[fn] = lastw;
2502 void Buffer::clearBibFileCache() const
2504 bibfileCache.clear();
2508 void Buffer::reloadBibInfoCache(bool const force) const
2510 // we should not need to do this for internal buffers
2514 // use the master's cache
2515 Buffer const * const tmp = masterBuffer();
2517 tmp->reloadBibInfoCache(force);
2522 checkIfBibInfoCacheIsValid();
2523 if (d->bibinfo_cache_valid_)
2527 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2528 // re-read file locations when this info changes
2529 // FIXME Is this sufficient? Or should we also force that
2530 // in some other cases? If so, then it is easy enough to
2531 // add the following line in some other places.
2532 clearBibFileCache();
2533 d->bibinfo_.clear();
2534 FileNameList checkedFiles;
2535 collectBibKeys(checkedFiles);
2536 d->bibinfo_cache_valid_ = true;
2540 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2542 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2543 it->collectBibKeys(it, checkedFiles);
2547 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2549 // We add the biblio info to the master buffer,
2550 // if there is one, but also to every single buffer,
2551 // in case a child is compiled alone.
2552 BiblioInfo & bi = d->bibinfo_;
2553 bi.mergeBiblioInfo(bin);
2555 if (parent() != 0) {
2556 BiblioInfo & masterbi = parent()->d->bibinfo_;
2557 masterbi.mergeBiblioInfo(bin);
2562 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2564 // We add the bibtex info to the master buffer,
2565 // if there is one, but also to every single buffer,
2566 // in case a child is compiled alone.
2567 BiblioInfo & bi = d->bibinfo_;
2570 if (parent() != 0) {
2571 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2572 masterbi[key] = bin;
2577 void Buffer::makeCitationLabels() const
2579 Buffer const * const master = masterBuffer();
2580 return d->bibinfo_.makeCitationLabels(*master);
2584 void Buffer::invalidateCiteLabels() const
2586 masterBuffer()->d->cite_labels_valid_ = false;
2589 bool Buffer::citeLabelsValid() const
2591 return masterBuffer()->d->cite_labels_valid_;
2595 void Buffer::removeBiblioTempFiles() const
2597 // We remove files that contain LaTeX commands specific to the
2598 // particular bibliographic style being used, in order to avoid
2599 // LaTeX errors when we switch style.
2600 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2601 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2602 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2603 aux_file.removeFile();
2604 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2605 bbl_file.removeFile();
2606 // Also for the parent buffer
2607 Buffer const * const pbuf = parent();
2609 pbuf->removeBiblioTempFiles();
2613 bool Buffer::isDepClean(string const & name) const
2615 DepClean::const_iterator const it = d->dep_clean.find(name);
2616 if (it == d->dep_clean.end())
2622 void Buffer::markDepClean(string const & name)
2624 d->dep_clean[name] = true;
2628 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2631 // FIXME? if there is an Buffer LFUN that can be dispatched even
2632 // if internal, put a switch '(cmd.action)' here.
2638 switch (cmd.action()) {
2640 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2641 flag.setOnOff(hasReadonlyFlag());
2644 // FIXME: There is need for a command-line import.
2645 //case LFUN_BUFFER_IMPORT:
2647 case LFUN_BUFFER_AUTO_SAVE:
2650 case LFUN_BUFFER_EXPORT_CUSTOM:
2651 // FIXME: Nothing to check here?
2654 case LFUN_BUFFER_EXPORT: {
2655 docstring const arg = cmd.argument();
2656 if (arg == "custom") {
2660 string format = (arg.empty() || arg == "default") ?
2661 params().getDefaultOutputFormat() : to_utf8(arg);
2662 size_t pos = format.find(' ');
2663 if (pos != string::npos)
2664 format = format.substr(0, pos);
2665 enable = params().isExportable(format, false);
2667 flag.message(bformat(
2668 _("Don't know how to export to format: %1$s"), arg));
2672 case LFUN_BUILD_PROGRAM:
2673 enable = params().isExportable("program", false);
2676 case LFUN_BRANCH_ACTIVATE:
2677 case LFUN_BRANCH_DEACTIVATE:
2678 case LFUN_BRANCH_MASTER_ACTIVATE:
2679 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2680 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2681 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2682 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2683 : params().branchlist();
2684 docstring const branchName = cmd.argument();
2685 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2689 case LFUN_BRANCH_ADD:
2690 case LFUN_BRANCHES_RENAME:
2691 // if no Buffer is present, then of course we won't be called!
2694 case LFUN_BUFFER_LANGUAGE:
2695 enable = !isReadonly();
2698 case LFUN_BUFFER_VIEW_CACHE:
2699 (d->preview_file_).refresh();
2700 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2703 case LFUN_CHANGES_TRACK:
2704 flag.setEnabled(true);
2705 flag.setOnOff(params().track_changes);
2708 case LFUN_CHANGES_OUTPUT:
2709 flag.setEnabled(true);
2710 flag.setOnOff(params().output_changes);
2713 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2714 flag.setOnOff(params().compressed);
2717 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2718 flag.setOnOff(params().output_sync);
2721 case LFUN_BUFFER_ANONYMIZE:
2727 flag.setEnabled(enable);
2732 void Buffer::dispatch(string const & command, DispatchResult & result)
2734 return dispatch(lyxaction.lookupFunc(command), result);
2738 // NOTE We can end up here even if we have no GUI, because we are called
2739 // by LyX::exec to handled command-line requests. So we may need to check
2740 // whether we have a GUI or not. The boolean use_gui holds this information.
2741 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2744 // FIXME? if there is an Buffer LFUN that can be dispatched even
2745 // if internal, put a switch '(cmd.action())' here.
2746 dr.dispatched(false);
2749 string const argument = to_utf8(func.argument());
2750 // We'll set this back to false if need be.
2751 bool dispatched = true;
2752 // This handles undo groups automagically
2753 UndoGroupHelper ugh(this);
2755 switch (func.action()) {
2756 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2757 if (lyxvc().inUse()) {
2758 string log = lyxvc().toggleReadOnly();
2763 setReadonly(!hasReadonlyFlag());
2766 case LFUN_BUFFER_EXPORT: {
2767 string const format = (argument.empty() || argument == "default") ?
2768 params().getDefaultOutputFormat() : argument;
2769 ExportStatus const status = doExport(format, false);
2770 dr.setError(status != ExportSuccess);
2771 if (status != ExportSuccess)
2772 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2773 from_utf8(format)));
2777 case LFUN_BUILD_PROGRAM: {
2778 ExportStatus const status = doExport("program", true);
2779 dr.setError(status != ExportSuccess);
2780 if (status != ExportSuccess)
2781 dr.setMessage(_("Error generating literate programming code."));
2785 case LFUN_BUFFER_EXPORT_CUSTOM: {
2787 string command = split(argument, format_name, ' ');
2788 Format const * format = theFormats().getFormat(format_name);
2790 lyxerr << "Format \"" << format_name
2791 << "\" not recognized!"
2796 // The name of the file created by the conversion process
2799 // Output to filename
2800 if (format->name() == "lyx") {
2801 string const latexname = latexName(false);
2802 filename = changeExtension(latexname,
2803 format->extension());
2804 filename = addName(temppath(), filename);
2806 if (!writeFile(FileName(filename)))
2810 doExport(format_name, true, filename);
2813 // Substitute $$FName for filename
2814 if (!contains(command, "$$FName"))
2815 command = "( " + command + " ) < $$FName";
2816 command = subst(command, "$$FName", filename);
2818 // Execute the command in the background
2820 call.startscript(Systemcall::DontWait, command,
2821 filePath(), layoutPos());
2825 // FIXME: There is need for a command-line import.
2827 case LFUN_BUFFER_IMPORT:
2832 case LFUN_BUFFER_AUTO_SAVE:
2834 resetAutosaveTimers();
2837 case LFUN_BRANCH_ACTIVATE:
2838 case LFUN_BRANCH_DEACTIVATE:
2839 case LFUN_BRANCH_MASTER_ACTIVATE:
2840 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2841 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2842 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2843 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2846 docstring const branch_name = func.argument();
2847 // the case without a branch name is handled elsewhere
2848 if (branch_name.empty()) {
2852 Branch * branch = buf->params().branchlist().find(branch_name);
2854 LYXERR0("Branch " << branch_name << " does not exist.");
2856 docstring const msg =
2857 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2861 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2862 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2863 if (branch->isSelected() != activate) {
2864 buf->undo().recordUndoBufferParams(CursorData());
2865 branch->setSelected(activate);
2867 dr.screenUpdate(Update::Force);
2868 dr.forceBufferUpdate();
2873 case LFUN_BRANCH_ADD: {
2874 docstring branchnames = func.argument();
2875 if (branchnames.empty()) {
2879 BranchList & branch_list = params().branchlist();
2880 vector<docstring> const branches =
2881 getVectorFromString(branchnames, branch_list.separator());
2883 for (docstring const & branch_name : branches) {
2884 Branch * branch = branch_list.find(branch_name);
2886 LYXERR0("Branch " << branch_name << " already exists.");
2890 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2892 undo().recordUndoBufferParams(CursorData());
2893 branch_list.add(branch_name);
2894 branch = branch_list.find(branch_name);
2895 string const x11hexname = X11hexname(branch->color());
2896 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2897 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2899 dr.screenUpdate(Update::Force);
2907 case LFUN_BRANCHES_RENAME: {
2908 if (func.argument().empty())
2911 docstring const oldname = from_utf8(func.getArg(0));
2912 docstring const newname = from_utf8(func.getArg(1));
2913 InsetIterator it = inset_iterator_begin(inset());
2914 InsetIterator const end = inset_iterator_end(inset());
2915 bool success = false;
2916 for (; it != end; ++it) {
2917 if (it->lyxCode() == BRANCH_CODE) {
2918 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2919 if (ins.branch() == oldname) {
2920 undo().recordUndo(CursorData(it));
2921 ins.rename(newname);
2926 if (it->lyxCode() == INCLUDE_CODE) {
2927 // get buffer of external file
2928 InsetInclude const & ins =
2929 static_cast<InsetInclude const &>(*it);
2930 Buffer * child = ins.getChildBuffer();
2933 child->dispatch(func, dr);
2938 dr.screenUpdate(Update::Force);
2939 dr.forceBufferUpdate();
2944 case LFUN_BUFFER_VIEW_CACHE:
2945 if (!theFormats().view(*this, d->preview_file_,
2946 d->preview_format_))
2947 dr.setMessage(_("Error viewing the output file."));
2950 case LFUN_CHANGES_TRACK:
2951 if (params().save_transient_properties)
2952 undo().recordUndoBufferParams(CursorData());
2953 params().track_changes = !params().track_changes;
2954 if (!params().track_changes)
2955 dr.forceChangesUpdate();
2958 case LFUN_CHANGES_OUTPUT:
2959 if (params().save_transient_properties)
2960 undo().recordUndoBufferParams(CursorData());
2961 params().output_changes = !params().output_changes;
2962 if (params().output_changes) {
2963 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2964 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2965 LaTeXFeatures::isAvailable("xcolor");
2967 if (!dvipost && !xcolorulem) {
2968 Alert::warning(_("Changes not shown in LaTeX output"),
2969 _("Changes will not be highlighted in LaTeX output, "
2970 "because neither dvipost nor xcolor/ulem are installed.\n"
2971 "Please install these packages or redefine "
2972 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2973 } else if (!xcolorulem) {
2974 Alert::warning(_("Changes not shown in LaTeX output"),
2975 _("Changes will not be highlighted in LaTeX output "
2976 "when using pdflatex, because xcolor and ulem are not installed.\n"
2977 "Please install both packages or redefine "
2978 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2983 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2984 // turn compression on/off
2985 undo().recordUndoBufferParams(CursorData());
2986 params().compressed = !params().compressed;
2989 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2990 undo().recordUndoBufferParams(CursorData());
2991 params().output_sync = !params().output_sync;
2994 case LFUN_BUFFER_ANONYMIZE: {
2995 undo().recordUndoFullBuffer(CursorData());
2996 CursorData cur(doc_iterator_begin(this));
2997 for ( ; cur ; cur.forwardPar())
2998 cur.paragraph().anonymize();
2999 dr.forceBufferUpdate();
3000 dr.screenUpdate(Update::Force);
3008 dr.dispatched(dispatched);
3012 void Buffer::changeLanguage(Language const * from, Language const * to)
3014 LASSERT(from, return);
3015 LASSERT(to, return);
3017 for_each(par_iterator_begin(),
3019 bind(&Paragraph::changeLanguage, _1, params(), from, to));
3023 bool Buffer::isMultiLingual() const
3025 ParConstIterator end = par_iterator_end();
3026 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3027 if (it->isMultiLingual(params()))
3034 std::set<Language const *> Buffer::getLanguages() const
3036 std::set<Language const *> langs;
3037 getLanguages(langs);
3042 void Buffer::getLanguages(std::set<Language const *> & langs) const
3044 ParConstIterator end = par_iterator_end();
3045 // add the buffer language, even if it's not actively used
3046 langs.insert(language());
3047 // iterate over the paragraphs
3048 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3049 it->getLanguages(langs);
3051 ListOfBuffers clist = getDescendents();
3052 for (auto const & cit : clist)
3053 cit->getLanguages(langs);
3057 DocIterator Buffer::getParFromID(int const id) const
3059 Buffer * buf = const_cast<Buffer *>(this);
3061 // This means non-existent
3062 return doc_iterator_end(buf);
3064 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3065 if (it.paragraph().id() == id)
3068 return doc_iterator_end(buf);
3072 bool Buffer::hasParWithID(int const id) const
3074 return !getParFromID(id).atEnd();
3078 ParIterator Buffer::par_iterator_begin()
3080 return ParIterator(doc_iterator_begin(this));
3084 ParIterator Buffer::par_iterator_end()
3086 return ParIterator(doc_iterator_end(this));
3090 ParConstIterator Buffer::par_iterator_begin() const
3092 return ParConstIterator(doc_iterator_begin(this));
3096 ParConstIterator Buffer::par_iterator_end() const
3098 return ParConstIterator(doc_iterator_end(this));
3102 Language const * Buffer::language() const
3104 return params().language;
3108 docstring const Buffer::B_(string const & l10n) const
3110 return params().B_(l10n);
3114 bool Buffer::isClean() const
3116 return d->lyx_clean;
3120 bool Buffer::isChecksumModified() const
3122 LASSERT(d->filename.exists(), return false);
3123 return d->checksum_ != d->filename.checksum();
3127 void Buffer::saveCheckSum() const
3129 FileName const & file = d->filename;
3131 d->checksum_ = file.exists() ? file.checksum()
3132 : 0; // in the case of save to a new file.
3136 void Buffer::markClean() const
3138 if (!d->lyx_clean) {
3139 d->lyx_clean = true;
3142 // if the .lyx file has been saved, we don't need an
3144 d->bak_clean = true;
3145 d->undo_.markDirty();
3146 clearExternalModification();
3150 void Buffer::setUnnamed(bool flag)
3156 bool Buffer::isUnnamed() const
3163 /// Don't check unnamed, here: isInternal() is used in
3164 /// newBuffer(), where the unnamed flag has not been set by anyone
3165 /// yet. Also, for an internal buffer, there should be no need for
3166 /// retrieving fileName() nor for checking if it is unnamed or not.
3167 bool Buffer::isInternal() const
3169 return d->internal_buffer;
3173 void Buffer::setInternal(bool flag)
3175 d->internal_buffer = flag;
3179 void Buffer::markDirty()
3182 d->lyx_clean = false;
3185 d->bak_clean = false;
3187 for (auto & depit : d->dep_clean)
3188 depit.second = false;
3192 FileName Buffer::fileName() const
3198 string Buffer::absFileName() const
3200 return d->filename.absFileName();
3204 string Buffer::filePath() const
3206 string const abs = d->filename.onlyPath().absFileName();
3209 int last = abs.length() - 1;
3211 return abs[last] == '/' ? abs : abs + '/';
3215 DocFileName Buffer::getReferencedFileName(string const & fn) const
3218 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3219 result.set(fn, filePath());
3221 // filePath() ends with a path separator
3222 FileName const test(filePath() + fn);
3224 result.set(fn, filePath());
3226 result.set(fn, params().origin);
3233 string const Buffer::prepareFileNameForLaTeX(string const & name,
3234 string const & ext, bool nice) const
3236 string const fname = makeAbsPath(name, filePath()).absFileName();
3237 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3243 return to_utf8(makeRelPath(from_utf8(fname),
3244 from_utf8(masterBuffer()->filePath())));
3248 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3249 docstring_list const & bibfilelist,
3250 bool const add_extension) const
3252 // If we are processing the LaTeX file in a temp directory then
3253 // copy the .bib databases to this temp directory, mangling their
3254 // names in the process. Store this mangled name in the list of
3256 // (We need to do all this because BibTeX *really*, *really*
3257 // can't handle "files with spaces" and Windows users tend to
3258 // use such filenames.)
3259 // Otherwise, store the (maybe absolute) path to the original,
3260 // unmangled database name.
3262 vector<docstring> res;
3264 // determine the export format
3265 string const tex_format = flavor2format(runparams.flavor);
3267 // check for spaces in paths
3268 bool found_space = false;
3270 for (auto const & bit : bibfilelist) {
3271 string utf8input = to_utf8(bit);
3273 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3274 FileName try_in_file =
3275 makeAbsPath(database + ".bib", filePath());
3276 bool not_from_texmf = try_in_file.isReadableFile();
3277 // If the file has not been found, try with the real file name
3278 // (it might come from a child in a sub-directory)
3279 if (!not_from_texmf) {
3280 try_in_file = getBibfilePath(bit);
3281 if (try_in_file.isReadableFile()) {
3282 // Check if the file is in texmf
3283 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3284 not_from_texmf = kpsefile.empty()
3285 || kpsefile.absFileName() != try_in_file.absFileName();
3287 // If this exists, make path relative to the master
3290 removeExtension(prepareFileNameForLaTeX(
3291 to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3292 from_utf8(filePath()))),
3293 ".bib", runparams.nice));
3297 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3299 // mangledFileName() needs the extension
3300 DocFileName const in_file = DocFileName(try_in_file);
3301 database = removeExtension(in_file.mangledFileName());
3302 FileName const out_file = makeAbsPath(database + ".bib",
3303 masterBuffer()->temppath());
3304 bool const success = in_file.copyTo(out_file);
3306 LYXERR0("Failed to copy '" << in_file
3307 << "' to '" << out_file << "'");
3309 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3310 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3311 if (!isValidLaTeXFileName(database)) {
3312 frontend::Alert::warning(_("Invalid filename"),
3313 _("The following filename will cause troubles "
3314 "when running the exported file through LaTeX: ") +
3315 from_utf8(database));
3317 if (!isValidDVIFileName(database)) {
3318 frontend::Alert::warning(_("Problematic filename for DVI"),
3319 _("The following filename can cause troubles "
3320 "when running the exported file through LaTeX "
3321 "and opening the resulting DVI: ") +
3322 from_utf8(database), true);
3330 docstring const path = from_utf8(latex_path(database));
3332 if (contains(path, ' '))
3335 if (find(res.begin(), res.end(), path) == res.end())
3336 res.push_back(path);
3339 // Check if there are spaces in the path and warn BibTeX users, if so.
3340 // (biber can cope with such paths)
3341 if (!prefixIs(runparams.bibtex_command, "biber")) {
3342 // Post this warning only once.
3343 static bool warned_about_spaces = false;
3344 if (!warned_about_spaces &&
3345 runparams.nice && found_space) {
3346 warned_about_spaces = true;
3347 Alert::warning(_("Export Warning!"),
3348 _("There are spaces in the paths to your BibTeX databases.\n"
3349 "BibTeX will be unable to find them."));
3358 string Buffer::layoutPos() const
3360 return d->layout_position;
3364 void Buffer::setLayoutPos(string const & path)
3367 d->layout_position.clear();
3371 LATTEST(FileName::isAbsolute(path));
3373 d->layout_position =
3374 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3376 if (d->layout_position.empty())
3377 d->layout_position = ".";
3381 bool Buffer::hasReadonlyFlag() const
3383 return d->read_only;
3387 bool Buffer::isReadonly() const
3389 return hasReadonlyFlag() || notifiesExternalModification();
3393 void Buffer::setParent(Buffer const * buffer)
3395 // Avoids recursive include.
3396 d->setParent(buffer == this ? 0 : buffer);
3401 Buffer const * Buffer::parent() const
3407 ListOfBuffers Buffer::allRelatives() const
3409 ListOfBuffers lb = masterBuffer()->getDescendents();
3410 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3415 Buffer const * Buffer::masterBuffer() const
3417 // FIXME Should be make sure we are not in some kind
3418 // of recursive include? A -> B -> A will crash this.
3419 Buffer const * const pbuf = d->parent();
3423 return pbuf->masterBuffer();
3427 bool Buffer::isChild(Buffer * child) const
3429 return d->children_positions.find(child) != d->children_positions.end();
3433 DocIterator Buffer::firstChildPosition(Buffer const * child)
3435 Impl::BufferPositionMap::iterator it;
3436 it = d->children_positions.find(child);
3437 if (it == d->children_positions.end())
3438 return DocIterator(this);
3443 bool Buffer::hasChildren() const
3445 return !d->children_positions.empty();
3449 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3451 // loop over children
3452 for (auto const & p : d->children_positions) {
3453 Buffer * child = const_cast<Buffer *>(p.first);
3455 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3456 if (bit != clist.end())
3458 clist.push_back(child);
3460 // there might be grandchildren
3461 child->collectChildren(clist, true);
3466 ListOfBuffers Buffer::getChildren() const
3469 collectChildren(v, false);
3470 // Make sure we have not included ourselves.
3471 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3472 if (bit != v.end()) {
3473 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3480 ListOfBuffers Buffer::getDescendents() const
3483 collectChildren(v, true);
3484 // Make sure we have not included ourselves.
3485 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3486 if (bit != v.end()) {
3487 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3494 template<typename M>
3495 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3500 typename M::const_iterator it = m.lower_bound(x);
3501 if (it == m.begin())
3509 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3510 DocIterator const & pos) const
3512 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3514 // if paragraphs have no macro context set, pos will be empty
3518 // we haven't found anything yet
3519 DocIterator bestPos = owner_->par_iterator_begin();
3520 MacroData const * bestData = 0;
3522 // find macro definitions for name
3523 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3524 if (nameIt != macros.end()) {
3525 // find last definition in front of pos or at pos itself
3526 PositionScopeMacroMap::const_iterator it
3527 = greatest_below(nameIt->second, pos);
3528 if (it != nameIt->second.end()) {
3530 // scope ends behind pos?
3531 if (pos < it->second.scope) {
3532 // Looks good, remember this. If there
3533 // is no external macro behind this,
3534 // we found the right one already.
3535 bestPos = it->first;
3536 bestData = &it->second.macro;
3540 // try previous macro if there is one
3541 if (it == nameIt->second.begin())
3548 // find macros in included files
3549 PositionScopeBufferMap::const_iterator it
3550 = greatest_below(position_to_children, pos);
3551 if (it == position_to_children.end())
3552 // no children before
3556 // do we know something better (i.e. later) already?
3557 if (it->first < bestPos )
3560 // scope ends behind pos?
3561 if (pos < it->second.scope
3562 && (cloned_buffer_ ||
3563 theBufferList().isLoaded(it->second.buffer))) {
3564 // look for macro in external file
3566 MacroData const * data
3567 = it->second.buffer->getMacro(name, false);
3570 bestPos = it->first;
3576 // try previous file if there is one
3577 if (it == position_to_children.begin())
3582 // return the best macro we have found
3587 MacroData const * Buffer::getMacro(docstring const & name,
3588 DocIterator const & pos, bool global) const
3593 // query buffer macros
3594 MacroData const * data = d->getBufferMacro(name, pos);
3598 // If there is a master buffer, query that
3599 Buffer const * const pbuf = d->parent();
3601 d->macro_lock = true;
3602 MacroData const * macro = pbuf->getMacro(
3603 name, *this, false);
3604 d->macro_lock = false;
3610 data = MacroTable::globalMacros().get(name);
3619 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3621 // set scope end behind the last paragraph
3622 DocIterator scope = par_iterator_begin();
3623 scope.pit() = scope.lastpit() + 1;
3625 return getMacro(name, scope, global);
3629 MacroData const * Buffer::getMacro(docstring const & name,
3630 Buffer const & child, bool global) const
3632 // look where the child buffer is included first
3633 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3634 if (it == d->children_positions.end())
3637 // check for macros at the inclusion position
3638 return getMacro(name, it->second, global);
3642 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3644 pit_type const lastpit = it.lastpit();
3646 // look for macros in each paragraph
3647 while (it.pit() <= lastpit) {
3648 Paragraph & par = it.paragraph();
3650 // FIXME Can this be done with the new-style iterators?
3651 // iterate over the insets of the current paragraph
3652 for (auto const & insit : par.insetList()) {
3653 it.pos() = insit.pos;
3655 // is it a nested text inset?
3656 if (insit.inset->asInsetText()) {
3657 // Inset needs its own scope?
3658 InsetText const * itext = insit.inset->asInsetText();
3659 bool newScope = itext->isMacroScope();
3661 // scope which ends just behind the inset
3662 DocIterator insetScope = it;
3665 // collect macros in inset
3666 it.push_back(CursorSlice(*insit.inset));
3667 updateMacros(it, newScope ? insetScope : scope);
3672 if (insit.inset->asInsetTabular()) {
3673 CursorSlice slice(*insit.inset);
3674 size_t const numcells = slice.nargs();
3675 for (; slice.idx() < numcells; slice.forwardIdx()) {
3676 it.push_back(slice);
3677 updateMacros(it, scope);
3683 // is it an external file?
3684 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3685 // get buffer of external file
3686 InsetInclude const & incinset =
3687 static_cast<InsetInclude const &>(*insit.inset);
3689 Buffer * child = incinset.getChildBuffer();
3694 // register its position, but only when it is
3695 // included first in the buffer
3696 if (children_positions.find(child) ==
3697 children_positions.end())
3698 children_positions[child] = it;
3700 // register child with its scope
3701 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3705 InsetMath * im = insit.inset->asInsetMath();
3706 if (doing_export && im) {
3707 InsetMathHull * hull = im->asHullInset();
3709 hull->recordLocation(it);
3712 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3716 InsetMathMacroTemplate & macroTemplate =
3717 *insit.inset->asInsetMath()->asMacroTemplate();
3718 MacroContext mc(owner_, it);
3719 macroTemplate.updateToContext(mc);
3722 bool valid = macroTemplate.validMacro();
3723 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3724 // then the BufferView's cursor will be invalid in
3725 // some cases which leads to crashes.
3730 // FIXME (Abdel), I don't understand why we pass 'it' here
3731 // instead of 'macroTemplate' defined above... is this correct?
3732 macros[macroTemplate.name()][it] =
3733 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3743 void Buffer::updateMacros() const
3748 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3750 // start with empty table
3752 d->children_positions.clear();
3753 d->position_to_children.clear();
3755 // Iterate over buffer, starting with first paragraph
3756 // The scope must be bigger than any lookup DocIterator
3757 // later. For the global lookup, lastpit+1 is used, hence
3758 // we use lastpit+2 here.
3759 DocIterator it = par_iterator_begin();
3760 DocIterator outerScope = it;
3761 outerScope.pit() = outerScope.lastpit() + 2;
3762 d->updateMacros(it, outerScope);
3766 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3768 InsetIterator it = inset_iterator_begin(inset());
3769 InsetIterator const end = inset_iterator_end(inset());
3770 for (; it != end; ++it) {
3771 if (it->lyxCode() == BRANCH_CODE) {
3772 InsetBranch & br = static_cast<InsetBranch &>(*it);
3773 docstring const name = br.branch();
3774 if (!from_master && !params().branchlist().find(name))
3775 result.push_back(name);
3776 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3777 result.push_back(name);
3780 if (it->lyxCode() == INCLUDE_CODE) {
3781 // get buffer of external file
3782 InsetInclude const & ins =
3783 static_cast<InsetInclude const &>(*it);
3784 Buffer * child = ins.getChildBuffer();
3787 child->getUsedBranches(result, true);
3790 // remove duplicates
3795 void Buffer::updateMacroInstances(UpdateType utype) const
3797 LYXERR(Debug::MACROS, "updateMacroInstances for "
3798 << d->filename.onlyFileName());
3799 DocIterator it = doc_iterator_begin(this);
3801 DocIterator const end = doc_iterator_end(this);
3802 for (; it != end; it.forwardInset()) {
3803 // look for MathData cells in InsetMathNest insets
3804 InsetMath * minset = it.nextInset()->asInsetMath();
3808 // update macro in all cells of the InsetMathNest
3809 DocIterator::idx_type n = minset->nargs();
3810 MacroContext mc = MacroContext(this, it);
3811 for (DocIterator::idx_type i = 0; i < n; ++i) {
3812 MathData & data = minset->cell(i);
3813 data.updateMacros(0, mc, utype, 0);
3819 void Buffer::listMacroNames(MacroNameSet & macros) const
3824 d->macro_lock = true;
3826 // loop over macro names
3827 for (auto const & nameit : d->macros)
3828 macros.insert(nameit.first);
3830 // loop over children
3831 for (auto const & p : d->children_positions) {
3832 Buffer * child = const_cast<Buffer *>(p.first);
3833 // The buffer might have been closed (see #10766).
3834 if (theBufferList().isLoaded(child))
3835 child->listMacroNames(macros);
3839 Buffer const * const pbuf = d->parent();
3841 pbuf->listMacroNames(macros);
3843 d->macro_lock = false;
3847 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3849 Buffer const * const pbuf = d->parent();
3854 pbuf->listMacroNames(names);
3857 for (auto const & mit : names) {
3859 MacroData const * data = pbuf->getMacro(mit, *this, false);
3861 macros.insert(data);
3863 // we cannot access the original InsetMathMacroTemplate anymore
3864 // here to calls validate method. So we do its work here manually.
3865 // FIXME: somehow make the template accessible here.
3866 if (data->optionals() > 0)
3867 features.require("xargs");
3873 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3876 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3878 RefCache::iterator it = d->ref_cache_.find(label);
3879 if (it != d->ref_cache_.end())
3880 return it->second.second;
3882 static InsetLabel const * dummy_il = 0;
3883 static References const dummy_refs = References();
3884 it = d->ref_cache_.insert(
3885 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3886 return it->second.second;
3890 Buffer::References const & Buffer::references(docstring const & label) const
3892 return const_cast<Buffer *>(this)->getReferenceCache(label);
3896 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3898 References & refs = getReferenceCache(label);
3899 refs.push_back(make_pair(inset, it));
3903 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3905 masterBuffer()->d->ref_cache_[label].first = il;
3909 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3911 return masterBuffer()->d->ref_cache_[label].first;
3915 void Buffer::clearReferenceCache() const
3918 d->ref_cache_.clear();
3922 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3924 //FIXME: This does not work for child documents yet.
3925 reloadBibInfoCache();
3927 // Check if the label 'from' appears more than once
3928 vector<docstring> labels;
3929 for (auto const & bibit : masterBibInfo())
3930 labels.push_back(bibit.first);
3932 if (count(labels.begin(), labels.end(), from) > 1)
3935 string const paramName = "key";
3936 InsetIterator it = inset_iterator_begin(inset());
3938 if (it->lyxCode() != CITE_CODE)
3940 InsetCommand * inset = it->asInsetCommand();
3941 docstring const oldValue = inset->getParam(paramName);
3942 if (oldValue == from)
3943 inset->setParam(paramName, to);
3947 // returns NULL if id-to-row conversion is unsupported
3948 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3949 pit_type par_begin, pit_type par_end,
3950 OutputWhat output, bool master) const
3952 unique_ptr<TexRow> texrow;
3953 OutputParams runparams(¶ms().encoding());
3954 runparams.nice = true;
3955 runparams.flavor = params().getOutputFlavor(format);
3956 runparams.linelen = lyxrc.plaintext_linelen;
3957 // No side effect of file copying and image conversion
3958 runparams.dryrun = true;
3960 // Some macros rely on font encoding
3961 runparams.main_fontenc = params().main_font_encoding();
3963 if (output == CurrentParagraph) {
3964 runparams.par_begin = par_begin;
3965 runparams.par_end = par_end;
3966 if (par_begin + 1 == par_end) {
3968 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3972 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3973 convert<docstring>(par_begin),
3974 convert<docstring>(par_end - 1))
3977 // output paragraphs
3978 if (runparams.flavor == OutputParams::LYX) {
3979 Paragraph const & par = text().paragraphs()[par_begin];
3981 depth_type dt = par.getDepth();
3982 par.write(ods, params(), dt);
3983 os << from_utf8(ods.str());
3984 } else if (runparams.flavor == OutputParams::HTML) {
3986 setMathFlavor(runparams);
3987 xhtmlParagraphs(text(), *this, xs, runparams);
3988 } else if (runparams.flavor == OutputParams::TEXT) {
3990 // FIXME Handles only one paragraph, unlike the others.
3991 // Probably should have some routine with a signature like them.
3992 writePlaintextParagraph(*this,
3993 text().paragraphs()[par_begin], os, runparams, dummy);
3994 } else if (params().isDocBook()) {
3995 docbookParagraphs(text(), *this, os, runparams);
3997 // If we are previewing a paragraph, even if this is the
3998 // child of some other buffer, let's cut the link here,
3999 // so that no concurring settings from the master
4000 // (e.g. branch state) interfere (see #8101).
4002 d->ignore_parent = true;
4003 // We need to validate the Buffer params' features here
4004 // in order to know if we should output polyglossia
4005 // macros (instead of babel macros)
4006 LaTeXFeatures features(*this, params(), runparams);
4008 runparams.use_polyglossia = features.usePolyglossia();
4009 // latex or literate
4012 ots.texrow().newlines(2);
4014 latexParagraphs(*this, text(), ots, runparams);
4015 texrow = ots.releaseTexRow();
4017 // Restore the parenthood
4019 d->ignore_parent = false;
4023 if (output == FullSource)
4024 os << _("Preview source code");
4025 else if (output == OnlyPreamble)
4026 os << _("Preview preamble");
4027 else if (output == OnlyBody)
4028 os << _("Preview body");
4030 if (runparams.flavor == OutputParams::LYX) {
4032 if (output == FullSource)
4034 else if (output == OnlyPreamble)
4035 params().writeFile(ods, this);
4036 else if (output == OnlyBody)
4038 os << from_utf8(ods.str());
4039 } else if (runparams.flavor == OutputParams::HTML) {
4040 writeLyXHTMLSource(os, runparams, output);
4041 } else if (runparams.flavor == OutputParams::TEXT) {
4042 if (output == OnlyPreamble) {
4043 os << "% "<< _("Plain text does not have a preamble.");
4045 writePlaintextFile(*this, os, runparams);
4046 } else if (params().isDocBook()) {
4047 writeDocBookSource(os, absFileName(), runparams, output);
4049 // latex or literate
4052 ots.texrow().newlines(2);
4054 runparams.is_child = true;
4056 writeLaTeXSource(ots, string(), runparams, output);
4057 texrow = ots.releaseTexRow();
4064 ErrorList & Buffer::errorList(string const & type) const
4066 return d->errorLists[type];
4070 void Buffer::updateTocItem(std::string const & type,
4071 DocIterator const & dit) const
4074 d->gui_->updateTocItem(type, dit);
4078 void Buffer::structureChanged() const
4081 d->gui_->structureChanged();
4085 void Buffer::errors(string const & err, bool from_master) const
4088 d->gui_->errors(err, from_master);
4092 void Buffer::message(docstring const & msg) const
4095 d->gui_->message(msg);
4099 void Buffer::setBusy(bool on) const
4102 d->gui_->setBusy(on);
4106 void Buffer::updateTitles() const
4109 d->wa_->updateTitles();
4113 void Buffer::resetAutosaveTimers() const
4116 d->gui_->resetAutosaveTimers();
4120 bool Buffer::hasGuiDelegate() const
4126 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4135 class AutoSaveBuffer : public ForkedProcess {
4138 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4139 : buffer_(buffer), fname_(fname) {}
4141 virtual shared_ptr<ForkedProcess> clone() const
4143 return make_shared<AutoSaveBuffer>(*this);
4148 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4149 from_utf8(fname_.absFileName())));
4150 return run(DontWait);
4154 virtual int generateChild();
4156 Buffer const & buffer_;
4161 int AutoSaveBuffer::generateChild()
4163 #if defined(__APPLE__)
4164 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4165 * We should use something else like threads.
4167 * Since I do not know how to determine at run time what is the OS X
4168 * version, I just disable forking altogether for now (JMarc)
4170 pid_t const pid = -1;
4172 // tmp_ret will be located (usually) in /tmp
4173 // will that be a problem?
4174 // Note that this calls ForkedCalls::fork(), so it's
4175 // ok cross-platform.
4176 pid_t const pid = fork();
4177 // If you want to debug the autosave
4178 // you should set pid to -1, and comment out the fork.
4179 if (pid != 0 && pid != -1)
4183 // pid = -1 signifies that lyx was unable
4184 // to fork. But we will do the save
4186 bool failed = false;
4187 TempFile tempfile("lyxautoXXXXXX.lyx");
4188 tempfile.setAutoRemove(false);
4189 FileName const tmp_ret = tempfile.name();
4190 if (!tmp_ret.empty()) {
4191 if (!buffer_.writeFile(tmp_ret))
4193 else if (!tmp_ret.moveTo(fname_))
4199 // failed to write/rename tmp_ret so try writing direct
4200 if (!buffer_.writeFile(fname_)) {
4201 // It is dangerous to do this in the child,
4202 // but safe in the parent, so...
4203 if (pid == -1) // emit message signal.
4204 buffer_.message(_("Autosave failed!"));
4208 if (pid == 0) // we are the child so...
4217 FileName Buffer::getEmergencyFileName() const
4219 return FileName(d->filename.absFileName() + ".emergency");
4223 FileName Buffer::getAutosaveFileName() const
4225 // if the document is unnamed try to save in the backup dir, else
4226 // in the default document path, and as a last try in the filePath,
4227 // which will most often be the temporary directory
4230 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4231 : lyxrc.backupdir_path;
4232 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4235 string const fname = "#" + d->filename.onlyFileName() + "#";
4237 return makeAbsPath(fname, fpath);
4241 void Buffer::removeAutosaveFile() const
4243 FileName const f = getAutosaveFileName();
4249 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4251 FileName const newauto = getAutosaveFileName();
4253 if (newauto != oldauto && oldauto.exists())
4254 if (!oldauto.moveTo(newauto))
4255 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4259 bool Buffer::autoSave() const
4261 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4262 if (buf->d->bak_clean || hasReadonlyFlag())
4265 message(_("Autosaving current document..."));
4266 buf->d->bak_clean = true;
4268 FileName const fname = getAutosaveFileName();
4269 LASSERT(d->cloned_buffer_, return false);
4271 // If this buffer is cloned, we assume that
4272 // we are running in a separate thread already.
4273 TempFile tempfile("lyxautoXXXXXX.lyx");
4274 tempfile.setAutoRemove(false);
4275 FileName const tmp_ret = tempfile.name();
4276 if (!tmp_ret.empty()) {
4278 // assume successful write of tmp_ret
4279 if (tmp_ret.moveTo(fname))
4282 // failed to write/rename tmp_ret so try writing direct
4283 return writeFile(fname);
4287 void Buffer::setExportStatus(bool e) const
4289 d->doing_export = e;
4290 ListOfBuffers clist = getDescendents();
4291 for (auto const & bit : clist)
4292 bit->d->doing_export = e;
4296 bool Buffer::isExporting() const
4298 return d->doing_export;
4302 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4306 return doExport(target, put_in_tempdir, result_file);
4309 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4310 string & result_file) const
4312 bool const update_unincluded =
4313 params().maintain_unincluded_children
4314 && !params().getIncludedChildren().empty();
4316 // (1) export with all included children (omit \includeonly)
4317 if (update_unincluded) {
4318 ExportStatus const status =
4319 doExport(target, put_in_tempdir, true, result_file);
4320 if (status != ExportSuccess)
4323 // (2) export with included children only
4324 return doExport(target, put_in_tempdir, false, result_file);
4328 void Buffer::setMathFlavor(OutputParams & op) const
4330 switch (params().html_math_output) {
4331 case BufferParams::MathML:
4332 op.math_flavor = OutputParams::MathAsMathML;
4334 case BufferParams::HTML:
4335 op.math_flavor = OutputParams::MathAsHTML;
4337 case BufferParams::Images:
4338 op.math_flavor = OutputParams::MathAsImages;
4340 case BufferParams::LaTeX:
4341 op.math_flavor = OutputParams::MathAsLaTeX;
4347 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4348 bool includeall, string & result_file) const
4350 LYXERR(Debug::FILES, "target=" << target);
4351 OutputParams runparams(¶ms().encoding());
4352 string format = target;
4353 string dest_filename;
4354 size_t pos = target.find(' ');
4355 if (pos != string::npos) {
4356 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4357 format = target.substr(0, pos);
4358 if (format == "default")
4359 format = params().getDefaultOutputFormat();
4360 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4361 FileName(dest_filename).onlyPath().createPath();
4362 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4364 MarkAsExporting exporting(this);
4365 string backend_format;
4366 runparams.flavor = OutputParams::LATEX;
4367 runparams.linelen = lyxrc.plaintext_linelen;
4368 runparams.includeall = includeall;
4369 vector<string> backs = params().backends();
4370 Converters converters = theConverters();
4371 bool need_nice_file = false;
4372 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4373 // Get shortest path to format
4374 converters.buildGraph();
4375 Graph::EdgePath path;
4376 for (string const & sit : backs) {
4377 Graph::EdgePath p = converters.getPath(sit, format);
4378 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4379 backend_format = sit;
4384 if (!put_in_tempdir) {
4385 // Only show this alert if this is an export to a non-temporary
4386 // file (not for previewing).
4387 Alert::error(_("Couldn't export file"), bformat(
4388 _("No information for exporting the format %1$s."),
4389 theFormats().prettyName(format)));
4391 return ExportNoPathToFormat;
4393 runparams.flavor = converters.getFlavor(path, this);
4394 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4395 for (auto const & edge : path)
4396 if (theConverters().get(edge).nice()) {
4397 need_nice_file = true;
4402 backend_format = format;
4403 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4404 // FIXME: Don't hardcode format names here, but use a flag
4405 if (backend_format == "pdflatex")
4406 runparams.flavor = OutputParams::PDFLATEX;
4407 else if (backend_format == "luatex")
4408 runparams.flavor = OutputParams::LUATEX;
4409 else if (backend_format == "dviluatex")
4410 runparams.flavor = OutputParams::DVILUATEX;
4411 else if (backend_format == "xetex")
4412 runparams.flavor = OutputParams::XETEX;
4415 string filename = latexName(false);
4416 filename = addName(temppath(), filename);
4417 filename = changeExtension(filename,
4418 theFormats().extension(backend_format));
4419 LYXERR(Debug::FILES, "filename=" << filename);
4421 // Plain text backend
4422 if (backend_format == "text") {
4423 runparams.flavor = OutputParams::TEXT;
4425 writePlaintextFile(*this, FileName(filename), runparams);
4427 catch (ConversionException const &) { return ExportCancel; }
4430 else if (backend_format == "xhtml") {
4431 runparams.flavor = OutputParams::HTML;
4432 setMathFlavor(runparams);
4433 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4434 return ExportKilled;
4435 } else if (backend_format == "lyx")
4436 writeFile(FileName(filename));
4438 else if (params().isDocBook()) {
4439 runparams.nice = !put_in_tempdir;
4440 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4441 return ExportKilled;
4444 else if (backend_format == format || need_nice_file) {
4445 runparams.nice = true;
4446 ExportStatus const retval =
4447 makeLaTeXFile(FileName(filename), string(), runparams);
4448 if (retval == ExportKilled)
4449 return ExportKilled;
4450 if (d->cloned_buffer_)
4451 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4452 if (retval != ExportSuccess)
4454 } else if (!lyxrc.tex_allows_spaces
4455 && contains(filePath(), ' ')) {
4456 Alert::error(_("File name error"),
4457 bformat(_("The directory path to the document\n%1$s\n"
4458 "contains spaces, but your TeX installation does "
4459 "not allow them. You should save the file to a directory "
4460 "whose name does not contain spaces."), from_ascii(filePath())));
4461 return ExportTexPathHasSpaces;
4463 runparams.nice = false;
4464 ExportStatus const retval =
4465 makeLaTeXFile(FileName(filename), filePath(), runparams);
4466 if (retval == ExportKilled)
4467 return ExportKilled;
4468 if (d->cloned_buffer_)
4469 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4470 if (retval != ExportSuccess)
4474 string const error_type = (format == "program")
4475 ? "Build" : params().bufferFormat();
4476 ErrorList & error_list = d->errorLists[error_type];
4477 string const ext = theFormats().extension(format);
4478 FileName const tmp_result_file(changeExtension(filename, ext));
4479 Converters::RetVal const retval =
4480 converters.convert(this, FileName(filename), tmp_result_file,
4481 FileName(absFileName()), backend_format, format, error_list);
4482 if (retval == Converters::KILLED)
4483 return ExportCancel;
4484 bool success = (retval == Converters::SUCCESS);
4486 // Emit the signal to show the error list or copy it back to the
4487 // cloned Buffer so that it can be emitted afterwards.
4488 if (format != backend_format) {
4489 if (runparams.silent)
4491 else if (d->cloned_buffer_)
4492 d->cloned_buffer_->d->errorLists[error_type] =
4493 d->errorLists[error_type];
4496 // also to the children, in case of master-buffer-view
4497 ListOfBuffers clist = getDescendents();
4498 for (auto const & bit : clist) {
4499 if (runparams.silent)
4500 bit->d->errorLists[error_type].clear();
4501 else if (d->cloned_buffer_) {
4502 // Enable reverse search by copying back the
4503 // texrow object to the cloned buffer.
4504 // FIXME: this is not thread safe.
4505 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4506 bit->d->cloned_buffer_->d->errorLists[error_type] =
4507 bit->d->errorLists[error_type];
4509 bit->errors(error_type, true);
4513 if (d->cloned_buffer_) {
4514 // Enable reverse dvi or pdf to work by copying back the texrow
4515 // object to the cloned buffer.
4516 // FIXME: There is a possibility of concurrent access to texrow
4517 // here from the main GUI thread that should be securized.
4518 d->cloned_buffer_->d->texrow = d->texrow;
4519 string const err_type = params().bufferFormat();
4520 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4524 if (put_in_tempdir) {
4525 result_file = tmp_result_file.absFileName();
4526 return success ? ExportSuccess : ExportConverterError;
4529 if (dest_filename.empty())
4530 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4532 result_file = dest_filename;
4533 // We need to copy referenced files (e. g. included graphics
4534 // if format == "dvi") to the result dir.
4535 vector<ExportedFile> const files =
4536 runparams.exportdata->externalFiles(format);
4537 string const dest = runparams.export_folder.empty() ?
4538 onlyPath(result_file) : runparams.export_folder;
4539 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4540 : force_overwrite == ALL_FILES;
4541 CopyStatus status = use_force ? FORCE : SUCCESS;
4543 for (ExportedFile const & exp : files) {
4544 if (status == CANCEL) {
4545 message(_("Document export cancelled."));
4546 return ExportCancel;
4548 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4549 string fixedName = exp.exportName;
4550 if (!runparams.export_folder.empty()) {
4551 // Relative pathnames starting with ../ will be sanitized
4552 // if exporting to a different folder
4553 while (fixedName.substr(0, 3) == "../")
4554 fixedName = fixedName.substr(3, fixedName.length() - 3);
4556 FileName fixedFileName = makeAbsPath(fixedName, dest);
4557 fixedFileName.onlyPath().createPath();
4558 status = copyFile(fmt, exp.sourceName,
4560 exp.exportName, status == FORCE,
4561 runparams.export_folder.empty());
4565 if (tmp_result_file.exists()) {
4566 // Finally copy the main file
4567 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4568 : force_overwrite != NO_FILES;
4569 if (status == SUCCESS && use_force)
4571 status = copyFile(format, tmp_result_file,
4572 FileName(result_file), result_file,
4574 if (status == CANCEL) {
4575 message(_("Document export cancelled."));
4576 return ExportCancel;
4578 message(bformat(_("Document exported as %1$s "
4580 theFormats().prettyName(format),
4581 makeDisplayPath(result_file)));
4584 // This must be a dummy converter like fax (bug 1888)
4585 message(bformat(_("Document exported as %1$s"),
4586 theFormats().prettyName(format)));
4589 return success ? ExportSuccess : ExportConverterError;
4593 Buffer::ExportStatus Buffer::preview(string const & format) const
4595 bool const update_unincluded =
4596 params().maintain_unincluded_children
4597 && !params().getIncludedChildren().empty();
4598 return preview(format, update_unincluded);
4602 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4604 MarkAsExporting exporting(this);
4606 // (1) export with all included children (omit \includeonly)
4608 ExportStatus const status = doExport(format, true, true, result_file);
4609 if (status != ExportSuccess)
4612 // (2) export with included children only
4613 ExportStatus const status = doExport(format, true, false, result_file);
4614 FileName const previewFile(result_file);
4616 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4617 theimpl->preview_file_ = previewFile;
4618 theimpl->preview_format_ = format;
4619 theimpl->preview_error_ = (status != ExportSuccess);
4621 if (status != ExportSuccess)
4624 if (previewFile.exists())
4625 return theFormats().view(*this, previewFile, format) ?
4626 PreviewSuccess : PreviewError;
4628 // Successful export but no output file?
4629 // Probably a bug in error detection.
4630 LATTEST(status != ExportSuccess);
4635 Buffer::ReadStatus Buffer::extractFromVC()
4637 bool const found = LyXVC::file_not_found_hook(d->filename);
4639 return ReadFileNotFound;
4640 if (!d->filename.isReadableFile())
4646 Buffer::ReadStatus Buffer::loadEmergency()
4648 FileName const emergencyFile = getEmergencyFileName();
4649 if (!emergencyFile.exists()
4650 || emergencyFile.lastModified() <= d->filename.lastModified())
4651 return ReadFileNotFound;
4653 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4654 docstring const text = bformat(_("An emergency save of the document "
4655 "%1$s exists.\n\nRecover emergency save?"), file);
4657 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4658 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4664 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4665 bool const success = (ret_llf == ReadSuccess);
4667 if (hasReadonlyFlag()) {
4668 Alert::warning(_("File is read-only"),
4669 bformat(_("An emergency file is successfully loaded, "
4670 "but the original file %1$s is marked read-only. "
4671 "Please make sure to save the document as a different "
4672 "file."), from_utf8(d->filename.absFileName())));
4675 lyxvc().file_found_hook(d->filename);
4676 str = _("Document was successfully recovered.");
4678 str = _("Document was NOT successfully recovered.");
4679 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4680 makeDisplayPath(emergencyFile.absFileName()));
4682 int const del_emerg =
4683 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4684 _("&Remove"), _("&Keep"));
4685 if (del_emerg == 0) {
4686 emergencyFile.removeFile();
4688 Alert::warning(_("Emergency file deleted"),
4689 _("Do not forget to save your file now!"), true);
4691 return success ? ReadSuccess : ReadEmergencyFailure;
4694 int const del_emerg =
4695 Alert::prompt(_("Delete emergency file?"),
4696 _("Remove emergency file now?"), 1, 1,
4697 _("&Remove"), _("&Keep"));
4699 emergencyFile.removeFile();
4700 return ReadOriginal;
4710 Buffer::ReadStatus Buffer::loadAutosave()
4712 // Now check if autosave file is newer.
4713 FileName const autosaveFile = getAutosaveFileName();
4714 if (!autosaveFile.exists()
4715 || autosaveFile.lastModified() <= d->filename.lastModified())
4716 return ReadFileNotFound;
4718 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4719 docstring const text = bformat(_("The backup of the document %1$s "
4720 "is newer.\n\nLoad the backup instead?"), file);
4721 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4722 _("&Load backup"), _("Load &original"), _("&Cancel"));
4727 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4728 // the file is not saved if we load the autosave file.
4729 if (ret_llf == ReadSuccess) {
4730 if (hasReadonlyFlag()) {
4731 Alert::warning(_("File is read-only"),
4732 bformat(_("A backup file is successfully loaded, "
4733 "but the original file %1$s is marked read-only. "
4734 "Please make sure to save the document as a "
4736 from_utf8(d->filename.absFileName())));
4739 lyxvc().file_found_hook(d->filename);
4742 return ReadAutosaveFailure;
4745 // Here we delete the autosave
4746 autosaveFile.removeFile();
4747 return ReadOriginal;
4755 Buffer::ReadStatus Buffer::loadLyXFile()
4757 if (!d->filename.isReadableFile()) {
4758 ReadStatus const ret_rvc = extractFromVC();
4759 if (ret_rvc != ReadSuccess)
4763 ReadStatus const ret_re = loadEmergency();
4764 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4767 ReadStatus const ret_ra = loadAutosave();
4768 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4771 return loadThisLyXFile(d->filename);
4775 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4777 return readFile(fn);
4781 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4783 for (auto const & err : terr) {
4784 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4785 int errorRow = err.error_in_line;
4786 Buffer const * buf = 0;
4788 if (err.child_name.empty())
4789 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4791 // The error occurred in a child
4792 for (Buffer const * child : getDescendents()) {
4793 string const child_name =
4794 DocFileName(changeExtension(child->absFileName(), "tex")).
4796 if (err.child_name != child_name)
4798 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4799 if (!TexRow::isNone(start)) {
4800 buf = d->cloned_buffer_
4801 ? child->d->cloned_buffer_->d->owner_
4808 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4814 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4816 LBUFERR(!text().paragraphs().empty());
4818 // Use the master text class also for child documents
4819 Buffer const * const master = masterBuffer();
4820 DocumentClass const & textclass = master->params().documentClass();
4822 docstring_list old_bibfiles;
4823 // Do this only if we are the top-level Buffer. We also need to account
4824 // for the case of a previewed child with ignored parent here.
4825 if (master == this && !d->ignore_parent) {
4826 textclass.counters().reset(from_ascii("bibitem"));
4827 reloadBibInfoCache();
4828 // we will re-read this cache as we go through, but we need
4829 // to know whether it's changed to know whether we need to
4830 // update the bibinfo cache.
4831 old_bibfiles = d->bibfiles_cache_;
4832 d->bibfiles_cache_.clear();
4835 // keep the buffers to be children in this set. If the call from the
4836 // master comes back we can see which of them were actually seen (i.e.
4837 // via an InsetInclude). The remaining ones in the set need still be updated.
4838 static std::set<Buffer const *> bufToUpdate;
4839 if (scope == UpdateMaster) {
4840 // If this is a child document start with the master
4841 if (master != this) {
4842 bufToUpdate.insert(this);
4843 master->updateBuffer(UpdateMaster, utype);
4844 // If the master buffer has no gui associated with it, then the TocModel is
4845 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4846 // (bug 5699). The same happens if the master buffer is open in a different
4847 // window. This test catches both possibilities.
4848 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4849 // There remains a problem here: If there is another child open in yet a third
4850 // window, that TOC is not updated. So some more general solution is needed at
4852 if (master->d->gui_ != d->gui_)
4855 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4856 if (bufToUpdate.find(this) == bufToUpdate.end())
4860 // start over the counters in the master
4861 textclass.counters().reset();
4864 // update will be done below for this buffer
4865 bufToUpdate.erase(this);
4867 // update all caches
4868 clearReferenceCache();
4870 setChangesPresent(false);
4872 Buffer & cbuf = const_cast<Buffer &>(*this);
4875 ParIterator parit = cbuf.par_iterator_begin();
4876 updateBuffer(parit, utype);
4878 // If this document has siblings, then update the TocBackend later. The
4879 // reason is to ensure that later siblings are up to date when e.g. the
4880 // broken or not status of references is computed. The update is called
4881 // in InsetInclude::addToToc.
4885 // if the bibfiles changed, the cache of bibinfo is invalid
4886 docstring_list new_bibfiles = d->bibfiles_cache_;
4887 // this is a trick to determine whether the two vectors have
4888 // the same elements.
4889 sort(new_bibfiles.begin(), new_bibfiles.end());
4890 sort(old_bibfiles.begin(), old_bibfiles.end());
4891 if (old_bibfiles != new_bibfiles) {
4892 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4893 invalidateBibinfoCache();
4894 reloadBibInfoCache();
4895 // We relied upon the bibinfo cache when recalculating labels. But that
4896 // cache was invalid, although we didn't find that out until now. So we
4897 // have to do it all again.
4898 // That said, the only thing we really need to do is update the citation
4899 // labels. Nothing else will have changed. So we could create a new
4900 // UpdateType that would signal that fact, if we needed to do so.
4901 parit = cbuf.par_iterator_begin();
4902 // we will be re-doing the counters and references and such.
4903 textclass.counters().reset();
4904 clearReferenceCache();
4905 // we should not need to do this again?
4907 setChangesPresent(false);
4908 updateBuffer(parit, utype);
4909 // this will already have been done by reloadBibInfoCache();
4910 // d->bibinfo_cache_valid_ = true;
4913 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4914 // this is also set to true on the other path, by reloadBibInfoCache.
4915 d->bibinfo_cache_valid_ = true;
4917 d->cite_labels_valid_ = true;
4919 cbuf.tocBackend().update(true, utype);
4920 if (scope == UpdateMaster)
4921 cbuf.structureChanged();
4925 static depth_type getDepth(DocIterator const & it)
4927 depth_type depth = 0;
4928 for (size_t i = 0 ; i < it.depth() ; ++i)
4929 if (!it[i].inset().inMathed())
4930 depth += it[i].paragraph().getDepth() + 1;
4931 // remove 1 since the outer inset does not count
4932 // we should have at least one non-math inset, so
4933 // depth should nevery be 0. but maybe it is worth
4934 // marking this, just in case.
4936 // coverity[INTEGER_OVERFLOW]
4940 static depth_type getItemDepth(ParIterator const & it)
4942 Paragraph const & par = *it;
4943 LabelType const labeltype = par.layout().labeltype;
4945 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4948 // this will hold the lowest depth encountered up to now.
4949 depth_type min_depth = getDepth(it);
4950 ParIterator prev_it = it;
4953 --prev_it.top().pit();
4955 // start of nested inset: go to outer par
4957 if (prev_it.empty()) {
4958 // start of document: nothing to do
4963 // We search for the first paragraph with same label
4964 // that is not more deeply nested.
4965 Paragraph & prev_par = *prev_it;
4966 depth_type const prev_depth = getDepth(prev_it);
4967 if (labeltype == prev_par.layout().labeltype) {
4968 if (prev_depth < min_depth)
4969 return prev_par.itemdepth + 1;
4970 if (prev_depth == min_depth)
4971 return prev_par.itemdepth;
4973 min_depth = min(min_depth, prev_depth);
4974 // small optimization: if we are at depth 0, we won't
4975 // find anything else
4976 if (prev_depth == 0)
4982 static bool needEnumCounterReset(ParIterator const & it)
4984 Paragraph const & par = *it;
4985 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4986 depth_type const cur_depth = par.getDepth();
4987 ParIterator prev_it = it;
4988 while (prev_it.pit()) {
4989 --prev_it.top().pit();
4990 Paragraph const & prev_par = *prev_it;
4991 if (prev_par.getDepth() <= cur_depth)
4992 return prev_par.layout().name() != par.layout().name();
4994 // start of nested inset: reset
4999 // set the label of a paragraph. This includes the counters.
5000 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5002 BufferParams const & bp = owner_->masterBuffer()->params();
5003 DocumentClass const & textclass = bp.documentClass();
5004 Paragraph & par = it.paragraph();
5005 Layout const & layout = par.layout();
5006 Counters & counters = textclass.counters();
5008 if (par.params().startOfAppendix()) {
5009 // We want to reset the counter corresponding to toplevel sectioning
5010 Layout const & lay = textclass.getTOCLayout();
5011 docstring const cnt = lay.counter;
5013 counters.reset(cnt);
5014 counters.appendix(true);
5016 par.params().appendix(counters.appendix());
5018 // Compute the item depth of the paragraph
5019 par.itemdepth = getItemDepth(it);
5021 if (layout.margintype == MARGIN_MANUAL) {
5022 if (par.params().labelWidthString().empty())
5023 par.params().labelWidthString(par.expandLabel(layout, bp));
5024 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5025 // we do not need to do anything here, since the empty case is
5026 // handled during export.
5028 par.params().labelWidthString(docstring());
5031 switch(layout.labeltype) {
5032 case LABEL_ITEMIZE: {
5033 // At some point of time we should do something more
5034 // clever here, like:
5035 // par.params().labelString(
5036 // bp.user_defined_bullet(par.itemdepth).getText());
5037 // for now, use a simple hardcoded label
5038 docstring itemlabel;
5039 switch (par.itemdepth) {
5041 itemlabel = char_type(0x2022);
5044 itemlabel = char_type(0x2013);
5047 itemlabel = char_type(0x2217);
5050 itemlabel = char_type(0x2219); // or 0x00b7
5053 par.params().labelString(itemlabel);
5057 case LABEL_ENUMERATE: {
5058 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5060 switch (par.itemdepth) {
5071 enumcounter += "iv";
5074 // not a valid enumdepth...
5078 if (needEnumCounterReset(it)) {
5079 // Increase the master counter?
5080 if (layout.stepmastercounter)
5081 counters.stepMaster(enumcounter, utype);
5082 // Maybe we have to reset the enumeration counter.
5083 if (!layout.resumecounter)
5084 counters.reset(enumcounter);
5086 counters.step(enumcounter, utype);
5088 string const & lang = par.getParLanguage(bp)->code();
5089 par.params().labelString(counters.theCounter(enumcounter, lang));
5094 case LABEL_SENSITIVE: {
5095 string const & type = counters.current_float();
5096 docstring full_label;
5098 full_label = owner_->B_("Senseless!!! ");
5100 docstring name = owner_->B_(textclass.floats().getType(type).name());
5101 if (counters.hasCounter(from_utf8(type))) {
5102 string const & lang = par.getParLanguage(bp)->code();
5103 counters.step(from_utf8(type), utype);
5104 full_label = bformat(from_ascii("%1$s %2$s:"),
5106 counters.theCounter(from_utf8(type), lang));
5108 full_label = bformat(from_ascii("%1$s #:"), name);
5110 par.params().labelString(full_label);
5114 case LABEL_NO_LABEL:
5115 par.params().labelString(docstring());
5119 case LABEL_CENTERED:
5120 case LABEL_STATIC: {
5121 docstring const & lcounter = layout.counter;
5122 if (!lcounter.empty()) {
5123 if (layout.toclevel <= bp.secnumdepth
5124 && (layout.latextype != LATEX_ENVIRONMENT
5125 || it.text()->isFirstInSequence(it.pit()))) {
5126 if (counters.hasCounter(lcounter))
5127 counters.step(lcounter, utype);
5128 par.params().labelString(par.expandLabel(layout, bp));
5130 par.params().labelString(docstring());
5132 par.params().labelString(par.expandLabel(layout, bp));
5138 par.params().labelString(par.expandLabel(layout, bp));
5143 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5145 // LASSERT: Is it safe to continue here, or should we just return?
5146 LASSERT(parit.pit() == 0, /**/);
5148 // Set the position of the text in the buffer to be able
5149 // to resolve macros in it.
5150 parit.text()->setMacrocontextPosition(parit);
5152 depth_type maxdepth = 0;
5153 pit_type const lastpit = parit.lastpit();
5154 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5155 // reduce depth if necessary
5156 if (parit->params().depth() > maxdepth) {
5157 /** FIXME: this function is const, but
5158 * nevertheless it modifies the buffer. To be
5159 * cleaner, one should modify the buffer in
5160 * another function, which is actually
5161 * non-const. This would however be costly in
5162 * terms of code duplication.
5164 CursorData(parit).recordUndo();
5165 parit->params().depth(maxdepth);
5167 maxdepth = parit->getMaxDepthAfter();
5169 if (utype == OutputUpdate) {
5170 // track the active counters
5171 // we have to do this for the master buffer, since the local
5172 // buffer isn't tracking anything.
5173 masterBuffer()->params().documentClass().counters().
5174 setActiveLayout(parit->layout());
5177 // set the counter for this paragraph
5178 d->setLabel(parit, utype);
5180 // update change-tracking flag
5181 parit->addChangesToBuffer(*this);
5184 for (auto const & insit : parit->insetList()) {
5185 parit.pos() = insit.pos;
5186 insit.inset->updateBuffer(parit, utype);
5192 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5193 WordLangTuple & word_lang, docstring_list & suggestions) const
5197 suggestions.clear();
5198 word_lang = WordLangTuple();
5199 bool const to_end = to.empty();
5200 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5201 // OK, we start from here.
5202 for (; from != end; from.forwardPos()) {
5203 // This skips all insets with spell check disabled.
5204 while (!from.allowSpellCheck()) {
5208 // If from is at the end of the document (which is possible
5209 // when "from" was changed above) LyX will crash later otherwise.
5210 if (from.atEnd() || (!to_end && from >= end))
5213 from.paragraph().spellCheck();
5214 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5215 if (SpellChecker::misspelled(res)) {
5219 // Do not increase progress when from == to, otherwise the word
5220 // count will be wrong.
5230 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5232 bool inword = false;
5237 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5238 if (!dit.inTexted()) {
5243 Paragraph const & par = dit.paragraph();
5244 pos_type const pos = dit.pos();
5246 // Copied and adapted from isWordSeparator() in Paragraph
5247 if (pos == dit.lastpos()) {
5250 Inset const * ins = par.getInset(pos);
5251 if (ins && skipNoOutput && !ins->producesOutput()) {
5254 // stop if end of range was skipped
5255 if (!to.atEnd() && dit >= to)
5258 } else if (!par.isDeleted(pos)) {
5259 if (par.isWordSeparator(pos))
5265 if (ins && ins->isLetter())
5267 else if (ins && ins->isSpace())
5270 char_type const c = par.getChar(pos);
5271 if (isPrintableNonspace(c))
5273 else if (isSpace(c))
5283 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5285 d->updateStatistics(from, to, skipNoOutput);
5289 int Buffer::wordCount() const
5291 return d->wordCount();
5295 int Buffer::charCount(bool with_blanks) const
5297 return d->charCount(with_blanks);
5301 Buffer::ReadStatus Buffer::reload()
5304 // c.f. bug https://www.lyx.org/trac/ticket/6587
5305 removeAutosaveFile();
5306 // e.g., read-only status could have changed due to version control
5307 d->filename.refresh();
5308 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5310 // clear parent. this will get reset if need be.
5312 ReadStatus const status = loadLyXFile();
5313 if (status == ReadSuccess) {
5318 message(bformat(_("Document %1$s reloaded."), disp_fn));
5321 message(bformat(_("Could not reload document %1$s."), disp_fn));
5331 bool Buffer::saveAs(FileName const & fn)
5333 FileName const old_name = fileName();
5334 FileName const old_auto = getAutosaveFileName();
5335 bool const old_unnamed = isUnnamed();
5336 bool success = true;
5337 d->old_position = filePath();
5344 // bring the autosave file with us, just in case.
5345 moveAutosaveFile(old_auto);
5346 // validate version control data and
5347 // correct buffer title
5348 lyxvc().file_found_hook(fileName());
5350 // the file has now been saved to the new location.
5351 // we need to check that the locations of child buffers
5353 checkChildBuffers();
5354 checkMasterBuffer();
5357 // reset the old filename and unnamed state
5358 setFileName(old_name);
5359 setUnnamed(old_unnamed);
5363 d->old_position.clear();
5368 void Buffer::checkChildBuffers()
5370 for (auto const & bit : d->children_positions) {
5371 DocIterator dit = bit.second;
5372 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5373 if (!cbuf || !theBufferList().isLoaded(cbuf))
5375 Inset * inset = dit.nextInset();
5376 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5377 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5378 docstring const & incfile = inset_inc->getParam("filename");
5379 string oldloc = cbuf->absFileName();
5380 string newloc = makeAbsPath(to_utf8(incfile),
5381 onlyPath(absFileName())).absFileName();
5382 if (oldloc == newloc)
5384 // the location of the child file is incorrect.
5386 inset_inc->setChildBuffer(0);
5388 // invalidate cache of children
5389 d->children_positions.clear();
5390 d->position_to_children.clear();
5394 // If a child has been saved under a different name/path, it might have been
5395 // orphaned. Therefore the master needs to be reset (bug 8161).
5396 void Buffer::checkMasterBuffer()
5398 Buffer const * const master = masterBuffer();
5402 // necessary to re-register the child (bug 5873)
5403 // FIXME: clean up updateMacros (here, only
5404 // child registering is needed).
5405 master->updateMacros();
5406 // (re)set master as master buffer, but only
5407 // if we are a real child
5408 if (master->isChild(this))
5415 string Buffer::includedFilePath(string const & name, string const & ext) const
5417 if (d->old_position.empty() ||
5418 equivalent(FileName(d->old_position), FileName(filePath())))
5421 bool isabsolute = FileName::isAbsolute(name);
5422 // both old_position and filePath() end with a path separator
5423 string absname = isabsolute ? name : d->old_position + name;
5425 // if old_position is set to origin, we need to do the equivalent of
5426 // getReferencedFileName() (see readDocument())
5427 if (!isabsolute && d->old_position == params().origin) {
5428 FileName const test(addExtension(filePath() + name, ext));
5430 absname = filePath() + name;
5433 if (!FileName(addExtension(absname, ext)).exists())
5437 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5439 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5440 from_utf8(filePath())));
5444 void Buffer::setChangesPresent(bool b) const
5446 d->tracked_changes_present_ = b;
5450 bool Buffer::areChangesPresent() const
5452 return d->tracked_changes_present_;
5456 void Buffer::updateChangesPresent() const
5458 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5459 setChangesPresent(false);
5460 ParConstIterator it = par_iterator_begin();
5461 ParConstIterator const end = par_iterator_end();
5462 for (; !areChangesPresent() && it != end; ++it)
5463 it->addChangesToBuffer(*this);
5467 void Buffer::Impl::refreshFileMonitor()
5469 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5470 file_monitor_->refresh();
5474 // The previous file monitor is invalid
5475 // This also destroys the previous file monitor and all its connections
5476 file_monitor_ = FileSystemWatcher::monitor(filename);
5477 // file_monitor_ will be destroyed with *this, so it is not going to call a
5478 // destroyed object method.
5479 file_monitor_->connect([this](bool exists) {
5480 fileExternallyModified(exists);
5485 void Buffer::Impl::fileExternallyModified(bool const exists)
5487 // ignore notifications after our own saving operations
5488 if (checksum_ == filename.checksum()) {
5489 LYXERR(Debug::FILES, "External modification but "
5490 "checksum unchanged: " << filename);
5493 // If the file has been deleted, only mark the file as dirty since it is
5494 // pointless to prompt for reloading. If later a file is moved into this
5495 // location, then the externally modified warning will appear then.
5497 externally_modified_ = true;
5498 // Update external modification notification.
5499 // Dirty buffers must be visible at all times.
5500 if (wa_ && wa_->unhide(owner_))
5501 wa_->updateTitles();
5503 // Unable to unhide the buffer (e.g. no GUI or not current View)
5508 bool Buffer::notifiesExternalModification() const
5510 return d->externally_modified_;
5514 void Buffer::clearExternalModification() const
5516 d->externally_modified_ = false;
5518 d->wa_->updateTitles();