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 support::FileName exportFileName() const;
182 mutable TexRow texrow;
184 /// need to regenerate .tex?
188 mutable bool lyx_clean;
190 /// is autosave needed?
191 mutable bool bak_clean;
193 /// is this an unnamed file (New...)?
196 /// is this an internal bufffer?
197 bool internal_buffer;
202 /// name of the file the buffer is associated with.
205 /** Set to true only when the file is fully loaded.
206 * Used to prevent the premature generation of previews
207 * and by the citation inset.
209 bool file_fully_loaded;
211 /// original format of loaded file
214 /// if the file was originally loaded from an older format, do
215 /// we need to back it up still?
216 bool need_format_backup;
218 /// Ignore the parent (e.g. when exporting a child standalone)?
222 mutable TocBackend toc_backend;
227 ScopeMacro(DocIterator const & s, MacroData const & m)
228 : scope(s), macro(m) {}
232 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
233 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
234 /// map from the macro name to the position map,
235 /// which maps the macro definition position to the scope and the MacroData.
236 NamePositionScopeMacroMap macros;
237 /// This seem to change the way Buffer::getMacro() works
238 mutable bool macro_lock;
240 /// positions of child buffers in the buffer
241 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
243 ScopeBuffer() : buffer(0) {}
244 ScopeBuffer(DocIterator const & s, Buffer const * b)
245 : scope(s), buffer(b) {}
247 Buffer const * buffer;
249 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
250 /// position of children buffers in this buffer
251 BufferPositionMap children_positions;
252 /// map from children inclusion positions to their scope and their buffer
253 PositionScopeBufferMap position_to_children;
255 /// Contains the old buffer filePath() while saving-as, or the
256 /// directory where the document was last saved while loading.
259 /** Keeps track of the path of local layout files.
260 * If possible, it is always relative to the buffer path.
261 * Empty for layouts in system or user directory.
263 string layout_position;
265 /// Container for all sort of Buffer dependant errors.
266 map<string, ErrorList> errorLists;
268 /// checksum used to test if the file has been externally modified. Used to
269 /// double check whether the file had been externally modified when saving.
270 unsigned long checksum_;
273 frontend::WorkAreaManager * wa_;
275 frontend::GuiBufferDelegate * gui_;
280 /// A cache for the bibfiles (including bibfiles of loaded child
281 /// documents), needed for appropriate update of natbib labels.
282 mutable docstring_list bibfiles_cache_;
284 // FIXME The caching mechanism could be improved. At present, we have a
285 // cache for each Buffer, that caches all the bibliography info for that
286 // Buffer. A more efficient solution would be to have a global cache per
287 // file, and then to construct the Buffer's bibinfo from that.
288 /// A cache for bibliography info
289 mutable BiblioInfo bibinfo_;
290 /// whether the bibinfo cache is valid
291 mutable bool bibinfo_cache_valid_;
292 /// whether the bibfile cache is valid
293 mutable bool bibfile_cache_valid_;
294 /// Cache of timestamps of .bib files
295 map<FileName, time_t> bibfile_status_;
296 /// Indicates whether the bibinfo has changed since the last time
297 /// we ran updateBuffer(), i.e., whether citation labels may need
299 mutable bool cite_labels_valid_;
301 /// These two hold the file name and format, written to by
302 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
303 FileName preview_file_;
304 string preview_format_;
305 /// If there was an error when previewing, on the next preview we do
306 /// a fresh compile (e.g. in case the user installed a package that
310 mutable RefCache ref_cache_;
312 /// our Text that should be wrapped in an InsetText
316 PreviewLoader * preview_loader_;
318 /// This is here to force the test to be done whenever parent_buffer
320 Buffer const * parent() const
322 // ignore_parent temporarily "orphans" a buffer
323 // (e.g. if a child is compiled standalone)
326 // if parent_buffer is not loaded, then it has been unloaded,
327 // which means that parent_buffer is an invalid pointer. So we
328 // set it to null in that case.
329 // however, the BufferList doesn't know about cloned buffers, so
330 // they will always be regarded as unloaded. in that case, we hope
332 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
334 return parent_buffer;
338 void setParent(Buffer const * pb)
340 if (parent_buffer == pb)
343 if (!cloned_buffer_ && parent_buffer && pb)
344 LYXERR0("Warning: a buffer should not have two parents!");
346 if (!cloned_buffer_ && parent_buffer) {
347 parent_buffer->invalidateBibinfoCache();
351 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
352 /// This one is useful for preview detached in a thread.
353 Buffer const * cloned_buffer_;
355 CloneList * clone_list_;
356 /// are we in the process of exporting this buffer?
357 mutable bool doing_export;
359 /// compute statistics
360 /// \p from initial position
361 /// \p to points to the end position
362 void updateStatistics(DocIterator & from, DocIterator & to,
363 bool skipNoOutput = true);
364 /// statistics accessor functions
365 int wordCount() const
369 int charCount(bool with_blanks) const
372 + (with_blanks ? blank_count_ : 0);
375 // does the buffer contain tracked changes? (if so, we automatically
376 // display the review toolbar, for instance)
377 mutable bool tracked_changes_present_;
379 // Make sure the file monitor monitors the good file.
380 void refreshFileMonitor();
382 /// Notify or clear of external modification
383 void fileExternallyModified(bool exists);
385 /// has been externally modified? Can be reset by the user.
386 mutable bool externally_modified_;
389 /// So we can force access via the accessors.
390 mutable Buffer const * parent_buffer;
396 FileMonitorPtr file_monitor_;
400 /// Creates the per buffer temporary directory
401 static FileName createBufferTmpDir()
403 // FIXME This would be the ideal application for a TempDir class (like
404 // TempFile but for directories)
409 Mutex::Locker locker(&mutex);
410 counter = convert<string>(count++);
412 // We are in our own directory. Why bother to mangle name?
413 // In fact I wrote this code to circumvent a problematic behaviour
414 // (bug?) of EMX mkstemp().
415 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
418 if (!tmpfl.createDirectory(0777)) {
419 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
420 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
421 from_utf8(tmpfl.absFileName())));
427 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
428 Buffer const * cloned_buffer)
429 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
430 internal_buffer(false), read_only(readonly_), filename(file),
431 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
432 ignore_parent(false), toc_backend(owner), macro_lock(false),
433 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
434 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
435 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
436 clone_list_(0), doing_export(false),
437 tracked_changes_present_(0), externally_modified_(false), parent_buffer(0),
438 word_count_(0), char_count_(0), blank_count_(0)
440 refreshFileMonitor();
441 if (!cloned_buffer_) {
442 temppath = createBufferTmpDir();
443 lyxvc.setBuffer(owner_);
445 wa_ = new frontend::WorkAreaManager;
448 temppath = cloned_buffer_->d->temppath;
449 file_fully_loaded = true;
450 params = cloned_buffer_->d->params;
451 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
452 bibinfo_ = cloned_buffer_->d->bibinfo_;
453 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
454 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
455 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
456 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
457 unnamed = cloned_buffer_->d->unnamed;
458 internal_buffer = cloned_buffer_->d->internal_buffer;
459 layout_position = cloned_buffer_->d->layout_position;
460 preview_file_ = cloned_buffer_->d->preview_file_;
461 preview_format_ = cloned_buffer_->d->preview_format_;
462 preview_error_ = cloned_buffer_->d->preview_error_;
463 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
467 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
468 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
470 LYXERR(Debug::INFO, "Buffer::Buffer()");
472 d->inset = new InsetText(*cloned_buffer->d->inset);
473 d->inset->setBuffer(*this);
474 // FIXME: optimize this loop somewhat, maybe by creating a new
475 // general recursive Inset::setId().
476 DocIterator it = doc_iterator_begin(this);
477 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
478 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
479 it.paragraph().setId(cloned_it.paragraph().id());
481 d->inset = new InsetText(this);
482 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
488 LYXERR(Debug::INFO, "Buffer::~Buffer()");
489 // here the buffer should take care that it is
490 // saved properly, before it goes into the void.
492 // GuiView already destroyed
496 // No need to do additional cleanups for internal buffer.
502 // this is in case of recursive includes: we won't try to delete
503 // ourselves as a child.
504 d->clone_list_->erase(this);
505 // loop over children
506 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
507 Impl::BufferPositionMap::iterator end = d->children_positions.end();
508 for (; it != end; ++it) {
509 Buffer * child = const_cast<Buffer *>(it->first);
510 if (d->clone_list_->erase(child))
513 // if we're the master buffer, then we should get rid of the list
516 // If this is not empty, we have leaked something. Worse, one of the
517 // children still has a reference to this list. But we will try to
518 // continue, rather than shut down.
519 LATTEST(d->clone_list_->empty());
520 list<CloneList *>::iterator it =
521 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
522 if (it == cloned_buffers.end()) {
523 // We will leak in this case, but it is safe to continue.
526 cloned_buffers.erase(it);
527 delete d->clone_list_;
529 // FIXME Do we really need to do this right before we delete d?
530 // clear references to children in macro tables
531 d->children_positions.clear();
532 d->position_to_children.clear();
534 // loop over children
535 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
536 Impl::BufferPositionMap::iterator end = d->children_positions.end();
537 for (; it != end; ++it) {
538 Buffer * child = const_cast<Buffer *>(it->first);
539 if (theBufferList().isLoaded(child)) {
540 if (theBufferList().isOthersChild(this, child))
543 theBufferList().release(child);
548 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
550 msg += emergencyWrite();
552 msg += " " + _("Save failed! Document is lost.");
554 Alert::warning(_("Attempting to close changed document!"), msg);
557 // FIXME Do we really need to do this right before we delete d?
558 // clear references to children in macro tables
559 d->children_positions.clear();
560 d->position_to_children.clear();
562 if (!d->temppath.destroyDirectory()) {
563 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
564 from_utf8(d->temppath.absFileName())));
573 Buffer * Buffer::cloneWithChildren() const
576 cloned_buffers.push_back(new CloneList);
577 CloneList * clones = cloned_buffers.back();
579 cloneWithChildren(bufmap, clones);
581 // make sure we got cloned
582 BufferMap::const_iterator bit = bufmap.find(this);
583 LASSERT(bit != bufmap.end(), return 0);
584 Buffer * cloned_buffer = bit->second;
586 return cloned_buffer;
590 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
592 // have we already been cloned?
593 if (bufmap.find(this) != bufmap.end())
596 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
598 // The clone needs its own DocumentClass, since running updateBuffer() will
599 // modify it, and we would otherwise be sharing it with the original Buffer.
600 buffer_clone->params().makeDocumentClass(true);
602 cap::switchBetweenClasses(
603 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
604 static_cast<InsetText &>(buffer_clone->inset()), el);
606 bufmap[this] = buffer_clone;
607 clones->insert(buffer_clone);
608 buffer_clone->d->clone_list_ = clones;
609 buffer_clone->d->macro_lock = true;
610 buffer_clone->d->children_positions.clear();
612 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
613 // math macro caches need to be rethought and simplified.
614 // I am not sure wether we should handle Buffer cloning here or in BufferList.
615 // Right now BufferList knows nothing about buffer clones.
616 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
617 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
618 for (; it != end; ++it) {
619 DocIterator dit = it->first.clone(buffer_clone);
620 dit.setBuffer(buffer_clone);
621 Buffer * child = const_cast<Buffer *>(it->second.buffer);
623 child->cloneWithChildren(bufmap, clones);
624 BufferMap::iterator const bit = bufmap.find(child);
625 LASSERT(bit != bufmap.end(), continue);
626 Buffer * child_clone = bit->second;
628 Inset * inset = dit.nextInset();
629 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
630 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
631 inset_inc->setChildBuffer(child_clone);
632 child_clone->d->setParent(buffer_clone);
633 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
634 buffer_clone->setChild(dit, child_clone);
636 buffer_clone->d->macro_lock = false;
641 Buffer * Buffer::cloneBufferOnly() const {
642 cloned_buffers.push_back(new CloneList);
643 CloneList * clones = cloned_buffers.back();
644 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
646 // The clone needs its own DocumentClass, since running updateBuffer() will
647 // modify it, and we would otherwise be sharing it with the original Buffer.
648 buffer_clone->params().makeDocumentClass(true);
650 cap::switchBetweenClasses(
651 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
652 static_cast<InsetText &>(buffer_clone->inset()), el);
654 clones->insert(buffer_clone);
655 buffer_clone->d->clone_list_ = clones;
657 // we won't be cloning the children
658 buffer_clone->d->children_positions.clear();
663 bool Buffer::isClone() const
665 return d->cloned_buffer_;
669 void Buffer::changed(bool update_metrics) const
672 d->wa_->redrawAll(update_metrics);
676 frontend::WorkAreaManager & Buffer::workAreaManager() const
683 Text & Buffer::text() const
685 return d->inset->text();
689 Inset & Buffer::inset() const
695 BufferParams & Buffer::params()
701 BufferParams const & Buffer::params() const
707 BufferParams const & Buffer::masterParams() const
709 if (masterBuffer() == this)
712 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
713 // Copy child authors to the params. We need those pointers.
714 AuthorList const & child_authors = params().authors();
715 AuthorList::Authors::const_iterator it = child_authors.begin();
716 for (; it != child_authors.end(); ++it)
717 mparams.authors().record(*it);
722 double Buffer::fontScalingFactor() const
724 return isExporting() ? 75.0 * params().html_math_img_scale
725 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
729 ParagraphList & Buffer::paragraphs()
731 return text().paragraphs();
735 ParagraphList const & Buffer::paragraphs() const
737 return text().paragraphs();
741 LyXVC & Buffer::lyxvc()
747 LyXVC const & Buffer::lyxvc() const
753 string const Buffer::temppath() const
755 return d->temppath.absFileName();
759 TexRow & Buffer::texrow()
765 TexRow const & Buffer::texrow() const
771 TocBackend & Buffer::tocBackend() const
773 return d->toc_backend;
777 Undo & Buffer::undo()
783 void Buffer::setChild(DocIterator const & dit, Buffer * child)
785 d->children_positions[child] = dit;
789 string Buffer::latexName(bool const no_path) const
791 FileName latex_name =
792 makeLatexName(d->exportFileName());
793 return no_path ? latex_name.onlyFileName()
794 : latex_name.absFileName();
798 FileName Buffer::Impl::exportFileName() const
800 docstring const branch_suffix =
801 params.branchlist().getFileNameSuffix();
802 if (branch_suffix.empty())
805 string const name = filename.onlyFileNameWithoutExt()
806 + to_utf8(branch_suffix);
807 FileName res(filename.onlyPath().absFileName() + "/" + name);
808 res.changeExtension(filename.extension());
814 string Buffer::logName(LogType * type) const
816 string const filename = latexName(false);
818 if (filename.empty()) {
824 string const path = temppath();
826 FileName const fname(addName(temppath(),
827 onlyFileName(changeExtension(filename,
830 // FIXME: how do we know this is the name of the build log?
831 FileName const bname(
832 addName(path, onlyFileName(
833 changeExtension(filename,
834 theFormats().extension(params().bufferFormat()) + ".out"))));
836 // Also consider the master buffer log file
837 FileName masterfname = fname;
838 LogType mtype = latexlog;
839 if (masterBuffer() != this) {
840 string const mlogfile = masterBuffer()->logName(&mtype);
841 masterfname = FileName(mlogfile);
844 // If no Latex log or Build log is newer, show Build log
845 if (bname.exists() &&
846 ((!fname.exists() && !masterfname.exists())
847 || (fname.lastModified() < bname.lastModified()
848 && masterfname.lastModified() < bname.lastModified()))) {
849 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
852 return bname.absFileName();
853 // If we have a newer master file log or only a master log, show this
854 } else if (fname != masterfname
855 && (!fname.exists() && (masterfname.exists()
856 || fname.lastModified() < masterfname.lastModified()))) {
857 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
860 return masterfname.absFileName();
862 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
865 return fname.absFileName();
869 void Buffer::setReadonly(bool const flag)
871 if (d->read_only != flag) {
878 void Buffer::setFileName(FileName const & fname)
880 bool const changed = fname != d->filename;
882 d->refreshFileMonitor();
884 lyxvc().file_found_hook(fname);
885 setReadonly(d->filename.isReadOnly());
891 int Buffer::readHeader(Lexer & lex)
893 int unknown_tokens = 0;
895 int begin_header_line = -1;
897 // Initialize parameters that may be/go lacking in header:
898 params().branchlist().clear();
899 params().preamble.erase();
900 params().options.erase();
901 params().master.erase();
902 params().float_placement.erase();
903 params().paperwidth.erase();
904 params().paperheight.erase();
905 params().leftmargin.erase();
906 params().rightmargin.erase();
907 params().topmargin.erase();
908 params().bottommargin.erase();
909 params().headheight.erase();
910 params().headsep.erase();
911 params().footskip.erase();
912 params().columnsep.erase();
913 params().fonts_cjk.erase();
914 params().listings_params.clear();
915 params().clearLayoutModules();
916 params().clearRemovedModules();
917 params().clearIncludedChildren();
918 params().pdfoptions().clear();
919 params().indiceslist().clear();
920 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
921 params().isbackgroundcolor = false;
922 params().fontcolor = RGBColor(0, 0, 0);
923 params().isfontcolor = false;
924 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
925 params().boxbgcolor = RGBColor(0xFF, 0, 0);
926 params().html_latex_start.clear();
927 params().html_latex_end.clear();
928 params().html_math_img_scale = 1.0;
929 params().output_sync_macro.erase();
930 params().setLocalLayout(docstring(), false);
931 params().setLocalLayout(docstring(), true);
932 params().biblio_opts.erase();
933 params().biblatex_bibstyle.erase();
934 params().biblatex_citestyle.erase();
935 params().multibib.erase();
937 for (int i = 0; i < 4; ++i) {
938 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
939 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
942 ErrorList & errorList = d->errorLists["Parse"];
951 if (token == "\\end_header")
955 if (token == "\\begin_header") {
956 begin_header_line = line;
960 LYXERR(Debug::PARSER, "Handling document header token: `"
963 string const result =
964 params().readToken(lex, token, d->filename.onlyPath());
965 if (!result.empty()) {
966 if (token == "\\textclass") {
967 d->layout_position = result;
970 docstring const s = bformat(_("Unknown token: "
974 errorList.push_back(ErrorItem(_("Document header error"), s));
978 if (begin_header_line) {
979 docstring const s = _("\\begin_header is missing");
980 errorList.push_back(ErrorItem(_("Document header error"), s));
983 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
985 params().makeDocumentClass();
987 return unknown_tokens;
992 // changed to be public and have one parameter
993 // Returns true if "\end_document" is not read (Asger)
994 bool Buffer::readDocument(Lexer & lex)
996 ErrorList & errorList = d->errorLists["Parse"];
999 // remove dummy empty par
1000 paragraphs().clear();
1002 if (!lex.checkFor("\\begin_document")) {
1003 docstring const s = _("\\begin_document is missing");
1004 errorList.push_back(ErrorItem(_("Document header error"), s));
1009 if (params().output_changes) {
1010 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1011 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1012 LaTeXFeatures::isAvailable("xcolor");
1014 if (!dvipost && !xcolorulem) {
1015 Alert::warning(_("Changes not shown in LaTeX output"),
1016 _("Changes will not be highlighted in LaTeX output, "
1017 "because neither dvipost nor xcolor/ulem are installed.\n"
1018 "Please install these packages or redefine "
1019 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1020 } else if (!xcolorulem) {
1021 Alert::warning(_("Changes not shown in LaTeX output"),
1022 _("Changes will not be highlighted in LaTeX output "
1023 "when using pdflatex, because xcolor and ulem are not installed.\n"
1024 "Please install both packages or redefine "
1025 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1029 if (!parent() && !params().master.empty()) {
1030 FileName const master_file = makeAbsPath(params().master,
1031 onlyPath(absFileName()));
1032 if (isLyXFileName(master_file.absFileName())) {
1034 checkAndLoadLyXFile(master_file, true);
1036 // necessary e.g. after a reload
1037 // to re-register the child (bug 5873)
1038 // FIXME: clean up updateMacros (here, only
1039 // child registering is needed).
1040 master->updateMacros();
1041 // set master as master buffer, but only
1042 // if we are a real child
1043 if (master->isChild(this))
1045 // if the master is not fully loaded
1046 // it is probably just loading this
1047 // child. No warning needed then.
1048 else if (master->isFullyLoaded())
1049 LYXERR0("The master '"
1051 << "' assigned to this document ("
1053 << ") does not include "
1054 "this document. Ignoring the master assignment.");
1055 // If the master has just been created, un-hide it (#11162)
1056 if (!master->fileName().exists())
1057 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH,
1058 master->absFileName()));
1063 // assure we have a default index
1064 params().indiceslist().addDefault(B_("Index"));
1067 if (FileName::isAbsolute(params().origin))
1068 d->old_position = params().origin;
1070 d->old_position = filePath();
1071 bool const res = text().read(lex, errorList, d->inset);
1072 d->old_position.clear();
1074 // inform parent buffer about local macros
1076 Buffer const * pbuf = parent();
1077 UserMacroSet::const_iterator cit = usermacros.begin();
1078 UserMacroSet::const_iterator end = usermacros.end();
1079 for (; cit != end; ++cit)
1080 pbuf->usermacros.insert(*cit);
1084 updateMacroInstances(InternalUpdate);
1089 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1091 Format const * fmt = theFormats().getFormat(format);
1094 // It is important to use the correct extension here, since some
1095 // converters create a wrong output file otherwise (e.g. html2latex)
1096 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1097 ofdocstream os(name.toFilesystemEncoding().c_str());
1098 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1099 bool const success = !(os << contents).fail();
1102 bool converted = false;
1104 params().compressed = false;
1106 // remove dummy empty par
1107 paragraphs().clear();
1109 converted = importFile(format, name, errorList);
1112 removeTempFile(name);
1117 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1119 if (!theConverters().isReachable(format, "lyx"))
1122 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1123 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList)) {
1124 bool const success = readFile(lyx) == ReadSuccess;
1125 removeTempFile(lyx);
1133 bool Buffer::readString(string const & s)
1135 params().compressed = false;
1138 istringstream is(s);
1140 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1141 FileName const fn = tempfile.name();
1144 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1146 if (success && file_format != LYX_FORMAT) {
1147 // We need to call lyx2lyx, so write the input to a file
1148 ofstream os(fn.toFilesystemEncoding().c_str());
1151 // lyxvc in readFile
1152 if (readFile(fn) != ReadSuccess)
1156 if (readDocument(lex))
1162 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1166 if (!lex.setFile(fname)) {
1167 Alert::error(_("File Not Found"),
1168 bformat(_("Unable to open file `%1$s'."),
1169 from_utf8(fn.absFileName())));
1170 return ReadFileNotFound;
1174 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1175 if (ret_plf != ReadSuccess)
1178 if (file_format != LYX_FORMAT) {
1180 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1181 if (ret_clf != ReadSuccess)
1183 ret_clf = readFile(tmpFile);
1184 if (ret_clf == ReadSuccess) {
1185 d->file_format = file_format;
1186 d->need_format_backup = true;
1191 // FIXME: InsetInfo needs to know whether the file is under VCS
1192 // during the parse process, so this has to be done before.
1193 lyxvc().file_found_hook(d->filename);
1195 if (readDocument(lex)) {
1196 Alert::error(_("Document format failure"),
1197 bformat(_("%1$s ended unexpectedly, which means"
1198 " that it is probably corrupted."),
1199 from_utf8(fn.absFileName())));
1200 return ReadDocumentFailure;
1203 d->file_fully_loaded = true;
1204 d->read_only = !d->filename.isWritable();
1205 params().compressed = theFormats().isZippedFile(d->filename);
1211 bool Buffer::isFullyLoaded() const
1213 return d->file_fully_loaded;
1217 void Buffer::setFullyLoaded(bool value)
1219 d->file_fully_loaded = value;
1223 bool Buffer::lastPreviewError() const
1225 return d->preview_error_;
1229 PreviewLoader * Buffer::loader() const
1231 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1233 if (!d->preview_loader_)
1234 d->preview_loader_ = new PreviewLoader(*this);
1235 return d->preview_loader_;
1239 void Buffer::removePreviews() const
1241 delete d->preview_loader_;
1242 d->preview_loader_ = 0;
1246 void Buffer::updatePreviews() const
1248 PreviewLoader * ploader = loader();
1252 InsetIterator it = inset_iterator_begin(*d->inset);
1253 InsetIterator const end = inset_iterator_end(*d->inset);
1254 for (; it != end; ++it)
1255 it->addPreview(it, *ploader);
1257 ploader->startLoading();
1261 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1262 FileName const & fn, int & file_format) const
1264 if(!lex.checkFor("\\lyxformat")) {
1265 Alert::error(_("Document format failure"),
1266 bformat(_("%1$s is not a readable LyX document."),
1267 from_utf8(fn.absFileName())));
1268 return ReadNoLyXFormat;
1274 // LyX formats 217 and earlier were written as 2.17. This corresponds
1275 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1276 // these cases. See also: www.lyx.org/trac/changeset/1313.
1277 size_t dot = tmp_format.find_first_of(".,");
1278 if (dot != string::npos)
1279 tmp_format.erase(dot, 1);
1281 file_format = convert<int>(tmp_format);
1286 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1287 FileName & tmpfile, int from_format)
1289 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1290 tempfile.setAutoRemove(false);
1291 tmpfile = tempfile.name();
1292 if(tmpfile.empty()) {
1293 Alert::error(_("Conversion failed"),
1294 bformat(_("%1$s is from a different"
1295 " version of LyX, but a temporary"
1296 " file for converting it could"
1297 " not be created."),
1298 from_utf8(fn.absFileName())));
1299 return LyX2LyXNoTempFile;
1302 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1303 if (lyx2lyx.empty()) {
1304 Alert::error(_("Conversion script not found"),
1305 bformat(_("%1$s is from a different"
1306 " version of LyX, but the"
1307 " conversion script lyx2lyx"
1308 " could not be found."),
1309 from_utf8(fn.absFileName())));
1310 return LyX2LyXNotFound;
1314 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1315 ostringstream command;
1316 command << os::python()
1317 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1318 << " -t " << convert<string>(LYX_FORMAT)
1319 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1320 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1321 string const command_str = command.str();
1323 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1325 cmd_ret const ret = runCommand(command_str);
1326 if (ret.first != 0) {
1327 if (from_format < LYX_FORMAT) {
1328 Alert::error(_("Conversion script failed"),
1329 bformat(_("%1$s is from an older version"
1330 " of LyX and the lyx2lyx script"
1331 " failed to convert it."),
1332 from_utf8(fn.absFileName())));
1333 return LyX2LyXOlderFormat;
1335 Alert::error(_("Conversion script failed"),
1336 bformat(_("%1$s is from a newer version"
1337 " of LyX and the lyx2lyx script"
1338 " failed to convert it."),
1339 from_utf8(fn.absFileName())));
1340 return LyX2LyXNewerFormat;
1347 FileName Buffer::getBackupName() const {
1348 FileName const & fn = fileName();
1349 string const fname = fn.onlyFileNameWithoutExt();
1350 string const fext = fn.extension() + "~";
1351 string const fpath = lyxrc.backupdir_path.empty() ?
1352 fn.onlyPath().absFileName() :
1353 lyxrc.backupdir_path;
1354 string const fform = convert<string>(d->file_format);
1355 string const backname = fname + "-lyxformat-" + fform;
1356 FileName backup(addName(fpath, addExtension(backname, fext)));
1358 // limit recursion, just in case
1360 unsigned long orig_checksum = 0;
1361 while (backup.exists() && v < 100) {
1362 if (orig_checksum == 0)
1363 orig_checksum = fn.checksum();
1364 unsigned long new_checksum = backup.checksum();
1365 if (orig_checksum == new_checksum) {
1366 LYXERR(Debug::FILES, "Not backing up " << fn <<
1367 "since " << backup << "has the same checksum.");
1368 // a bit of a hack, but we have to check this anyway
1369 // below, and setting this is simpler than introducing
1370 // a special boolean for this purpose.
1374 string const newbackname = backname + "-" + convert<string>(v);
1375 backup.set(addName(fpath, addExtension(newbackname, fext)));
1378 return v < 100 ? backup : FileName();
1382 // Should probably be moved to somewhere else: BufferView? GuiView?
1383 bool Buffer::save() const
1385 docstring const file = makeDisplayPath(absFileName(), 20);
1386 d->filename.refresh();
1388 // check the read-only status before moving the file as a backup
1389 if (d->filename.exists()) {
1390 bool const read_only = !d->filename.isWritable();
1392 Alert::warning(_("File is read-only"),
1393 bformat(_("The file %1$s cannot be written because it "
1394 "is marked as read-only."), file));
1399 // ask if the disk file has been externally modified (use checksum method)
1400 if (fileName().exists() && isChecksumModified()) {
1402 bformat(_("Document %1$s has been externally modified. "
1403 "Are you sure you want to overwrite this file?"), file);
1404 int const ret = Alert::prompt(_("Overwrite modified file?"),
1405 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1410 // We don't need autosaves in the immediate future. (Asger)
1411 resetAutosaveTimers();
1413 // if the file does not yet exist, none of the backup activity
1414 // that follows is necessary
1415 if (!fileName().exists()) {
1416 if (!writeFile(fileName()))
1422 // we first write the file to a new name, then move it to its
1423 // proper location once that has been done successfully. that
1424 // way we preserve the original file if something goes wrong.
1425 string const justname = fileName().onlyFileNameWithoutExt();
1426 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1427 justname + "-XXXXXX.lyx");
1428 bool const symlink = fileName().isSymLink();
1430 tempfile->setAutoRemove(false);
1432 FileName savefile(tempfile->name());
1433 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1434 if (!savefile.clonePermissions(fileName()))
1435 LYXERR0("Failed to clone the permission from " << fileName().absFileName() << " to " << savefile.absFileName());
1437 if (!writeFile(savefile))
1440 // we will set this to false if we fail
1441 bool made_backup = true;
1443 FileName backupName;
1444 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1446 if (d->need_format_backup)
1447 backupName = getBackupName();
1449 // If we for some reason failed to find a backup name in case of
1450 // a format change, this will still set one. It's the best we can
1452 if (backupName.empty()) {
1453 backupName.set(fileName().absFileName() + "~");
1454 if (!lyxrc.backupdir_path.empty()) {
1455 string const mangledName =
1456 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1457 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1461 LYXERR(Debug::FILES, "Backing up original file to " <<
1462 backupName.absFileName());
1463 // Except file is symlink do not copy because of #6587.
1464 // Hard links have bad luck.
1465 made_backup = symlink ?
1466 fileName().copyTo(backupName):
1467 fileName().moveTo(backupName);
1470 Alert::error(_("Backup failure"),
1471 bformat(_("Cannot create backup file %1$s.\n"
1472 "Please check whether the directory exists and is writable."),
1473 from_utf8(backupName.absFileName())));
1474 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1475 } else if (d->need_format_backup) {
1476 // the original file has been backed up successfully, so we
1477 // will not need to do that again
1478 d->need_format_backup = false;
1482 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1483 // Only do this if tempfile is not in autoremove mode
1486 // If we have no symlink, we can simply rename the temp file.
1487 // Otherwise, we need to copy it so the symlink stays intact.
1488 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1489 savefile.moveTo(fileName()))
1491 // saveCheckSum() was already called by writeFile(), but the
1492 // time stamp is invalidated by copying/moving
1495 if (d->file_format != LYX_FORMAT)
1496 // the file associated with this buffer is now in the current format
1497 d->file_format = LYX_FORMAT;
1500 // else we saved the file, but failed to move it to the right location.
1502 if (needBackup && made_backup && !symlink) {
1503 // the original file was moved to some new location, so it will look
1504 // to the user as if it was deleted. (see bug #9234.) we could try
1505 // to restore it, but that would basically mean trying to do again
1506 // what we just failed to do. better to leave things as they are.
1507 Alert::error(_("Write failure"),
1508 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1509 "But LyX could not move it to:\n %2$s.\n"
1510 "Your original file has been backed up to:\n %3$s"),
1511 from_utf8(savefile.absFileName()),
1512 from_utf8(fileName().absFileName()),
1513 from_utf8(backupName.absFileName())));
1515 // either we did not try to make a backup, or else we tried and failed,
1516 // or else the original file was a symlink, in which case it was copied,
1517 // not moved. so the original file is intact.
1518 Alert::error(_("Write failure"),
1519 bformat(_("Cannot move saved file to:\n %1$s.\n"
1520 "But the file has successfully been saved as:\n %2$s."),
1521 from_utf8(fileName().absFileName()),
1522 from_utf8(savefile.absFileName())));
1528 bool Buffer::writeFile(FileName const & fname) const
1530 if (d->read_only && fname == d->filename)
1533 bool retval = false;
1535 docstring const str = bformat(_("Saving document %1$s..."),
1536 makeDisplayPath(fname.absFileName()));
1539 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1541 if (params().compressed) {
1542 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1543 retval = ofs && write(ofs);
1545 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1546 retval = ofs && write(ofs);
1550 message(str + _(" could not write file!"));
1555 // removeAutosaveFile();
1558 message(str + _(" done."));
1564 docstring Buffer::emergencyWrite()
1566 // No need to save if the buffer has not changed.
1570 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1572 docstring user_message = bformat(
1573 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1575 // We try to save three places:
1576 // 1) Same place as document. Unless it is an unnamed doc.
1578 string s = absFileName();
1581 if (writeFile(FileName(s))) {
1583 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1584 return user_message;
1586 user_message += " " + _("Save failed! Trying again...\n");
1590 // 2) In HOME directory.
1591 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1593 lyxerr << ' ' << s << endl;
1594 if (writeFile(FileName(s))) {
1596 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1597 return user_message;
1600 user_message += " " + _("Save failed! Trying yet again...\n");
1602 // 3) In "/tmp" directory.
1603 // MakeAbsPath to prepend the current
1604 // drive letter on OS/2
1605 s = addName(package().temp_dir().absFileName(), absFileName());
1607 lyxerr << ' ' << s << endl;
1608 if (writeFile(FileName(s))) {
1610 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1611 return user_message;
1614 user_message += " " + _("Save failed! Document is lost.");
1617 return user_message;
1621 bool Buffer::write(ostream & ofs) const
1624 // Use the standard "C" locale for file output.
1625 ofs.imbue(locale::classic());
1628 // The top of the file should not be written by params().
1630 // write out a comment in the top of the file
1631 // Important: Keep the version formatting in sync with lyx2lyx and
1632 // tex2lyx (bug 7951)
1633 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1634 << " created this file. For more info see http://www.lyx.org/\n"
1635 << "\\lyxformat " << LYX_FORMAT << "\n"
1636 << "\\begin_document\n";
1638 /// For each author, set 'used' to true if there is a change
1639 /// by this author in the document; otherwise set it to 'false'.
1640 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1641 AuthorList::Authors::const_iterator a_end = params().authors().end();
1642 for (; a_it != a_end; ++a_it)
1643 a_it->setUsed(false);
1645 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1646 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1647 for ( ; it != end; ++it)
1648 it->checkAuthors(params().authors());
1650 // now write out the buffer parameters.
1651 ofs << "\\begin_header\n";
1652 params().writeFile(ofs, this);
1653 ofs << "\\end_header\n";
1656 ofs << "\n\\begin_body\n";
1658 ofs << "\n\\end_body\n";
1660 // Write marker that shows file is complete
1661 ofs << "\\end_document" << endl;
1663 // Shouldn't really be needed....
1666 // how to check if close went ok?
1667 // Following is an attempt... (BE 20001011)
1669 // good() returns false if any error occurred, including some
1670 // formatting error.
1671 // bad() returns true if something bad happened in the buffer,
1672 // which should include file system full errors.
1677 lyxerr << "File was not closed properly." << endl;
1684 bool Buffer::makeLaTeXFile(FileName const & fname,
1685 string const & original_path,
1686 OutputParams const & runparams_in,
1687 OutputWhat output) const
1689 OutputParams runparams = runparams_in;
1691 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1692 // Check here, because the "flavor" is not known in BufferParams::encoding()
1693 // (power users can override this safety measure selecting "utf8-plain").
1694 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1695 && (runparams.encoding->name() != "utf8-plain"))
1696 runparams.encoding = encodings.fromLyXName("ascii");
1698 string const encoding = runparams.encoding->iconvName();
1699 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1702 try { ofs.reset(encoding); }
1703 catch (iconv_codecvt_facet_exception const & e) {
1704 lyxerr << "Caught iconv exception: " << e.what() << endl;
1705 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1706 "verify that the support software for your encoding (%1$s) is "
1707 "properly installed"), from_ascii(encoding)));
1710 if (!openFileWrite(ofs, fname))
1713 ErrorList & errorList = d->errorLists["Export"];
1715 bool failed_export = false;
1718 // make sure we are ready to export
1719 // this needs to be done before we validate
1720 // FIXME Do we need to do this all the time? I.e., in children
1721 // of a master we are exporting?
1723 updateMacroInstances(OutputUpdate);
1726 writeLaTeXSource(os, original_path, runparams, output);
1728 catch (EncodingException const & e) {
1729 docstring const failed(1, e.failed_char);
1731 oss << "0x" << hex << e.failed_char << dec;
1732 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1733 " (code point %2$s)"),
1734 failed, from_utf8(oss.str()));
1735 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1736 "representable in the chosen encoding.\n"
1737 "Changing the document encoding to utf8 could help."),
1738 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1739 failed_export = true;
1741 catch (iconv_codecvt_facet_exception const & e) {
1742 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1744 failed_export = true;
1746 catch (exception const & e) {
1747 errorList.push_back(ErrorItem(_("conversion failed"),
1749 lyxerr << e.what() << endl;
1750 failed_export = true;
1753 lyxerr << "Caught some really weird exception..." << endl;
1757 d->texrow = move(os.texrow());
1761 failed_export = true;
1762 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1765 if (runparams_in.silent)
1769 return !failed_export;
1773 void Buffer::writeLaTeXSource(otexstream & os,
1774 string const & original_path,
1775 OutputParams const & runparams_in,
1776 OutputWhat output) const
1778 // The child documents, if any, shall be already loaded at this point.
1780 OutputParams runparams = runparams_in;
1782 // XeTeX with TeX fonts is only safe with ASCII encoding,
1783 // Check here, because the "flavor" is not known in BufferParams::encoding()
1784 // (power users can override this safety measure selecting "utf8-plain").
1785 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1786 && (runparams.encoding->name() != "utf8-plain"))
1787 runparams.encoding = encodings.fromLyXName("ascii");
1788 // FIXME: when only the current paragraph is shown, this is ignored
1789 // (or not reached) and characters encodable in the current
1790 // encoding are not converted to ASCII-representation.
1792 // If we are compiling a file standalone, even if this is the
1793 // child of some other buffer, let's cut the link here, so the
1794 // file is really independent and no concurring settings from
1795 // the master (e.g. branch state) interfere (see #8100).
1796 if (!runparams.is_child)
1797 d->ignore_parent = true;
1799 // Classify the unicode characters appearing in math insets
1800 BufferEncodings::initUnicodeMath(*this);
1802 // validate the buffer.
1803 LYXERR(Debug::LATEX, " Validating buffer...");
1804 LaTeXFeatures features(*this, params(), runparams);
1806 // This is only set once per document (in master)
1807 if (!runparams.is_child)
1808 runparams.use_polyglossia = features.usePolyglossia();
1809 LYXERR(Debug::LATEX, " Buffer validation done.");
1811 bool const output_preamble =
1812 output == FullSource || output == OnlyPreamble;
1813 bool const output_body =
1814 output == FullSource || output == OnlyBody;
1816 // The starting paragraph of the coming rows is the
1817 // first paragraph of the document. (Asger)
1818 if (output_preamble && runparams.nice) {
1819 os << "%% LyX " << lyx_version << " created this file. "
1820 "For more info, see http://www.lyx.org/.\n"
1821 "%% Do not edit unless you really know what "
1824 LYXERR(Debug::INFO, "lyx document header finished");
1826 // There are a few differences between nice LaTeX and usual files:
1827 // usual files have \batchmode and special input@path to allow
1828 // inclusion of figures specified by an explicitly relative path
1829 // (i.e., a path starting with './' or '../') with either \input or
1830 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1831 // input@path is set when the actual parameter original_path is set.
1832 // This is done for usual tex-file, but not for nice-latex-file.
1833 // (Matthias 250696)
1834 // Note that input@path is only needed for something the user does
1835 // in the preamble, included .tex files or ERT, files included by
1836 // LyX work without it.
1837 if (output_preamble) {
1838 if (!runparams.nice) {
1839 // code for usual, NOT nice-latex-file
1840 os << "\\batchmode\n"; // changed from \nonstopmode
1842 if (!original_path.empty()) {
1844 // We don't know the encoding of inputpath
1845 docstring const inputpath = from_utf8(original_path);
1846 docstring uncodable_glyphs;
1847 Encoding const * const enc = runparams.encoding;
1849 for (size_t n = 0; n < inputpath.size(); ++n) {
1850 if (!enc->encodable(inputpath[n])) {
1851 docstring const glyph(1, inputpath[n]);
1852 LYXERR0("Uncodable character '"
1854 << "' in input path!");
1855 uncodable_glyphs += glyph;
1860 // warn user if we found uncodable glyphs.
1861 if (!uncodable_glyphs.empty()) {
1862 frontend::Alert::warning(
1863 _("Uncodable character in file path"),
1865 _("The path of your document\n"
1867 "contains glyphs that are unknown "
1868 "in the current document encoding "
1869 "(namely %2$s). This may result in "
1870 "incomplete output, unless "
1871 "TEXINPUTS contains the document "
1872 "directory and you don't use "
1873 "explicitly relative paths (i.e., "
1874 "paths starting with './' or "
1875 "'../') in the preamble or in ERT."
1876 "\n\nIn case of problems, choose "
1877 "an appropriate document encoding\n"
1878 "(such as utf8) or change the "
1880 inputpath, uncodable_glyphs));
1882 string docdir = os::latex_path(original_path);
1883 if (contains(docdir, '#')) {
1884 docdir = subst(docdir, "#", "\\#");
1885 os << "\\catcode`\\#=11"
1886 "\\def\\#{#}\\catcode`\\#=6\n";
1888 if (contains(docdir, '%')) {
1889 docdir = subst(docdir, "%", "\\%");
1890 os << "\\catcode`\\%=11"
1891 "\\def\\%{%}\\catcode`\\%=14\n";
1893 bool const detokenize = !isAscii(from_utf8(docdir));
1894 bool const quote = contains(docdir, ' ');
1895 os << "\\makeatletter\n"
1896 << "\\def\\input@path{{";
1898 os << "\\detokenize{";
1907 << "\\makeatother\n";
1911 // get parent macros (if this buffer has a parent) which will be
1912 // written at the document begin further down.
1913 MacroSet parentMacros;
1914 listParentMacros(parentMacros, features);
1916 // Write the preamble
1917 runparams.use_babel = params().writeLaTeX(os, features,
1918 d->filename.onlyPath());
1920 // Biblatex bibliographies are loaded here
1921 if (params().useBiblatex()) {
1922 vector<docstring> const bibfiles =
1923 prepareBibFilePaths(runparams, getBibfiles(), true);
1924 for (docstring const & file: bibfiles)
1925 os << "\\addbibresource{" << file << "}\n";
1928 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1929 && !features.hasOnlyPolyglossiaLanguages()) {
1932 vector<string> bll = features.getBabelExclusiveLanguages();
1933 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1936 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1941 blangs = bll.size() > 1 ?
1942 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1943 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1947 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1952 plangs = pll.size() > 1 ?
1953 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1954 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1955 if (!blangs.empty())
1959 frontend::Alert::warning(
1960 _("Incompatible Languages!"),
1962 _("You cannot use the following languages "
1963 "together in one LaTeX document because "
1964 "they require conflicting language packages:\n"
1969 // Japanese might be required only in some children of a document,
1970 // but once required, we must keep use_japanese true.
1971 runparams.use_japanese |= features.isRequired("japanese");
1974 // Restore the parenthood if needed
1975 if (!runparams.is_child)
1976 d->ignore_parent = false;
1981 // mark the beginning of the body to separate it from InPreamble insets
1982 os.texrow().start(TexRow::beginDocument());
1983 os << "\\begin{document}\n";
1985 // mark the start of a new paragraph by simulating a newline,
1986 // so that os.afterParbreak() returns true at document start
1989 // output the parent macros
1990 MacroSet::iterator it = parentMacros.begin();
1991 MacroSet::iterator end = parentMacros.end();
1992 for (; it != end; ++it) {
1993 int num_lines = (*it)->write(os.os(), true);
1994 os.texrow().newlines(num_lines);
1997 } // output_preamble
1999 LYXERR(Debug::INFO, "preamble finished, now the body.");
2002 latexParagraphs(*this, text(), os, runparams);
2004 // Restore the parenthood if needed
2005 if (!runparams.is_child)
2006 d->ignore_parent = false;
2008 // add this just in case after all the paragraphs
2011 if (output_preamble) {
2012 os << "\\end{document}\n";
2013 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2015 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2017 runparams_in.encoding = runparams.encoding;
2019 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2020 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2024 void Buffer::makeDocBookFile(FileName const & fname,
2025 OutputParams const & runparams,
2026 OutputWhat output) const
2028 LYXERR(Debug::LATEX, "makeDocBookFile...");
2031 if (!openFileWrite(ofs, fname))
2034 // make sure we are ready to export
2035 // this needs to be done before we validate
2037 updateMacroInstances(OutputUpdate);
2039 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2043 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2047 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2048 OutputParams const & runparams,
2049 OutputWhat output) const
2051 LaTeXFeatures features(*this, params(), runparams);
2056 DocumentClass const & tclass = params().documentClass();
2057 string const & top_element = tclass.latexname();
2059 bool const output_preamble =
2060 output == FullSource || output == OnlyPreamble;
2061 bool const output_body =
2062 output == FullSource || output == OnlyBody;
2064 if (output_preamble) {
2065 if (runparams.flavor == OutputParams::XML)
2066 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2069 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2072 if (! tclass.class_header().empty())
2073 os << from_ascii(tclass.class_header());
2074 else if (runparams.flavor == OutputParams::XML)
2075 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2076 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2078 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2080 docstring preamble = params().preamble;
2081 if (runparams.flavor != OutputParams::XML ) {
2082 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2083 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2084 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2085 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2088 string const name = runparams.nice
2089 ? changeExtension(absFileName(), ".sgml") : fname;
2090 preamble += features.getIncludedFiles(name);
2091 preamble += features.getLyXSGMLEntities();
2093 if (!preamble.empty()) {
2094 os << "\n [ " << preamble << " ]";
2100 string top = top_element;
2102 if (runparams.flavor == OutputParams::XML)
2103 top += params().language->code();
2105 top += params().language->code().substr(0, 2);
2108 if (!params().options.empty()) {
2110 top += params().options;
2113 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2114 << " file was created by LyX " << lyx_version
2115 << "\n See http://www.lyx.org/ for more information -->\n";
2117 params().documentClass().counters().reset();
2119 sgml::openTag(os, top);
2121 docbookParagraphs(text(), *this, os, runparams);
2122 sgml::closeTag(os, top_element);
2127 void Buffer::makeLyXHTMLFile(FileName const & fname,
2128 OutputParams const & runparams) const
2130 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2133 if (!openFileWrite(ofs, fname))
2136 // make sure we are ready to export
2137 // this has to be done before we validate
2138 updateBuffer(UpdateMaster, OutputUpdate);
2139 updateMacroInstances(OutputUpdate);
2141 writeLyXHTMLSource(ofs, runparams, FullSource);
2145 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2149 void Buffer::writeLyXHTMLSource(odocstream & os,
2150 OutputParams const & runparams,
2151 OutputWhat output) const
2153 LaTeXFeatures features(*this, params(), runparams);
2155 d->bibinfo_.makeCitationLabels(*this);
2157 bool const output_preamble =
2158 output == FullSource || output == OnlyPreamble;
2159 bool const output_body =
2160 output == FullSource || output == OnlyBody || output == IncludedFile;
2162 if (output_preamble) {
2163 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2164 << "<!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"
2165 // FIXME Language should be set properly.
2166 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2168 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2169 // FIXME Presumably need to set this right
2170 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2172 docstring const & doctitle = features.htmlTitle();
2174 << (doctitle.empty() ?
2175 from_ascii("LyX Document") :
2176 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2179 docstring styles = features.getTClassHTMLPreamble();
2180 if (!styles.empty())
2181 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2183 styles = features.getPreambleSnippets().str;
2184 if (!styles.empty())
2185 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2187 // we will collect CSS information in a stream, and then output it
2188 // either here, as part of the header, or else in a separate file.
2189 odocstringstream css;
2190 styles = features.getCSSSnippets();
2191 if (!styles.empty())
2192 css << "/* LyX Provided Styles */\n" << styles << '\n';
2194 styles = features.getTClassHTMLStyles();
2195 if (!styles.empty())
2196 css << "/* Layout-provided Styles */\n" << styles << '\n';
2198 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2199 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2200 if (needfg || needbg) {
2201 css << "\nbody {\n";
2204 << from_ascii(X11hexname(params().fontcolor))
2207 css << " background-color: "
2208 << from_ascii(X11hexname(params().backgroundcolor))
2213 docstring const dstyles = css.str();
2214 if (!dstyles.empty()) {
2215 bool written = false;
2216 if (params().html_css_as_file) {
2217 // open a file for CSS info
2219 string const fcssname = addName(temppath(), "docstyle.css");
2220 FileName const fcssfile = FileName(fcssname);
2221 if (openFileWrite(ocss, fcssfile)) {
2225 // write link to header
2226 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2228 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2231 // we are here if the CSS is supposed to be written to the header
2232 // or if we failed to write it to an external file.
2234 os << "<style type='text/css'>\n"
2243 bool const output_body_tag = (output != IncludedFile);
2244 if (output_body_tag)
2245 os << "<body dir=\"auto\">\n";
2247 if (output != IncludedFile)
2248 // if we're an included file, the counters are in the master.
2249 params().documentClass().counters().reset();
2250 xhtmlParagraphs(text(), *this, xs, runparams);
2251 if (output_body_tag)
2255 if (output_preamble)
2260 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2261 // Other flags: -wall -v0 -x
2262 int Buffer::runChktex()
2266 // get LaTeX-Filename
2267 FileName const path(temppath());
2268 string const name = addName(path.absFileName(), latexName());
2269 string const org_path = filePath();
2271 PathChanger p(path); // path to LaTeX file
2272 message(_("Running chktex..."));
2274 // Generate the LaTeX file if neccessary
2275 OutputParams runparams(¶ms().encoding());
2276 runparams.flavor = OutputParams::LATEX;
2277 runparams.nice = false;
2278 runparams.linelen = lyxrc.plaintext_linelen;
2279 makeLaTeXFile(FileName(name), org_path, runparams);
2282 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2283 int const res = chktex.run(terr); // run chktex
2286 Alert::error(_("chktex failure"),
2287 _("Could not run chktex successfully."));
2289 ErrorList & errlist = d->errorLists["ChkTeX"];
2291 bufferErrors(terr, errlist);
2296 if (runparams.silent)
2297 d->errorLists["ChkTeX"].clear();
2305 void Buffer::validate(LaTeXFeatures & features) const
2307 // Validate the buffer params, but not for included
2308 // files, since they also use the parent buffer's
2310 if (!features.runparams().is_child)
2311 params().validate(features);
2313 for (Paragraph const & p : paragraphs())
2314 p.validate(features);
2316 if (lyxerr.debugging(Debug::LATEX)) {
2317 features.showStruct();
2322 void Buffer::getLabelList(vector<docstring> & list) const
2324 // If this is a child document, use the master's list instead.
2326 masterBuffer()->getLabelList(list);
2331 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2332 Toc::const_iterator toc_it = toc->begin();
2333 Toc::const_iterator end = toc->end();
2334 for (; toc_it != end; ++toc_it) {
2335 if (toc_it->depth() == 0)
2336 list.push_back(toc_it->str());
2341 // This is not in master, so it has been removed at 2126d5a3, on
2342 // 14 December 2018, so as to test whether it's needed. If there
2343 // aren't any complaints, it can be fully removed.
2345 void Buffer::updateBibfilesCache(UpdateScope scope) const
2347 // FIXME This is probably unnecssary, given where we call this.
2348 // If this is a child document, use the parent's cache instead.
2349 if (parent() && scope != UpdateChildOnly) {
2350 masterBuffer()->updateBibfilesCache();
2354 docstring_list old_cache = d->bibfiles_cache_;
2355 d->bibfiles_cache_.clear();
2356 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2357 if (it->lyxCode() == BIBTEX_CODE) {
2358 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2359 docstring_list const bibfiles = inset.getBibFiles();
2360 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2363 } else if (it->lyxCode() == INCLUDE_CODE) {
2364 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2365 Buffer const * const incbuf = inset.getChildBuffer();
2368 docstring_list const & bibfiles =
2369 incbuf->getBibfiles(UpdateChildOnly);
2370 if (!bibfiles.empty()) {
2371 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2377 d->bibfile_cache_valid_ = true;
2378 d->cite_labels_valid_ = false;
2379 if (d->bibfiles_cache_ != old_cache)
2380 d->bibinfo_cache_valid_ = false;
2385 void Buffer::invalidateBibinfoCache() const
2387 d->bibinfo_cache_valid_ = false;
2388 d->cite_labels_valid_ = false;
2389 // also invalidate the cache for the parent buffer
2390 Buffer const * const pbuf = d->parent();
2392 pbuf->invalidateBibinfoCache();
2396 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2398 // FIXME This is probably unnecessary, given where we call this.
2399 // If this is a child document, use the master's cache instead.
2400 Buffer const * const pbuf = masterBuffer();
2401 if (pbuf != this && scope != UpdateChildOnly)
2402 return pbuf->getBibfiles();
2404 return d->bibfiles_cache_;
2408 BiblioInfo const & Buffer::masterBibInfo() const
2410 Buffer const * const tmp = masterBuffer();
2412 return tmp->masterBibInfo();
2417 BiblioInfo const & Buffer::bibInfo() const
2423 void Buffer::registerBibfiles(const docstring_list & bf) const
2425 // We register the bib files in the master buffer,
2426 // if there is one, but also in every single buffer,
2427 // in case a child is compiled alone.
2428 Buffer const * const tmp = masterBuffer();
2430 tmp->registerBibfiles(bf);
2432 for (auto const & p : bf) {
2433 docstring_list::const_iterator temp =
2434 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2435 if (temp == d->bibfiles_cache_.end())
2436 d->bibfiles_cache_.push_back(p);
2441 static map<docstring, FileName> bibfileCache;
2443 FileName Buffer::getBibfilePath(docstring const & bibid) const
2445 map<docstring, FileName>::const_iterator it =
2446 bibfileCache.find(bibid);
2447 if (it != bibfileCache.end()) {
2448 // i.e., bibfileCache[bibid]
2452 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2453 string texfile = changeExtension(to_utf8(bibid), "bib");
2454 // note that, if the filename can be found directly from the path,
2455 // findtexfile will just return a FileName object for that path.
2456 FileName file(findtexfile(texfile, "bib"));
2458 file = FileName(makeAbsPath(texfile, filePath()));
2459 LYXERR(Debug::FILES, "Found at: " << file);
2461 bibfileCache[bibid] = file;
2462 return bibfileCache[bibid];
2466 void Buffer::checkIfBibInfoCacheIsValid() const
2468 // use the master's cache
2469 Buffer const * const tmp = masterBuffer();
2471 tmp->checkIfBibInfoCacheIsValid();
2475 // we'll assume it's ok and change this if it's not
2476 d->bibinfo_cache_valid_ = true;
2477 d->cite_labels_valid_ = true;
2478 // compare the cached timestamps with the actual ones.
2479 docstring_list const & bibfiles_cache = getBibfiles();
2480 for (auto const & bf : bibfiles_cache) {
2481 FileName const fn = getBibfilePath(bf);
2482 time_t lastw = fn.lastModified();
2483 time_t prevw = d->bibfile_status_[fn];
2484 if (lastw != prevw) {
2485 d->bibinfo_cache_valid_ = false;
2486 d->cite_labels_valid_ = false;
2487 d->bibfile_status_[fn] = lastw;
2493 void Buffer::clearBibFileCache() const
2495 bibfileCache.clear();
2499 void Buffer::reloadBibInfoCache() const
2504 // use the master's cache
2505 Buffer const * const tmp = masterBuffer();
2507 tmp->reloadBibInfoCache();
2511 checkIfBibInfoCacheIsValid();
2512 if (d->bibinfo_cache_valid_)
2514 LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2516 // re-read file locations when this info changes
2517 // FIXME Is this sufficient? Or should we also force that
2518 // in some other cases? If so, then it is easy enough to
2519 // add the following line in some other places.
2520 clearBibFileCache();
2521 d->bibinfo_.clear();
2522 FileNameList checkedFiles;
2523 collectBibKeys(checkedFiles);
2524 d->bibinfo_cache_valid_ = true;
2528 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2530 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2531 it->collectBibKeys(it, checkedFiles);
2535 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2537 // We add the biblio info to the master buffer,
2538 // if there is one, but also to every single buffer,
2539 // in case a child is compiled alone.
2540 BiblioInfo & bi = d->bibinfo_;
2541 bi.mergeBiblioInfo(bin);
2543 if (parent() != 0) {
2544 BiblioInfo & masterbi = parent()->d->bibinfo_;
2545 masterbi.mergeBiblioInfo(bin);
2550 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2552 // We add the bibtex info to the master buffer,
2553 // if there is one, but also to every single buffer,
2554 // in case a child is compiled alone.
2555 BiblioInfo & bi = d->bibinfo_;
2558 if (parent() != 0) {
2559 BiblioInfo & masterbi = parent()->d->bibinfo_;
2560 masterbi[key] = bin;
2565 void Buffer::makeCitationLabels() const
2567 Buffer const * const master = masterBuffer();
2568 return d->bibinfo_.makeCitationLabels(*master);
2572 void Buffer::invalidateCiteLabels() const
2574 masterBuffer()->d->cite_labels_valid_ = false;
2577 bool Buffer::citeLabelsValid() const
2579 return masterBuffer()->d->cite_labels_valid_;
2583 void Buffer::removeBiblioTempFiles() const
2585 // We remove files that contain LaTeX commands specific to the
2586 // particular bibliographic style being used, in order to avoid
2587 // LaTeX errors when we switch style.
2588 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2589 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2590 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2591 aux_file.removeFile();
2592 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2593 bbl_file.removeFile();
2594 // Also for the parent buffer
2595 Buffer const * const pbuf = parent();
2597 pbuf->removeBiblioTempFiles();
2601 bool Buffer::isDepClean(string const & name) const
2603 DepClean::const_iterator const it = d->dep_clean.find(name);
2604 if (it == d->dep_clean.end())
2610 void Buffer::markDepClean(string const & name)
2612 d->dep_clean[name] = true;
2616 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2619 // FIXME? if there is an Buffer LFUN that can be dispatched even
2620 // if internal, put a switch '(cmd.action)' here.
2626 switch (cmd.action()) {
2628 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2629 flag.setOnOff(hasReadonlyFlag());
2632 // FIXME: There is need for a command-line import.
2633 //case LFUN_BUFFER_IMPORT:
2635 case LFUN_BUFFER_AUTO_SAVE:
2638 case LFUN_BUFFER_EXPORT_CUSTOM:
2639 // FIXME: Nothing to check here?
2642 case LFUN_BUFFER_EXPORT: {
2643 docstring const arg = cmd.argument();
2644 if (arg == "custom") {
2648 string format = (arg.empty() || arg == "default") ?
2649 params().getDefaultOutputFormat() : to_utf8(arg);
2650 size_t pos = format.find(' ');
2651 if (pos != string::npos)
2652 format = format.substr(0, pos);
2653 enable = params().isExportable(format, false);
2655 flag.message(bformat(
2656 _("Don't know how to export to format: %1$s"), arg));
2660 case LFUN_BUILD_PROGRAM:
2661 enable = params().isExportable("program", false);
2664 case LFUN_BRANCH_ACTIVATE:
2665 case LFUN_BRANCH_DEACTIVATE:
2666 case LFUN_BRANCH_MASTER_ACTIVATE:
2667 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2668 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2669 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2670 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2671 : params().branchlist();
2672 docstring const branchName = cmd.argument();
2673 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2677 case LFUN_BRANCH_ADD:
2678 case LFUN_BRANCHES_RENAME:
2679 // if no Buffer is present, then of course we won't be called!
2682 case LFUN_BUFFER_LANGUAGE:
2683 enable = !isReadonly();
2686 case LFUN_BUFFER_VIEW_CACHE:
2687 (d->preview_file_).refresh();
2688 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2691 case LFUN_CHANGES_TRACK:
2692 flag.setEnabled(true);
2693 flag.setOnOff(params().track_changes);
2696 case LFUN_CHANGES_OUTPUT:
2697 flag.setEnabled(true);
2698 flag.setOnOff(params().output_changes);
2701 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2702 flag.setOnOff(params().compressed);
2705 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2706 flag.setOnOff(params().output_sync);
2709 case LFUN_BUFFER_ANONYMIZE:
2715 flag.setEnabled(enable);
2720 void Buffer::dispatch(string const & command, DispatchResult & result)
2722 return dispatch(lyxaction.lookupFunc(command), result);
2726 // NOTE We can end up here even if we have no GUI, because we are called
2727 // by LyX::exec to handled command-line requests. So we may need to check
2728 // whether we have a GUI or not. The boolean use_gui holds this information.
2729 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2732 // FIXME? if there is an Buffer LFUN that can be dispatched even
2733 // if internal, put a switch '(cmd.action())' here.
2734 dr.dispatched(false);
2737 string const argument = to_utf8(func.argument());
2738 // We'll set this back to false if need be.
2739 bool dispatched = true;
2740 // This handles undo groups automagically
2741 UndoGroupHelper ugh(this);
2743 switch (func.action()) {
2744 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2745 if (lyxvc().inUse()) {
2746 string log = lyxvc().toggleReadOnly();
2751 setReadonly(!hasReadonlyFlag());
2754 case LFUN_BUFFER_EXPORT: {
2755 string const format = (argument.empty() || argument == "default") ?
2756 params().getDefaultOutputFormat() : argument;
2757 ExportStatus const status = doExport(format, false);
2758 dr.setError(status != ExportSuccess);
2759 if (status != ExportSuccess)
2760 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2761 from_utf8(format)));
2765 case LFUN_BUILD_PROGRAM: {
2766 ExportStatus const status = doExport("program", true);
2767 dr.setError(status != ExportSuccess);
2768 if (status != ExportSuccess)
2769 dr.setMessage(_("Error generating literate programming code."));
2773 case LFUN_BUFFER_EXPORT_CUSTOM: {
2775 string command = split(argument, format_name, ' ');
2776 Format const * format = theFormats().getFormat(format_name);
2778 lyxerr << "Format \"" << format_name
2779 << "\" not recognized!"
2784 // The name of the file created by the conversion process
2787 // Output to filename
2788 if (format->name() == "lyx") {
2789 string const latexname = latexName(false);
2790 filename = changeExtension(latexname,
2791 format->extension());
2792 filename = addName(temppath(), filename);
2794 if (!writeFile(FileName(filename)))
2798 doExport(format_name, true, filename);
2801 // Substitute $$FName for filename
2802 if (!contains(command, "$$FName"))
2803 command = "( " + command + " ) < $$FName";
2804 command = subst(command, "$$FName", filename);
2806 // Execute the command in the background
2808 call.startscript(Systemcall::DontWait, command,
2809 filePath(), layoutPos());
2813 // FIXME: There is need for a command-line import.
2815 case LFUN_BUFFER_IMPORT:
2820 case LFUN_BUFFER_AUTO_SAVE:
2822 resetAutosaveTimers();
2825 case LFUN_BRANCH_ACTIVATE:
2826 case LFUN_BRANCH_DEACTIVATE:
2827 case LFUN_BRANCH_MASTER_ACTIVATE:
2828 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2829 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2830 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2831 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2834 docstring const branch_name = func.argument();
2835 // the case without a branch name is handled elsewhere
2836 if (branch_name.empty()) {
2840 Branch * branch = buf->params().branchlist().find(branch_name);
2842 LYXERR0("Branch " << branch_name << " does not exist.");
2844 docstring const msg =
2845 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2849 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2850 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2851 if (branch->isSelected() != activate) {
2852 buf->undo().recordUndoBufferParams(CursorData());
2853 branch->setSelected(activate);
2855 dr.screenUpdate(Update::Force);
2856 dr.forceBufferUpdate();
2861 case LFUN_BRANCH_ADD: {
2862 docstring branch_name = func.argument();
2863 if (branch_name.empty()) {
2867 BranchList & branch_list = params().branchlist();
2868 vector<docstring> const branches =
2869 getVectorFromString(branch_name, branch_list.separator());
2871 for (vector<docstring>::const_iterator it = branches.begin();
2872 it != branches.end(); ++it) {
2874 Branch * branch = branch_list.find(branch_name);
2876 LYXERR0("Branch " << branch_name << " already exists.");
2880 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2882 undo().recordUndoBufferParams(CursorData());
2883 branch_list.add(branch_name);
2884 branch = branch_list.find(branch_name);
2885 string const x11hexname = X11hexname(branch->color());
2886 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2887 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2889 dr.screenUpdate(Update::Force);
2897 case LFUN_BRANCHES_RENAME: {
2898 if (func.argument().empty())
2901 docstring const oldname = from_utf8(func.getArg(0));
2902 docstring const newname = from_utf8(func.getArg(1));
2903 InsetIterator it = inset_iterator_begin(inset());
2904 InsetIterator const end = inset_iterator_end(inset());
2905 bool success = false;
2906 for (; it != end; ++it) {
2907 if (it->lyxCode() == BRANCH_CODE) {
2908 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2909 if (ins.branch() == oldname) {
2910 undo().recordUndo(CursorData(it));
2911 ins.rename(newname);
2916 if (it->lyxCode() == INCLUDE_CODE) {
2917 // get buffer of external file
2918 InsetInclude const & ins =
2919 static_cast<InsetInclude const &>(*it);
2920 Buffer * child = ins.getChildBuffer();
2923 child->dispatch(func, dr);
2928 dr.screenUpdate(Update::Force);
2929 dr.forceBufferUpdate();
2934 case LFUN_BUFFER_VIEW_CACHE:
2935 if (!theFormats().view(*this, d->preview_file_,
2936 d->preview_format_))
2937 dr.setMessage(_("Error viewing the output file."));
2940 case LFUN_CHANGES_TRACK:
2941 if (params().save_transient_properties)
2942 undo().recordUndoBufferParams(CursorData());
2943 params().track_changes = !params().track_changes;
2944 if (!params().track_changes)
2945 dr.forceChangesUpdate();
2948 case LFUN_CHANGES_OUTPUT:
2949 if (params().save_transient_properties)
2950 undo().recordUndoBufferParams(CursorData());
2951 params().output_changes = !params().output_changes;
2952 if (params().output_changes) {
2953 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2954 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2955 LaTeXFeatures::isAvailable("xcolor");
2957 if (!dvipost && !xcolorulem) {
2958 Alert::warning(_("Changes not shown in LaTeX output"),
2959 _("Changes will not be highlighted in LaTeX output, "
2960 "because neither dvipost nor xcolor/ulem are installed.\n"
2961 "Please install these packages or redefine "
2962 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2963 } else if (!xcolorulem) {
2964 Alert::warning(_("Changes not shown in LaTeX output"),
2965 _("Changes will not be highlighted in LaTeX output "
2966 "when using pdflatex, because xcolor and ulem are not installed.\n"
2967 "Please install both packages or redefine "
2968 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2973 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2974 // turn compression on/off
2975 undo().recordUndoBufferParams(CursorData());
2976 params().compressed = !params().compressed;
2979 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2980 undo().recordUndoBufferParams(CursorData());
2981 params().output_sync = !params().output_sync;
2984 case LFUN_BUFFER_ANONYMIZE: {
2985 undo().recordUndoFullBuffer(CursorData());
2986 CursorData cur(doc_iterator_begin(this));
2987 for ( ; cur ; cur.forwardPar())
2988 cur.paragraph().anonymize();
2989 dr.forceBufferUpdate();
2990 dr.screenUpdate(Update::Force);
2998 dr.dispatched(dispatched);
3002 void Buffer::changeLanguage(Language const * from, Language const * to)
3004 LASSERT(from, return);
3005 LASSERT(to, return);
3007 for_each(par_iterator_begin(),
3009 bind(&Paragraph::changeLanguage, _1, params(), from, to));
3013 bool Buffer::isMultiLingual() const
3015 ParConstIterator end = par_iterator_end();
3016 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3017 if (it->isMultiLingual(params()))
3024 std::set<Language const *> Buffer::getLanguages() const
3026 std::set<Language const *> languages;
3027 getLanguages(languages);
3032 void Buffer::getLanguages(std::set<Language const *> & languages) const
3034 ParConstIterator end = par_iterator_end();
3035 // add the buffer language, even if it's not actively used
3036 languages.insert(language());
3037 // iterate over the paragraphs
3038 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3039 it->getLanguages(languages);
3041 ListOfBuffers clist = getDescendents();
3042 ListOfBuffers::const_iterator cit = clist.begin();
3043 ListOfBuffers::const_iterator const cen = clist.end();
3044 for (; cit != cen; ++cit)
3045 (*cit)->getLanguages(languages);
3049 DocIterator Buffer::getParFromID(int const id) const
3051 Buffer * buf = const_cast<Buffer *>(this);
3053 // This means non-existent
3054 return doc_iterator_end(buf);
3056 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3057 if (it.paragraph().id() == id)
3060 return doc_iterator_end(buf);
3064 bool Buffer::hasParWithID(int const id) const
3066 return !getParFromID(id).atEnd();
3070 ParIterator Buffer::par_iterator_begin()
3072 return ParIterator(doc_iterator_begin(this));
3076 ParIterator Buffer::par_iterator_end()
3078 return ParIterator(doc_iterator_end(this));
3082 ParConstIterator Buffer::par_iterator_begin() const
3084 return ParConstIterator(doc_iterator_begin(this));
3088 ParConstIterator Buffer::par_iterator_end() const
3090 return ParConstIterator(doc_iterator_end(this));
3094 Language const * Buffer::language() const
3096 return params().language;
3100 docstring const Buffer::B_(string const & l10n) const
3102 return params().B_(l10n);
3106 bool Buffer::isClean() const
3108 return d->lyx_clean;
3112 bool Buffer::isChecksumModified() const
3114 LASSERT(d->filename.exists(), return false);
3115 return d->checksum_ != d->filename.checksum();
3119 void Buffer::saveCheckSum() const
3121 FileName const & file = d->filename;
3123 d->checksum_ = file.exists() ? file.checksum()
3124 : 0; // in the case of save to a new file.
3128 void Buffer::markClean() const
3130 if (!d->lyx_clean) {
3131 d->lyx_clean = true;
3134 // if the .lyx file has been saved, we don't need an
3136 d->bak_clean = true;
3137 d->undo_.markDirty();
3138 clearExternalModification();
3142 void Buffer::setUnnamed(bool flag)
3148 bool Buffer::isUnnamed() const
3155 /// Don't check unnamed, here: isInternal() is used in
3156 /// newBuffer(), where the unnamed flag has not been set by anyone
3157 /// yet. Also, for an internal buffer, there should be no need for
3158 /// retrieving fileName() nor for checking if it is unnamed or not.
3159 bool Buffer::isInternal() const
3161 return d->internal_buffer;
3165 void Buffer::setInternal(bool flag)
3167 d->internal_buffer = flag;
3171 void Buffer::markDirty()
3174 d->lyx_clean = false;
3177 d->bak_clean = false;
3179 DepClean::iterator it = d->dep_clean.begin();
3180 DepClean::const_iterator const end = d->dep_clean.end();
3182 for (; it != end; ++it)
3187 FileName Buffer::fileName() const
3193 string Buffer::absFileName() const
3195 return d->filename.absFileName();
3199 string Buffer::filePath() const
3201 string const abs = d->filename.onlyPath().absFileName();
3204 int last = abs.length() - 1;
3206 return abs[last] == '/' ? abs : abs + '/';
3210 DocFileName Buffer::getReferencedFileName(string const & fn) const
3213 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3214 result.set(fn, filePath());
3216 // filePath() ends with a path separator
3217 FileName const test(filePath() + fn);
3219 result.set(fn, filePath());
3221 result.set(fn, params().origin);
3228 string const Buffer::prepareFileNameForLaTeX(string const & name,
3229 string const & ext, bool nice) const
3231 string const fname = makeAbsPath(name, filePath()).absFileName();
3232 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3238 return to_utf8(makeRelPath(from_utf8(fname),
3239 from_utf8(masterBuffer()->filePath())));
3243 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3244 docstring_list const & bibfilelist,
3245 bool const add_extension) const
3247 // If we are processing the LaTeX file in a temp directory then
3248 // copy the .bib databases to this temp directory, mangling their
3249 // names in the process. Store this mangled name in the list of
3251 // (We need to do all this because BibTeX *really*, *really*
3252 // can't handle "files with spaces" and Windows users tend to
3253 // use such filenames.)
3254 // Otherwise, store the (maybe absolute) path to the original,
3255 // unmangled database name.
3257 vector<docstring> res;
3259 // determine the export format
3260 string const tex_format = flavor2format(runparams.flavor);
3262 // check for spaces in paths
3263 bool found_space = false;
3265 for (auto const & bit : bibfilelist) {
3266 string utf8input = to_utf8(bit);
3268 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3269 FileName try_in_file =
3270 makeAbsPath(database + ".bib", filePath());
3271 bool not_from_texmf = try_in_file.isReadableFile();
3272 // If the file has not been found, try with the real file name
3273 // (it might come from a child in a sub-directory)
3274 if (!not_from_texmf) {
3275 try_in_file = getBibfilePath(bit);
3276 if (try_in_file.isReadableFile()) {
3277 // Check if the file is in texmf
3278 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3279 not_from_texmf = kpsefile.empty()
3280 || kpsefile.absFileName() != try_in_file.absFileName();
3282 // If this exists, make path relative to the master
3284 database = removeExtension(
3285 prepareFileNameForLaTeX(to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3286 from_utf8(filePath()))),
3287 ".bib", runparams.nice));
3291 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3293 // mangledFileName() needs the extension
3294 DocFileName const in_file = DocFileName(try_in_file);
3295 database = removeExtension(in_file.mangledFileName());
3296 FileName const out_file = makeAbsPath(database + ".bib",
3297 masterBuffer()->temppath());
3298 bool const success = in_file.copyTo(out_file);
3300 LYXERR0("Failed to copy '" << in_file
3301 << "' to '" << out_file << "'");
3303 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3304 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3305 if (!isValidLaTeXFileName(database)) {
3306 frontend::Alert::warning(_("Invalid filename"),
3307 _("The following filename will cause troubles "
3308 "when running the exported file through LaTeX: ") +
3309 from_utf8(database));
3311 if (!isValidDVIFileName(database)) {
3312 frontend::Alert::warning(_("Problematic filename for DVI"),
3313 _("The following filename can cause troubles "
3314 "when running the exported file through LaTeX "
3315 "and opening the resulting DVI: ") +
3316 from_utf8(database), true);
3324 docstring const path = from_utf8(latex_path(database));
3326 if (contains(path, ' '))
3329 if (find(res.begin(), res.end(), path) == res.end())
3330 res.push_back(path);
3333 // Check if there are spaces in the path and warn BibTeX users, if so.
3334 // (biber can cope with such paths)
3335 if (!prefixIs(runparams.bibtex_command, "biber")) {
3336 // Post this warning only once.
3337 static bool warned_about_spaces = false;
3338 if (!warned_about_spaces &&
3339 runparams.nice && found_space) {
3340 warned_about_spaces = true;
3341 Alert::warning(_("Export Warning!"),
3342 _("There are spaces in the paths to your BibTeX databases.\n"
3343 "BibTeX will be unable to find them."));
3352 string Buffer::layoutPos() const
3354 return d->layout_position;
3358 void Buffer::setLayoutPos(string const & path)
3361 d->layout_position.clear();
3365 LATTEST(FileName::isAbsolute(path));
3367 d->layout_position =
3368 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3370 if (d->layout_position.empty())
3371 d->layout_position = ".";
3375 bool Buffer::hasReadonlyFlag() const
3377 return d->read_only;
3381 bool Buffer::isReadonly() const
3383 return hasReadonlyFlag() || notifiesExternalModification();
3387 void Buffer::setParent(Buffer const * buffer)
3389 // Avoids recursive include.
3390 d->setParent(buffer == this ? 0 : buffer);
3395 Buffer const * Buffer::parent() const
3401 ListOfBuffers Buffer::allRelatives() const
3403 ListOfBuffers lb = masterBuffer()->getDescendents();
3404 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3409 Buffer const * Buffer::masterBuffer() const
3411 // FIXME Should be make sure we are not in some kind
3412 // of recursive include? A -> B -> A will crash this.
3413 Buffer const * const pbuf = d->parent();
3417 return pbuf->masterBuffer();
3421 bool Buffer::isChild(Buffer * child) const
3423 return d->children_positions.find(child) != d->children_positions.end();
3427 DocIterator Buffer::firstChildPosition(Buffer const * child)
3429 Impl::BufferPositionMap::iterator it;
3430 it = d->children_positions.find(child);
3431 if (it == d->children_positions.end())
3432 return DocIterator(this);
3437 bool Buffer::hasChildren() const
3439 return !d->children_positions.empty();
3443 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3445 // loop over children
3446 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3447 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3448 for (; it != end; ++it) {
3449 Buffer * child = const_cast<Buffer *>(it->first);
3451 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3452 if (bit != clist.end())
3454 clist.push_back(child);
3456 // there might be grandchildren
3457 child->collectChildren(clist, true);
3462 ListOfBuffers Buffer::getChildren() const
3465 collectChildren(v, false);
3466 // Make sure we have not included ourselves.
3467 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3468 if (bit != v.end()) {
3469 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3476 ListOfBuffers Buffer::getDescendents() const
3479 collectChildren(v, true);
3480 // Make sure we have not included ourselves.
3481 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3482 if (bit != v.end()) {
3483 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3490 template<typename M>
3491 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3496 typename M::const_iterator it = m.lower_bound(x);
3497 if (it == m.begin())
3505 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3506 DocIterator const & pos) const
3508 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3510 // if paragraphs have no macro context set, pos will be empty
3514 // we haven't found anything yet
3515 DocIterator bestPos = owner_->par_iterator_begin();
3516 MacroData const * bestData = 0;
3518 // find macro definitions for name
3519 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3520 if (nameIt != macros.end()) {
3521 // find last definition in front of pos or at pos itself
3522 PositionScopeMacroMap::const_iterator it
3523 = greatest_below(nameIt->second, pos);
3524 if (it != nameIt->second.end()) {
3526 // scope ends behind pos?
3527 if (pos < it->second.scope) {
3528 // Looks good, remember this. If there
3529 // is no external macro behind this,
3530 // we found the right one already.
3531 bestPos = it->first;
3532 bestData = &it->second.macro;
3536 // try previous macro if there is one
3537 if (it == nameIt->second.begin())
3544 // find macros in included files
3545 PositionScopeBufferMap::const_iterator it
3546 = greatest_below(position_to_children, pos);
3547 if (it == position_to_children.end())
3548 // no children before
3552 // do we know something better (i.e. later) already?
3553 if (it->first < bestPos )
3556 // scope ends behind pos?
3557 if (pos < it->second.scope
3558 && (cloned_buffer_ ||
3559 theBufferList().isLoaded(it->second.buffer))) {
3560 // look for macro in external file
3562 MacroData const * data
3563 = it->second.buffer->getMacro(name, false);
3566 bestPos = it->first;
3572 // try previous file if there is one
3573 if (it == position_to_children.begin())
3578 // return the best macro we have found
3583 MacroData const * Buffer::getMacro(docstring const & name,
3584 DocIterator const & pos, bool global) const
3589 // query buffer macros
3590 MacroData const * data = d->getBufferMacro(name, pos);
3594 // If there is a master buffer, query that
3595 Buffer const * const pbuf = d->parent();
3597 d->macro_lock = true;
3598 MacroData const * macro = pbuf->getMacro(
3599 name, *this, false);
3600 d->macro_lock = false;
3606 data = MacroTable::globalMacros().get(name);
3615 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3617 // set scope end behind the last paragraph
3618 DocIterator scope = par_iterator_begin();
3619 scope.pit() = scope.lastpit() + 1;
3621 return getMacro(name, scope, global);
3625 MacroData const * Buffer::getMacro(docstring const & name,
3626 Buffer const & child, bool global) const
3628 // look where the child buffer is included first
3629 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3630 if (it == d->children_positions.end())
3633 // check for macros at the inclusion position
3634 return getMacro(name, it->second, global);
3638 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3640 pit_type const lastpit = it.lastpit();
3642 // look for macros in each paragraph
3643 while (it.pit() <= lastpit) {
3644 Paragraph & par = it.paragraph();
3646 // iterate over the insets of the current paragraph
3647 InsetList const & insets = par.insetList();
3648 InsetList::const_iterator iit = insets.begin();
3649 InsetList::const_iterator end = insets.end();
3650 for (; iit != end; ++iit) {
3651 it.pos() = iit->pos;
3653 // is it a nested text inset?
3654 if (iit->inset->asInsetText()) {
3655 // Inset needs its own scope?
3656 InsetText const * itext = iit->inset->asInsetText();
3657 bool newScope = itext->isMacroScope();
3659 // scope which ends just behind the inset
3660 DocIterator insetScope = it;
3663 // collect macros in inset
3664 it.push_back(CursorSlice(*iit->inset));
3665 updateMacros(it, newScope ? insetScope : scope);
3670 if (iit->inset->asInsetTabular()) {
3671 CursorSlice slice(*iit->inset);
3672 size_t const numcells = slice.nargs();
3673 for (; slice.idx() < numcells; slice.forwardIdx()) {
3674 it.push_back(slice);
3675 updateMacros(it, scope);
3681 // is it an external file?
3682 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3683 // get buffer of external file
3684 InsetInclude const & inset =
3685 static_cast<InsetInclude const &>(*iit->inset);
3687 Buffer * child = inset.getChildBuffer();
3692 // register its position, but only when it is
3693 // included first in the buffer
3694 if (children_positions.find(child) ==
3695 children_positions.end())
3696 children_positions[child] = it;
3698 // register child with its scope
3699 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3703 InsetMath * im = iit->inset->asInsetMath();
3704 if (doing_export && im) {
3705 InsetMathHull * hull = im->asHullInset();
3707 hull->recordLocation(it);
3710 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3714 InsetMathMacroTemplate & macroTemplate =
3715 *iit->inset->asInsetMath()->asMacroTemplate();
3716 MacroContext mc(owner_, it);
3717 macroTemplate.updateToContext(mc);
3720 bool valid = macroTemplate.validMacro();
3721 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3722 // then the BufferView's cursor will be invalid in
3723 // some cases which leads to crashes.
3728 // FIXME (Abdel), I don't understand why we pass 'it' here
3729 // instead of 'macroTemplate' defined above... is this correct?
3730 macros[macroTemplate.name()][it] =
3731 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3741 void Buffer::updateMacros() const
3746 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3748 // start with empty table
3750 d->children_positions.clear();
3751 d->position_to_children.clear();
3753 // Iterate over buffer, starting with first paragraph
3754 // The scope must be bigger than any lookup DocIterator
3755 // later. For the global lookup, lastpit+1 is used, hence
3756 // we use lastpit+2 here.
3757 DocIterator it = par_iterator_begin();
3758 DocIterator outerScope = it;
3759 outerScope.pit() = outerScope.lastpit() + 2;
3760 d->updateMacros(it, outerScope);
3764 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3766 InsetIterator it = inset_iterator_begin(inset());
3767 InsetIterator const end = inset_iterator_end(inset());
3768 for (; it != end; ++it) {
3769 if (it->lyxCode() == BRANCH_CODE) {
3770 InsetBranch & br = static_cast<InsetBranch &>(*it);
3771 docstring const name = br.branch();
3772 if (!from_master && !params().branchlist().find(name))
3773 result.push_back(name);
3774 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3775 result.push_back(name);
3778 if (it->lyxCode() == INCLUDE_CODE) {
3779 // get buffer of external file
3780 InsetInclude const & ins =
3781 static_cast<InsetInclude const &>(*it);
3782 Buffer * child = ins.getChildBuffer();
3785 child->getUsedBranches(result, true);
3788 // remove duplicates
3793 void Buffer::updateMacroInstances(UpdateType utype) const
3795 LYXERR(Debug::MACROS, "updateMacroInstances for "
3796 << d->filename.onlyFileName());
3797 DocIterator it = doc_iterator_begin(this);
3799 DocIterator const end = doc_iterator_end(this);
3800 for (; it != end; it.forwardInset()) {
3801 // look for MathData cells in InsetMathNest insets
3802 InsetMath * minset = it.nextInset()->asInsetMath();
3806 // update macro in all cells of the InsetMathNest
3807 DocIterator::idx_type n = minset->nargs();
3808 MacroContext mc = MacroContext(this, it);
3809 for (DocIterator::idx_type i = 0; i < n; ++i) {
3810 MathData & data = minset->cell(i);
3811 data.updateMacros(0, mc, utype, 0);
3817 void Buffer::listMacroNames(MacroNameSet & macros) const
3822 d->macro_lock = true;
3824 // loop over macro names
3825 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3826 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3827 for (; nameIt != nameEnd; ++nameIt)
3828 macros.insert(nameIt->first);
3830 // loop over children
3831 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3832 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3833 for (; it != end; ++it) {
3834 Buffer * child = const_cast<Buffer *>(it->first);
3835 // The buffer might have been closed (see #10766).
3836 if (theBufferList().isLoaded(child))
3837 child->listMacroNames(macros);
3841 Buffer const * const pbuf = d->parent();
3843 pbuf->listMacroNames(macros);
3845 d->macro_lock = false;
3849 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3851 Buffer const * const pbuf = d->parent();
3856 pbuf->listMacroNames(names);
3859 MacroNameSet::iterator it = names.begin();
3860 MacroNameSet::iterator end = names.end();
3861 for (; it != end; ++it) {
3863 MacroData const * data =
3864 pbuf->getMacro(*it, *this, false);
3866 macros.insert(data);
3868 // we cannot access the original InsetMathMacroTemplate anymore
3869 // here to calls validate method. So we do its work here manually.
3870 // FIXME: somehow make the template accessible here.
3871 if (data->optionals() > 0)
3872 features.require("xargs");
3878 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3881 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3883 RefCache::iterator it = d->ref_cache_.find(label);
3884 if (it != d->ref_cache_.end())
3885 return it->second.second;
3887 static InsetLabel const * dummy_il = 0;
3888 static References const dummy_refs = References();
3889 it = d->ref_cache_.insert(
3890 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3891 return it->second.second;
3895 Buffer::References const & Buffer::references(docstring const & label) const
3897 return const_cast<Buffer *>(this)->getReferenceCache(label);
3901 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3903 References & refs = getReferenceCache(label);
3904 refs.push_back(make_pair(inset, it));
3908 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3910 masterBuffer()->d->ref_cache_[label].first = il;
3914 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3916 return masterBuffer()->d->ref_cache_[label].first;
3920 void Buffer::clearReferenceCache() const
3923 d->ref_cache_.clear();
3927 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3929 //FIXME: This does not work for child documents yet.
3930 reloadBibInfoCache();
3932 // Check if the label 'from' appears more than once
3933 BiblioInfo const & keys = masterBibInfo();
3934 BiblioInfo::const_iterator bit = keys.begin();
3935 BiblioInfo::const_iterator bend = keys.end();
3936 vector<docstring> labels;
3938 for (; bit != bend; ++bit)
3940 labels.push_back(bit->first);
3942 if (count(labels.begin(), labels.end(), from) > 1)
3945 string const paramName = "key";
3946 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3947 if (it->lyxCode() != CITE_CODE)
3949 InsetCommand * inset = it->asInsetCommand();
3950 docstring const oldValue = inset->getParam(paramName);
3951 if (oldValue == from)
3952 inset->setParam(paramName, to);
3956 // returns NULL if id-to-row conversion is unsupported
3957 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3958 pit_type par_begin, pit_type par_end,
3959 OutputWhat output, bool master) const
3961 unique_ptr<TexRow> texrow;
3962 OutputParams runparams(¶ms().encoding());
3963 runparams.nice = true;
3964 runparams.flavor = params().getOutputFlavor(format);
3965 runparams.linelen = lyxrc.plaintext_linelen;
3966 // No side effect of file copying and image conversion
3967 runparams.dryrun = true;
3969 if (output == CurrentParagraph) {
3970 runparams.par_begin = par_begin;
3971 runparams.par_end = par_end;
3972 if (par_begin + 1 == par_end) {
3974 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3978 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3979 convert<docstring>(par_begin),
3980 convert<docstring>(par_end - 1))
3983 // output paragraphs
3984 if (runparams.flavor == OutputParams::LYX) {
3985 Paragraph const & par = text().paragraphs()[par_begin];
3987 depth_type dt = par.getDepth();
3988 par.write(ods, params(), dt);
3989 os << from_utf8(ods.str());
3990 } else if (runparams.flavor == OutputParams::HTML) {
3992 setMathFlavor(runparams);
3993 xhtmlParagraphs(text(), *this, xs, runparams);
3994 } else if (runparams.flavor == OutputParams::TEXT) {
3996 // FIXME Handles only one paragraph, unlike the others.
3997 // Probably should have some routine with a signature like them.
3998 writePlaintextParagraph(*this,
3999 text().paragraphs()[par_begin], os, runparams, dummy);
4000 } else if (params().isDocBook()) {
4001 docbookParagraphs(text(), *this, os, runparams);
4003 // If we are previewing a paragraph, even if this is the
4004 // child of some other buffer, let's cut the link here,
4005 // so that no concurring settings from the master
4006 // (e.g. branch state) interfere (see #8101).
4008 d->ignore_parent = true;
4009 // We need to validate the Buffer params' features here
4010 // in order to know if we should output polyglossia
4011 // macros (instead of babel macros)
4012 LaTeXFeatures features(*this, params(), runparams);
4014 runparams.use_polyglossia = features.usePolyglossia();
4015 // latex or literate
4018 ots.texrow().newlines(2);
4020 latexParagraphs(*this, text(), ots, runparams);
4021 texrow = ots.releaseTexRow();
4023 // Restore the parenthood
4025 d->ignore_parent = false;
4029 if (output == FullSource)
4030 os << _("Preview source code");
4031 else if (output == OnlyPreamble)
4032 os << _("Preview preamble");
4033 else if (output == OnlyBody)
4034 os << _("Preview body");
4036 if (runparams.flavor == OutputParams::LYX) {
4038 if (output == FullSource)
4040 else if (output == OnlyPreamble)
4041 params().writeFile(ods, this);
4042 else if (output == OnlyBody)
4044 os << from_utf8(ods.str());
4045 } else if (runparams.flavor == OutputParams::HTML) {
4046 writeLyXHTMLSource(os, runparams, output);
4047 } else if (runparams.flavor == OutputParams::TEXT) {
4048 if (output == OnlyPreamble) {
4049 os << "% "<< _("Plain text does not have a preamble.");
4051 writePlaintextFile(*this, os, runparams);
4052 } else if (params().isDocBook()) {
4053 writeDocBookSource(os, absFileName(), runparams, output);
4055 // latex or literate
4058 ots.texrow().newlines(2);
4060 runparams.is_child = true;
4062 writeLaTeXSource(ots, string(), runparams, output);
4063 texrow = ots.releaseTexRow();
4070 ErrorList & Buffer::errorList(string const & type) const
4072 return d->errorLists[type];
4076 void Buffer::updateTocItem(std::string const & type,
4077 DocIterator const & dit) const
4080 d->gui_->updateTocItem(type, dit);
4084 void Buffer::structureChanged() const
4087 d->gui_->structureChanged();
4091 void Buffer::errors(string const & err, bool from_master) const
4094 d->gui_->errors(err, from_master);
4098 void Buffer::message(docstring const & msg) const
4101 d->gui_->message(msg);
4105 void Buffer::setBusy(bool on) const
4108 d->gui_->setBusy(on);
4112 void Buffer::updateTitles() const
4115 d->wa_->updateTitles();
4119 void Buffer::resetAutosaveTimers() const
4122 d->gui_->resetAutosaveTimers();
4126 bool Buffer::hasGuiDelegate() const
4132 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4141 class AutoSaveBuffer : public ForkedProcess {
4144 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4145 : buffer_(buffer), fname_(fname) {}
4147 virtual shared_ptr<ForkedProcess> clone() const
4149 return make_shared<AutoSaveBuffer>(*this);
4154 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4155 from_utf8(fname_.absFileName())));
4156 return run(DontWait);
4160 virtual int generateChild();
4162 Buffer const & buffer_;
4167 int AutoSaveBuffer::generateChild()
4169 #if defined(__APPLE__)
4170 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4171 * We should use something else like threads.
4173 * Since I do not know how to determine at run time what is the OS X
4174 * version, I just disable forking altogether for now (JMarc)
4176 pid_t const pid = -1;
4178 // tmp_ret will be located (usually) in /tmp
4179 // will that be a problem?
4180 // Note that this calls ForkedCalls::fork(), so it's
4181 // ok cross-platform.
4182 pid_t const pid = fork();
4183 // If you want to debug the autosave
4184 // you should set pid to -1, and comment out the fork.
4185 if (pid != 0 && pid != -1)
4189 // pid = -1 signifies that lyx was unable
4190 // to fork. But we will do the save
4192 bool failed = false;
4193 TempFile tempfile("lyxautoXXXXXX.lyx");
4194 tempfile.setAutoRemove(false);
4195 FileName const tmp_ret = tempfile.name();
4196 if (!tmp_ret.empty()) {
4197 if (!buffer_.writeFile(tmp_ret))
4199 else if (!tmp_ret.moveTo(fname_))
4205 // failed to write/rename tmp_ret so try writing direct
4206 if (!buffer_.writeFile(fname_)) {
4207 // It is dangerous to do this in the child,
4208 // but safe in the parent, so...
4209 if (pid == -1) // emit message signal.
4210 buffer_.message(_("Autosave failed!"));
4214 if (pid == 0) // we are the child so...
4223 FileName Buffer::getEmergencyFileName() const
4225 return FileName(d->filename.absFileName() + ".emergency");
4229 FileName Buffer::getAutosaveFileName() const
4231 // if the document is unnamed try to save in the backup dir, else
4232 // in the default document path, and as a last try in the filePath,
4233 // which will most often be the temporary directory
4236 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4237 : lyxrc.backupdir_path;
4238 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4241 string const fname = "#" + d->filename.onlyFileName() + "#";
4243 return makeAbsPath(fname, fpath);
4247 void Buffer::removeAutosaveFile() const
4249 FileName const f = getAutosaveFileName();
4255 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4257 FileName const newauto = getAutosaveFileName();
4259 if (newauto != oldauto && oldauto.exists())
4260 if (!oldauto.moveTo(newauto))
4261 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4265 bool Buffer::autoSave() const
4267 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4268 if (buf->d->bak_clean || hasReadonlyFlag())
4271 message(_("Autosaving current document..."));
4272 buf->d->bak_clean = true;
4274 FileName const fname = getAutosaveFileName();
4275 LASSERT(d->cloned_buffer_, return false);
4277 // If this buffer is cloned, we assume that
4278 // we are running in a separate thread already.
4279 TempFile tempfile("lyxautoXXXXXX.lyx");
4280 tempfile.setAutoRemove(false);
4281 FileName const tmp_ret = tempfile.name();
4282 if (!tmp_ret.empty()) {
4284 // assume successful write of tmp_ret
4285 if (tmp_ret.moveTo(fname))
4288 // failed to write/rename tmp_ret so try writing direct
4289 return writeFile(fname);
4293 void Buffer::setExportStatus(bool e) const
4295 d->doing_export = e;
4296 ListOfBuffers clist = getDescendents();
4297 ListOfBuffers::const_iterator cit = clist.begin();
4298 ListOfBuffers::const_iterator const cen = clist.end();
4299 for (; cit != cen; ++cit)
4300 (*cit)->d->doing_export = e;
4304 bool Buffer::isExporting() const
4306 return d->doing_export;
4310 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4314 return doExport(target, put_in_tempdir, result_file);
4317 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4318 string & result_file) const
4320 bool const update_unincluded =
4321 params().maintain_unincluded_children
4322 && !params().getIncludedChildren().empty();
4324 // (1) export with all included children (omit \includeonly)
4325 if (update_unincluded) {
4326 ExportStatus const status =
4327 doExport(target, put_in_tempdir, true, result_file);
4328 if (status != ExportSuccess)
4331 // (2) export with included children only
4332 return doExport(target, put_in_tempdir, false, result_file);
4336 void Buffer::setMathFlavor(OutputParams & op) const
4338 switch (params().html_math_output) {
4339 case BufferParams::MathML:
4340 op.math_flavor = OutputParams::MathAsMathML;
4342 case BufferParams::HTML:
4343 op.math_flavor = OutputParams::MathAsHTML;
4345 case BufferParams::Images:
4346 op.math_flavor = OutputParams::MathAsImages;
4348 case BufferParams::LaTeX:
4349 op.math_flavor = OutputParams::MathAsLaTeX;
4355 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4356 bool includeall, string & result_file) const
4358 LYXERR(Debug::FILES, "target=" << target);
4359 OutputParams runparams(¶ms().encoding());
4360 string format = target;
4361 string dest_filename;
4362 size_t pos = target.find(' ');
4363 if (pos != string::npos) {
4364 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4365 format = target.substr(0, pos);
4366 if (format == "default")
4367 format = params().getDefaultOutputFormat();
4368 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4369 FileName(dest_filename).onlyPath().createPath();
4370 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4372 MarkAsExporting exporting(this);
4373 string backend_format;
4374 runparams.flavor = OutputParams::LATEX;
4375 runparams.linelen = lyxrc.plaintext_linelen;
4376 runparams.includeall = includeall;
4377 vector<string> backs = params().backends();
4378 Converters converters = theConverters();
4379 bool need_nice_file = false;
4380 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4381 // Get shortest path to format
4382 converters.buildGraph();
4383 Graph::EdgePath path;
4384 for (vector<string>::const_iterator it = backs.begin();
4385 it != backs.end(); ++it) {
4386 Graph::EdgePath p = converters.getPath(*it, format);
4387 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4388 backend_format = *it;
4393 if (!put_in_tempdir) {
4394 // Only show this alert if this is an export to a non-temporary
4395 // file (not for previewing).
4396 Alert::error(_("Couldn't export file"), bformat(
4397 _("No information for exporting the format %1$s."),
4398 theFormats().prettyName(format)));
4400 return ExportNoPathToFormat;
4402 runparams.flavor = converters.getFlavor(path, this);
4403 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4404 Graph::EdgePath::const_iterator it = path.begin();
4405 Graph::EdgePath::const_iterator en = path.end();
4406 for (; it != en; ++it)
4407 if (theConverters().get(*it).nice()) {
4408 need_nice_file = true;
4413 backend_format = format;
4414 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4415 // FIXME: Don't hardcode format names here, but use a flag
4416 if (backend_format == "pdflatex")
4417 runparams.flavor = OutputParams::PDFLATEX;
4418 else if (backend_format == "luatex")
4419 runparams.flavor = OutputParams::LUATEX;
4420 else if (backend_format == "dviluatex")
4421 runparams.flavor = OutputParams::DVILUATEX;
4422 else if (backend_format == "xetex")
4423 runparams.flavor = OutputParams::XETEX;
4426 string filename = latexName(false);
4427 filename = addName(temppath(), filename);
4428 filename = changeExtension(filename,
4429 theFormats().extension(backend_format));
4430 LYXERR(Debug::FILES, "filename=" << filename);
4432 // Plain text backend
4433 if (backend_format == "text") {
4434 runparams.flavor = OutputParams::TEXT;
4435 writePlaintextFile(*this, FileName(filename), runparams);
4438 else if (backend_format == "xhtml") {
4439 runparams.flavor = OutputParams::HTML;
4440 setMathFlavor(runparams);
4441 makeLyXHTMLFile(FileName(filename), runparams);
4442 } else if (backend_format == "lyx")
4443 writeFile(FileName(filename));
4445 else if (params().isDocBook()) {
4446 runparams.nice = !put_in_tempdir;
4447 makeDocBookFile(FileName(filename), runparams);
4450 else if (backend_format == format || need_nice_file) {
4451 runparams.nice = true;
4452 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4453 if (d->cloned_buffer_)
4454 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4457 } else if (!lyxrc.tex_allows_spaces
4458 && contains(filePath(), ' ')) {
4459 Alert::error(_("File name error"),
4460 bformat(_("The directory path to the document\n%1$s\n"
4461 "contains spaces, but your TeX installation does "
4462 "not allow them. You should save the file to a directory "
4463 "whose name does not contain spaces."), from_ascii(filePath())));
4464 return ExportTexPathHasSpaces;
4466 runparams.nice = false;
4467 bool const success = makeLaTeXFile(
4468 FileName(filename), filePath(), runparams);
4469 if (d->cloned_buffer_)
4470 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4475 string const error_type = (format == "program")
4476 ? "Build" : params().bufferFormat();
4477 ErrorList & error_list = d->errorLists[error_type];
4478 string const ext = theFormats().extension(format);
4479 FileName const tmp_result_file(changeExtension(filename, ext));
4480 bool const success = converters.convert(this, FileName(filename),
4481 tmp_result_file, FileName(absFileName()), backend_format, format,
4484 // Emit the signal to show the error list or copy it back to the
4485 // cloned Buffer so that it can be emitted afterwards.
4486 if (format != backend_format) {
4487 if (runparams.silent)
4489 else if (d->cloned_buffer_)
4490 d->cloned_buffer_->d->errorLists[error_type] =
4491 d->errorLists[error_type];
4494 // also to the children, in case of master-buffer-view
4495 ListOfBuffers clist = getDescendents();
4496 ListOfBuffers::const_iterator cit = clist.begin();
4497 ListOfBuffers::const_iterator const cen = clist.end();
4498 for (; cit != cen; ++cit) {
4499 if (runparams.silent)
4500 (*cit)->d->errorLists[error_type].clear();
4501 else if (d->cloned_buffer_) {
4502 // Enable reverse search by copying back the
4503 // texrow object to the cloned buffer.
4504 // FIXME: this is not thread safe.
4505 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4506 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4507 (*cit)->d->errorLists[error_type];
4509 (*cit)->errors(error_type, true);
4513 if (d->cloned_buffer_) {
4514 // Enable reverse dvi or pdf to work by copying back the texrow
4515 // object to the cloned buffer.
4516 // FIXME: There is a possibility of concurrent access to texrow
4517 // here from the main GUI thread that should be securized.
4518 d->cloned_buffer_->d->texrow = d->texrow;
4519 string const error_type = params().bufferFormat();
4520 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4524 if (put_in_tempdir) {
4525 result_file = tmp_result_file.absFileName();
4526 return success ? ExportSuccess : ExportConverterError;
4529 if (dest_filename.empty())
4530 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4532 result_file = dest_filename;
4533 // We need to copy referenced files (e. g. included graphics
4534 // if format == "dvi") to the result dir.
4535 vector<ExportedFile> const files =
4536 runparams.exportdata->externalFiles(format);
4537 string const dest = runparams.export_folder.empty() ?
4538 onlyPath(result_file) : runparams.export_folder;
4539 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4540 : force_overwrite == ALL_FILES;
4541 CopyStatus status = use_force ? FORCE : SUCCESS;
4543 vector<ExportedFile>::const_iterator it = files.begin();
4544 vector<ExportedFile>::const_iterator const en = files.end();
4545 for (; it != en && status != CANCEL; ++it) {
4546 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4547 string fixedName = it->exportName;
4548 if (!runparams.export_folder.empty()) {
4549 // Relative pathnames starting with ../ will be sanitized
4550 // if exporting to a different folder
4551 while (fixedName.substr(0, 3) == "../")
4552 fixedName = fixedName.substr(3, fixedName.length() - 3);
4554 FileName fixedFileName = makeAbsPath(fixedName, dest);
4555 fixedFileName.onlyPath().createPath();
4556 status = copyFile(fmt, it->sourceName,
4558 it->exportName, status == FORCE,
4559 runparams.export_folder.empty());
4562 if (status == CANCEL) {
4563 message(_("Document export cancelled."));
4564 return ExportCancel;
4567 if (tmp_result_file.exists()) {
4568 // Finally copy the main file
4569 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4570 : force_overwrite != NO_FILES;
4571 if (status == SUCCESS && use_force)
4573 status = copyFile(format, tmp_result_file,
4574 FileName(result_file), result_file,
4576 if (status == CANCEL) {
4577 message(_("Document export cancelled."));
4578 return ExportCancel;
4580 message(bformat(_("Document exported as %1$s "
4582 theFormats().prettyName(format),
4583 makeDisplayPath(result_file)));
4586 // This must be a dummy converter like fax (bug 1888)
4587 message(bformat(_("Document exported as %1$s"),
4588 theFormats().prettyName(format)));
4591 return success ? ExportSuccess : ExportConverterError;
4595 Buffer::ExportStatus Buffer::preview(string const & format) const
4597 bool const update_unincluded =
4598 params().maintain_unincluded_children
4599 && !params().getIncludedChildren().empty();
4600 return preview(format, update_unincluded);
4604 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4606 MarkAsExporting exporting(this);
4608 // (1) export with all included children (omit \includeonly)
4610 ExportStatus const status = doExport(format, true, true, result_file);
4611 if (status != ExportSuccess)
4614 // (2) export with included children only
4615 ExportStatus const status = doExport(format, true, false, result_file);
4616 FileName const previewFile(result_file);
4618 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4619 theimpl->preview_file_ = previewFile;
4620 theimpl->preview_format_ = format;
4621 theimpl->preview_error_ = (status != ExportSuccess);
4623 if (status != ExportSuccess)
4626 if (previewFile.exists())
4627 return theFormats().view(*this, previewFile, format) ?
4628 PreviewSuccess : PreviewError;
4630 // Successful export but no output file?
4631 // Probably a bug in error detection.
4632 LATTEST(status != ExportSuccess);
4637 Buffer::ReadStatus Buffer::extractFromVC()
4639 bool const found = LyXVC::file_not_found_hook(d->filename);
4641 return ReadFileNotFound;
4642 if (!d->filename.isReadableFile())
4648 Buffer::ReadStatus Buffer::loadEmergency()
4650 FileName const emergencyFile = getEmergencyFileName();
4651 if (!emergencyFile.exists()
4652 || emergencyFile.lastModified() <= d->filename.lastModified())
4653 return ReadFileNotFound;
4655 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4656 docstring const text = bformat(_("An emergency save of the document "
4657 "%1$s exists.\n\nRecover emergency save?"), file);
4659 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4660 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4666 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4667 bool const success = (ret_llf == ReadSuccess);
4669 if (hasReadonlyFlag()) {
4670 Alert::warning(_("File is read-only"),
4671 bformat(_("An emergency file is successfully loaded, "
4672 "but the original file %1$s is marked read-only. "
4673 "Please make sure to save the document as a different "
4674 "file."), from_utf8(d->filename.absFileName())));
4677 lyxvc().file_found_hook(d->filename);
4678 str = _("Document was successfully recovered.");
4680 str = _("Document was NOT successfully recovered.");
4681 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4682 makeDisplayPath(emergencyFile.absFileName()));
4684 int const del_emerg =
4685 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4686 _("&Remove"), _("&Keep"));
4687 if (del_emerg == 0) {
4688 emergencyFile.removeFile();
4690 Alert::warning(_("Emergency file deleted"),
4691 _("Do not forget to save your file now!"), true);
4693 return success ? ReadSuccess : ReadEmergencyFailure;
4696 int const del_emerg =
4697 Alert::prompt(_("Delete emergency file?"),
4698 _("Remove emergency file now?"), 1, 1,
4699 _("&Remove"), _("&Keep"));
4701 emergencyFile.removeFile();
4702 return ReadOriginal;
4712 Buffer::ReadStatus Buffer::loadAutosave()
4714 // Now check if autosave file is newer.
4715 FileName const autosaveFile = getAutosaveFileName();
4716 if (!autosaveFile.exists()
4717 || autosaveFile.lastModified() <= d->filename.lastModified())
4718 return ReadFileNotFound;
4720 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4721 docstring const text = bformat(_("The backup of the document %1$s "
4722 "is newer.\n\nLoad the backup instead?"), file);
4723 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4724 _("&Load backup"), _("Load &original"), _("&Cancel"));
4729 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4730 // the file is not saved if we load the autosave file.
4731 if (ret_llf == ReadSuccess) {
4732 if (hasReadonlyFlag()) {
4733 Alert::warning(_("File is read-only"),
4734 bformat(_("A backup file is successfully loaded, "
4735 "but the original file %1$s is marked read-only. "
4736 "Please make sure to save the document as a "
4738 from_utf8(d->filename.absFileName())));
4741 lyxvc().file_found_hook(d->filename);
4744 return ReadAutosaveFailure;
4747 // Here we delete the autosave
4748 autosaveFile.removeFile();
4749 return ReadOriginal;
4757 Buffer::ReadStatus Buffer::loadLyXFile()
4759 if (!d->filename.isReadableFile()) {
4760 ReadStatus const ret_rvc = extractFromVC();
4761 if (ret_rvc != ReadSuccess)
4765 ReadStatus const ret_re = loadEmergency();
4766 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4769 ReadStatus const ret_ra = loadAutosave();
4770 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4773 return loadThisLyXFile(d->filename);
4777 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4779 return readFile(fn);
4783 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4785 for (auto const & err : terr) {
4786 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4787 int errorRow = err.error_in_line;
4788 Buffer const * buf = 0;
4790 if (err.child_name.empty())
4791 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4793 // The error occurred in a child
4794 for (Buffer const * child : getDescendents()) {
4795 string const child_name =
4796 DocFileName(changeExtension(child->absFileName(), "tex")).
4798 if (err.child_name != child_name)
4800 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4801 if (!TexRow::isNone(start)) {
4802 buf = d->cloned_buffer_
4803 ? child->d->cloned_buffer_->d->owner_
4810 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4816 void Buffer::setBuffersForInsets() const
4818 inset().setBuffer(const_cast<Buffer &>(*this));
4822 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4824 LBUFERR(!text().paragraphs().empty());
4826 // Use the master text class also for child documents
4827 Buffer const * const master = masterBuffer();
4828 DocumentClass const & textclass = master->params().documentClass();
4830 docstring_list old_bibfiles;
4831 // Do this only if we are the top-level Buffer. We also need to account
4832 // for the case of a previewed child with ignored parent here.
4833 if (master == this && !d->ignore_parent) {
4834 textclass.counters().reset(from_ascii("bibitem"));
4835 reloadBibInfoCache();
4836 // we will re-read this cache as we go through, but we need
4837 // to know whether it's changed to know whether we need to
4838 // update the bibinfo cache.
4839 old_bibfiles = d->bibfiles_cache_;
4840 d->bibfiles_cache_.clear();
4843 // keep the buffers to be children in this set. If the call from the
4844 // master comes back we can see which of them were actually seen (i.e.
4845 // via an InsetInclude). The remaining ones in the set need still be updated.
4846 static std::set<Buffer const *> bufToUpdate;
4847 if (scope == UpdateMaster) {
4848 // If this is a child document start with the master
4849 if (master != this) {
4850 bufToUpdate.insert(this);
4851 master->updateBuffer(UpdateMaster, utype);
4852 // If the master buffer has no gui associated with it, then the TocModel is
4853 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4854 // (bug 5699). The same happens if the master buffer is open in a different
4855 // window. This test catches both possibilities.
4856 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4857 // There remains a problem here: If there is another child open in yet a third
4858 // window, that TOC is not updated. So some more general solution is needed at
4860 if (master->d->gui_ != d->gui_)
4863 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4864 if (bufToUpdate.find(this) == bufToUpdate.end())
4868 // start over the counters in the master
4869 textclass.counters().reset();
4872 // update will be done below for this buffer
4873 bufToUpdate.erase(this);
4875 // update all caches
4876 clearReferenceCache();
4878 setChangesPresent(false);
4880 Buffer & cbuf = const_cast<Buffer &>(*this);
4883 ParIterator parit = cbuf.par_iterator_begin();
4884 updateBuffer(parit, utype);
4887 // If this document has siblings, then update the TocBackend later. The
4888 // reason is to ensure that later siblings are up to date when e.g. the
4889 // broken or not status of references is computed. The update is called
4890 // in InsetInclude::addToToc.
4893 // if the bibfiles changed, the cache of bibinfo is invalid
4894 docstring_list new_bibfiles = d->bibfiles_cache_;
4895 // this is a trick to determine whether the two vectors have
4896 // the same elements.
4897 sort(new_bibfiles.begin(), new_bibfiles.end());
4898 sort(old_bibfiles.begin(), old_bibfiles.end());
4899 if (old_bibfiles != new_bibfiles) {
4900 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4901 invalidateBibinfoCache();
4902 reloadBibInfoCache();
4903 // We relied upon the bibinfo cache when recalculating labels. But that
4904 // cache was invalid, although we didn't find that out until now. So we
4905 // have to do it all again.
4906 // That said, the only thing we really need to do is update the citation
4907 // labels. Nothing else will have changed. So we could create a new
4908 // UpdateType that would signal that fact, if we needed to do so.
4909 parit = cbuf.par_iterator_begin();
4910 // we will be re-doing the counters and references and such.
4911 textclass.counters().reset();
4912 clearReferenceCache();
4913 // we should not need to do this again?
4915 setChangesPresent(false);
4916 updateBuffer(parit, utype);
4917 // this will already have been done by reloadBibInfoCache();
4918 // d->bibinfo_cache_valid_ = true;
4921 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4922 // this is also set to true on the other path, by reloadBibInfoCache.
4923 d->bibinfo_cache_valid_ = true;
4925 d->cite_labels_valid_ = true;
4927 cbuf.tocBackend().update(true, utype);
4928 if (scope == UpdateMaster)
4929 cbuf.structureChanged();
4933 static depth_type getDepth(DocIterator const & it)
4935 depth_type depth = 0;
4936 for (size_t i = 0 ; i < it.depth() ; ++i)
4937 if (!it[i].inset().inMathed())
4938 depth += it[i].paragraph().getDepth() + 1;
4939 // remove 1 since the outer inset does not count
4940 // we should have at least one non-math inset, so
4941 // depth should nevery be 0. but maybe it is worth
4942 // marking this, just in case.
4944 // coverity[INTEGER_OVERFLOW]
4948 static depth_type getItemDepth(ParIterator const & it)
4950 Paragraph const & par = *it;
4951 LabelType const labeltype = par.layout().labeltype;
4953 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4956 // this will hold the lowest depth encountered up to now.
4957 depth_type min_depth = getDepth(it);
4958 ParIterator prev_it = it;
4961 --prev_it.top().pit();
4963 // start of nested inset: go to outer par
4965 if (prev_it.empty()) {
4966 // start of document: nothing to do
4971 // We search for the first paragraph with same label
4972 // that is not more deeply nested.
4973 Paragraph & prev_par = *prev_it;
4974 depth_type const prev_depth = getDepth(prev_it);
4975 if (labeltype == prev_par.layout().labeltype) {
4976 if (prev_depth < min_depth)
4977 return prev_par.itemdepth + 1;
4978 if (prev_depth == min_depth)
4979 return prev_par.itemdepth;
4981 min_depth = min(min_depth, prev_depth);
4982 // small optimization: if we are at depth 0, we won't
4983 // find anything else
4984 if (prev_depth == 0)
4990 static bool needEnumCounterReset(ParIterator const & it)
4992 Paragraph const & par = *it;
4993 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4994 depth_type const cur_depth = par.getDepth();
4995 ParIterator prev_it = it;
4996 while (prev_it.pit()) {
4997 --prev_it.top().pit();
4998 Paragraph const & prev_par = *prev_it;
4999 if (prev_par.getDepth() <= cur_depth)
5000 return prev_par.layout().name() != par.layout().name();
5002 // start of nested inset: reset
5007 // set the label of a paragraph. This includes the counters.
5008 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5010 BufferParams const & bp = owner_->masterBuffer()->params();
5011 DocumentClass const & textclass = bp.documentClass();
5012 Paragraph & par = it.paragraph();
5013 Layout const & layout = par.layout();
5014 Counters & counters = textclass.counters();
5016 if (par.params().startOfAppendix()) {
5017 // We want to reset the counter corresponding to toplevel sectioning
5018 Layout const & lay = textclass.getTOCLayout();
5019 docstring const cnt = lay.counter;
5021 counters.reset(cnt);
5022 counters.appendix(true);
5024 par.params().appendix(counters.appendix());
5026 // Compute the item depth of the paragraph
5027 par.itemdepth = getItemDepth(it);
5029 if (layout.margintype == MARGIN_MANUAL) {
5030 if (par.params().labelWidthString().empty())
5031 par.params().labelWidthString(par.expandLabel(layout, bp));
5032 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5033 // we do not need to do anything here, since the empty case is
5034 // handled during export.
5036 par.params().labelWidthString(docstring());
5039 switch(layout.labeltype) {
5040 case LABEL_ITEMIZE: {
5041 // At some point of time we should do something more
5042 // clever here, like:
5043 // par.params().labelString(
5044 // bp.user_defined_bullet(par.itemdepth).getText());
5045 // for now, use a simple hardcoded label
5046 docstring itemlabel;
5047 switch (par.itemdepth) {
5049 itemlabel = char_type(0x2022);
5052 itemlabel = char_type(0x2013);
5055 itemlabel = char_type(0x2217);
5058 itemlabel = char_type(0x2219); // or 0x00b7
5061 par.params().labelString(itemlabel);
5065 case LABEL_ENUMERATE: {
5066 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5068 switch (par.itemdepth) {
5079 enumcounter += "iv";
5082 // not a valid enumdepth...
5086 // Increase the master counter?
5087 if (layout.stepmastercounter && needEnumCounterReset(it))
5088 counters.stepMaster(enumcounter, utype);
5090 // Maybe we have to reset the enumeration counter.
5091 if (!layout.resumecounter && needEnumCounterReset(it))
5092 counters.reset(enumcounter);
5093 counters.step(enumcounter, utype);
5095 string const & lang = par.getParLanguage(bp)->code();
5096 par.params().labelString(counters.theCounter(enumcounter, lang));
5101 case LABEL_SENSITIVE: {
5102 string const & type = counters.current_float();
5103 docstring full_label;
5105 full_label = owner_->B_("Senseless!!! ");
5107 docstring name = owner_->B_(textclass.floats().getType(type).name());
5108 if (counters.hasCounter(from_utf8(type))) {
5109 string const & lang = par.getParLanguage(bp)->code();
5110 counters.step(from_utf8(type), utype);
5111 full_label = bformat(from_ascii("%1$s %2$s:"),
5113 counters.theCounter(from_utf8(type), lang));
5115 full_label = bformat(from_ascii("%1$s #:"), name);
5117 par.params().labelString(full_label);
5121 case LABEL_NO_LABEL:
5122 par.params().labelString(docstring());
5126 case LABEL_CENTERED:
5127 case LABEL_STATIC: {
5128 docstring const & lcounter = layout.counter;
5129 if (!lcounter.empty()) {
5130 if (layout.toclevel <= bp.secnumdepth
5131 && (layout.latextype != LATEX_ENVIRONMENT
5132 || it.text()->isFirstInSequence(it.pit()))) {
5133 if (counters.hasCounter(lcounter))
5134 counters.step(lcounter, utype);
5135 par.params().labelString(par.expandLabel(layout, bp));
5137 par.params().labelString(docstring());
5139 par.params().labelString(par.expandLabel(layout, bp));
5145 par.params().labelString(par.expandLabel(layout, bp));
5150 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5152 // LASSERT: Is it safe to continue here, or should we just return?
5153 LASSERT(parit.pit() == 0, /**/);
5155 // Set the position of the text in the buffer to be able
5156 // to resolve macros in it.
5157 parit.text()->setMacrocontextPosition(parit);
5159 depth_type maxdepth = 0;
5160 pit_type const lastpit = parit.lastpit();
5161 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5162 // reduce depth if necessary
5163 if (parit->params().depth() > maxdepth) {
5164 /** FIXME: this function is const, but
5165 * nevertheless it modifies the buffer. To be
5166 * cleaner, one should modify the buffer in
5167 * another function, which is actually
5168 * non-const. This would however be costly in
5169 * terms of code duplication.
5171 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5172 parit->params().depth(maxdepth);
5174 maxdepth = parit->getMaxDepthAfter();
5176 if (utype == OutputUpdate) {
5177 // track the active counters
5178 // we have to do this for the master buffer, since the local
5179 // buffer isn't tracking anything.
5180 masterBuffer()->params().documentClass().counters().
5181 setActiveLayout(parit->layout());
5184 // set the counter for this paragraph
5185 d->setLabel(parit, utype);
5187 // update change-tracking flag
5188 parit->addChangesToBuffer(*this);
5191 InsetList::const_iterator iit = parit->insetList().begin();
5192 InsetList::const_iterator end = parit->insetList().end();
5193 for (; iit != end; ++iit) {
5194 parit.pos() = iit->pos;
5195 iit->inset->updateBuffer(parit, utype);
5201 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5202 WordLangTuple & word_lang, docstring_list & suggestions) const
5206 suggestions.clear();
5207 word_lang = WordLangTuple();
5208 bool const to_end = to.empty();
5209 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5210 // OK, we start from here.
5211 for (; from != end; from.forwardPos()) {
5212 // This skips all insets with spell check disabled.
5213 while (!from.allowSpellCheck()) {
5217 // If from is at the end of the document (which is possible
5218 // when "from" was changed above) LyX will crash later otherwise.
5219 if (from.atEnd() || (!to_end && from >= end))
5222 from.paragraph().spellCheck();
5223 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5224 if (SpellChecker::misspelled(res)) {
5228 // Do not increase progress when from == to, otherwise the word
5229 // count will be wrong.
5239 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5241 bool inword = false;
5246 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5247 if (!dit.inTexted()) {
5252 Paragraph const & par = dit.paragraph();
5253 pos_type const pos = dit.pos();
5255 // Copied and adapted from isWordSeparator() in Paragraph
5256 if (pos == dit.lastpos()) {
5259 Inset const * ins = par.getInset(pos);
5260 if (ins && skipNoOutput && !ins->producesOutput()) {
5263 // stop if end of range was skipped
5264 if (!to.atEnd() && dit >= to)
5267 } else if (!par.isDeleted(pos)) {
5268 if (par.isWordSeparator(pos))
5274 if (ins && ins->isLetter())
5276 else if (ins && ins->isSpace())
5279 char_type const c = par.getChar(pos);
5280 if (isPrintableNonspace(c))
5282 else if (isSpace(c))
5292 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5294 d->updateStatistics(from, to, skipNoOutput);
5298 int Buffer::wordCount() const
5300 return d->wordCount();
5304 int Buffer::charCount(bool with_blanks) const
5306 return d->charCount(with_blanks);
5310 Buffer::ReadStatus Buffer::reload()
5313 // c.f. bug https://www.lyx.org/trac/ticket/6587
5314 removeAutosaveFile();
5315 // e.g., read-only status could have changed due to version control
5316 d->filename.refresh();
5317 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5319 // clear parent. this will get reset if need be.
5321 ReadStatus const status = loadLyXFile();
5322 if (status == ReadSuccess) {
5327 message(bformat(_("Document %1$s reloaded."), disp_fn));
5330 message(bformat(_("Could not reload document %1$s."), disp_fn));
5340 bool Buffer::saveAs(FileName const & fn)
5342 FileName const old_name = fileName();
5343 FileName const old_auto = getAutosaveFileName();
5344 bool const old_unnamed = isUnnamed();
5345 bool success = true;
5346 d->old_position = filePath();
5353 // bring the autosave file with us, just in case.
5354 moveAutosaveFile(old_auto);
5355 // validate version control data and
5356 // correct buffer title
5357 lyxvc().file_found_hook(fileName());
5359 // the file has now been saved to the new location.
5360 // we need to check that the locations of child buffers
5362 checkChildBuffers();
5363 checkMasterBuffer();
5366 // reset the old filename and unnamed state
5367 setFileName(old_name);
5368 setUnnamed(old_unnamed);
5372 d->old_position.clear();
5377 void Buffer::checkChildBuffers()
5379 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5380 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5381 for (; it != en; ++it) {
5382 DocIterator dit = it->second;
5383 Buffer * cbuf = const_cast<Buffer *>(it->first);
5384 if (!cbuf || !theBufferList().isLoaded(cbuf))
5386 Inset * inset = dit.nextInset();
5387 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5388 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5389 docstring const & incfile = inset_inc->getParam("filename");
5390 string oldloc = cbuf->absFileName();
5391 string newloc = makeAbsPath(to_utf8(incfile),
5392 onlyPath(absFileName())).absFileName();
5393 if (oldloc == newloc)
5395 // the location of the child file is incorrect.
5397 inset_inc->setChildBuffer(0);
5399 // invalidate cache of children
5400 d->children_positions.clear();
5401 d->position_to_children.clear();
5405 // If a child has been saved under a different name/path, it might have been
5406 // orphaned. Therefore the master needs to be reset (bug 8161).
5407 void Buffer::checkMasterBuffer()
5409 Buffer const * const master = masterBuffer();
5413 // necessary to re-register the child (bug 5873)
5414 // FIXME: clean up updateMacros (here, only
5415 // child registering is needed).
5416 master->updateMacros();
5417 // (re)set master as master buffer, but only
5418 // if we are a real child
5419 if (master->isChild(this))
5426 string Buffer::includedFilePath(string const & name, string const & ext) const
5428 if (d->old_position.empty() ||
5429 equivalent(FileName(d->old_position), FileName(filePath())))
5432 bool isabsolute = FileName::isAbsolute(name);
5433 // both old_position and filePath() end with a path separator
5434 string absname = isabsolute ? name : d->old_position + name;
5436 // if old_position is set to origin, we need to do the equivalent of
5437 // getReferencedFileName() (see readDocument())
5438 if (!isabsolute && d->old_position == params().origin) {
5439 FileName const test(addExtension(filePath() + name, ext));
5441 absname = filePath() + name;
5444 if (!FileName(addExtension(absname, ext)).exists())
5448 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5450 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5451 from_utf8(filePath())));
5455 void Buffer::setChangesPresent(bool b) const
5457 d->tracked_changes_present_ = b;
5461 bool Buffer::areChangesPresent() const
5463 return d->tracked_changes_present_;
5467 void Buffer::updateChangesPresent() const
5469 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5470 setChangesPresent(false);
5471 ParConstIterator it = par_iterator_begin();
5472 ParConstIterator const end = par_iterator_end();
5473 for (; !areChangesPresent() && it != end; ++it)
5474 it->addChangesToBuffer(*this);
5478 void Buffer::Impl::refreshFileMonitor()
5480 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5481 file_monitor_->refresh();
5485 // The previous file monitor is invalid
5486 // This also destroys the previous file monitor and all its connections
5487 file_monitor_ = FileSystemWatcher::monitor(filename);
5488 // file_monitor_ will be destroyed with *this, so it is not going to call a
5489 // destroyed object method.
5490 file_monitor_->connect([this](bool exists) {
5491 fileExternallyModified(exists);
5496 void Buffer::Impl::fileExternallyModified(bool const exists)
5498 // ignore notifications after our own saving operations
5499 if (checksum_ == filename.checksum()) {
5500 LYXERR(Debug::FILES, "External modification but "
5501 "checksum unchanged: " << filename);
5504 // If the file has been deleted, only mark the file as dirty since it is
5505 // pointless to prompt for reloading. If later a file is moved into this
5506 // location, then the externally modified warning will appear then.
5508 externally_modified_ = true;
5509 // Update external modification notification.
5510 // Dirty buffers must be visible at all times.
5511 if (wa_ && wa_->unhide(owner_))
5512 wa_->updateTitles();
5514 // Unable to unhide the buffer (e.g. no GUI or not current View)
5519 bool Buffer::notifiesExternalModification() const
5521 return d->externally_modified_;
5525 void Buffer::clearExternalModification() const
5527 d->externally_modified_ = false;
5529 d->wa_->updateTitles();