3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
59 #include "SpellChecker.h"
61 #include "texstream.h"
64 #include "TextClass.h"
65 #include "TocBackend.h"
67 #include "VCBackend.h"
69 #include "WordLangTuple.h"
72 #include "insets/InsetBibtex.h"
73 #include "insets/InsetBranch.h"
74 #include "insets/InsetInclude.h"
75 #include "insets/InsetTabular.h"
76 #include "insets/InsetText.h"
78 #include "mathed/InsetMathHull.h"
79 #include "mathed/MacroTable.h"
80 #include "mathed/InsetMathMacroTemplate.h"
81 #include "mathed/MathSupport.h"
83 #include "graphics/GraphicsCache.h"
84 #include "graphics/PreviewLoader.h"
86 #include "frontends/alert.h"
87 #include "frontends/Delegates.h"
88 #include "frontends/WorkAreaManager.h"
90 #include "support/lassert.h"
91 #include "support/convert.h"
92 #include "support/debug.h"
93 #include "support/docstring_list.h"
94 #include "support/ExceptionMessage.h"
95 #include "support/FileMonitor.h"
96 #include "support/FileName.h"
97 #include "support/FileNameList.h"
98 #include "support/filetools.h"
99 #include "support/ForkedCalls.h"
100 #include "support/gettext.h"
101 #include "support/gzstream.h"
102 #include "support/lstrings.h"
103 #include "support/lyxalgo.h"
104 #include "support/mutex.h"
105 #include "support/os.h"
106 #include "support/Package.h"
107 #include "support/PathChanger.h"
108 #include "support/Systemcall.h"
109 #include "support/TempFile.h"
110 #include "support/textutils.h"
111 #include "support/types.h"
113 #include "support/bind.h"
125 using namespace lyx::support;
126 using namespace lyx::graphics;
130 namespace Alert = frontend::Alert;
131 namespace os = support::os;
135 int const LYX_FORMAT = LYX_FORMAT_LYX;
137 typedef map<string, bool> DepClean;
138 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
143 // A storehouse for the cloned buffers.
144 list<CloneList *> cloned_buffers;
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
154 delete preview_loader_;
162 /// search for macro in local (buffer) table or in children
163 MacroData const * getBufferMacro(docstring const & name,
164 DocIterator const & pos) const;
166 /// Update macro table starting with position of it \param it in some
168 void updateMacros(DocIterator & it, DocIterator & scope);
170 void setLabel(ParIterator & it, UpdateType utype) const;
172 /** If we have branches that use the file suffix
173 feature, return the file name with suffix appended.
175 FileName exportFileName() const;
182 mutable TexRow texrow;
184 /// need to regenerate .tex?
188 mutable bool lyx_clean;
190 /// is autosave needed?
191 mutable bool bak_clean;
193 /// is this an unnamed file (New...)?
196 /// is this an internal bufffer?
197 bool internal_buffer;
202 /// name of the file the buffer is associated with.
205 /** Set to true only when the file is fully loaded.
206 * Used to prevent the premature generation of previews
207 * and by the citation inset.
209 bool file_fully_loaded;
211 /// original format of loaded file
214 /// if the file was originally loaded from an older format, do
215 /// we need to back it up still?
216 bool need_format_backup;
218 /// Ignore the parent (e.g. when exporting a child standalone)?
222 mutable TocBackend toc_backend;
227 ScopeMacro(DocIterator const & s, MacroData const & m)
228 : scope(s), macro(m) {}
232 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
233 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
234 /// map from the macro name to the position map,
235 /// which maps the macro definition position to the scope and the MacroData.
236 NamePositionScopeMacroMap macros;
237 /// This seem to change the way Buffer::getMacro() works
238 mutable bool macro_lock;
240 /// positions of child buffers in the buffer
241 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
243 ScopeBuffer() : buffer(0) {}
244 ScopeBuffer(DocIterator const & s, Buffer const * b)
245 : scope(s), buffer(b) {}
247 Buffer const * buffer;
249 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
250 /// position of children buffers in this buffer
251 BufferPositionMap children_positions;
252 /// map from children inclusion positions to their scope and their buffer
253 PositionScopeBufferMap position_to_children;
255 /// Contains the old buffer filePath() while saving-as, or the
256 /// directory where the document was last saved while loading.
259 /** Keeps track of the path of local layout files.
260 * If possible, it is always relative to the buffer path.
261 * Empty for layouts in system or user directory.
263 string layout_position;
265 /// Container for all sort of Buffer dependant errors.
266 map<string, ErrorList> errorLists;
268 /// checksum used to test if the file has been externally modified. Used to
269 /// double check whether the file had been externally modified when saving.
270 unsigned long checksum_;
273 frontend::WorkAreaManager * wa_;
275 frontend::GuiBufferDelegate * gui_;
280 /// A cache for the bibfiles (including bibfiles of loaded child
281 /// documents), needed for appropriate update of natbib labels.
282 mutable FileNamePairList bibfiles_cache_;
284 // FIXME The caching mechanism could be improved. At present, we have a
285 // cache for each Buffer, that caches all the bibliography info for that
286 // Buffer. A more efficient solution would be to have a global cache per
287 // file, and then to construct the Buffer's bibinfo from that.
288 /// A cache for bibliography info
289 mutable BiblioInfo bibinfo_;
290 /// whether the bibinfo cache is valid
291 mutable bool bibinfo_cache_valid_;
292 /// Cache of timestamps of .bib files
293 map<FileName, time_t> bibfile_status_;
294 /// Indicates whether the bibinfo has changed since the last time
295 /// we ran updateBuffer(), i.e., whether citation labels may need
297 mutable bool cite_labels_valid_;
299 /// These two hold the file name and format, written to by
300 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
301 FileName preview_file_;
302 string preview_format_;
303 /// If there was an error when previewing, on the next preview we do
304 /// a fresh compile (e.g. in case the user installed a package that
308 mutable RefCache ref_cache_;
310 /// our Text that should be wrapped in an InsetText
314 PreviewLoader * preview_loader_;
316 /// This is here to force the test to be done whenever parent_buffer
318 Buffer const * parent() const
320 // ignore_parent temporarily "orphans" a buffer
321 // (e.g. if a child is compiled standalone)
324 // if parent_buffer is not loaded, then it has been unloaded,
325 // which means that parent_buffer is an invalid pointer. So we
326 // set it to null in that case.
327 // however, the BufferList doesn't know about cloned buffers, so
328 // they will always be regarded as unloaded. in that case, we hope
330 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
332 return parent_buffer;
336 void setParent(Buffer const * pb)
338 if (parent_buffer == pb)
341 if (!cloned_buffer_ && parent_buffer && pb)
342 LYXERR0("Warning: a buffer should not have two parents!");
344 if (!cloned_buffer_ && parent_buffer)
345 parent_buffer->invalidateBibinfoCache();
348 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
349 /// This one is useful for preview detached in a thread.
350 Buffer const * cloned_buffer_;
352 CloneList * clone_list_;
353 /// are we in the process of exporting this buffer?
354 mutable bool doing_export;
356 /// compute statistics
357 /// \p from initial position
358 /// \p to points to the end position
359 void updateStatistics(DocIterator & from, DocIterator & to,
360 bool skipNoOutput = true);
361 /// statistics accessor functions
362 int wordCount() const
366 int charCount(bool with_blanks) const
369 + (with_blanks ? blank_count_ : 0);
372 // does the buffer contain tracked changes? (if so, we automatically
373 // display the review toolbar, for instance)
374 mutable bool tracked_changes_present_;
376 // Make sure the file monitor monitors the good file.
377 void refreshFileMonitor();
379 /// Notify or clear of external modification
380 void fileExternallyModified(bool exists);
382 /// has been externally modified? Can be reset by the user.
383 mutable bool externally_modified_;
386 /// So we can force access via the accessors.
387 mutable Buffer const * parent_buffer;
393 FileMonitorPtr file_monitor_;
397 /// Creates the per buffer temporary directory
398 static FileName createBufferTmpDir()
400 // FIXME This would be the ideal application for a TempDir class (like
401 // TempFile but for directories)
406 Mutex::Locker locker(&mutex);
407 counter = convert<string>(count++);
409 // We are in our own directory. Why bother to mangle name?
410 // In fact I wrote this code to circumvent a problematic behaviour
411 // (bug?) of EMX mkstemp().
412 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
415 if (!tmpfl.createDirectory(0777)) {
416 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
417 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
418 from_utf8(tmpfl.absFileName())));
424 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
425 Buffer const * cloned_buffer)
426 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
427 internal_buffer(false), read_only(readonly_), filename(file),
428 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
429 ignore_parent(false), toc_backend(owner), macro_lock(false),
430 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
431 cite_labels_valid_(false), preview_error_(false),
432 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
433 clone_list_(0), doing_export(false),
434 tracked_changes_present_(0), externally_modified_(false), parent_buffer(0),
435 word_count_(0), char_count_(0), blank_count_(0)
437 refreshFileMonitor();
438 if (!cloned_buffer_) {
439 temppath = createBufferTmpDir();
440 lyxvc.setBuffer(owner_);
442 wa_ = new frontend::WorkAreaManager;
445 temppath = cloned_buffer_->d->temppath;
446 file_fully_loaded = true;
447 params = cloned_buffer_->d->params;
448 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
449 bibinfo_ = cloned_buffer_->d->bibinfo_;
450 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
451 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
452 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
453 unnamed = cloned_buffer_->d->unnamed;
454 internal_buffer = cloned_buffer_->d->internal_buffer;
455 layout_position = cloned_buffer_->d->layout_position;
456 preview_file_ = cloned_buffer_->d->preview_file_;
457 preview_format_ = cloned_buffer_->d->preview_format_;
458 preview_error_ = cloned_buffer_->d->preview_error_;
459 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
463 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
464 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
466 LYXERR(Debug::INFO, "Buffer::Buffer()");
468 d->inset = new InsetText(*cloned_buffer->d->inset);
469 d->inset->setBuffer(*this);
470 // FIXME: optimize this loop somewhat, maybe by creating a new
471 // general recursive Inset::setId().
472 DocIterator it = doc_iterator_begin(this);
473 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
474 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
475 it.paragraph().setId(cloned_it.paragraph().id());
477 d->inset = new InsetText(this);
478 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
484 LYXERR(Debug::INFO, "Buffer::~Buffer()");
485 // here the buffer should take care that it is
486 // saved properly, before it goes into the void.
488 // GuiView already destroyed
492 // No need to do additional cleanups for internal buffer.
498 // this is in case of recursive includes: we won't try to delete
499 // ourselves as a child.
500 d->clone_list_->erase(this);
501 // loop over children
502 for (auto const & p : d->children_positions) {
503 Buffer * child = const_cast<Buffer *>(p.first);
504 if (d->clone_list_->erase(child))
507 // if we're the master buffer, then we should get rid of the list
510 // If this is not empty, we have leaked something. Worse, one of the
511 // children still has a reference to this list. But we will try to
512 // continue, rather than shut down.
513 LATTEST(d->clone_list_->empty());
514 list<CloneList *>::iterator it =
515 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
516 if (it == cloned_buffers.end()) {
517 // We will leak in this case, but it is safe to continue.
520 cloned_buffers.erase(it);
521 delete d->clone_list_;
523 // FIXME Do we really need to do this right before we delete d?
524 // clear references to children in macro tables
525 d->children_positions.clear();
526 d->position_to_children.clear();
528 // loop over children
529 for (auto const & p : d->children_positions) {
530 Buffer * child = const_cast<Buffer *>(p.first);
531 if (theBufferList().isLoaded(child)) {
532 if (theBufferList().isOthersChild(this, child))
535 theBufferList().release(child);
540 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
542 msg += emergencyWrite();
544 msg += " " + _("Save failed! Document is lost.");
546 Alert::warning(_("Attempting to close changed document!"), msg);
549 // FIXME Do we really need to do this right before we delete d?
550 // clear references to children in macro tables
551 d->children_positions.clear();
552 d->position_to_children.clear();
554 if (!d->temppath.destroyDirectory()) {
555 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
556 from_utf8(d->temppath.absFileName())));
565 Buffer * Buffer::cloneFromMaster() const
568 cloned_buffers.push_back(new CloneList);
569 CloneList * clones = cloned_buffers.back();
571 masterBuffer()->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().paperwidth.erase();
892 params().paperheight.erase();
893 params().leftmargin.erase();
894 params().rightmargin.erase();
895 params().topmargin.erase();
896 params().bottommargin.erase();
897 params().headheight.erase();
898 params().headsep.erase();
899 params().footskip.erase();
900 params().columnsep.erase();
901 params().fonts_cjk.erase();
902 params().listings_params.clear();
903 params().clearLayoutModules();
904 params().clearRemovedModules();
905 params().clearIncludedChildren();
906 params().pdfoptions().clear();
907 params().indiceslist().clear();
908 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
909 params().isbackgroundcolor = false;
910 params().fontcolor = RGBColor(0, 0, 0);
911 params().isfontcolor = false;
912 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
913 params().boxbgcolor = RGBColor(0xFF, 0, 0);
914 params().html_latex_start.clear();
915 params().html_latex_end.clear();
916 params().html_math_img_scale = 1.0;
917 params().output_sync_macro.erase();
918 params().setLocalLayout(docstring(), false);
919 params().setLocalLayout(docstring(), true);
920 params().biblio_opts.erase();
921 params().biblatex_bibstyle.erase();
922 params().biblatex_citestyle.erase();
923 params().multibib.erase();
925 for (int i = 0; i < 4; ++i) {
926 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
927 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
930 ErrorList & errorList = d->errorLists["Parse"];
939 if (token == "\\end_header")
943 if (token == "\\begin_header") {
944 begin_header_line = line;
948 LYXERR(Debug::PARSER, "Handling document header token: `"
951 string const result =
952 params().readToken(lex, token, d->filename.onlyPath());
953 if (!result.empty()) {
954 if (token == "\\textclass") {
955 d->layout_position = result;
958 docstring const s = bformat(_("Unknown token: "
962 errorList.push_back(ErrorItem(_("Document header error"), s));
966 if (begin_header_line) {
967 docstring const s = _("\\begin_header is missing");
968 errorList.push_back(ErrorItem(_("Document header error"), s));
971 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
973 params().makeDocumentClass();
975 return unknown_tokens;
980 // changed to be public and have one parameter
981 // Returns true if "\end_document" is not read (Asger)
982 bool Buffer::readDocument(Lexer & lex)
984 ErrorList & errorList = d->errorLists["Parse"];
987 // remove dummy empty par
988 paragraphs().clear();
990 if (!lex.checkFor("\\begin_document")) {
991 docstring const s = _("\\begin_document is missing");
992 errorList.push_back(ErrorItem(_("Document header error"), s));
997 if (params().output_changes) {
998 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
999 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1000 LaTeXFeatures::isAvailable("xcolor");
1002 if (!dvipost && !xcolorulem) {
1003 Alert::warning(_("Changes not shown in LaTeX output"),
1004 _("Changes will not be highlighted in LaTeX output, "
1005 "because neither dvipost nor xcolor/ulem are installed.\n"
1006 "Please install these packages or redefine "
1007 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1008 } else if (!xcolorulem) {
1009 Alert::warning(_("Changes not shown in LaTeX output"),
1010 _("Changes will not be highlighted in LaTeX output "
1011 "when using pdflatex, because xcolor and ulem are not installed.\n"
1012 "Please install both packages or redefine "
1013 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1017 if (!parent() && !params().master.empty()) {
1018 FileName const master_file = makeAbsPath(params().master,
1019 onlyPath(absFileName()));
1020 if (isLyXFileName(master_file.absFileName())) {
1022 checkAndLoadLyXFile(master_file, true);
1024 // necessary e.g. after a reload
1025 // to re-register the child (bug 5873)
1026 // FIXME: clean up updateMacros (here, only
1027 // child registering is needed).
1028 master->updateMacros();
1029 // set master as master buffer, but only
1030 // if we are a real child
1031 if (master->isChild(this))
1033 // if the master is not fully loaded
1034 // it is probably just loading this
1035 // child. No warning needed then.
1036 else if (master->isFullyLoaded())
1037 LYXERR0("The master '"
1039 << "' assigned to this document ("
1041 << ") does not include "
1042 "this document. Ignoring the master assignment.");
1047 // assure we have a default index
1048 params().indiceslist().addDefault(B_("Index"));
1051 if (FileName::isAbsolute(params().origin))
1052 d->old_position = params().origin;
1054 d->old_position = filePath();
1055 bool const res = text().read(lex, errorList, d->inset);
1056 d->old_position.clear();
1058 // inform parent buffer about local macros
1060 Buffer const * pbuf = parent();
1061 for (auto const & m : usermacros)
1062 pbuf->usermacros.insert(m);
1066 updateMacroInstances(InternalUpdate);
1071 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1073 Format const * fmt = theFormats().getFormat(format);
1076 // It is important to use the correct extension here, since some
1077 // converters create a wrong output file otherwise (e.g. html2latex)
1078 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1079 ofdocstream os(name.toFilesystemEncoding().c_str());
1080 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1081 bool const success = !(os << contents).fail();
1084 bool converted = false;
1086 params().compressed = false;
1088 // remove dummy empty par
1089 paragraphs().clear();
1091 converted = importFile(format, name, errorList);
1094 removeTempFile(name);
1099 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1101 if (!theConverters().isReachable(format, "lyx"))
1104 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1105 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList)) {
1106 bool const success = readFile(lyx) == ReadSuccess;
1107 removeTempFile(lyx);
1115 bool Buffer::readString(string const & s)
1117 params().compressed = false;
1120 istringstream is(s);
1122 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1123 FileName const fn = tempfile.name();
1126 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1128 if (success && file_format != LYX_FORMAT) {
1129 // We need to call lyx2lyx, so write the input to a file
1130 ofstream os(fn.toFilesystemEncoding().c_str());
1133 // lyxvc in readFile
1134 if (readFile(fn) != ReadSuccess)
1138 if (readDocument(lex))
1144 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1148 if (!lex.setFile(fname)) {
1149 Alert::error(_("File Not Found"),
1150 bformat(_("Unable to open file `%1$s'."),
1151 from_utf8(fn.absFileName())));
1152 return ReadFileNotFound;
1156 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1157 if (ret_plf != ReadSuccess)
1160 if (file_format != LYX_FORMAT) {
1162 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1163 if (ret_clf != ReadSuccess)
1165 ret_clf = readFile(tmpFile);
1166 if (ret_clf == ReadSuccess) {
1167 d->file_format = file_format;
1168 d->need_format_backup = true;
1173 // FIXME: InsetInfo needs to know whether the file is under VCS
1174 // during the parse process, so this has to be done before.
1175 lyxvc().file_found_hook(d->filename);
1177 if (readDocument(lex)) {
1178 Alert::error(_("Document format failure"),
1179 bformat(_("%1$s ended unexpectedly, which means"
1180 " that it is probably corrupted."),
1181 from_utf8(fn.absFileName())));
1182 return ReadDocumentFailure;
1185 d->file_fully_loaded = true;
1186 d->read_only = !d->filename.isWritable();
1187 params().compressed = theFormats().isZippedFile(d->filename);
1193 bool Buffer::isFullyLoaded() const
1195 return d->file_fully_loaded;
1199 void Buffer::setFullyLoaded(bool value)
1201 d->file_fully_loaded = value;
1205 bool Buffer::lastPreviewError() const
1207 return d->preview_error_;
1211 PreviewLoader * Buffer::loader() const
1213 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1215 if (!d->preview_loader_)
1216 d->preview_loader_ = new PreviewLoader(*this);
1217 return d->preview_loader_;
1221 void Buffer::removePreviews() const
1223 delete d->preview_loader_;
1224 d->preview_loader_ = 0;
1228 void Buffer::updatePreviews() const
1230 PreviewLoader * ploader = loader();
1234 InsetIterator it = inset_iterator_begin(*d->inset);
1235 InsetIterator const end = inset_iterator_end(*d->inset);
1236 for (; it != end; ++it)
1237 it->addPreview(it, *ploader);
1239 ploader->startLoading();
1243 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1244 FileName const & fn, int & file_format) const
1246 if(!lex.checkFor("\\lyxformat")) {
1247 Alert::error(_("Document format failure"),
1248 bformat(_("%1$s is not a readable LyX document."),
1249 from_utf8(fn.absFileName())));
1250 return ReadNoLyXFormat;
1256 // LyX formats 217 and earlier were written as 2.17. This corresponds
1257 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1258 // these cases. See also: www.lyx.org/trac/changeset/1313.
1259 size_t dot = tmp_format.find_first_of(".,");
1260 if (dot != string::npos)
1261 tmp_format.erase(dot, 1);
1263 file_format = convert<int>(tmp_format);
1268 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1269 FileName & tmpfile, int from_format)
1271 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1272 tempfile.setAutoRemove(false);
1273 tmpfile = tempfile.name();
1274 if(tmpfile.empty()) {
1275 Alert::error(_("Conversion failed"),
1276 bformat(_("%1$s is from a different"
1277 " version of LyX, but a temporary"
1278 " file for converting it could"
1279 " not be created."),
1280 from_utf8(fn.absFileName())));
1281 return LyX2LyXNoTempFile;
1284 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1285 if (lyx2lyx.empty()) {
1286 Alert::error(_("Conversion script not found"),
1287 bformat(_("%1$s is from a different"
1288 " version of LyX, but the"
1289 " conversion script lyx2lyx"
1290 " could not be found."),
1291 from_utf8(fn.absFileName())));
1292 return LyX2LyXNotFound;
1296 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1297 ostringstream command;
1298 command << os::python()
1299 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1300 << " -t " << convert<string>(LYX_FORMAT)
1301 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1302 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1303 string const command_str = command.str();
1305 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1307 cmd_ret const ret = runCommand(command_str);
1308 if (ret.first != 0) {
1309 if (from_format < LYX_FORMAT) {
1310 Alert::error(_("Conversion script failed"),
1311 bformat(_("%1$s is from an older version"
1312 " of LyX and the lyx2lyx script"
1313 " failed to convert it."),
1314 from_utf8(fn.absFileName())));
1315 return LyX2LyXOlderFormat;
1317 Alert::error(_("Conversion script failed"),
1318 bformat(_("%1$s is from a newer version"
1319 " of LyX and the lyx2lyx script"
1320 " failed to convert it."),
1321 from_utf8(fn.absFileName())));
1322 return LyX2LyXNewerFormat;
1329 FileName Buffer::getBackupName() const {
1330 FileName const & fn = fileName();
1331 string const fname = fn.onlyFileNameWithoutExt();
1332 string const fext = fn.extension() + "~";
1333 string const fpath = lyxrc.backupdir_path.empty() ?
1334 fn.onlyPath().absFileName() :
1335 lyxrc.backupdir_path;
1336 string const fform = convert<string>(d->file_format);
1337 string const backname = fname + "-lyxformat-" + fform;
1338 FileName backup(addName(fpath, addExtension(backname, fext)));
1340 // limit recursion, just in case
1342 unsigned long orig_checksum = 0;
1343 while (backup.exists() && v < 100) {
1344 if (orig_checksum == 0)
1345 orig_checksum = fn.checksum();
1346 unsigned long new_checksum = backup.checksum();
1347 if (orig_checksum == new_checksum) {
1348 LYXERR(Debug::FILES, "Not backing up " << fn <<
1349 "since " << backup << "has the same checksum.");
1350 // a bit of a hack, but we have to check this anyway
1351 // below, and setting this is simpler than introducing
1352 // a special boolean for this purpose.
1356 string const newbackname = backname + "-" + convert<string>(v);
1357 backup.set(addName(fpath, addExtension(newbackname, fext)));
1360 return v < 100 ? backup : FileName();
1364 // Should probably be moved to somewhere else: BufferView? GuiView?
1365 bool Buffer::save() const
1367 docstring const file = makeDisplayPath(absFileName(), 20);
1368 d->filename.refresh();
1370 // check the read-only status before moving the file as a backup
1371 if (d->filename.exists()) {
1372 bool const read_only = !d->filename.isWritable();
1374 Alert::warning(_("File is read-only"),
1375 bformat(_("The file %1$s cannot be written because it "
1376 "is marked as read-only."), file));
1381 // ask if the disk file has been externally modified (use checksum method)
1382 if (fileName().exists() && isChecksumModified()) {
1384 bformat(_("Document %1$s has been externally modified. "
1385 "Are you sure you want to overwrite this file?"), file);
1386 int const ret = Alert::prompt(_("Overwrite modified file?"),
1387 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1392 // We don't need autosaves in the immediate future. (Asger)
1393 resetAutosaveTimers();
1395 // if the file does not yet exist, none of the backup activity
1396 // that follows is necessary
1397 if (!fileName().exists()) {
1398 if (!writeFile(fileName()))
1404 // we first write the file to a new name, then move it to its
1405 // proper location once that has been done successfully. that
1406 // way we preserve the original file if something goes wrong.
1407 string const justname = fileName().onlyFileNameWithoutExt();
1408 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1409 justname + "-XXXXXX.lyx");
1410 bool const symlink = fileName().isSymLink();
1412 tempfile->setAutoRemove(false);
1414 FileName savefile(tempfile->name());
1415 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1416 if (!writeFile(savefile))
1419 // we will set this to false if we fail
1420 bool made_backup = true;
1422 FileName backupName;
1423 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1425 if (d->need_format_backup)
1426 backupName = getBackupName();
1428 // If we for some reason failed to find a backup name in case of
1429 // a format change, this will still set one. It's the best we can
1431 if (backupName.empty()) {
1432 backupName.set(fileName().absFileName() + "~");
1433 if (!lyxrc.backupdir_path.empty()) {
1434 string const mangledName =
1435 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1436 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1440 LYXERR(Debug::FILES, "Backing up original file to " <<
1441 backupName.absFileName());
1442 // Except file is symlink do not copy because of #6587.
1443 // Hard links have bad luck.
1444 made_backup = symlink ?
1445 fileName().copyTo(backupName):
1446 fileName().moveTo(backupName);
1449 Alert::error(_("Backup failure"),
1450 bformat(_("Cannot create backup file %1$s.\n"
1451 "Please check whether the directory exists and is writable."),
1452 from_utf8(backupName.absFileName())));
1453 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1454 } else if (d->need_format_backup) {
1455 // the original file has been backed up successfully, so we
1456 // will not need to do that again
1457 d->need_format_backup = false;
1461 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1462 // Only do this if tempfile is not in autoremove mode
1465 // If we have no symlink, we can simply rename the temp file.
1466 // Otherwise, we need to copy it so the symlink stays intact.
1467 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1468 savefile.moveTo(fileName()))
1470 // saveCheckSum() was already called by writeFile(), but the
1471 // time stamp is invalidated by copying/moving
1474 if (d->file_format != LYX_FORMAT)
1475 // the file associated with this buffer is now in the current format
1476 d->file_format = LYX_FORMAT;
1479 // else we saved the file, but failed to move it to the right location.
1481 if (needBackup && made_backup && !symlink) {
1482 // the original file was moved to some new location, so it will look
1483 // to the user as if it was deleted. (see bug #9234.) we could try
1484 // to restore it, but that would basically mean trying to do again
1485 // what we just failed to do. better to leave things as they are.
1486 Alert::error(_("Write failure"),
1487 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1488 "But LyX could not move it to:\n %2$s.\n"
1489 "Your original file has been backed up to:\n %3$s"),
1490 from_utf8(savefile.absFileName()),
1491 from_utf8(fileName().absFileName()),
1492 from_utf8(backupName.absFileName())));
1494 // either we did not try to make a backup, or else we tried and failed,
1495 // or else the original file was a symlink, in which case it was copied,
1496 // not moved. so the original file is intact.
1497 Alert::error(_("Write failure"),
1498 bformat(_("Cannot move saved file to:\n %1$s.\n"
1499 "But the file has successfully been saved as:\n %2$s."),
1500 from_utf8(fileName().absFileName()),
1501 from_utf8(savefile.absFileName())));
1507 bool Buffer::writeFile(FileName const & fname) const
1509 if (d->read_only && fname == d->filename)
1512 bool retval = false;
1514 docstring const str = bformat(_("Saving document %1$s..."),
1515 makeDisplayPath(fname.absFileName()));
1518 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1520 if (params().compressed) {
1521 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1522 retval = ofs && write(ofs);
1524 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1525 retval = ofs && write(ofs);
1529 message(str + _(" could not write file!"));
1534 // removeAutosaveFile();
1537 message(str + _(" done."));
1543 docstring Buffer::emergencyWrite()
1545 // No need to save if the buffer has not changed.
1549 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1551 docstring user_message = bformat(
1552 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1554 // We try to save three places:
1555 // 1) Same place as document. Unless it is an unnamed doc.
1557 string s = absFileName();
1560 if (writeFile(FileName(s))) {
1562 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1563 return user_message;
1565 user_message += " " + _("Save failed! Trying again...\n");
1569 // 2) In HOME directory.
1570 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1572 lyxerr << ' ' << s << endl;
1573 if (writeFile(FileName(s))) {
1575 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1576 return user_message;
1579 user_message += " " + _("Save failed! Trying yet again...\n");
1581 // 3) In "/tmp" directory.
1582 // MakeAbsPath to prepend the current
1583 // drive letter on OS/2
1584 s = addName(package().temp_dir().absFileName(), absFileName());
1586 lyxerr << ' ' << s << endl;
1587 if (writeFile(FileName(s))) {
1589 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1590 return user_message;
1593 user_message += " " + _("Save failed! Document is lost.");
1596 return user_message;
1600 bool Buffer::write(ostream & ofs) const
1603 // Use the standard "C" locale for file output.
1604 ofs.imbue(locale::classic());
1607 // The top of the file should not be written by params().
1609 // write out a comment in the top of the file
1610 // Important: Keep the version formatting in sync with lyx2lyx and
1611 // tex2lyx (bug 7951)
1612 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1613 << " created this file. For more info see https://www.lyx.org/\n"
1614 << "\\lyxformat " << LYX_FORMAT << "\n"
1615 << "\\begin_document\n";
1617 /// For each author, set 'used' to true if there is a change
1618 /// by this author in the document; otherwise set it to 'false'.
1619 for (Author const & a : params().authors())
1622 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1623 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1624 for ( ; it != end; ++it)
1625 it->checkAuthors(params().authors());
1627 // now write out the buffer parameters.
1628 ofs << "\\begin_header\n";
1629 params().writeFile(ofs, this);
1630 ofs << "\\end_header\n";
1633 ofs << "\n\\begin_body\n";
1635 ofs << "\n\\end_body\n";
1637 // Write marker that shows file is complete
1638 ofs << "\\end_document" << endl;
1640 // Shouldn't really be needed....
1643 // how to check if close went ok?
1644 // Following is an attempt... (BE 20001011)
1646 // good() returns false if any error occurred, including some
1647 // formatting error.
1648 // bad() returns true if something bad happened in the buffer,
1649 // which should include file system full errors.
1654 lyxerr << "File was not closed properly." << endl;
1661 bool Buffer::makeLaTeXFile(FileName const & fname,
1662 string const & original_path,
1663 OutputParams const & runparams_in,
1664 OutputWhat output) const
1666 OutputParams runparams = runparams_in;
1668 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1669 // Check here, because the "flavor" is not known in BufferParams::encoding()
1670 // (power users can override this safety measure selecting "utf8-plain").
1671 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1672 && (runparams.encoding->name() != "utf8-plain"))
1673 runparams.encoding = encodings.fromLyXName("ascii");
1675 string const encoding = runparams.encoding->iconvName();
1676 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1679 try { ofs.reset(encoding); }
1680 catch (iconv_codecvt_facet_exception const & e) {
1681 lyxerr << "Caught iconv exception: " << e.what() << endl;
1682 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1683 "verify that the support software for your encoding (%1$s) is "
1684 "properly installed"), from_ascii(encoding)));
1687 if (!openFileWrite(ofs, fname))
1690 ErrorList & errorList = d->errorLists["Export"];
1692 bool failed_export = false;
1695 // make sure we are ready to export
1696 // this needs to be done before we validate
1697 // FIXME Do we need to do this all the time? I.e., in children
1698 // of a master we are exporting?
1700 updateMacroInstances(OutputUpdate);
1703 writeLaTeXSource(os, original_path, runparams, output);
1705 catch (EncodingException const & e) {
1706 docstring const failed(1, e.failed_char);
1708 oss << "0x" << hex << e.failed_char << dec;
1709 if (getParFromID(e.par_id).paragraph().layout().pass_thru) {
1710 docstring msg = bformat(_("Uncodable character '%1$s'"
1711 " (code point %2$s)"),
1712 failed, from_utf8(oss.str()));
1713 errorList.push_back(ErrorItem(msg, _("Some characters of your document are not "
1714 "representable in specific verbatim contexts.\n"
1715 "Changing the document encoding to utf8 could help."),
1716 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1718 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1719 " (code point %2$s)"),
1720 failed, from_utf8(oss.str()));
1721 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1722 "representable in the chosen encoding.\n"
1723 "Changing the document encoding to utf8 could help."),
1724 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1726 failed_export = true;
1728 catch (iconv_codecvt_facet_exception const & e) {
1729 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1731 failed_export = true;
1733 catch (exception const & e) {
1734 errorList.push_back(ErrorItem(_("conversion failed"),
1736 lyxerr << e.what() << endl;
1737 failed_export = true;
1740 lyxerr << "Caught some really weird exception..." << endl;
1744 d->texrow = move(os.texrow());
1748 failed_export = true;
1749 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1752 if (runparams_in.silent)
1756 return !failed_export;
1760 void Buffer::writeLaTeXSource(otexstream & os,
1761 string const & original_path,
1762 OutputParams const & runparams_in,
1763 OutputWhat output) const
1765 // The child documents, if any, shall be already loaded at this point.
1767 OutputParams runparams = runparams_in;
1769 // XeTeX with TeX fonts is only safe with ASCII encoding,
1770 // Check here, because the "flavor" is not known in BufferParams::encoding()
1771 // (power users can override this safety measure selecting "utf8-plain").
1772 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1773 && (runparams.encoding->name() != "utf8-plain"))
1774 runparams.encoding = encodings.fromLyXName("ascii");
1775 // FIXME: when only the current paragraph is shown, this is ignored
1776 // (or not reached) and characters encodable in the current
1777 // encoding are not converted to ASCII-representation.
1779 // If we are compiling a file standalone, even if this is the
1780 // child of some other buffer, let's cut the link here, so the
1781 // file is really independent and no concurring settings from
1782 // the master (e.g. branch state) interfere (see #8100).
1783 if (!runparams.is_child)
1784 d->ignore_parent = true;
1786 // Classify the unicode characters appearing in math insets
1787 BufferEncodings::initUnicodeMath(*this);
1789 // validate the buffer.
1790 LYXERR(Debug::LATEX, " Validating buffer...");
1791 LaTeXFeatures features(*this, params(), runparams);
1793 // This is only set once per document (in master)
1794 if (!runparams.is_child)
1795 runparams.use_polyglossia = features.usePolyglossia();
1796 LYXERR(Debug::LATEX, " Buffer validation done.");
1798 bool const output_preamble =
1799 output == FullSource || output == OnlyPreamble;
1800 bool const output_body =
1801 output == FullSource || output == OnlyBody;
1803 // The starting paragraph of the coming rows is the
1804 // first paragraph of the document. (Asger)
1805 if (output_preamble && runparams.nice) {
1806 os << "%% LyX " << lyx_version << " created this file. "
1807 "For more info, see https://www.lyx.org/.\n"
1808 "%% Do not edit unless you really know what "
1811 LYXERR(Debug::INFO, "lyx document header finished");
1813 // There are a few differences between nice LaTeX and usual files:
1814 // usual files have \batchmode and special input@path to allow
1815 // inclusion of figures specified by an explicitly relative path
1816 // (i.e., a path starting with './' or '../') with either \input or
1817 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1818 // input@path is set when the actual parameter original_path is set.
1819 // This is done for usual tex-file, but not for nice-latex-file.
1820 // (Matthias 250696)
1821 // Note that input@path is only needed for something the user does
1822 // in the preamble, included .tex files or ERT, files included by
1823 // LyX work without it.
1824 if (output_preamble) {
1825 if (!runparams.nice) {
1826 // code for usual, NOT nice-latex-file
1827 os << "\\batchmode\n"; // changed from \nonstopmode
1829 if (!original_path.empty()) {
1831 // We don't know the encoding of inputpath
1832 docstring const inputpath = from_utf8(original_path);
1833 docstring uncodable_glyphs;
1834 Encoding const * const enc = runparams.encoding;
1836 for (size_t n = 0; n < inputpath.size(); ++n) {
1837 if (!enc->encodable(inputpath[n])) {
1838 docstring const glyph(1, inputpath[n]);
1839 LYXERR0("Uncodable character '"
1841 << "' in input path!");
1842 uncodable_glyphs += glyph;
1847 // warn user if we found uncodable glyphs.
1848 if (!uncodable_glyphs.empty()) {
1849 frontend::Alert::warning(
1850 _("Uncodable character in file path"),
1852 _("The path of your document\n"
1854 "contains glyphs that are unknown "
1855 "in the current document encoding "
1856 "(namely %2$s). This may result in "
1857 "incomplete output, unless "
1858 "TEXINPUTS contains the document "
1859 "directory and you don't use "
1860 "explicitly relative paths (i.e., "
1861 "paths starting with './' or "
1862 "'../') in the preamble or in ERT."
1863 "\n\nIn case of problems, choose "
1864 "an appropriate document encoding\n"
1865 "(such as utf8) or change the "
1867 inputpath, uncodable_glyphs));
1870 latex_path(original_path);
1871 if (contains(docdir, '#')) {
1872 docdir = subst(docdir, "#", "\\#");
1873 os << "\\catcode`\\#=11"
1874 "\\def\\#{#}\\catcode`\\#=6\n";
1876 if (contains(docdir, '%')) {
1877 docdir = subst(docdir, "%", "\\%");
1878 os << "\\catcode`\\%=11"
1879 "\\def\\%{%}\\catcode`\\%=14\n";
1881 os << "\\makeatletter\n"
1882 << "\\def\\input@path{{"
1884 << "\\makeatother\n";
1888 // get parent macros (if this buffer has a parent) which will be
1889 // written at the document begin further down.
1890 MacroSet parentMacros;
1891 listParentMacros(parentMacros, features);
1893 // Write the preamble
1894 runparams.use_babel = params().writeLaTeX(os, features,
1895 d->filename.onlyPath());
1897 // Biblatex bibliographies are loaded here
1898 if (params().useBiblatex()) {
1899 vector<docstring> const bibfiles =
1900 prepareBibFilePaths(runparams, getBibfiles(), true);
1901 for (docstring const & file: bibfiles)
1902 os << "\\addbibresource{" << file << "}\n";
1905 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1906 && !features.hasOnlyPolyglossiaLanguages()) {
1909 vector<string> bll = features.getBabelExclusiveLanguages();
1910 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1913 for (string const & sit : bll) {
1918 blangs = bll.size() > 1 ?
1919 bformat(_("The languages %1$s are only supported by Babel."), langs)
1920 : bformat(_("The language %1$s is only supported by Babel."), langs);
1924 for (string const & pit : pll) {
1929 plangs = pll.size() > 1 ?
1930 bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1931 : bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1932 if (!blangs.empty())
1936 frontend::Alert::warning(
1937 _("Incompatible Languages!"),
1939 _("You cannot use the following languages "
1940 "together in one LaTeX document because "
1941 "they require conflicting language packages:\n"
1946 // Japanese might be required only in some children of a document,
1947 // but once required, we must keep use_japanese true.
1948 runparams.use_japanese |= features.isRequired("japanese");
1951 // Restore the parenthood if needed
1952 if (!runparams.is_child)
1953 d->ignore_parent = false;
1958 // mark the beginning of the body to separate it from InPreamble insets
1959 os.texrow().start(TexRow::beginDocument());
1960 os << "\\begin{document}\n";
1962 // mark the start of a new paragraph by simulating a newline,
1963 // so that os.afterParbreak() returns true at document start
1966 // output the parent macros
1967 for (auto const & mac : parentMacros) {
1968 int num_lines = mac->write(os.os(), true);
1969 os.texrow().newlines(num_lines);
1972 } // output_preamble
1974 LYXERR(Debug::INFO, "preamble finished, now the body.");
1977 latexParagraphs(*this, text(), os, runparams);
1979 // Restore the parenthood if needed
1980 if (!runparams.is_child)
1981 d->ignore_parent = false;
1983 // add this just in case after all the paragraphs
1986 if (output_preamble) {
1987 os << "\\end{document}\n";
1988 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1990 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1992 runparams_in.encoding = runparams.encoding;
1994 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1995 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1999 void Buffer::makeDocBookFile(FileName const & fname,
2000 OutputParams const & runparams,
2001 OutputWhat output) const
2003 LYXERR(Debug::LATEX, "makeDocBookFile...");
2006 if (!openFileWrite(ofs, fname))
2009 // make sure we are ready to export
2010 // this needs to be done before we validate
2012 updateMacroInstances(OutputUpdate);
2014 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2018 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2022 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2023 OutputParams const & runparams,
2024 OutputWhat output) const
2026 LaTeXFeatures features(*this, params(), runparams);
2031 DocumentClass const & tclass = params().documentClass();
2032 string const & top_element = tclass.latexname();
2034 bool const output_preamble =
2035 output == FullSource || output == OnlyPreamble;
2036 bool const output_body =
2037 output == FullSource || output == OnlyBody;
2039 if (output_preamble) {
2040 if (runparams.flavor == OutputParams::XML)
2041 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2044 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2047 if (! tclass.class_header().empty())
2048 os << from_ascii(tclass.class_header());
2049 else if (runparams.flavor == OutputParams::XML)
2050 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2051 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2053 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2055 docstring preamble = params().preamble;
2056 if (runparams.flavor != OutputParams::XML ) {
2057 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2058 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2059 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2060 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2063 string const name = runparams.nice
2064 ? changeExtension(absFileName(), ".sgml") : fname;
2065 preamble += features.getIncludedFiles(name);
2066 preamble += features.getLyXSGMLEntities();
2068 if (!preamble.empty()) {
2069 os << "\n [ " << preamble << " ]";
2075 string top = top_element;
2077 if (runparams.flavor == OutputParams::XML)
2078 top += params().language->code();
2080 top += params().language->code().substr(0, 2);
2083 if (!params().options.empty()) {
2085 top += params().options;
2088 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2089 << " file was created by LyX " << lyx_version
2090 << "\n See https://www.lyx.org/ for more information -->\n";
2092 params().documentClass().counters().reset();
2094 sgml::openTag(os, top);
2096 docbookParagraphs(text(), *this, os, runparams);
2097 sgml::closeTag(os, top_element);
2102 void Buffer::makeLyXHTMLFile(FileName const & fname,
2103 OutputParams const & runparams) const
2105 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2108 if (!openFileWrite(ofs, fname))
2111 // make sure we are ready to export
2112 // this has to be done before we validate
2113 updateBuffer(UpdateMaster, OutputUpdate);
2114 updateMacroInstances(OutputUpdate);
2116 writeLyXHTMLSource(ofs, runparams, FullSource);
2120 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2124 void Buffer::writeLyXHTMLSource(odocstream & os,
2125 OutputParams const & runparams,
2126 OutputWhat output) const
2128 LaTeXFeatures features(*this, params(), runparams);
2130 d->bibinfo_.makeCitationLabels(*this);
2132 bool const output_preamble =
2133 output == FullSource || output == OnlyPreamble;
2134 bool const output_body =
2135 output == FullSource || output == OnlyBody || output == IncludedFile;
2137 if (output_preamble) {
2138 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2139 << "<!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"
2140 // FIXME Language should be set properly.
2141 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2143 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2144 // FIXME Presumably need to set this right
2145 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2147 docstring const & doctitle = features.htmlTitle();
2149 << (doctitle.empty() ?
2150 from_ascii("LyX Document") :
2151 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2154 docstring styles = features.getTClassHTMLPreamble();
2155 if (!styles.empty())
2156 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2158 styles = features.getPreambleSnippets().str;
2159 if (!styles.empty())
2160 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2162 // we will collect CSS information in a stream, and then output it
2163 // either here, as part of the header, or else in a separate file.
2164 odocstringstream css;
2165 styles = features.getCSSSnippets();
2166 if (!styles.empty())
2167 css << "/* LyX Provided Styles */\n" << styles << '\n';
2169 styles = features.getTClassHTMLStyles();
2170 if (!styles.empty())
2171 css << "/* Layout-provided Styles */\n" << styles << '\n';
2173 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2174 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2175 if (needfg || needbg) {
2176 css << "\nbody {\n";
2179 << from_ascii(X11hexname(params().fontcolor))
2182 css << " background-color: "
2183 << from_ascii(X11hexname(params().backgroundcolor))
2188 docstring const dstyles = css.str();
2189 if (!dstyles.empty()) {
2190 bool written = false;
2191 if (params().html_css_as_file) {
2192 // open a file for CSS info
2194 string const fcssname = addName(temppath(), "docstyle.css");
2195 FileName const fcssfile = FileName(fcssname);
2196 if (openFileWrite(ocss, fcssfile)) {
2200 // write link to header
2201 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2203 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2206 // we are here if the CSS is supposed to be written to the header
2207 // or if we failed to write it to an external file.
2209 os << "<style type='text/css'>\n"
2218 bool const output_body_tag = (output != IncludedFile);
2219 if (output_body_tag)
2220 os << "<body dir=\"auto\">\n";
2222 if (output != IncludedFile)
2223 // if we're an included file, the counters are in the master.
2224 params().documentClass().counters().reset();
2225 xhtmlParagraphs(text(), *this, xs, runparams);
2226 if (output_body_tag)
2230 if (output_preamble)
2235 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2236 // Other flags: -wall -v0 -x
2237 int Buffer::runChktex()
2241 // get LaTeX-Filename
2242 FileName const path(temppath());
2243 string const name = addName(path.absFileName(), latexName());
2244 string const org_path = filePath();
2246 PathChanger p(path); // path to LaTeX file
2247 message(_("Running chktex..."));
2249 // Generate the LaTeX file if neccessary
2250 OutputParams runparams(¶ms().encoding());
2251 runparams.flavor = OutputParams::LATEX;
2252 runparams.nice = false;
2253 runparams.linelen = lyxrc.plaintext_linelen;
2254 makeLaTeXFile(FileName(name), org_path, runparams);
2257 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2258 int const res = chktex.run(terr); // run chktex
2261 Alert::error(_("chktex failure"),
2262 _("Could not run chktex successfully."));
2264 ErrorList & errlist = d->errorLists["ChkTeX"];
2266 bufferErrors(terr, errlist);
2271 if (runparams.silent)
2272 d->errorLists["ChkTeX"].clear();
2280 void Buffer::validate(LaTeXFeatures & features) const
2282 // Validate the buffer params, but not for included
2283 // files, since they also use the parent buffer's
2285 if (!features.runparams().is_child)
2286 params().validate(features);
2288 for (Paragraph const & p : paragraphs())
2289 p.validate(features);
2291 if (lyxerr.debugging(Debug::LATEX)) {
2292 features.showStruct();
2297 void Buffer::getLabelList(vector<docstring> & list) const
2299 // If this is a child document, use the master's list instead.
2301 masterBuffer()->getLabelList(list);
2306 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2307 for (auto const & tocit : *toc) {
2308 if (tocit.depth() == 0)
2309 list.push_back(tocit.str());
2314 void Buffer::invalidateBibinfoCache() const
2316 d->bibinfo_cache_valid_ = false;
2317 d->cite_labels_valid_ = false;
2318 removeBiblioTempFiles();
2319 // also invalidate the cache for the parent buffer
2320 Buffer const * const pbuf = d->parent();
2322 pbuf->invalidateBibinfoCache();
2326 FileNamePairList const & Buffer::getBibfiles(UpdateScope scope) const
2328 // FIXME This is probably unnecessary, given where we call this.
2329 // If this is a child document, use the master instead.
2330 Buffer const * const pbuf = masterBuffer();
2331 if (pbuf != this && scope != UpdateChildOnly)
2332 return pbuf->getBibfiles();
2333 return d->bibfiles_cache_;
2337 BiblioInfo const & Buffer::masterBibInfo() const
2339 Buffer const * const tmp = masterBuffer();
2341 return tmp->masterBibInfo();
2346 void Buffer::registerBibfiles(FileNamePairList const & bf) const {
2347 Buffer const * const tmp = masterBuffer();
2349 return tmp->registerBibfiles(bf);
2351 for (auto const & p : bf) {
2352 FileNamePairList::const_iterator temp =
2353 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2354 if (temp == d->bibfiles_cache_.end())
2355 d->bibfiles_cache_.push_back(p);
2360 void Buffer::checkIfBibInfoCacheIsValid() const
2362 // use the master's cache
2363 Buffer const * const tmp = masterBuffer();
2365 tmp->checkIfBibInfoCacheIsValid();
2369 // if we already know the cache is invalid, no need to check
2371 if (!d->bibinfo_cache_valid_)
2374 // compare the cached timestamps with the actual ones.
2375 FileNamePairList const & bibfiles_cache = getBibfiles();
2376 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2377 FileNamePairList::const_iterator en = bibfiles_cache.end();
2378 for (; ei != en; ++ ei) {
2379 FileName const fn = ei->second;
2380 time_t lastw = fn.lastModified();
2381 time_t prevw = d->bibfile_status_[fn];
2382 if (lastw != prevw) {
2383 d->bibinfo_cache_valid_ = false;
2384 d->cite_labels_valid_ = false;
2385 d->bibfile_status_[fn] = lastw;
2391 void Buffer::reloadBibInfoCache() const
2393 // use the master's cache
2394 Buffer const * const tmp = masterBuffer();
2396 tmp->reloadBibInfoCache();
2400 checkIfBibInfoCacheIsValid();
2401 if (d->bibinfo_cache_valid_)
2404 d->bibinfo_.clear();
2405 FileNameList checkedFiles;
2406 collectBibKeys(checkedFiles);
2407 d->bibinfo_cache_valid_ = true;
2411 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2413 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2414 it->collectBibKeys(it, checkedFiles);
2418 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2420 Buffer const * tmp = masterBuffer();
2421 BiblioInfo & masterbi = (tmp == this) ?
2422 d->bibinfo_ : tmp->d->bibinfo_;
2423 masterbi.mergeBiblioInfo(bi);
2427 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2429 Buffer const * tmp = masterBuffer();
2430 BiblioInfo & masterbi = (tmp == this) ?
2431 d->bibinfo_ : tmp->d->bibinfo_;
2436 void Buffer::makeCitationLabels() const
2438 Buffer const * const master = masterBuffer();
2439 return d->bibinfo_.makeCitationLabels(*master);
2443 void Buffer::invalidateCiteLabels() const
2445 masterBuffer()->d->cite_labels_valid_ = false;
2448 bool Buffer::citeLabelsValid() const
2450 return masterBuffer()->d->cite_labels_valid_;
2454 void Buffer::removeBiblioTempFiles() const
2456 // We remove files that contain LaTeX commands specific to the
2457 // particular bibliographic style being used, in order to avoid
2458 // LaTeX errors when we switch style.
2459 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2460 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2461 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2462 aux_file.removeFile();
2463 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2464 bbl_file.removeFile();
2465 // Also for the parent buffer
2466 Buffer const * const pbuf = parent();
2468 pbuf->removeBiblioTempFiles();
2472 bool Buffer::isDepClean(string const & name) const
2474 DepClean::const_iterator const it = d->dep_clean.find(name);
2475 if (it == d->dep_clean.end())
2481 void Buffer::markDepClean(string const & name)
2483 d->dep_clean[name] = true;
2487 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2490 // FIXME? if there is an Buffer LFUN that can be dispatched even
2491 // if internal, put a switch '(cmd.action)' here.
2497 switch (cmd.action()) {
2499 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2500 flag.setOnOff(hasReadonlyFlag());
2503 // FIXME: There is need for a command-line import.
2504 //case LFUN_BUFFER_IMPORT:
2506 case LFUN_BUFFER_AUTO_SAVE:
2509 case LFUN_BUFFER_EXPORT_CUSTOM:
2510 // FIXME: Nothing to check here?
2513 case LFUN_BUFFER_EXPORT: {
2514 docstring const arg = cmd.argument();
2515 if (arg == "custom") {
2519 string format = (arg.empty() || arg == "default") ?
2520 params().getDefaultOutputFormat() : to_utf8(arg);
2521 size_t pos = format.find(' ');
2522 if (pos != string::npos)
2523 format = format.substr(0, pos);
2524 enable = params().isExportable(format, false);
2526 flag.message(bformat(
2527 _("Don't know how to export to format: %1$s"), arg));
2531 case LFUN_BUILD_PROGRAM:
2532 enable = params().isExportable("program", false);
2535 case LFUN_BRANCH_ACTIVATE:
2536 case LFUN_BRANCH_DEACTIVATE:
2537 case LFUN_BRANCH_MASTER_ACTIVATE:
2538 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2539 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2540 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2541 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2542 : params().branchlist();
2543 docstring const branchName = cmd.argument();
2544 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2548 case LFUN_BRANCH_ADD:
2549 case LFUN_BRANCHES_RENAME:
2550 // if no Buffer is present, then of course we won't be called!
2553 case LFUN_BUFFER_LANGUAGE:
2554 enable = !isReadonly();
2557 case LFUN_BUFFER_VIEW_CACHE:
2558 (d->preview_file_).refresh();
2559 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2562 case LFUN_CHANGES_TRACK:
2563 flag.setEnabled(true);
2564 flag.setOnOff(params().track_changes);
2567 case LFUN_CHANGES_OUTPUT:
2568 flag.setEnabled(true);
2569 flag.setOnOff(params().output_changes);
2572 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2573 flag.setOnOff(params().compressed);
2576 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2577 flag.setOnOff(params().output_sync);
2580 case LFUN_BUFFER_ANONYMIZE:
2586 flag.setEnabled(enable);
2591 void Buffer::dispatch(string const & command, DispatchResult & result)
2593 return dispatch(lyxaction.lookupFunc(command), result);
2597 // NOTE We can end up here even if we have no GUI, because we are called
2598 // by LyX::exec to handled command-line requests. So we may need to check
2599 // whether we have a GUI or not. The boolean use_gui holds this information.
2600 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2603 // FIXME? if there is an Buffer LFUN that can be dispatched even
2604 // if internal, put a switch '(cmd.action())' here.
2605 dr.dispatched(false);
2608 string const argument = to_utf8(func.argument());
2609 // We'll set this back to false if need be.
2610 bool dispatched = true;
2611 // This handles undo groups automagically
2612 UndoGroupHelper ugh(this);
2614 switch (func.action()) {
2615 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2616 if (lyxvc().inUse()) {
2617 string log = lyxvc().toggleReadOnly();
2622 setReadonly(!hasReadonlyFlag());
2625 case LFUN_BUFFER_EXPORT: {
2626 string const format = (argument.empty() || argument == "default") ?
2627 params().getDefaultOutputFormat() : argument;
2628 ExportStatus const status = doExport(format, false);
2629 dr.setError(status != ExportSuccess);
2630 if (status != ExportSuccess)
2631 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2632 from_utf8(format)));
2636 case LFUN_BUILD_PROGRAM: {
2637 ExportStatus const status = doExport("program", true);
2638 dr.setError(status != ExportSuccess);
2639 if (status != ExportSuccess)
2640 dr.setMessage(_("Error generating literate programming code."));
2644 case LFUN_BUFFER_EXPORT_CUSTOM: {
2646 string command = split(argument, format_name, ' ');
2647 Format const * format = theFormats().getFormat(format_name);
2649 lyxerr << "Format \"" << format_name
2650 << "\" not recognized!"
2655 // The name of the file created by the conversion process
2658 // Output to filename
2659 if (format->name() == "lyx") {
2660 string const latexname = latexName(false);
2661 filename = changeExtension(latexname,
2662 format->extension());
2663 filename = addName(temppath(), filename);
2665 if (!writeFile(FileName(filename)))
2669 doExport(format_name, true, filename);
2672 // Substitute $$FName for filename
2673 if (!contains(command, "$$FName"))
2674 command = "( " + command + " ) < $$FName";
2675 command = subst(command, "$$FName", filename);
2677 // Execute the command in the background
2679 call.startscript(Systemcall::DontWait, command,
2680 filePath(), layoutPos());
2684 // FIXME: There is need for a command-line import.
2686 case LFUN_BUFFER_IMPORT:
2691 case LFUN_BUFFER_AUTO_SAVE:
2693 resetAutosaveTimers();
2696 case LFUN_BRANCH_ACTIVATE:
2697 case LFUN_BRANCH_DEACTIVATE:
2698 case LFUN_BRANCH_MASTER_ACTIVATE:
2699 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2700 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2701 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2702 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2705 docstring const branch_name = func.argument();
2706 // the case without a branch name is handled elsewhere
2707 if (branch_name.empty()) {
2711 Branch * branch = buf->params().branchlist().find(branch_name);
2713 LYXERR0("Branch " << branch_name << " does not exist.");
2715 docstring const msg =
2716 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2720 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2721 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2722 if (branch->isSelected() != activate) {
2723 buf->undo().recordUndoBufferParams(CursorData());
2724 branch->setSelected(activate);
2726 dr.screenUpdate(Update::Force);
2727 dr.forceBufferUpdate();
2732 case LFUN_BRANCH_ADD: {
2733 docstring branchnames = func.argument();
2734 if (branchnames.empty()) {
2738 BranchList & branch_list = params().branchlist();
2739 vector<docstring> const branches =
2740 getVectorFromString(branchnames, branch_list.separator());
2742 for (docstring const & branch_name : branches) {
2743 Branch * branch = branch_list.find(branch_name);
2745 LYXERR0("Branch " << branch_name << " already exists.");
2749 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2751 undo().recordUndoBufferParams(CursorData());
2752 branch_list.add(branch_name);
2753 branch = branch_list.find(branch_name);
2754 string const x11hexname = X11hexname(branch->color());
2755 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2756 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2758 dr.screenUpdate(Update::Force);
2766 case LFUN_BRANCHES_RENAME: {
2767 if (func.argument().empty())
2770 docstring const oldname = from_utf8(func.getArg(0));
2771 docstring const newname = from_utf8(func.getArg(1));
2772 InsetIterator it = inset_iterator_begin(inset());
2773 InsetIterator const end = inset_iterator_end(inset());
2774 bool success = false;
2775 for (; it != end; ++it) {
2776 if (it->lyxCode() == BRANCH_CODE) {
2777 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2778 if (ins.branch() == oldname) {
2779 undo().recordUndo(CursorData(it));
2780 ins.rename(newname);
2785 if (it->lyxCode() == INCLUDE_CODE) {
2786 // get buffer of external file
2787 InsetInclude const & ins =
2788 static_cast<InsetInclude const &>(*it);
2789 Buffer * child = ins.getChildBuffer();
2792 child->dispatch(func, dr);
2797 dr.screenUpdate(Update::Force);
2798 dr.forceBufferUpdate();
2803 case LFUN_BUFFER_VIEW_CACHE:
2804 if (!theFormats().view(*this, d->preview_file_,
2805 d->preview_format_))
2806 dr.setMessage(_("Error viewing the output file."));
2809 case LFUN_CHANGES_TRACK:
2810 if (params().save_transient_properties)
2811 undo().recordUndoBufferParams(CursorData());
2812 params().track_changes = !params().track_changes;
2813 if (!params().track_changes)
2814 dr.forceChangesUpdate();
2817 case LFUN_CHANGES_OUTPUT:
2818 if (params().save_transient_properties)
2819 undo().recordUndoBufferParams(CursorData());
2820 params().output_changes = !params().output_changes;
2821 if (params().output_changes) {
2822 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2823 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2824 LaTeXFeatures::isAvailable("xcolor");
2826 if (!dvipost && !xcolorulem) {
2827 Alert::warning(_("Changes not shown in LaTeX output"),
2828 _("Changes will not be highlighted in LaTeX output, "
2829 "because neither dvipost nor xcolor/ulem are installed.\n"
2830 "Please install these packages or redefine "
2831 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2832 } else if (!xcolorulem) {
2833 Alert::warning(_("Changes not shown in LaTeX output"),
2834 _("Changes will not be highlighted in LaTeX output "
2835 "when using pdflatex, because xcolor and ulem are not installed.\n"
2836 "Please install both packages or redefine "
2837 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2842 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2843 // turn compression on/off
2844 undo().recordUndoBufferParams(CursorData());
2845 params().compressed = !params().compressed;
2848 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2849 undo().recordUndoBufferParams(CursorData());
2850 params().output_sync = !params().output_sync;
2853 case LFUN_BUFFER_ANONYMIZE: {
2854 undo().recordUndoFullBuffer(CursorData());
2855 CursorData cur(doc_iterator_begin(this));
2856 for ( ; cur ; cur.forwardPar())
2857 cur.paragraph().anonymize();
2858 dr.forceBufferUpdate();
2866 dr.dispatched(dispatched);
2870 void Buffer::changeLanguage(Language const * from, Language const * to)
2872 LASSERT(from, return);
2873 LASSERT(to, return);
2875 for_each(par_iterator_begin(),
2877 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2881 bool Buffer::isMultiLingual() const
2883 ParConstIterator end = par_iterator_end();
2884 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2885 if (it->isMultiLingual(params()))
2892 std::set<Language const *> Buffer::getLanguages() const
2894 std::set<Language const *> langs;
2895 getLanguages(langs);
2900 void Buffer::getLanguages(std::set<Language const *> & langs) const
2902 ParConstIterator end = par_iterator_end();
2903 // add the buffer language, even if it's not actively used
2904 langs.insert(language());
2905 // iterate over the paragraphs
2906 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2907 it->getLanguages(langs);
2909 ListOfBuffers clist = getDescendents();
2910 for (auto const & cit : clist)
2911 cit->getLanguages(langs);
2915 DocIterator Buffer::getParFromID(int const id) const
2917 Buffer * buf = const_cast<Buffer *>(this);
2919 // This means non-existent
2920 return doc_iterator_end(buf);
2922 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2923 if (it.paragraph().id() == id)
2926 return doc_iterator_end(buf);
2930 bool Buffer::hasParWithID(int const id) const
2932 return !getParFromID(id).atEnd();
2936 ParIterator Buffer::par_iterator_begin()
2938 return ParIterator(doc_iterator_begin(this));
2942 ParIterator Buffer::par_iterator_end()
2944 return ParIterator(doc_iterator_end(this));
2948 ParConstIterator Buffer::par_iterator_begin() const
2950 return ParConstIterator(doc_iterator_begin(this));
2954 ParConstIterator Buffer::par_iterator_end() const
2956 return ParConstIterator(doc_iterator_end(this));
2960 Language const * Buffer::language() const
2962 return params().language;
2966 docstring const Buffer::B_(string const & l10n) const
2968 return params().B_(l10n);
2972 bool Buffer::isClean() const
2974 return d->lyx_clean;
2978 bool Buffer::isChecksumModified() const
2980 LASSERT(d->filename.exists(), return false);
2981 return d->checksum_ != d->filename.checksum();
2985 void Buffer::saveCheckSum() const
2987 FileName const & file = d->filename;
2989 d->checksum_ = file.exists() ? file.checksum()
2990 : 0; // in the case of save to a new file.
2994 void Buffer::markClean() const
2996 if (!d->lyx_clean) {
2997 d->lyx_clean = true;
3000 // if the .lyx file has been saved, we don't need an
3002 d->bak_clean = true;
3003 d->undo_.markDirty();
3004 clearExternalModification();
3008 void Buffer::setUnnamed(bool flag)
3014 bool Buffer::isUnnamed() const
3021 /// Don't check unnamed, here: isInternal() is used in
3022 /// newBuffer(), where the unnamed flag has not been set by anyone
3023 /// yet. Also, for an internal buffer, there should be no need for
3024 /// retrieving fileName() nor for checking if it is unnamed or not.
3025 bool Buffer::isInternal() const
3027 return d->internal_buffer;
3031 void Buffer::setInternal(bool flag)
3033 d->internal_buffer = flag;
3037 void Buffer::markDirty()
3040 d->lyx_clean = false;
3043 d->bak_clean = false;
3045 for (auto & depit : d->dep_clean)
3046 depit.second = false;
3050 FileName Buffer::fileName() const
3056 string Buffer::absFileName() const
3058 return d->filename.absFileName();
3062 string Buffer::filePath() const
3064 string const abs = d->filename.onlyPath().absFileName();
3067 int last = abs.length() - 1;
3069 return abs[last] == '/' ? abs : abs + '/';
3073 DocFileName Buffer::getReferencedFileName(string const & fn) const
3076 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3077 result.set(fn, filePath());
3079 // filePath() ends with a path separator
3080 FileName const test(filePath() + fn);
3082 result.set(fn, filePath());
3084 result.set(fn, params().origin);
3091 string const Buffer::prepareFileNameForLaTeX(string const & name,
3092 string const & ext, bool nice) const
3094 string const fname = makeAbsPath(name, filePath()).absFileName();
3095 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3101 return to_utf8(makeRelPath(from_utf8(fname),
3102 from_utf8(masterBuffer()->filePath())));
3106 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3107 FileNamePairList const bibfilelist,
3108 bool const add_extension) const
3110 // If we are processing the LaTeX file in a temp directory then
3111 // copy the .bib databases to this temp directory, mangling their
3112 // names in the process. Store this mangled name in the list of
3114 // (We need to do all this because BibTeX *really*, *really*
3115 // can't handle "files with spaces" and Windows users tend to
3116 // use such filenames.)
3117 // Otherwise, store the (maybe absolute) path to the original,
3118 // unmangled database name.
3120 vector<docstring> res;
3122 // determine the export format
3123 string const tex_format = flavor2format(runparams.flavor);
3125 // check for spaces in paths
3126 bool found_space = false;
3128 for (auto const & bit : bibfilelist) {
3129 string utf8input = to_utf8(bit.first);
3131 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3132 FileName const try_in_file =
3133 makeAbsPath(database + ".bib", filePath());
3134 bool const not_from_texmf = try_in_file.isReadableFile();
3136 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3138 // mangledFileName() needs the extension
3139 DocFileName const in_file = DocFileName(try_in_file);
3140 database = removeExtension(in_file.mangledFileName());
3141 FileName const out_file = makeAbsPath(database + ".bib",
3142 masterBuffer()->temppath());
3143 bool const success = in_file.copyTo(out_file);
3145 LYXERR0("Failed to copy '" << in_file
3146 << "' to '" << out_file << "'");
3148 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3149 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3150 if (!isValidLaTeXFileName(database)) {
3151 frontend::Alert::warning(_("Invalid filename"),
3152 _("The following filename will cause troubles "
3153 "when running the exported file through LaTeX: ") +
3154 from_utf8(database));
3156 if (!isValidDVIFileName(database)) {
3157 frontend::Alert::warning(_("Problematic filename for DVI"),
3158 _("The following filename can cause troubles "
3159 "when running the exported file through LaTeX "
3160 "and opening the resulting DVI: ") +
3161 from_utf8(database), true);
3169 docstring const path = from_utf8(latex_path(database));
3171 if (contains(path, ' '))
3174 if (find(res.begin(), res.end(), path) == res.end())
3175 res.push_back(path);
3178 // Check if there are spaces in the path and warn BibTeX users, if so.
3179 // (biber can cope with such paths)
3180 if (!prefixIs(runparams.bibtex_command, "biber")) {
3181 // Post this warning only once.
3182 static bool warned_about_spaces = false;
3183 if (!warned_about_spaces &&
3184 runparams.nice && found_space) {
3185 warned_about_spaces = true;
3186 Alert::warning(_("Export Warning!"),
3187 _("There are spaces in the paths to your BibTeX databases.\n"
3188 "BibTeX will be unable to find them."));
3197 string Buffer::layoutPos() const
3199 return d->layout_position;
3203 void Buffer::setLayoutPos(string const & path)
3206 d->layout_position.clear();
3210 LATTEST(FileName::isAbsolute(path));
3212 d->layout_position =
3213 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3215 if (d->layout_position.empty())
3216 d->layout_position = ".";
3220 bool Buffer::hasReadonlyFlag() const
3222 return d->read_only;
3226 bool Buffer::isReadonly() const
3228 return hasReadonlyFlag() || notifiesExternalModification();
3232 void Buffer::setParent(Buffer const * buffer)
3234 // Avoids recursive include.
3235 d->setParent(buffer == this ? 0 : buffer);
3240 Buffer const * Buffer::parent() const
3246 ListOfBuffers Buffer::allRelatives() const
3248 ListOfBuffers lb = masterBuffer()->getDescendents();
3249 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3254 Buffer const * Buffer::masterBuffer() const
3256 // FIXME Should be make sure we are not in some kind
3257 // of recursive include? A -> B -> A will crash this.
3258 Buffer const * const pbuf = d->parent();
3262 return pbuf->masterBuffer();
3266 bool Buffer::isChild(Buffer * child) const
3268 return d->children_positions.find(child) != d->children_positions.end();
3272 DocIterator Buffer::firstChildPosition(Buffer const * child)
3274 Impl::BufferPositionMap::iterator it;
3275 it = d->children_positions.find(child);
3276 if (it == d->children_positions.end())
3277 return DocIterator(this);
3282 bool Buffer::hasChildren() const
3284 return !d->children_positions.empty();
3288 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3290 // loop over children
3291 for (auto const & p : d->children_positions) {
3292 Buffer * child = const_cast<Buffer *>(p.first);
3294 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3295 if (bit != clist.end())
3297 clist.push_back(child);
3299 // there might be grandchildren
3300 child->collectChildren(clist, true);
3305 ListOfBuffers Buffer::getChildren() const
3308 collectChildren(v, false);
3309 // Make sure we have not included ourselves.
3310 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3311 if (bit != v.end()) {
3312 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3319 ListOfBuffers Buffer::getDescendents() const
3322 collectChildren(v, true);
3323 // Make sure we have not included ourselves.
3324 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3325 if (bit != v.end()) {
3326 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3333 template<typename M>
3334 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3339 typename M::const_iterator it = m.lower_bound(x);
3340 if (it == m.begin())
3348 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3349 DocIterator const & pos) const
3351 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3353 // if paragraphs have no macro context set, pos will be empty
3357 // we haven't found anything yet
3358 DocIterator bestPos = owner_->par_iterator_begin();
3359 MacroData const * bestData = 0;
3361 // find macro definitions for name
3362 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3363 if (nameIt != macros.end()) {
3364 // find last definition in front of pos or at pos itself
3365 PositionScopeMacroMap::const_iterator it
3366 = greatest_below(nameIt->second, pos);
3367 if (it != nameIt->second.end()) {
3369 // scope ends behind pos?
3370 if (pos < it->second.scope) {
3371 // Looks good, remember this. If there
3372 // is no external macro behind this,
3373 // we found the right one already.
3374 bestPos = it->first;
3375 bestData = &it->second.macro;
3379 // try previous macro if there is one
3380 if (it == nameIt->second.begin())
3387 // find macros in included files
3388 PositionScopeBufferMap::const_iterator it
3389 = greatest_below(position_to_children, pos);
3390 if (it == position_to_children.end())
3391 // no children before
3395 // do we know something better (i.e. later) already?
3396 if (it->first < bestPos )
3399 // scope ends behind pos?
3400 if (pos < it->second.scope
3401 && (cloned_buffer_ ||
3402 theBufferList().isLoaded(it->second.buffer))) {
3403 // look for macro in external file
3405 MacroData const * data
3406 = it->second.buffer->getMacro(name, false);
3409 bestPos = it->first;
3415 // try previous file if there is one
3416 if (it == position_to_children.begin())
3421 // return the best macro we have found
3426 MacroData const * Buffer::getMacro(docstring const & name,
3427 DocIterator const & pos, bool global) const
3432 // query buffer macros
3433 MacroData const * data = d->getBufferMacro(name, pos);
3437 // If there is a master buffer, query that
3438 Buffer const * const pbuf = d->parent();
3440 d->macro_lock = true;
3441 MacroData const * macro = pbuf->getMacro(
3442 name, *this, false);
3443 d->macro_lock = false;
3449 data = MacroTable::globalMacros().get(name);
3458 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3460 // set scope end behind the last paragraph
3461 DocIterator scope = par_iterator_begin();
3462 scope.pit() = scope.lastpit() + 1;
3464 return getMacro(name, scope, global);
3468 MacroData const * Buffer::getMacro(docstring const & name,
3469 Buffer const & child, bool global) const
3471 // look where the child buffer is included first
3472 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3473 if (it == d->children_positions.end())
3476 // check for macros at the inclusion position
3477 return getMacro(name, it->second, global);
3481 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3483 pit_type const lastpit = it.lastpit();
3485 // look for macros in each paragraph
3486 while (it.pit() <= lastpit) {
3487 Paragraph & par = it.paragraph();
3489 // FIXME Can this be done with the new-style iterators?
3490 // iterate over the insets of the current paragraph
3491 for (auto const & insit : par.insetList()) {
3492 it.pos() = insit.pos;
3494 // is it a nested text inset?
3495 if (insit.inset->asInsetText()) {
3496 // Inset needs its own scope?
3497 InsetText const * itext = insit.inset->asInsetText();
3498 bool newScope = itext->isMacroScope();
3500 // scope which ends just behind the inset
3501 DocIterator insetScope = it;
3504 // collect macros in inset
3505 it.push_back(CursorSlice(*insit.inset));
3506 updateMacros(it, newScope ? insetScope : scope);
3511 if (insit.inset->asInsetTabular()) {
3512 CursorSlice slice(*insit.inset);
3513 size_t const numcells = slice.nargs();
3514 for (; slice.idx() < numcells; slice.forwardIdx()) {
3515 it.push_back(slice);
3516 updateMacros(it, scope);
3522 // is it an external file?
3523 if (insit.inset->lyxCode() == INCLUDE_CODE) {
3524 // get buffer of external file
3525 InsetInclude const & incinset =
3526 static_cast<InsetInclude const &>(*insit.inset);
3528 Buffer * child = incinset.getChildBuffer();
3533 // register its position, but only when it is
3534 // included first in the buffer
3535 if (children_positions.find(child) ==
3536 children_positions.end())
3537 children_positions[child] = it;
3539 // register child with its scope
3540 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3544 InsetMath * im = insit.inset->asInsetMath();
3545 if (doing_export && im) {
3546 InsetMathHull * hull = im->asHullInset();
3548 hull->recordLocation(it);
3551 if (insit.inset->lyxCode() != MATHMACRO_CODE)
3555 InsetMathMacroTemplate & macroTemplate =
3556 *insit.inset->asInsetMath()->asMacroTemplate();
3557 MacroContext mc(owner_, it);
3558 macroTemplate.updateToContext(mc);
3561 bool valid = macroTemplate.validMacro();
3562 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3563 // then the BufferView's cursor will be invalid in
3564 // some cases which leads to crashes.
3569 // FIXME (Abdel), I don't understand why we pass 'it' here
3570 // instead of 'macroTemplate' defined above... is this correct?
3571 macros[macroTemplate.name()][it] =
3572 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3582 void Buffer::updateMacros() const
3587 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3589 // start with empty table
3591 d->children_positions.clear();
3592 d->position_to_children.clear();
3594 // Iterate over buffer, starting with first paragraph
3595 // The scope must be bigger than any lookup DocIterator
3596 // later. For the global lookup, lastpit+1 is used, hence
3597 // we use lastpit+2 here.
3598 DocIterator it = par_iterator_begin();
3599 DocIterator outerScope = it;
3600 outerScope.pit() = outerScope.lastpit() + 2;
3601 d->updateMacros(it, outerScope);
3605 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3607 InsetIterator it = inset_iterator_begin(inset());
3608 InsetIterator const end = inset_iterator_end(inset());
3609 for (; it != end; ++it) {
3610 if (it->lyxCode() == BRANCH_CODE) {
3611 InsetBranch & br = static_cast<InsetBranch &>(*it);
3612 docstring const name = br.branch();
3613 if (!from_master && !params().branchlist().find(name))
3614 result.push_back(name);
3615 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3616 result.push_back(name);
3619 if (it->lyxCode() == INCLUDE_CODE) {
3620 // get buffer of external file
3621 InsetInclude const & ins =
3622 static_cast<InsetInclude const &>(*it);
3623 Buffer * child = ins.getChildBuffer();
3626 child->getUsedBranches(result, true);
3629 // remove duplicates
3634 void Buffer::updateMacroInstances(UpdateType utype) const
3636 LYXERR(Debug::MACROS, "updateMacroInstances for "
3637 << d->filename.onlyFileName());
3638 DocIterator it = doc_iterator_begin(this);
3640 DocIterator const end = doc_iterator_end(this);
3641 for (; it != end; it.forwardInset()) {
3642 // look for MathData cells in InsetMathNest insets
3643 InsetMath * minset = it.nextInset()->asInsetMath();
3647 // update macro in all cells of the InsetMathNest
3648 DocIterator::idx_type n = minset->nargs();
3649 MacroContext mc = MacroContext(this, it);
3650 for (DocIterator::idx_type i = 0; i < n; ++i) {
3651 MathData & data = minset->cell(i);
3652 data.updateMacros(0, mc, utype, 0);
3658 void Buffer::listMacroNames(MacroNameSet & macros) const
3663 d->macro_lock = true;
3665 // loop over macro names
3666 for (auto const & nameit : d->macros)
3667 macros.insert(nameit.first);
3669 // loop over children
3670 for (auto const & p : d->children_positions) {
3671 Buffer * child = const_cast<Buffer *>(p.first);
3672 // The buffer might have been closed (see #10766).
3673 if (theBufferList().isLoaded(child))
3674 child->listMacroNames(macros);
3678 Buffer const * const pbuf = d->parent();
3680 pbuf->listMacroNames(macros);
3682 d->macro_lock = false;
3686 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3688 Buffer const * const pbuf = d->parent();
3693 pbuf->listMacroNames(names);
3696 for (auto const & mit : names) {
3698 MacroData const * data = pbuf->getMacro(mit, *this, false);
3700 macros.insert(data);
3702 // we cannot access the original InsetMathMacroTemplate anymore
3703 // here to calls validate method. So we do its work here manually.
3704 // FIXME: somehow make the template accessible here.
3705 if (data->optionals() > 0)
3706 features.require("xargs");
3712 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3715 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3717 RefCache::iterator it = d->ref_cache_.find(label);
3718 if (it != d->ref_cache_.end())
3719 return it->second.second;
3721 static InsetLabel const * dummy_il = 0;
3722 static References const dummy_refs = References();
3723 it = d->ref_cache_.insert(
3724 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3725 return it->second.second;
3729 Buffer::References const & Buffer::references(docstring const & label) const
3731 return const_cast<Buffer *>(this)->getReferenceCache(label);
3735 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3737 References & refs = getReferenceCache(label);
3738 refs.push_back(make_pair(inset, it));
3742 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3744 masterBuffer()->d->ref_cache_[label].first = il;
3748 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3750 return masterBuffer()->d->ref_cache_[label].first;
3754 void Buffer::clearReferenceCache() const
3757 d->ref_cache_.clear();
3761 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3763 //FIXME: This does not work for child documents yet.
3764 reloadBibInfoCache();
3766 // Check if the label 'from' appears more than once
3767 vector<docstring> labels;
3768 for (auto const & bibit : masterBibInfo())
3769 labels.push_back(bibit.first);
3771 if (count(labels.begin(), labels.end(), from) > 1)
3774 string const paramName = "key";
3775 InsetIterator it = inset_iterator_begin(inset());
3777 if (it->lyxCode() != CITE_CODE)
3779 InsetCommand * inset = it->asInsetCommand();
3780 docstring const oldValue = inset->getParam(paramName);
3781 if (oldValue == from)
3782 inset->setParam(paramName, to);
3786 // returns NULL if id-to-row conversion is unsupported
3787 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3788 pit_type par_begin, pit_type par_end,
3789 OutputWhat output, bool master) const
3791 unique_ptr<TexRow> texrow;
3792 OutputParams runparams(¶ms().encoding());
3793 runparams.nice = true;
3794 runparams.flavor = params().getOutputFlavor(format);
3795 runparams.linelen = lyxrc.plaintext_linelen;
3796 // No side effect of file copying and image conversion
3797 runparams.dryrun = true;
3799 if (output == CurrentParagraph) {
3800 runparams.par_begin = par_begin;
3801 runparams.par_end = par_end;
3802 if (par_begin + 1 == par_end) {
3804 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3808 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3809 convert<docstring>(par_begin),
3810 convert<docstring>(par_end - 1))
3813 // output paragraphs
3814 if (runparams.flavor == OutputParams::LYX) {
3815 Paragraph const & par = text().paragraphs()[par_begin];
3817 depth_type dt = par.getDepth();
3818 par.write(ods, params(), dt);
3819 os << from_utf8(ods.str());
3820 } else if (runparams.flavor == OutputParams::HTML) {
3822 setMathFlavor(runparams);
3823 xhtmlParagraphs(text(), *this, xs, runparams);
3824 } else if (runparams.flavor == OutputParams::TEXT) {
3826 // FIXME Handles only one paragraph, unlike the others.
3827 // Probably should have some routine with a signature like them.
3828 writePlaintextParagraph(*this,
3829 text().paragraphs()[par_begin], os, runparams, dummy);
3830 } else if (params().isDocBook()) {
3831 docbookParagraphs(text(), *this, os, runparams);
3833 // If we are previewing a paragraph, even if this is the
3834 // child of some other buffer, let's cut the link here,
3835 // so that no concurring settings from the master
3836 // (e.g. branch state) interfere (see #8101).
3838 d->ignore_parent = true;
3839 // We need to validate the Buffer params' features here
3840 // in order to know if we should output polyglossia
3841 // macros (instead of babel macros)
3842 LaTeXFeatures features(*this, params(), runparams);
3844 runparams.use_polyglossia = features.usePolyglossia();
3845 // latex or literate
3848 ots.texrow().newlines(2);
3850 latexParagraphs(*this, text(), ots, runparams);
3851 texrow = ots.releaseTexRow();
3853 // Restore the parenthood
3855 d->ignore_parent = false;
3859 if (output == FullSource)
3860 os << _("Preview source code");
3861 else if (output == OnlyPreamble)
3862 os << _("Preview preamble");
3863 else if (output == OnlyBody)
3864 os << _("Preview body");
3866 if (runparams.flavor == OutputParams::LYX) {
3868 if (output == FullSource)
3870 else if (output == OnlyPreamble)
3871 params().writeFile(ods, this);
3872 else if (output == OnlyBody)
3874 os << from_utf8(ods.str());
3875 } else if (runparams.flavor == OutputParams::HTML) {
3876 writeLyXHTMLSource(os, runparams, output);
3877 } else if (runparams.flavor == OutputParams::TEXT) {
3878 if (output == OnlyPreamble) {
3879 os << "% "<< _("Plain text does not have a preamble.");
3881 writePlaintextFile(*this, os, runparams);
3882 } else if (params().isDocBook()) {
3883 writeDocBookSource(os, absFileName(), runparams, output);
3885 // latex or literate
3888 ots.texrow().newlines(2);
3890 runparams.is_child = true;
3892 writeLaTeXSource(ots, string(), runparams, output);
3893 texrow = ots.releaseTexRow();
3900 ErrorList & Buffer::errorList(string const & type) const
3902 return d->errorLists[type];
3906 void Buffer::updateTocItem(std::string const & type,
3907 DocIterator const & dit) const
3910 d->gui_->updateTocItem(type, dit);
3914 void Buffer::structureChanged() const
3917 d->gui_->structureChanged();
3921 void Buffer::errors(string const & err, bool from_master) const
3924 d->gui_->errors(err, from_master);
3928 void Buffer::message(docstring const & msg) const
3931 d->gui_->message(msg);
3935 void Buffer::setBusy(bool on) const
3938 d->gui_->setBusy(on);
3942 void Buffer::updateTitles() const
3945 d->wa_->updateTitles();
3949 void Buffer::resetAutosaveTimers() const
3952 d->gui_->resetAutosaveTimers();
3956 bool Buffer::hasGuiDelegate() const
3962 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3971 class AutoSaveBuffer : public ForkedProcess {
3974 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3975 : buffer_(buffer), fname_(fname) {}
3977 virtual shared_ptr<ForkedProcess> clone() const
3979 return make_shared<AutoSaveBuffer>(*this);
3984 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3985 from_utf8(fname_.absFileName())));
3986 return run(DontWait);
3990 virtual int generateChild();
3992 Buffer const & buffer_;
3997 int AutoSaveBuffer::generateChild()
3999 #if defined(__APPLE__)
4000 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4001 * We should use something else like threads.
4003 * Since I do not know how to determine at run time what is the OS X
4004 * version, I just disable forking altogether for now (JMarc)
4006 pid_t const pid = -1;
4008 // tmp_ret will be located (usually) in /tmp
4009 // will that be a problem?
4010 // Note that this calls ForkedCalls::fork(), so it's
4011 // ok cross-platform.
4012 pid_t const pid = fork();
4013 // If you want to debug the autosave
4014 // you should set pid to -1, and comment out the fork.
4015 if (pid != 0 && pid != -1)
4019 // pid = -1 signifies that lyx was unable
4020 // to fork. But we will do the save
4022 bool failed = false;
4023 TempFile tempfile("lyxautoXXXXXX.lyx");
4024 tempfile.setAutoRemove(false);
4025 FileName const tmp_ret = tempfile.name();
4026 if (!tmp_ret.empty()) {
4027 if (!buffer_.writeFile(tmp_ret))
4029 else if (!tmp_ret.moveTo(fname_))
4035 // failed to write/rename tmp_ret so try writing direct
4036 if (!buffer_.writeFile(fname_)) {
4037 // It is dangerous to do this in the child,
4038 // but safe in the parent, so...
4039 if (pid == -1) // emit message signal.
4040 buffer_.message(_("Autosave failed!"));
4044 if (pid == 0) // we are the child so...
4053 FileName Buffer::getEmergencyFileName() const
4055 return FileName(d->filename.absFileName() + ".emergency");
4059 FileName Buffer::getAutosaveFileName() const
4061 // if the document is unnamed try to save in the backup dir, else
4062 // in the default document path, and as a last try in the filePath,
4063 // which will most often be the temporary directory
4066 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4067 : lyxrc.backupdir_path;
4068 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4071 string const fname = "#" + d->filename.onlyFileName() + "#";
4073 return makeAbsPath(fname, fpath);
4077 void Buffer::removeAutosaveFile() const
4079 FileName const f = getAutosaveFileName();
4085 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4087 FileName const newauto = getAutosaveFileName();
4089 if (newauto != oldauto && oldauto.exists())
4090 if (!oldauto.moveTo(newauto))
4091 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4095 bool Buffer::autoSave() const
4097 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4098 if (buf->d->bak_clean || hasReadonlyFlag())
4101 message(_("Autosaving current document..."));
4102 buf->d->bak_clean = true;
4104 FileName const fname = getAutosaveFileName();
4105 LASSERT(d->cloned_buffer_, return false);
4107 // If this buffer is cloned, we assume that
4108 // we are running in a separate thread already.
4109 TempFile tempfile("lyxautoXXXXXX.lyx");
4110 tempfile.setAutoRemove(false);
4111 FileName const tmp_ret = tempfile.name();
4112 if (!tmp_ret.empty()) {
4114 // assume successful write of tmp_ret
4115 if (tmp_ret.moveTo(fname))
4118 // failed to write/rename tmp_ret so try writing direct
4119 return writeFile(fname);
4123 void Buffer::setExportStatus(bool e) const
4125 d->doing_export = e;
4126 ListOfBuffers clist = getDescendents();
4127 for (auto const & bit : clist)
4128 bit->d->doing_export = e;
4132 bool Buffer::isExporting() const
4134 return d->doing_export;
4138 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4142 return doExport(target, put_in_tempdir, result_file);
4145 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4146 string & result_file) const
4148 bool const update_unincluded =
4149 params().maintain_unincluded_children
4150 && !params().getIncludedChildren().empty();
4152 // (1) export with all included children (omit \includeonly)
4153 if (update_unincluded) {
4154 ExportStatus const status =
4155 doExport(target, put_in_tempdir, true, result_file);
4156 if (status != ExportSuccess)
4159 // (2) export with included children only
4160 return doExport(target, put_in_tempdir, false, result_file);
4164 void Buffer::setMathFlavor(OutputParams & op) const
4166 switch (params().html_math_output) {
4167 case BufferParams::MathML:
4168 op.math_flavor = OutputParams::MathAsMathML;
4170 case BufferParams::HTML:
4171 op.math_flavor = OutputParams::MathAsHTML;
4173 case BufferParams::Images:
4174 op.math_flavor = OutputParams::MathAsImages;
4176 case BufferParams::LaTeX:
4177 op.math_flavor = OutputParams::MathAsLaTeX;
4183 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4184 bool includeall, string & result_file) const
4186 LYXERR(Debug::FILES, "target=" << target);
4187 OutputParams runparams(¶ms().encoding());
4188 string format = target;
4189 string dest_filename;
4190 size_t pos = target.find(' ');
4191 if (pos != string::npos) {
4192 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4193 format = target.substr(0, pos);
4194 if (format == "default")
4195 format = params().getDefaultOutputFormat();
4196 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4197 FileName(dest_filename).onlyPath().createPath();
4198 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4200 MarkAsExporting exporting(this);
4201 string backend_format;
4202 runparams.flavor = OutputParams::LATEX;
4203 runparams.linelen = lyxrc.plaintext_linelen;
4204 runparams.includeall = includeall;
4205 vector<string> backs = params().backends();
4206 Converters converters = theConverters();
4207 bool need_nice_file = false;
4208 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4209 // Get shortest path to format
4210 converters.buildGraph();
4211 Graph::EdgePath path;
4212 for (string const & sit : backs) {
4213 Graph::EdgePath p = converters.getPath(sit, format);
4214 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4215 backend_format = sit;
4220 if (!put_in_tempdir) {
4221 // Only show this alert if this is an export to a non-temporary
4222 // file (not for previewing).
4223 Alert::error(_("Couldn't export file"), bformat(
4224 _("No information for exporting the format %1$s."),
4225 theFormats().prettyName(format)));
4227 return ExportNoPathToFormat;
4229 runparams.flavor = converters.getFlavor(path, this);
4230 for (auto const & edge : path)
4231 if (theConverters().get(edge).nice()) {
4232 need_nice_file = true;
4237 backend_format = format;
4238 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4239 // FIXME: Don't hardcode format names here, but use a flag
4240 if (backend_format == "pdflatex")
4241 runparams.flavor = OutputParams::PDFLATEX;
4242 else if (backend_format == "luatex")
4243 runparams.flavor = OutputParams::LUATEX;
4244 else if (backend_format == "dviluatex")
4245 runparams.flavor = OutputParams::DVILUATEX;
4246 else if (backend_format == "xetex")
4247 runparams.flavor = OutputParams::XETEX;
4250 string filename = latexName(false);
4251 filename = addName(temppath(), filename);
4252 filename = changeExtension(filename,
4253 theFormats().extension(backend_format));
4254 LYXERR(Debug::FILES, "filename=" << filename);
4256 // Plain text backend
4257 if (backend_format == "text") {
4258 runparams.flavor = OutputParams::TEXT;
4259 writePlaintextFile(*this, FileName(filename), runparams);
4262 else if (backend_format == "xhtml") {
4263 runparams.flavor = OutputParams::HTML;
4264 setMathFlavor(runparams);
4265 makeLyXHTMLFile(FileName(filename), runparams);
4266 } else if (backend_format == "lyx")
4267 writeFile(FileName(filename));
4269 else if (params().isDocBook()) {
4270 runparams.nice = !put_in_tempdir;
4271 makeDocBookFile(FileName(filename), runparams);
4274 else if (backend_format == format || need_nice_file) {
4275 runparams.nice = true;
4276 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4277 if (d->cloned_buffer_)
4278 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4281 } else if (!lyxrc.tex_allows_spaces
4282 && contains(filePath(), ' ')) {
4283 Alert::error(_("File name error"),
4284 _("The directory path to the document cannot contain spaces."));
4285 return ExportTexPathHasSpaces;
4287 runparams.nice = false;
4288 bool const success = makeLaTeXFile(
4289 FileName(filename), filePath(), runparams);
4290 if (d->cloned_buffer_)
4291 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4296 string const error_type = (format == "program")
4297 ? "Build" : params().bufferFormat();
4298 ErrorList & error_list = d->errorLists[error_type];
4299 string const ext = theFormats().extension(format);
4300 FileName const tmp_result_file(changeExtension(filename, ext));
4301 bool const success = converters.convert(this, FileName(filename),
4302 tmp_result_file, FileName(absFileName()), backend_format, format,
4305 // Emit the signal to show the error list or copy it back to the
4306 // cloned Buffer so that it can be emitted afterwards.
4307 if (format != backend_format) {
4308 if (runparams.silent)
4310 else if (d->cloned_buffer_)
4311 d->cloned_buffer_->d->errorLists[error_type] =
4312 d->errorLists[error_type];
4315 // also to the children, in case of master-buffer-view
4316 ListOfBuffers clist = getDescendents();
4317 for (auto const & bit : clist) {
4318 if (runparams.silent)
4319 bit->d->errorLists[error_type].clear();
4320 else if (d->cloned_buffer_) {
4321 // Enable reverse search by copying back the
4322 // texrow object to the cloned buffer.
4323 // FIXME: this is not thread safe.
4324 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4325 bit->d->cloned_buffer_->d->errorLists[error_type] =
4326 bit->d->errorLists[error_type];
4328 bit->errors(error_type, true);
4332 if (d->cloned_buffer_) {
4333 // Enable reverse dvi or pdf to work by copying back the texrow
4334 // object to the cloned buffer.
4335 // FIXME: There is a possibility of concurrent access to texrow
4336 // here from the main GUI thread that should be securized.
4337 d->cloned_buffer_->d->texrow = d->texrow;
4338 string const err_type = params().bufferFormat();
4339 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4343 if (put_in_tempdir) {
4344 result_file = tmp_result_file.absFileName();
4345 return success ? ExportSuccess : ExportConverterError;
4348 if (dest_filename.empty())
4349 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4351 result_file = dest_filename;
4352 // We need to copy referenced files (e. g. included graphics
4353 // if format == "dvi") to the result dir.
4354 vector<ExportedFile> const files =
4355 runparams.exportdata->externalFiles(format);
4356 string const dest = runparams.export_folder.empty() ?
4357 onlyPath(result_file) : runparams.export_folder;
4358 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4359 : force_overwrite == ALL_FILES;
4360 CopyStatus status = use_force ? FORCE : SUCCESS;
4362 for (ExportedFile const & exp : files) {
4363 if (status == CANCEL) {
4364 message(_("Document export cancelled."));
4365 return ExportCancel;
4367 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4368 string fixedName = exp.exportName;
4369 if (!runparams.export_folder.empty()) {
4370 // Relative pathnames starting with ../ will be sanitized
4371 // if exporting to a different folder
4372 while (fixedName.substr(0, 3) == "../")
4373 fixedName = fixedName.substr(3, fixedName.length() - 3);
4375 FileName fixedFileName = makeAbsPath(fixedName, dest);
4376 fixedFileName.onlyPath().createPath();
4377 status = copyFile(fmt, exp.sourceName,
4379 exp.exportName, status == FORCE,
4380 runparams.export_folder.empty());
4384 if (tmp_result_file.exists()) {
4385 // Finally copy the main file
4386 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4387 : force_overwrite != NO_FILES;
4388 if (status == SUCCESS && use_force)
4390 status = copyFile(format, tmp_result_file,
4391 FileName(result_file), result_file,
4393 if (status == CANCEL) {
4394 message(_("Document export cancelled."));
4395 return ExportCancel;
4397 message(bformat(_("Document exported as %1$s "
4399 theFormats().prettyName(format),
4400 makeDisplayPath(result_file)));
4403 // This must be a dummy converter like fax (bug 1888)
4404 message(bformat(_("Document exported as %1$s"),
4405 theFormats().prettyName(format)));
4408 return success ? ExportSuccess : ExportConverterError;
4412 Buffer::ExportStatus Buffer::preview(string const & format) const
4414 bool const update_unincluded =
4415 params().maintain_unincluded_children
4416 && !params().getIncludedChildren().empty();
4417 return preview(format, update_unincluded);
4421 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4423 MarkAsExporting exporting(this);
4425 // (1) export with all included children (omit \includeonly)
4427 ExportStatus const status = doExport(format, true, true, result_file);
4428 if (status != ExportSuccess)
4431 // (2) export with included children only
4432 ExportStatus const status = doExport(format, true, false, result_file);
4433 FileName const previewFile(result_file);
4435 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4436 theimpl->preview_file_ = previewFile;
4437 theimpl->preview_format_ = format;
4438 theimpl->preview_error_ = (status != ExportSuccess);
4440 if (status != ExportSuccess)
4443 if (previewFile.exists())
4444 return theFormats().view(*this, previewFile, format) ?
4445 PreviewSuccess : PreviewError;
4447 // Successful export but no output file?
4448 // Probably a bug in error detection.
4449 LATTEST(status != ExportSuccess);
4454 Buffer::ReadStatus Buffer::extractFromVC()
4456 bool const found = LyXVC::file_not_found_hook(d->filename);
4458 return ReadFileNotFound;
4459 if (!d->filename.isReadableFile())
4465 Buffer::ReadStatus Buffer::loadEmergency()
4467 FileName const emergencyFile = getEmergencyFileName();
4468 if (!emergencyFile.exists()
4469 || emergencyFile.lastModified() <= d->filename.lastModified())
4470 return ReadFileNotFound;
4472 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4473 docstring const text = bformat(_("An emergency save of the document "
4474 "%1$s exists.\n\nRecover emergency save?"), file);
4476 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4477 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4483 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4484 bool const success = (ret_llf == ReadSuccess);
4486 if (hasReadonlyFlag()) {
4487 Alert::warning(_("File is read-only"),
4488 bformat(_("An emergency file is successfully loaded, "
4489 "but the original file %1$s is marked read-only. "
4490 "Please make sure to save the document as a different "
4491 "file."), from_utf8(d->filename.absFileName())));
4494 lyxvc().file_found_hook(d->filename);
4495 str = _("Document was successfully recovered.");
4497 str = _("Document was NOT successfully recovered.");
4498 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4499 makeDisplayPath(emergencyFile.absFileName()));
4501 int const del_emerg =
4502 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4503 _("&Remove"), _("&Keep"));
4504 if (del_emerg == 0) {
4505 emergencyFile.removeFile();
4507 Alert::warning(_("Emergency file deleted"),
4508 _("Do not forget to save your file now!"), true);
4510 return success ? ReadSuccess : ReadEmergencyFailure;
4513 int const del_emerg =
4514 Alert::prompt(_("Delete emergency file?"),
4515 _("Remove emergency file now?"), 1, 1,
4516 _("&Remove"), _("&Keep"));
4518 emergencyFile.removeFile();
4519 return ReadOriginal;
4529 Buffer::ReadStatus Buffer::loadAutosave()
4531 // Now check if autosave file is newer.
4532 FileName const autosaveFile = getAutosaveFileName();
4533 if (!autosaveFile.exists()
4534 || autosaveFile.lastModified() <= d->filename.lastModified())
4535 return ReadFileNotFound;
4537 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4538 docstring const text = bformat(_("The backup of the document %1$s "
4539 "is newer.\n\nLoad the backup instead?"), file);
4540 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4541 _("&Load backup"), _("Load &original"), _("&Cancel"));
4546 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4547 // the file is not saved if we load the autosave file.
4548 if (ret_llf == ReadSuccess) {
4549 if (hasReadonlyFlag()) {
4550 Alert::warning(_("File is read-only"),
4551 bformat(_("A backup file is successfully loaded, "
4552 "but the original file %1$s is marked read-only. "
4553 "Please make sure to save the document as a "
4555 from_utf8(d->filename.absFileName())));
4558 lyxvc().file_found_hook(d->filename);
4561 return ReadAutosaveFailure;
4564 // Here we delete the autosave
4565 autosaveFile.removeFile();
4566 return ReadOriginal;
4574 Buffer::ReadStatus Buffer::loadLyXFile()
4576 if (!d->filename.isReadableFile()) {
4577 ReadStatus const ret_rvc = extractFromVC();
4578 if (ret_rvc != ReadSuccess)
4582 ReadStatus const ret_re = loadEmergency();
4583 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4586 ReadStatus const ret_ra = loadAutosave();
4587 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4590 return loadThisLyXFile(d->filename);
4594 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4596 return readFile(fn);
4600 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4602 for (auto const & err : terr) {
4603 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4604 int errorRow = err.error_in_line;
4605 Buffer const * buf = 0;
4607 if (err.child_name.empty())
4608 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4610 // The error occurred in a child
4611 for (Buffer const * child : getDescendents()) {
4612 string const child_name =
4613 DocFileName(changeExtension(child->absFileName(), "tex")).
4615 if (err.child_name != child_name)
4617 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4618 if (!TexRow::isNone(start)) {
4619 buf = d->cloned_buffer_
4620 ? child->d->cloned_buffer_->d->owner_
4627 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4633 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4635 LBUFERR(!text().paragraphs().empty());
4637 // Use the master text class also for child documents
4638 Buffer const * const master = masterBuffer();
4639 DocumentClass const & textclass = master->params().documentClass();
4641 FileNamePairList old_bibfiles;
4642 // do this only if we are the top-level Buffer
4643 if (master == this) {
4644 textclass.counters().reset(from_ascii("bibitem"));
4645 reloadBibInfoCache();
4646 // we will re-read this cache as we go through, but we need
4647 // to know whether it's changed to know whether we need to
4648 // update the bibinfo cache.
4649 old_bibfiles = d->bibfiles_cache_;
4650 d->bibfiles_cache_.clear();
4653 // keep the buffers to be children in this set. If the call from the
4654 // master comes back we can see which of them were actually seen (i.e.
4655 // via an InsetInclude). The remaining ones in the set need still be updated.
4656 static std::set<Buffer const *> bufToUpdate;
4657 if (scope == UpdateMaster) {
4658 // If this is a child document start with the master
4659 if (master != this) {
4660 bufToUpdate.insert(this);
4661 master->updateBuffer(UpdateMaster, utype);
4662 // If the master buffer has no gui associated with it, then the TocModel is
4663 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4664 // (bug 5699). The same happens if the master buffer is open in a different
4665 // window. This test catches both possibilities.
4666 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4667 // There remains a problem here: If there is another child open in yet a third
4668 // window, that TOC is not updated. So some more general solution is needed at
4670 if (master->d->gui_ != d->gui_)
4673 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4674 if (bufToUpdate.find(this) == bufToUpdate.end())
4678 // start over the counters in the master
4679 textclass.counters().reset();
4682 // update will be done below for this buffer
4683 bufToUpdate.erase(this);
4685 // update all caches
4686 clearReferenceCache();
4688 setChangesPresent(false);
4690 Buffer & cbuf = const_cast<Buffer &>(*this);
4693 ParIterator parit = cbuf.par_iterator_begin();
4694 updateBuffer(parit, utype);
4696 // If this document has siblings, then update the TocBackend later. The
4697 // reason is to ensure that later siblings are up to date when e.g. the
4698 // broken or not status of references is computed. The update is called
4699 // in InsetInclude::addToToc.
4703 // if the bibfiles changed, the cache of bibinfo is invalid
4704 sort(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end());
4705 // the old one should already be sorted
4706 if (old_bibfiles != d->bibfiles_cache_) {
4707 invalidateBibinfoCache();
4708 reloadBibInfoCache();
4709 // We relied upon the bibinfo cache when recalculating labels. But that
4710 // cache was invalid, although we didn't find that out until now. So we
4711 // have to do it all again.
4712 // That said, the only thing we really need to do is update the citation
4713 // labels. Nothing else will have changed. So we could create a new
4714 // UpdateType that would signal that fact, if we needed to do so.
4715 parit = cbuf.par_iterator_begin();
4716 updateBuffer(parit, utype);
4719 d->bibinfo_cache_valid_ = true;
4720 d->cite_labels_valid_ = true;
4722 cbuf.tocBackend().update(true, utype);
4723 if (scope == UpdateMaster)
4724 cbuf.structureChanged();
4728 static depth_type getDepth(DocIterator const & it)
4730 depth_type depth = 0;
4731 for (size_t i = 0 ; i < it.depth() ; ++i)
4732 if (!it[i].inset().inMathed())
4733 depth += it[i].paragraph().getDepth() + 1;
4734 // remove 1 since the outer inset does not count
4735 // we should have at least one non-math inset, so
4736 // depth should nevery be 0. but maybe it is worth
4737 // marking this, just in case.
4739 // coverity[INTEGER_OVERFLOW]
4743 static depth_type getItemDepth(ParIterator const & it)
4745 Paragraph const & par = *it;
4746 LabelType const labeltype = par.layout().labeltype;
4748 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4751 // this will hold the lowest depth encountered up to now.
4752 depth_type min_depth = getDepth(it);
4753 ParIterator prev_it = it;
4756 --prev_it.top().pit();
4758 // start of nested inset: go to outer par
4760 if (prev_it.empty()) {
4761 // start of document: nothing to do
4766 // We search for the first paragraph with same label
4767 // that is not more deeply nested.
4768 Paragraph & prev_par = *prev_it;
4769 depth_type const prev_depth = getDepth(prev_it);
4770 if (labeltype == prev_par.layout().labeltype) {
4771 if (prev_depth < min_depth)
4772 return prev_par.itemdepth + 1;
4773 if (prev_depth == min_depth)
4774 return prev_par.itemdepth;
4776 min_depth = min(min_depth, prev_depth);
4777 // small optimization: if we are at depth 0, we won't
4778 // find anything else
4779 if (prev_depth == 0)
4785 static bool needEnumCounterReset(ParIterator const & it)
4787 Paragraph const & par = *it;
4788 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4789 depth_type const cur_depth = par.getDepth();
4790 ParIterator prev_it = it;
4791 while (prev_it.pit()) {
4792 --prev_it.top().pit();
4793 Paragraph const & prev_par = *prev_it;
4794 if (prev_par.getDepth() <= cur_depth)
4795 return prev_par.layout().name() != par.layout().name();
4797 // start of nested inset: reset
4802 // set the label of a paragraph. This includes the counters.
4803 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4805 BufferParams const & bp = owner_->masterBuffer()->params();
4806 DocumentClass const & textclass = bp.documentClass();
4807 Paragraph & par = it.paragraph();
4808 Layout const & layout = par.layout();
4809 Counters & counters = textclass.counters();
4811 if (par.params().startOfAppendix()) {
4812 // We want to reset the counter corresponding to toplevel sectioning
4813 Layout const & lay = textclass.getTOCLayout();
4814 docstring const cnt = lay.counter;
4816 counters.reset(cnt);
4817 counters.appendix(true);
4819 par.params().appendix(counters.appendix());
4821 // Compute the item depth of the paragraph
4822 par.itemdepth = getItemDepth(it);
4824 if (layout.margintype == MARGIN_MANUAL) {
4825 if (par.params().labelWidthString().empty())
4826 par.params().labelWidthString(par.expandLabel(layout, bp));
4827 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4828 // we do not need to do anything here, since the empty case is
4829 // handled during export.
4831 par.params().labelWidthString(docstring());
4834 switch(layout.labeltype) {
4835 case LABEL_ITEMIZE: {
4836 // At some point of time we should do something more
4837 // clever here, like:
4838 // par.params().labelString(
4839 // bp.user_defined_bullet(par.itemdepth).getText());
4840 // for now, use a simple hardcoded label
4841 docstring itemlabel;
4842 switch (par.itemdepth) {
4844 itemlabel = char_type(0x2022);
4847 itemlabel = char_type(0x2013);
4850 itemlabel = char_type(0x2217);
4853 itemlabel = char_type(0x2219); // or 0x00b7
4856 par.params().labelString(itemlabel);
4860 case LABEL_ENUMERATE: {
4861 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4863 switch (par.itemdepth) {
4874 enumcounter += "iv";
4877 // not a valid enumdepth...
4881 if (needEnumCounterReset(it)) {
4882 // Increase the master counter?
4883 if (layout.stepmastercounter)
4884 counters.stepMaster(enumcounter, utype);
4885 // Maybe we have to reset the enumeration counter.
4886 if (!layout.resumecounter)
4887 counters.reset(enumcounter);
4889 counters.step(enumcounter, utype);
4891 string const & lang = par.getParLanguage(bp)->code();
4892 par.params().labelString(counters.theCounter(enumcounter, lang));
4897 case LABEL_SENSITIVE: {
4898 string const & type = counters.current_float();
4899 docstring full_label;
4901 full_label = owner_->B_("Senseless!!! ");
4903 docstring name = owner_->B_(textclass.floats().getType(type).name());
4904 if (counters.hasCounter(from_utf8(type))) {
4905 string const & lang = par.getParLanguage(bp)->code();
4906 counters.step(from_utf8(type), utype);
4907 full_label = bformat(from_ascii("%1$s %2$s:"),
4909 counters.theCounter(from_utf8(type), lang));
4911 full_label = bformat(from_ascii("%1$s #:"), name);
4913 par.params().labelString(full_label);
4917 case LABEL_NO_LABEL:
4918 par.params().labelString(docstring());
4922 case LABEL_CENTERED:
4923 case LABEL_STATIC: {
4924 docstring const & lcounter = layout.counter;
4925 if (!lcounter.empty()) {
4926 if (layout.toclevel <= bp.secnumdepth
4927 && (layout.latextype != LATEX_ENVIRONMENT
4928 || it.text()->isFirstInSequence(it.pit()))) {
4929 if (counters.hasCounter(lcounter))
4930 counters.step(lcounter, utype);
4931 par.params().labelString(par.expandLabel(layout, bp));
4933 par.params().labelString(docstring());
4935 par.params().labelString(par.expandLabel(layout, bp));
4941 par.params().labelString(par.expandLabel(layout, bp));
4946 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4948 // LASSERT: Is it safe to continue here, or should we just return?
4949 LASSERT(parit.pit() == 0, /**/);
4951 // Set the position of the text in the buffer to be able
4952 // to resolve macros in it.
4953 parit.text()->setMacrocontextPosition(parit);
4955 depth_type maxdepth = 0;
4956 pit_type const lastpit = parit.lastpit();
4957 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4958 // reduce depth if necessary
4959 if (parit->params().depth() > maxdepth) {
4960 /** FIXME: this function is const, but
4961 * nevertheless it modifies the buffer. To be
4962 * cleaner, one should modify the buffer in
4963 * another function, which is actually
4964 * non-const. This would however be costly in
4965 * terms of code duplication.
4967 CursorData(parit).recordUndo();
4968 parit->params().depth(maxdepth);
4970 maxdepth = parit->getMaxDepthAfter();
4972 if (utype == OutputUpdate) {
4973 // track the active counters
4974 // we have to do this for the master buffer, since the local
4975 // buffer isn't tracking anything.
4976 masterBuffer()->params().documentClass().counters().
4977 setActiveLayout(parit->layout());
4980 // set the counter for this paragraph
4981 d->setLabel(parit, utype);
4983 // update change-tracking flag
4984 parit->addChangesToBuffer(*this);
4987 for (auto const & insit : parit->insetList()) {
4988 parit.pos() = insit.pos;
4989 insit.inset->updateBuffer(parit, utype);
4995 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4996 WordLangTuple & word_lang, docstring_list & suggestions) const
5000 suggestions.clear();
5001 word_lang = WordLangTuple();
5002 bool const to_end = to.empty();
5003 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5004 // OK, we start from here.
5005 for (; from != end; from.forwardPos()) {
5006 // This skips all insets with spell check disabled.
5007 while (!from.allowSpellCheck()) {
5011 // If from is at the end of the document (which is possible
5012 // when "from" was changed above) LyX will crash later otherwise.
5013 if (from.atEnd() || (!to_end && from >= end))
5016 from.paragraph().spellCheck();
5017 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5018 if (SpellChecker::misspelled(res)) {
5022 // Do not increase progress when from == to, otherwise the word
5023 // count will be wrong.
5033 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5035 bool inword = false;
5040 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5041 if (!dit.inTexted()) {
5046 Paragraph const & par = dit.paragraph();
5047 pos_type const pos = dit.pos();
5049 // Copied and adapted from isWordSeparator() in Paragraph
5050 if (pos == dit.lastpos()) {
5053 Inset const * ins = par.getInset(pos);
5054 if (ins && skipNoOutput && !ins->producesOutput()) {
5057 // stop if end of range was skipped
5058 if (!to.atEnd() && dit >= to)
5061 } else if (!par.isDeleted(pos)) {
5062 if (par.isWordSeparator(pos))
5068 if (ins && ins->isLetter())
5070 else if (ins && ins->isSpace())
5073 char_type const c = par.getChar(pos);
5074 if (isPrintableNonspace(c))
5076 else if (isSpace(c))
5086 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5088 d->updateStatistics(from, to, skipNoOutput);
5092 int Buffer::wordCount() const
5094 return d->wordCount();
5098 int Buffer::charCount(bool with_blanks) const
5100 return d->charCount(with_blanks);
5104 Buffer::ReadStatus Buffer::reload()
5107 // c.f. bug https://www.lyx.org/trac/ticket/6587
5108 removeAutosaveFile();
5109 // e.g., read-only status could have changed due to version control
5110 d->filename.refresh();
5111 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5113 // clear parent. this will get reset if need be.
5115 ReadStatus const status = loadLyXFile();
5116 if (status == ReadSuccess) {
5121 message(bformat(_("Document %1$s reloaded."), disp_fn));
5124 message(bformat(_("Could not reload document %1$s."), disp_fn));
5134 bool Buffer::saveAs(FileName const & fn)
5136 FileName const old_name = fileName();
5137 FileName const old_auto = getAutosaveFileName();
5138 bool const old_unnamed = isUnnamed();
5139 bool success = true;
5140 d->old_position = filePath();
5147 // bring the autosave file with us, just in case.
5148 moveAutosaveFile(old_auto);
5149 // validate version control data and
5150 // correct buffer title
5151 lyxvc().file_found_hook(fileName());
5153 // the file has now been saved to the new location.
5154 // we need to check that the locations of child buffers
5156 checkChildBuffers();
5157 checkMasterBuffer();
5160 // reset the old filename and unnamed state
5161 setFileName(old_name);
5162 setUnnamed(old_unnamed);
5166 d->old_position.clear();
5171 void Buffer::checkChildBuffers()
5173 for (auto const & bit : d->children_positions) {
5174 DocIterator dit = bit.second;
5175 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5176 if (!cbuf || !theBufferList().isLoaded(cbuf))
5178 Inset * inset = dit.nextInset();
5179 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5180 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5181 docstring const & incfile = inset_inc->getParam("filename");
5182 string oldloc = cbuf->absFileName();
5183 string newloc = makeAbsPath(to_utf8(incfile),
5184 onlyPath(absFileName())).absFileName();
5185 if (oldloc == newloc)
5187 // the location of the child file is incorrect.
5189 inset_inc->setChildBuffer(0);
5191 // invalidate cache of children
5192 d->children_positions.clear();
5193 d->position_to_children.clear();
5197 // If a child has been saved under a different name/path, it might have been
5198 // orphaned. Therefore the master needs to be reset (bug 8161).
5199 void Buffer::checkMasterBuffer()
5201 Buffer const * const master = masterBuffer();
5205 // necessary to re-register the child (bug 5873)
5206 // FIXME: clean up updateMacros (here, only
5207 // child registering is needed).
5208 master->updateMacros();
5209 // (re)set master as master buffer, but only
5210 // if we are a real child
5211 if (master->isChild(this))
5218 string Buffer::includedFilePath(string const & name, string const & ext) const
5220 if (d->old_position.empty() ||
5221 equivalent(FileName(d->old_position), FileName(filePath())))
5224 bool isabsolute = FileName::isAbsolute(name);
5225 // both old_position and filePath() end with a path separator
5226 string absname = isabsolute ? name : d->old_position + name;
5228 // if old_position is set to origin, we need to do the equivalent of
5229 // getReferencedFileName() (see readDocument())
5230 if (!isabsolute && d->old_position == params().origin) {
5231 FileName const test(addExtension(filePath() + name, ext));
5233 absname = filePath() + name;
5236 if (!FileName(addExtension(absname, ext)).exists())
5240 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5242 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5243 from_utf8(filePath())));
5247 void Buffer::setChangesPresent(bool b) const
5249 d->tracked_changes_present_ = b;
5253 bool Buffer::areChangesPresent() const
5255 return d->tracked_changes_present_;
5259 void Buffer::updateChangesPresent() const
5261 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5262 setChangesPresent(false);
5263 ParConstIterator it = par_iterator_begin();
5264 ParConstIterator const end = par_iterator_end();
5265 for (; !areChangesPresent() && it != end; ++it)
5266 it->addChangesToBuffer(*this);
5270 void Buffer::Impl::refreshFileMonitor()
5272 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5273 file_monitor_->refresh();
5277 // The previous file monitor is invalid
5278 // This also destroys the previous file monitor and all its connections
5279 file_monitor_ = FileSystemWatcher::monitor(filename);
5280 // file_monitor_ will be destroyed with *this, so it is not going to call a
5281 // destroyed object method.
5282 file_monitor_->connect([this](bool exists) {
5283 fileExternallyModified(exists);
5288 void Buffer::Impl::fileExternallyModified(bool const exists)
5290 // ignore notifications after our own saving operations
5291 if (checksum_ == filename.checksum()) {
5292 LYXERR(Debug::FILES, "External modification but "
5293 "checksum unchanged: " << filename);
5296 lyx_clean = bak_clean = false;
5297 // If the file has been deleted, only mark the file as dirty since it is
5298 // pointless to prompt for reloading. If later a file is moved into this
5299 // location, then the externally modified warning will appear then.
5301 externally_modified_ = true;
5302 // Update external modification notification.
5303 // Dirty buffers must be visible at all times.
5304 if (wa_ && wa_->unhide(owner_))
5305 wa_->updateTitles();
5307 // Unable to unhide the buffer (e.g. no GUI or not current View)
5312 bool Buffer::notifiesExternalModification() const
5314 return d->externally_modified_;
5318 void Buffer::clearExternalModification() const
5320 d->externally_modified_ = false;
5322 d->wa_->updateTitles();