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 (!writeFile(savefile))
1437 // we will set this to false if we fail
1438 bool made_backup = true;
1440 FileName backupName;
1441 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1443 if (d->need_format_backup)
1444 backupName = getBackupName();
1446 // If we for some reason failed to find a backup name in case of
1447 // a format change, this will still set one. It's the best we can
1449 if (backupName.empty()) {
1450 backupName.set(fileName().absFileName() + "~");
1451 if (!lyxrc.backupdir_path.empty()) {
1452 string const mangledName =
1453 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1454 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1458 LYXERR(Debug::FILES, "Backing up original file to " <<
1459 backupName.absFileName());
1460 // Except file is symlink do not copy because of #6587.
1461 // Hard links have bad luck.
1462 made_backup = symlink ?
1463 fileName().copyTo(backupName):
1464 fileName().moveTo(backupName);
1467 Alert::error(_("Backup failure"),
1468 bformat(_("Cannot create backup file %1$s.\n"
1469 "Please check whether the directory exists and is writable."),
1470 from_utf8(backupName.absFileName())));
1471 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1472 } else if (d->need_format_backup) {
1473 // the original file has been backed up successfully, so we
1474 // will not need to do that again
1475 d->need_format_backup = false;
1479 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1480 // Only do this if tempfile is not in autoremove mode
1483 // If we have no symlink, we can simply rename the temp file.
1484 // Otherwise, we need to copy it so the symlink stays intact.
1485 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1486 savefile.moveTo(fileName()))
1488 // saveCheckSum() was already called by writeFile(), but the
1489 // time stamp is invalidated by copying/moving
1492 if (d->file_format != LYX_FORMAT)
1493 // the file associated with this buffer is now in the current format
1494 d->file_format = LYX_FORMAT;
1497 // else we saved the file, but failed to move it to the right location.
1499 if (needBackup && made_backup && !symlink) {
1500 // the original file was moved to some new location, so it will look
1501 // to the user as if it was deleted. (see bug #9234.) we could try
1502 // to restore it, but that would basically mean trying to do again
1503 // what we just failed to do. better to leave things as they are.
1504 Alert::error(_("Write failure"),
1505 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1506 "But LyX could not move it to:\n %2$s.\n"
1507 "Your original file has been backed up to:\n %3$s"),
1508 from_utf8(savefile.absFileName()),
1509 from_utf8(fileName().absFileName()),
1510 from_utf8(backupName.absFileName())));
1512 // either we did not try to make a backup, or else we tried and failed,
1513 // or else the original file was a symlink, in which case it was copied,
1514 // not moved. so the original file is intact.
1515 Alert::error(_("Write failure"),
1516 bformat(_("Cannot move saved file to:\n %1$s.\n"
1517 "But the file has successfully been saved as:\n %2$s."),
1518 from_utf8(fileName().absFileName()),
1519 from_utf8(savefile.absFileName())));
1525 bool Buffer::writeFile(FileName const & fname) const
1527 if (d->read_only && fname == d->filename)
1530 bool retval = false;
1532 docstring const str = bformat(_("Saving document %1$s..."),
1533 makeDisplayPath(fname.absFileName()));
1536 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1538 if (params().compressed) {
1539 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1540 retval = ofs && write(ofs);
1542 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1543 retval = ofs && write(ofs);
1547 message(str + _(" could not write file!"));
1552 // removeAutosaveFile();
1555 message(str + _(" done."));
1561 docstring Buffer::emergencyWrite()
1563 // No need to save if the buffer has not changed.
1567 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1569 docstring user_message = bformat(
1570 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1572 // We try to save three places:
1573 // 1) Same place as document. Unless it is an unnamed doc.
1575 string s = absFileName();
1578 if (writeFile(FileName(s))) {
1580 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1581 return user_message;
1583 user_message += " " + _("Save failed! Trying again...\n");
1587 // 2) In HOME directory.
1588 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1590 lyxerr << ' ' << s << endl;
1591 if (writeFile(FileName(s))) {
1593 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1594 return user_message;
1597 user_message += " " + _("Save failed! Trying yet again...\n");
1599 // 3) In "/tmp" directory.
1600 // MakeAbsPath to prepend the current
1601 // drive letter on OS/2
1602 s = addName(package().temp_dir().absFileName(), absFileName());
1604 lyxerr << ' ' << s << endl;
1605 if (writeFile(FileName(s))) {
1607 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1608 return user_message;
1611 user_message += " " + _("Save failed! Document is lost.");
1614 return user_message;
1618 bool Buffer::write(ostream & ofs) const
1621 // Use the standard "C" locale for file output.
1622 ofs.imbue(locale::classic());
1625 // The top of the file should not be written by params().
1627 // write out a comment in the top of the file
1628 // Important: Keep the version formatting in sync with lyx2lyx and
1629 // tex2lyx (bug 7951)
1630 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1631 << " created this file. For more info see http://www.lyx.org/\n"
1632 << "\\lyxformat " << LYX_FORMAT << "\n"
1633 << "\\begin_document\n";
1635 /// For each author, set 'used' to true if there is a change
1636 /// by this author in the document; otherwise set it to 'false'.
1637 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1638 AuthorList::Authors::const_iterator a_end = params().authors().end();
1639 for (; a_it != a_end; ++a_it)
1640 a_it->setUsed(false);
1642 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1643 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1644 for ( ; it != end; ++it)
1645 it->checkAuthors(params().authors());
1647 // now write out the buffer parameters.
1648 ofs << "\\begin_header\n";
1649 params().writeFile(ofs, this);
1650 ofs << "\\end_header\n";
1653 ofs << "\n\\begin_body\n";
1655 ofs << "\n\\end_body\n";
1657 // Write marker that shows file is complete
1658 ofs << "\\end_document" << endl;
1660 // Shouldn't really be needed....
1663 // how to check if close went ok?
1664 // Following is an attempt... (BE 20001011)
1666 // good() returns false if any error occurred, including some
1667 // formatting error.
1668 // bad() returns true if something bad happened in the buffer,
1669 // which should include file system full errors.
1674 lyxerr << "File was not closed properly." << endl;
1681 bool Buffer::makeLaTeXFile(FileName const & fname,
1682 string const & original_path,
1683 OutputParams const & runparams_in,
1684 OutputWhat output) const
1686 OutputParams runparams = runparams_in;
1688 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1689 // Check here, because the "flavor" is not known in BufferParams::encoding()
1690 // (power users can override this safety measure selecting "utf8-plain").
1691 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1692 && (runparams.encoding->name() != "utf8-plain"))
1693 runparams.encoding = encodings.fromLyXName("ascii");
1695 string const encoding = runparams.encoding->iconvName();
1696 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1699 try { ofs.reset(encoding); }
1700 catch (iconv_codecvt_facet_exception const & e) {
1701 lyxerr << "Caught iconv exception: " << e.what() << endl;
1702 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1703 "verify that the support software for your encoding (%1$s) is "
1704 "properly installed"), from_ascii(encoding)));
1707 if (!openFileWrite(ofs, fname))
1710 ErrorList & errorList = d->errorLists["Export"];
1712 bool failed_export = false;
1715 // make sure we are ready to export
1716 // this needs to be done before we validate
1717 // FIXME Do we need to do this all the time? I.e., in children
1718 // of a master we are exporting?
1720 updateMacroInstances(OutputUpdate);
1723 writeLaTeXSource(os, original_path, runparams, output);
1725 catch (EncodingException const & e) {
1726 docstring const failed(1, e.failed_char);
1728 oss << "0x" << hex << e.failed_char << dec;
1729 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1730 " (code point %2$s)"),
1731 failed, from_utf8(oss.str()));
1732 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1733 "representable in the chosen encoding.\n"
1734 "Changing the document encoding to utf8 could help."),
1735 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1736 failed_export = true;
1738 catch (iconv_codecvt_facet_exception const & e) {
1739 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1741 failed_export = true;
1743 catch (exception const & e) {
1744 errorList.push_back(ErrorItem(_("conversion failed"),
1746 lyxerr << e.what() << endl;
1747 failed_export = true;
1750 lyxerr << "Caught some really weird exception..." << endl;
1754 d->texrow = move(os.texrow());
1758 failed_export = true;
1759 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1762 if (runparams_in.silent)
1766 return !failed_export;
1770 void Buffer::writeLaTeXSource(otexstream & os,
1771 string const & original_path,
1772 OutputParams const & runparams_in,
1773 OutputWhat output) const
1775 // The child documents, if any, shall be already loaded at this point.
1777 OutputParams runparams = runparams_in;
1779 // XeTeX with TeX fonts is only safe with ASCII encoding,
1780 // Check here, because the "flavor" is not known in BufferParams::encoding()
1781 // (power users can override this safety measure selecting "utf8-plain").
1782 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1783 && (runparams.encoding->name() != "utf8-plain"))
1784 runparams.encoding = encodings.fromLyXName("ascii");
1785 // FIXME: when only the current paragraph is shown, this is ignored
1786 // (or not reached) and characters encodable in the current
1787 // encoding are not converted to ASCII-representation.
1789 // If we are compiling a file standalone, even if this is the
1790 // child of some other buffer, let's cut the link here, so the
1791 // file is really independent and no concurring settings from
1792 // the master (e.g. branch state) interfere (see #8100).
1793 if (!runparams.is_child)
1794 d->ignore_parent = true;
1796 // Classify the unicode characters appearing in math insets
1797 BufferEncodings::initUnicodeMath(*this);
1799 // validate the buffer.
1800 LYXERR(Debug::LATEX, " Validating buffer...");
1801 LaTeXFeatures features(*this, params(), runparams);
1803 // This is only set once per document (in master)
1804 if (!runparams.is_child)
1805 runparams.use_polyglossia = features.usePolyglossia();
1806 LYXERR(Debug::LATEX, " Buffer validation done.");
1808 bool const output_preamble =
1809 output == FullSource || output == OnlyPreamble;
1810 bool const output_body =
1811 output == FullSource || output == OnlyBody;
1813 // The starting paragraph of the coming rows is the
1814 // first paragraph of the document. (Asger)
1815 if (output_preamble && runparams.nice) {
1816 os << "%% LyX " << lyx_version << " created this file. "
1817 "For more info, see http://www.lyx.org/.\n"
1818 "%% Do not edit unless you really know what "
1821 LYXERR(Debug::INFO, "lyx document header finished");
1823 // There are a few differences between nice LaTeX and usual files:
1824 // usual files have \batchmode and special input@path to allow
1825 // inclusion of figures specified by an explicitly relative path
1826 // (i.e., a path starting with './' or '../') with either \input or
1827 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1828 // input@path is set when the actual parameter original_path is set.
1829 // This is done for usual tex-file, but not for nice-latex-file.
1830 // (Matthias 250696)
1831 // Note that input@path is only needed for something the user does
1832 // in the preamble, included .tex files or ERT, files included by
1833 // LyX work without it.
1834 if (output_preamble) {
1835 if (!runparams.nice) {
1836 // code for usual, NOT nice-latex-file
1837 os << "\\batchmode\n"; // changed from \nonstopmode
1839 if (!original_path.empty()) {
1841 // We don't know the encoding of inputpath
1842 docstring const inputpath = from_utf8(original_path);
1843 docstring uncodable_glyphs;
1844 Encoding const * const enc = runparams.encoding;
1846 for (size_t n = 0; n < inputpath.size(); ++n) {
1847 if (!enc->encodable(inputpath[n])) {
1848 docstring const glyph(1, inputpath[n]);
1849 LYXERR0("Uncodable character '"
1851 << "' in input path!");
1852 uncodable_glyphs += glyph;
1857 // warn user if we found uncodable glyphs.
1858 if (!uncodable_glyphs.empty()) {
1859 frontend::Alert::warning(
1860 _("Uncodable character in file path"),
1862 _("The path of your document\n"
1864 "contains glyphs that are unknown "
1865 "in the current document encoding "
1866 "(namely %2$s). This may result in "
1867 "incomplete output, unless "
1868 "TEXINPUTS contains the document "
1869 "directory and you don't use "
1870 "explicitly relative paths (i.e., "
1871 "paths starting with './' or "
1872 "'../') in the preamble or in ERT."
1873 "\n\nIn case of problems, choose "
1874 "an appropriate document encoding\n"
1875 "(such as utf8) or change the "
1877 inputpath, uncodable_glyphs));
1880 support::latex_path(original_path);
1881 if (contains(docdir, '#')) {
1882 docdir = subst(docdir, "#", "\\#");
1883 os << "\\catcode`\\#=11"
1884 "\\def\\#{#}\\catcode`\\#=6\n";
1886 if (contains(docdir, '%')) {
1887 docdir = subst(docdir, "%", "\\%");
1888 os << "\\catcode`\\%=11"
1889 "\\def\\%{%}\\catcode`\\%=14\n";
1891 os << "\\makeatletter\n"
1892 << "\\def\\input@path{{"
1894 << "\\makeatother\n";
1898 // get parent macros (if this buffer has a parent) which will be
1899 // written at the document begin further down.
1900 MacroSet parentMacros;
1901 listParentMacros(parentMacros, features);
1903 // Write the preamble
1904 runparams.use_babel = params().writeLaTeX(os, features,
1905 d->filename.onlyPath());
1907 // Biblatex bibliographies are loaded here
1908 if (params().useBiblatex()) {
1909 vector<docstring> const bibfiles =
1910 prepareBibFilePaths(runparams, getBibfiles(), true);
1911 for (docstring const & file: bibfiles)
1912 os << "\\addbibresource{" << file << "}\n";
1915 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1916 && !features.hasOnlyPolyglossiaLanguages()) {
1919 vector<string> bll = features.getBabelExclusiveLanguages();
1920 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1923 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1928 blangs = bll.size() > 1 ?
1929 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1930 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1934 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1939 plangs = pll.size() > 1 ?
1940 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1941 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1942 if (!blangs.empty())
1946 frontend::Alert::warning(
1947 _("Incompatible Languages!"),
1949 _("You cannot use the following languages "
1950 "together in one LaTeX document because "
1951 "they require conflicting language packages:\n"
1956 // Japanese might be required only in some children of a document,
1957 // but once required, we must keep use_japanese true.
1958 runparams.use_japanese |= features.isRequired("japanese");
1961 // Restore the parenthood if needed
1962 if (!runparams.is_child)
1963 d->ignore_parent = false;
1968 // mark the beginning of the body to separate it from InPreamble insets
1969 os.texrow().start(TexRow::beginDocument());
1970 os << "\\begin{document}\n";
1972 // mark the start of a new paragraph by simulating a newline,
1973 // so that os.afterParbreak() returns true at document start
1976 // output the parent macros
1977 MacroSet::iterator it = parentMacros.begin();
1978 MacroSet::iterator end = parentMacros.end();
1979 for (; it != end; ++it) {
1980 int num_lines = (*it)->write(os.os(), true);
1981 os.texrow().newlines(num_lines);
1984 } // output_preamble
1986 LYXERR(Debug::INFO, "preamble finished, now the body.");
1989 latexParagraphs(*this, text(), os, runparams);
1991 // Restore the parenthood if needed
1992 if (!runparams.is_child)
1993 d->ignore_parent = false;
1995 // add this just in case after all the paragraphs
1998 if (output_preamble) {
1999 os << "\\end{document}\n";
2000 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2002 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2004 runparams_in.encoding = runparams.encoding;
2006 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2007 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2011 void Buffer::makeDocBookFile(FileName const & fname,
2012 OutputParams const & runparams,
2013 OutputWhat output) const
2015 LYXERR(Debug::LATEX, "makeDocBookFile...");
2018 if (!openFileWrite(ofs, fname))
2021 // make sure we are ready to export
2022 // this needs to be done before we validate
2024 updateMacroInstances(OutputUpdate);
2026 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2030 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2034 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2035 OutputParams const & runparams,
2036 OutputWhat output) const
2038 LaTeXFeatures features(*this, params(), runparams);
2043 DocumentClass const & tclass = params().documentClass();
2044 string const & top_element = tclass.latexname();
2046 bool const output_preamble =
2047 output == FullSource || output == OnlyPreamble;
2048 bool const output_body =
2049 output == FullSource || output == OnlyBody;
2051 if (output_preamble) {
2052 if (runparams.flavor == OutputParams::XML)
2053 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2056 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2059 if (! tclass.class_header().empty())
2060 os << from_ascii(tclass.class_header());
2061 else if (runparams.flavor == OutputParams::XML)
2062 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2063 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2065 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2067 docstring preamble = params().preamble;
2068 if (runparams.flavor != OutputParams::XML ) {
2069 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2070 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2071 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2072 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2075 string const name = runparams.nice
2076 ? changeExtension(absFileName(), ".sgml") : fname;
2077 preamble += features.getIncludedFiles(name);
2078 preamble += features.getLyXSGMLEntities();
2080 if (!preamble.empty()) {
2081 os << "\n [ " << preamble << " ]";
2087 string top = top_element;
2089 if (runparams.flavor == OutputParams::XML)
2090 top += params().language->code();
2092 top += params().language->code().substr(0, 2);
2095 if (!params().options.empty()) {
2097 top += params().options;
2100 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2101 << " file was created by LyX " << lyx_version
2102 << "\n See http://www.lyx.org/ for more information -->\n";
2104 params().documentClass().counters().reset();
2106 sgml::openTag(os, top);
2108 docbookParagraphs(text(), *this, os, runparams);
2109 sgml::closeTag(os, top_element);
2114 void Buffer::makeLyXHTMLFile(FileName const & fname,
2115 OutputParams const & runparams) const
2117 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2120 if (!openFileWrite(ofs, fname))
2123 // make sure we are ready to export
2124 // this has to be done before we validate
2125 updateBuffer(UpdateMaster, OutputUpdate);
2126 updateMacroInstances(OutputUpdate);
2128 writeLyXHTMLSource(ofs, runparams, FullSource);
2132 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2136 void Buffer::writeLyXHTMLSource(odocstream & os,
2137 OutputParams const & runparams,
2138 OutputWhat output) const
2140 LaTeXFeatures features(*this, params(), runparams);
2142 d->bibinfo_.makeCitationLabels(*this);
2144 bool const output_preamble =
2145 output == FullSource || output == OnlyPreamble;
2146 bool const output_body =
2147 output == FullSource || output == OnlyBody || output == IncludedFile;
2149 if (output_preamble) {
2150 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2151 << "<!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"
2152 // FIXME Language should be set properly.
2153 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2155 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2156 // FIXME Presumably need to set this right
2157 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2159 docstring const & doctitle = features.htmlTitle();
2161 << (doctitle.empty() ?
2162 from_ascii("LyX Document") :
2163 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2166 docstring styles = features.getTClassHTMLPreamble();
2167 if (!styles.empty())
2168 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2170 styles = features.getPreambleSnippets().str;
2171 if (!styles.empty())
2172 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2174 // we will collect CSS information in a stream, and then output it
2175 // either here, as part of the header, or else in a separate file.
2176 odocstringstream css;
2177 styles = features.getCSSSnippets();
2178 if (!styles.empty())
2179 css << "/* LyX Provided Styles */\n" << styles << '\n';
2181 styles = features.getTClassHTMLStyles();
2182 if (!styles.empty())
2183 css << "/* Layout-provided Styles */\n" << styles << '\n';
2185 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2186 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2187 if (needfg || needbg) {
2188 css << "\nbody {\n";
2191 << from_ascii(X11hexname(params().fontcolor))
2194 css << " background-color: "
2195 << from_ascii(X11hexname(params().backgroundcolor))
2200 docstring const dstyles = css.str();
2201 if (!dstyles.empty()) {
2202 bool written = false;
2203 if (params().html_css_as_file) {
2204 // open a file for CSS info
2206 string const fcssname = addName(temppath(), "docstyle.css");
2207 FileName const fcssfile = FileName(fcssname);
2208 if (openFileWrite(ocss, fcssfile)) {
2212 // write link to header
2213 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2215 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2218 // we are here if the CSS is supposed to be written to the header
2219 // or if we failed to write it to an external file.
2221 os << "<style type='text/css'>\n"
2230 bool const output_body_tag = (output != IncludedFile);
2231 if (output_body_tag)
2232 os << "<body dir=\"auto\">\n";
2234 if (output != IncludedFile)
2235 // if we're an included file, the counters are in the master.
2236 params().documentClass().counters().reset();
2237 xhtmlParagraphs(text(), *this, xs, runparams);
2238 if (output_body_tag)
2242 if (output_preamble)
2247 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2248 // Other flags: -wall -v0 -x
2249 int Buffer::runChktex()
2253 // get LaTeX-Filename
2254 FileName const path(temppath());
2255 string const name = addName(path.absFileName(), latexName());
2256 string const org_path = filePath();
2258 PathChanger p(path); // path to LaTeX file
2259 message(_("Running chktex..."));
2261 // Generate the LaTeX file if neccessary
2262 OutputParams runparams(¶ms().encoding());
2263 runparams.flavor = OutputParams::LATEX;
2264 runparams.nice = false;
2265 runparams.linelen = lyxrc.plaintext_linelen;
2266 makeLaTeXFile(FileName(name), org_path, runparams);
2269 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2270 int const res = chktex.run(terr); // run chktex
2273 Alert::error(_("chktex failure"),
2274 _("Could not run chktex successfully."));
2276 ErrorList & errlist = d->errorLists["ChkTeX"];
2278 bufferErrors(terr, errlist);
2283 if (runparams.silent)
2284 d->errorLists["ChkTeX"].clear();
2292 void Buffer::validate(LaTeXFeatures & features) const
2294 // Validate the buffer params, but not for included
2295 // files, since they also use the parent buffer's
2297 if (!features.runparams().is_child)
2298 params().validate(features);
2300 for (Paragraph const & p : paragraphs())
2301 p.validate(features);
2303 if (lyxerr.debugging(Debug::LATEX)) {
2304 features.showStruct();
2309 void Buffer::getLabelList(vector<docstring> & list) const
2311 // If this is a child document, use the master's list instead.
2313 masterBuffer()->getLabelList(list);
2318 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2319 Toc::const_iterator toc_it = toc->begin();
2320 Toc::const_iterator end = toc->end();
2321 for (; toc_it != end; ++toc_it) {
2322 if (toc_it->depth() == 0)
2323 list.push_back(toc_it->str());
2328 void Buffer::updateBibfilesCache(UpdateScope scope) const
2330 // FIXME This is probably unnecssary, given where we call this.
2331 // If this is a child document, use the parent's cache instead.
2332 if (parent() && scope != UpdateChildOnly) {
2333 masterBuffer()->updateBibfilesCache();
2337 d->bibfiles_cache_.clear();
2338 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2339 if (it->lyxCode() == BIBTEX_CODE) {
2340 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2341 docstring_list const bibfiles = inset.getBibFiles();
2342 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2345 } else if (it->lyxCode() == INCLUDE_CODE) {
2346 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2347 Buffer const * const incbuf = inset.getChildBuffer();
2350 docstring_list const & bibfiles =
2351 incbuf->getBibfiles(UpdateChildOnly);
2352 if (!bibfiles.empty()) {
2353 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2359 d->bibfile_cache_valid_ = true;
2360 d->bibinfo_cache_valid_ = false;
2361 d->cite_labels_valid_ = false;
2365 void Buffer::invalidateBibinfoCache() const
2367 d->bibinfo_cache_valid_ = false;
2368 d->cite_labels_valid_ = false;
2369 // also invalidate the cache for the parent buffer
2370 Buffer const * const pbuf = d->parent();
2372 pbuf->invalidateBibinfoCache();
2376 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2378 // FIXME This is probably unnecessary, given where we call this.
2379 // If this is a child document, use the master's cache instead.
2380 Buffer const * const pbuf = masterBuffer();
2381 if (pbuf != this && scope != UpdateChildOnly)
2382 return pbuf->getBibfiles();
2384 if (!d->bibfile_cache_valid_)
2385 this->updateBibfilesCache(scope);
2387 return d->bibfiles_cache_;
2391 BiblioInfo const & Buffer::masterBibInfo() const
2393 Buffer const * const tmp = masterBuffer();
2395 return tmp->masterBibInfo();
2400 BiblioInfo const & Buffer::bibInfo() const
2406 void Buffer::registerBibfiles(const docstring_list & bf) const
2408 // We register the bib files in the master buffer,
2409 // if there is one, but also in every single buffer,
2410 // in case a child is compiled alone.
2411 Buffer const * const tmp = masterBuffer();
2413 tmp->registerBibfiles(bf);
2415 for (auto const & p : bf) {
2416 docstring_list::const_iterator temp =
2417 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2418 if (temp == d->bibfiles_cache_.end())
2419 d->bibfiles_cache_.push_back(p);
2424 static map<docstring, FileName> bibfileCache;
2426 FileName Buffer::getBibfilePath(docstring const & bibid) const
2428 map<docstring, FileName>::const_iterator it =
2429 bibfileCache.find(bibid);
2430 if (it != bibfileCache.end()) {
2431 // i.e., bibfileCache[bibid]
2435 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2436 string texfile = changeExtension(to_utf8(bibid), "bib");
2437 // note that, if the filename can be found directly from the path,
2438 // findtexfile will just return a FileName object for that path.
2439 FileName file(findtexfile(texfile, "bib"));
2441 file = FileName(makeAbsPath(texfile, filePath()));
2442 LYXERR(Debug::FILES, "Found at: " << file);
2444 bibfileCache[bibid] = file;
2445 return bibfileCache[bibid];
2449 void Buffer::checkIfBibInfoCacheIsValid() const
2451 // use the master's cache
2452 Buffer const * const tmp = masterBuffer();
2454 tmp->checkIfBibInfoCacheIsValid();
2458 // compare the cached timestamps with the actual ones.
2459 docstring_list const & bibfiles_cache = getBibfiles();
2460 for (auto const & bf : bibfiles_cache) {
2461 FileName const fn = getBibfilePath(bf);
2462 time_t lastw = fn.lastModified();
2463 time_t prevw = d->bibfile_status_[fn];
2464 if (lastw != prevw) {
2465 d->bibinfo_cache_valid_ = false;
2466 d->cite_labels_valid_ = false;
2467 d->bibfile_status_[fn] = lastw;
2473 void Buffer::clearBibFileCache() const
2475 bibfileCache.clear();
2479 void Buffer::reloadBibInfoCache() const
2481 // use the master's cache
2482 Buffer const * const tmp = masterBuffer();
2484 tmp->reloadBibInfoCache();
2488 checkIfBibInfoCacheIsValid();
2489 if (d->bibinfo_cache_valid_)
2492 // re-read file locations when this info changes
2493 // FIXME Is this sufficient? Or should we also force that
2494 // in some other cases? If so, then it is easy enough to
2495 // add the following line in some other places.
2496 clearBibFileCache();
2497 d->bibinfo_.clear();
2498 FileNameList checkedFiles;
2499 collectBibKeys(checkedFiles);
2500 d->bibinfo_cache_valid_ = true;
2504 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2506 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2507 it->collectBibKeys(it, checkedFiles);
2511 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2513 // We add the biblio info to the master buffer,
2514 // if there is one, but also to every single buffer,
2515 // in case a child is compiled alone.
2516 BiblioInfo & bi = d->bibinfo_;
2517 bi.mergeBiblioInfo(bin);
2519 if (parent() != 0) {
2520 BiblioInfo & masterbi = parent()->d->bibinfo_;
2521 masterbi.mergeBiblioInfo(bin);
2526 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2528 // We add the bibtex info to the master buffer,
2529 // if there is one, but also to every single buffer,
2530 // in case a child is compiled alone.
2531 BiblioInfo & bi = d->bibinfo_;
2534 if (parent() != 0) {
2535 BiblioInfo & masterbi = parent()->d->bibinfo_;
2536 masterbi[key] = bin;
2541 void Buffer::makeCitationLabels() const
2543 Buffer const * const master = masterBuffer();
2544 return d->bibinfo_.makeCitationLabels(*master);
2548 void Buffer::invalidateCiteLabels() const
2550 masterBuffer()->d->cite_labels_valid_ = false;
2553 bool Buffer::citeLabelsValid() const
2555 return masterBuffer()->d->cite_labels_valid_;
2559 void Buffer::removeBiblioTempFiles() const
2561 // We remove files that contain LaTeX commands specific to the
2562 // particular bibliographic style being used, in order to avoid
2563 // LaTeX errors when we switch style.
2564 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2565 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2566 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2567 aux_file.removeFile();
2568 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2569 bbl_file.removeFile();
2570 // Also for the parent buffer
2571 Buffer const * const pbuf = parent();
2573 pbuf->removeBiblioTempFiles();
2577 bool Buffer::isDepClean(string const & name) const
2579 DepClean::const_iterator const it = d->dep_clean.find(name);
2580 if (it == d->dep_clean.end())
2586 void Buffer::markDepClean(string const & name)
2588 d->dep_clean[name] = true;
2592 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2595 // FIXME? if there is an Buffer LFUN that can be dispatched even
2596 // if internal, put a switch '(cmd.action)' here.
2602 switch (cmd.action()) {
2604 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2605 flag.setOnOff(hasReadonlyFlag());
2608 // FIXME: There is need for a command-line import.
2609 //case LFUN_BUFFER_IMPORT:
2611 case LFUN_BUFFER_AUTO_SAVE:
2614 case LFUN_BUFFER_EXPORT_CUSTOM:
2615 // FIXME: Nothing to check here?
2618 case LFUN_BUFFER_EXPORT: {
2619 docstring const arg = cmd.argument();
2620 if (arg == "custom") {
2624 string format = (arg.empty() || arg == "default") ?
2625 params().getDefaultOutputFormat() : to_utf8(arg);
2626 size_t pos = format.find(' ');
2627 if (pos != string::npos)
2628 format = format.substr(0, pos);
2629 enable = params().isExportable(format, false);
2631 flag.message(bformat(
2632 _("Don't know how to export to format: %1$s"), arg));
2636 case LFUN_BUILD_PROGRAM:
2637 enable = params().isExportable("program", false);
2640 case LFUN_BRANCH_ACTIVATE:
2641 case LFUN_BRANCH_DEACTIVATE:
2642 case LFUN_BRANCH_MASTER_ACTIVATE:
2643 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2644 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2645 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2646 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2647 : params().branchlist();
2648 docstring const branchName = cmd.argument();
2649 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2653 case LFUN_BRANCH_ADD:
2654 case LFUN_BRANCHES_RENAME:
2655 // if no Buffer is present, then of course we won't be called!
2658 case LFUN_BUFFER_LANGUAGE:
2659 enable = !isReadonly();
2662 case LFUN_BUFFER_VIEW_CACHE:
2663 (d->preview_file_).refresh();
2664 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2667 case LFUN_CHANGES_TRACK:
2668 flag.setEnabled(true);
2669 flag.setOnOff(params().track_changes);
2672 case LFUN_CHANGES_OUTPUT:
2673 flag.setEnabled(true);
2674 flag.setOnOff(params().output_changes);
2677 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2678 flag.setOnOff(params().compressed);
2681 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2682 flag.setOnOff(params().output_sync);
2685 case LFUN_BUFFER_ANONYMIZE:
2691 flag.setEnabled(enable);
2696 void Buffer::dispatch(string const & command, DispatchResult & result)
2698 return dispatch(lyxaction.lookupFunc(command), result);
2702 // NOTE We can end up here even if we have no GUI, because we are called
2703 // by LyX::exec to handled command-line requests. So we may need to check
2704 // whether we have a GUI or not. The boolean use_gui holds this information.
2705 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2708 // FIXME? if there is an Buffer LFUN that can be dispatched even
2709 // if internal, put a switch '(cmd.action())' here.
2710 dr.dispatched(false);
2713 string const argument = to_utf8(func.argument());
2714 // We'll set this back to false if need be.
2715 bool dispatched = true;
2716 // This handles undo groups automagically
2717 UndoGroupHelper ugh(this);
2719 switch (func.action()) {
2720 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2721 if (lyxvc().inUse()) {
2722 string log = lyxvc().toggleReadOnly();
2727 setReadonly(!hasReadonlyFlag());
2730 case LFUN_BUFFER_EXPORT: {
2731 string const format = (argument.empty() || argument == "default") ?
2732 params().getDefaultOutputFormat() : argument;
2733 ExportStatus const status = doExport(format, false);
2734 dr.setError(status != ExportSuccess);
2735 if (status != ExportSuccess)
2736 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2737 from_utf8(format)));
2741 case LFUN_BUILD_PROGRAM: {
2742 ExportStatus const status = doExport("program", true);
2743 dr.setError(status != ExportSuccess);
2744 if (status != ExportSuccess)
2745 dr.setMessage(_("Error generating literate programming code."));
2749 case LFUN_BUFFER_EXPORT_CUSTOM: {
2751 string command = split(argument, format_name, ' ');
2752 Format const * format = theFormats().getFormat(format_name);
2754 lyxerr << "Format \"" << format_name
2755 << "\" not recognized!"
2760 // The name of the file created by the conversion process
2763 // Output to filename
2764 if (format->name() == "lyx") {
2765 string const latexname = latexName(false);
2766 filename = changeExtension(latexname,
2767 format->extension());
2768 filename = addName(temppath(), filename);
2770 if (!writeFile(FileName(filename)))
2774 doExport(format_name, true, filename);
2777 // Substitute $$FName for filename
2778 if (!contains(command, "$$FName"))
2779 command = "( " + command + " ) < $$FName";
2780 command = subst(command, "$$FName", filename);
2782 // Execute the command in the background
2784 call.startscript(Systemcall::DontWait, command,
2785 filePath(), layoutPos());
2789 // FIXME: There is need for a command-line import.
2791 case LFUN_BUFFER_IMPORT:
2796 case LFUN_BUFFER_AUTO_SAVE:
2798 resetAutosaveTimers();
2801 case LFUN_BRANCH_ACTIVATE:
2802 case LFUN_BRANCH_DEACTIVATE:
2803 case LFUN_BRANCH_MASTER_ACTIVATE:
2804 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2805 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2806 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2807 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2810 docstring const branch_name = func.argument();
2811 // the case without a branch name is handled elsewhere
2812 if (branch_name.empty()) {
2816 Branch * branch = buf->params().branchlist().find(branch_name);
2818 LYXERR0("Branch " << branch_name << " does not exist.");
2820 docstring const msg =
2821 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2825 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2826 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2827 if (branch->isSelected() != activate) {
2828 buf->undo().recordUndoBufferParams(CursorData());
2829 branch->setSelected(activate);
2831 dr.screenUpdate(Update::Force);
2832 dr.forceBufferUpdate();
2837 case LFUN_BRANCH_ADD: {
2838 docstring branch_name = func.argument();
2839 if (branch_name.empty()) {
2843 BranchList & branch_list = params().branchlist();
2844 vector<docstring> const branches =
2845 getVectorFromString(branch_name, branch_list.separator());
2847 for (vector<docstring>::const_iterator it = branches.begin();
2848 it != branches.end(); ++it) {
2850 Branch * branch = branch_list.find(branch_name);
2852 LYXERR0("Branch " << branch_name << " already exists.");
2856 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2858 undo().recordUndoBufferParams(CursorData());
2859 branch_list.add(branch_name);
2860 branch = branch_list.find(branch_name);
2861 string const x11hexname = X11hexname(branch->color());
2862 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2863 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2865 dr.screenUpdate(Update::Force);
2873 case LFUN_BRANCHES_RENAME: {
2874 if (func.argument().empty())
2877 docstring const oldname = from_utf8(func.getArg(0));
2878 docstring const newname = from_utf8(func.getArg(1));
2879 InsetIterator it = inset_iterator_begin(inset());
2880 InsetIterator const end = inset_iterator_end(inset());
2881 bool success = false;
2882 for (; it != end; ++it) {
2883 if (it->lyxCode() == BRANCH_CODE) {
2884 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2885 if (ins.branch() == oldname) {
2886 undo().recordUndo(CursorData(it));
2887 ins.rename(newname);
2892 if (it->lyxCode() == INCLUDE_CODE) {
2893 // get buffer of external file
2894 InsetInclude const & ins =
2895 static_cast<InsetInclude const &>(*it);
2896 Buffer * child = ins.getChildBuffer();
2899 child->dispatch(func, dr);
2904 dr.screenUpdate(Update::Force);
2905 dr.forceBufferUpdate();
2910 case LFUN_BUFFER_VIEW_CACHE:
2911 if (!theFormats().view(*this, d->preview_file_,
2912 d->preview_format_))
2913 dr.setMessage(_("Error viewing the output file."));
2916 case LFUN_CHANGES_TRACK:
2917 if (params().save_transient_properties)
2918 undo().recordUndoBufferParams(CursorData());
2919 params().track_changes = !params().track_changes;
2920 if (!params().track_changes)
2921 dr.forceChangesUpdate();
2924 case LFUN_CHANGES_OUTPUT:
2925 if (params().save_transient_properties)
2926 undo().recordUndoBufferParams(CursorData());
2927 params().output_changes = !params().output_changes;
2928 if (params().output_changes) {
2929 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2930 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2931 LaTeXFeatures::isAvailable("xcolor");
2933 if (!dvipost && !xcolorulem) {
2934 Alert::warning(_("Changes not shown in LaTeX output"),
2935 _("Changes will not be highlighted in LaTeX output, "
2936 "because neither dvipost nor xcolor/ulem are installed.\n"
2937 "Please install these packages or redefine "
2938 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2939 } else if (!xcolorulem) {
2940 Alert::warning(_("Changes not shown in LaTeX output"),
2941 _("Changes will not be highlighted in LaTeX output "
2942 "when using pdflatex, because xcolor and ulem are not installed.\n"
2943 "Please install both packages or redefine "
2944 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2949 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2950 // turn compression on/off
2951 undo().recordUndoBufferParams(CursorData());
2952 params().compressed = !params().compressed;
2955 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2956 undo().recordUndoBufferParams(CursorData());
2957 params().output_sync = !params().output_sync;
2960 case LFUN_BUFFER_ANONYMIZE: {
2961 undo().recordUndoFullBuffer(CursorData());
2962 CursorData cur(doc_iterator_begin(this));
2963 for ( ; cur ; cur.forwardPar())
2964 cur.paragraph().anonymize();
2965 dr.forceBufferUpdate();
2973 dr.dispatched(dispatched);
2977 void Buffer::changeLanguage(Language const * from, Language const * to)
2979 LASSERT(from, return);
2980 LASSERT(to, return);
2982 for_each(par_iterator_begin(),
2984 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2988 bool Buffer::isMultiLingual() const
2990 ParConstIterator end = par_iterator_end();
2991 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2992 if (it->isMultiLingual(params()))
2999 std::set<Language const *> Buffer::getLanguages() const
3001 std::set<Language const *> languages;
3002 getLanguages(languages);
3007 void Buffer::getLanguages(std::set<Language const *> & languages) const
3009 ParConstIterator end = par_iterator_end();
3010 // add the buffer language, even if it's not actively used
3011 languages.insert(language());
3012 // iterate over the paragraphs
3013 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3014 it->getLanguages(languages);
3016 ListOfBuffers clist = getDescendents();
3017 ListOfBuffers::const_iterator cit = clist.begin();
3018 ListOfBuffers::const_iterator const cen = clist.end();
3019 for (; cit != cen; ++cit)
3020 (*cit)->getLanguages(languages);
3024 DocIterator Buffer::getParFromID(int const id) const
3026 Buffer * buf = const_cast<Buffer *>(this);
3028 // This means non-existent
3029 return doc_iterator_end(buf);
3031 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3032 if (it.paragraph().id() == id)
3035 return doc_iterator_end(buf);
3039 bool Buffer::hasParWithID(int const id) const
3041 return !getParFromID(id).atEnd();
3045 ParIterator Buffer::par_iterator_begin()
3047 return ParIterator(doc_iterator_begin(this));
3051 ParIterator Buffer::par_iterator_end()
3053 return ParIterator(doc_iterator_end(this));
3057 ParConstIterator Buffer::par_iterator_begin() const
3059 return ParConstIterator(doc_iterator_begin(this));
3063 ParConstIterator Buffer::par_iterator_end() const
3065 return ParConstIterator(doc_iterator_end(this));
3069 Language const * Buffer::language() const
3071 return params().language;
3075 docstring const Buffer::B_(string const & l10n) const
3077 return params().B_(l10n);
3081 bool Buffer::isClean() const
3083 return d->lyx_clean;
3087 bool Buffer::isChecksumModified() const
3089 LASSERT(d->filename.exists(), return false);
3090 return d->checksum_ != d->filename.checksum();
3094 void Buffer::saveCheckSum() const
3096 FileName const & file = d->filename;
3098 d->checksum_ = file.exists() ? file.checksum()
3099 : 0; // in the case of save to a new file.
3103 void Buffer::markClean() const
3105 if (!d->lyx_clean) {
3106 d->lyx_clean = true;
3109 // if the .lyx file has been saved, we don't need an
3111 d->bak_clean = true;
3112 d->undo_.markDirty();
3113 clearExternalModification();
3117 void Buffer::setUnnamed(bool flag)
3123 bool Buffer::isUnnamed() const
3130 /// Don't check unnamed, here: isInternal() is used in
3131 /// newBuffer(), where the unnamed flag has not been set by anyone
3132 /// yet. Also, for an internal buffer, there should be no need for
3133 /// retrieving fileName() nor for checking if it is unnamed or not.
3134 bool Buffer::isInternal() const
3136 return d->internal_buffer;
3140 void Buffer::setInternal(bool flag)
3142 d->internal_buffer = flag;
3146 void Buffer::markDirty()
3149 d->lyx_clean = false;
3152 d->bak_clean = false;
3154 DepClean::iterator it = d->dep_clean.begin();
3155 DepClean::const_iterator const end = d->dep_clean.end();
3157 for (; it != end; ++it)
3162 FileName Buffer::fileName() const
3168 string Buffer::absFileName() const
3170 return d->filename.absFileName();
3174 string Buffer::filePath() const
3176 string const abs = d->filename.onlyPath().absFileName();
3179 int last = abs.length() - 1;
3181 return abs[last] == '/' ? abs : abs + '/';
3185 DocFileName Buffer::getReferencedFileName(string const & fn) const
3188 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3189 result.set(fn, filePath());
3191 // filePath() ends with a path separator
3192 FileName const test(filePath() + fn);
3194 result.set(fn, filePath());
3196 result.set(fn, params().origin);
3203 string const Buffer::prepareFileNameForLaTeX(string const & name,
3204 string const & ext, bool nice) const
3206 string const fname = makeAbsPath(name, filePath()).absFileName();
3207 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3213 return to_utf8(makeRelPath(from_utf8(fname),
3214 from_utf8(masterBuffer()->filePath())));
3218 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3219 docstring_list const & bibfilelist,
3220 bool const add_extension) const
3222 // If we are processing the LaTeX file in a temp directory then
3223 // copy the .bib databases to this temp directory, mangling their
3224 // names in the process. Store this mangled name in the list of
3226 // (We need to do all this because BibTeX *really*, *really*
3227 // can't handle "files with spaces" and Windows users tend to
3228 // use such filenames.)
3229 // Otherwise, store the (maybe absolute) path to the original,
3230 // unmangled database name.
3232 vector<docstring> res;
3234 // determine the export format
3235 string const tex_format = flavor2format(runparams.flavor);
3237 // check for spaces in paths
3238 bool found_space = false;
3240 for (auto const & bit : bibfilelist) {
3241 string utf8input = to_utf8(bit);
3243 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3244 FileName try_in_file =
3245 makeAbsPath(database + ".bib", filePath());
3246 bool not_from_texmf = try_in_file.isReadableFile();
3247 // If the file has not been found, try with the real file name
3248 // (it might come from a child in a sub-directory)
3249 if (!not_from_texmf) {
3250 try_in_file = getBibfilePath(bit);
3251 if (try_in_file.isReadableFile()) {
3252 // Check if the file is in texmf
3253 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3254 not_from_texmf = kpsefile.empty()
3255 || kpsefile.absFileName() != try_in_file.absFileName();
3257 // If this exists, make path relative to the master
3259 database = removeExtension(
3260 prepareFileNameForLaTeX(to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3261 from_utf8(filePath()))),
3262 ".bib", runparams.nice));
3266 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3268 // mangledFileName() needs the extension
3269 DocFileName const in_file = DocFileName(try_in_file);
3270 database = removeExtension(in_file.mangledFileName());
3271 FileName const out_file = makeAbsPath(database + ".bib",
3272 masterBuffer()->temppath());
3273 bool const success = in_file.copyTo(out_file);
3275 LYXERR0("Failed to copy '" << in_file
3276 << "' to '" << out_file << "'");
3278 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3279 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3280 if (!isValidLaTeXFileName(database)) {
3281 frontend::Alert::warning(_("Invalid filename"),
3282 _("The following filename will cause troubles "
3283 "when running the exported file through LaTeX: ") +
3284 from_utf8(database));
3286 if (!isValidDVIFileName(database)) {
3287 frontend::Alert::warning(_("Problematic filename for DVI"),
3288 _("The following filename can cause troubles "
3289 "when running the exported file through LaTeX "
3290 "and opening the resulting DVI: ") +
3291 from_utf8(database), true);
3299 docstring const path = from_utf8(latex_path(database));
3301 if (contains(path, ' '))
3304 if (find(res.begin(), res.end(), path) == res.end())
3305 res.push_back(path);
3308 // Check if there are spaces in the path and warn BibTeX users, if so.
3309 // (biber can cope with such paths)
3310 if (!prefixIs(runparams.bibtex_command, "biber")) {
3311 // Post this warning only once.
3312 static bool warned_about_spaces = false;
3313 if (!warned_about_spaces &&
3314 runparams.nice && found_space) {
3315 warned_about_spaces = true;
3316 Alert::warning(_("Export Warning!"),
3317 _("There are spaces in the paths to your BibTeX databases.\n"
3318 "BibTeX will be unable to find them."));
3327 string Buffer::layoutPos() const
3329 return d->layout_position;
3333 void Buffer::setLayoutPos(string const & path)
3336 d->layout_position.clear();
3340 LATTEST(FileName::isAbsolute(path));
3342 d->layout_position =
3343 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3345 if (d->layout_position.empty())
3346 d->layout_position = ".";
3350 bool Buffer::hasReadonlyFlag() const
3352 return d->read_only;
3356 bool Buffer::isReadonly() const
3358 return hasReadonlyFlag() || notifiesExternalModification();
3362 void Buffer::setParent(Buffer const * buffer)
3364 // Avoids recursive include.
3365 d->setParent(buffer == this ? 0 : buffer);
3370 Buffer const * Buffer::parent() const
3376 ListOfBuffers Buffer::allRelatives() const
3378 ListOfBuffers lb = masterBuffer()->getDescendents();
3379 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3384 Buffer const * Buffer::masterBuffer() const
3386 // FIXME Should be make sure we are not in some kind
3387 // of recursive include? A -> B -> A will crash this.
3388 Buffer const * const pbuf = d->parent();
3392 return pbuf->masterBuffer();
3396 bool Buffer::isChild(Buffer * child) const
3398 return d->children_positions.find(child) != d->children_positions.end();
3402 DocIterator Buffer::firstChildPosition(Buffer const * child)
3404 Impl::BufferPositionMap::iterator it;
3405 it = d->children_positions.find(child);
3406 if (it == d->children_positions.end())
3407 return DocIterator(this);
3412 bool Buffer::hasChildren() const
3414 return !d->children_positions.empty();
3418 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3420 // loop over children
3421 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3422 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3423 for (; it != end; ++it) {
3424 Buffer * child = const_cast<Buffer *>(it->first);
3426 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3427 if (bit != clist.end())
3429 clist.push_back(child);
3431 // there might be grandchildren
3432 child->collectChildren(clist, true);
3437 ListOfBuffers Buffer::getChildren() const
3440 collectChildren(v, false);
3441 // Make sure we have not included ourselves.
3442 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3443 if (bit != v.end()) {
3444 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3451 ListOfBuffers Buffer::getDescendents() const
3454 collectChildren(v, true);
3455 // Make sure we have not included ourselves.
3456 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3457 if (bit != v.end()) {
3458 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3465 template<typename M>
3466 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3471 typename M::const_iterator it = m.lower_bound(x);
3472 if (it == m.begin())
3480 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3481 DocIterator const & pos) const
3483 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3485 // if paragraphs have no macro context set, pos will be empty
3489 // we haven't found anything yet
3490 DocIterator bestPos = owner_->par_iterator_begin();
3491 MacroData const * bestData = 0;
3493 // find macro definitions for name
3494 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3495 if (nameIt != macros.end()) {
3496 // find last definition in front of pos or at pos itself
3497 PositionScopeMacroMap::const_iterator it
3498 = greatest_below(nameIt->second, pos);
3499 if (it != nameIt->second.end()) {
3501 // scope ends behind pos?
3502 if (pos < it->second.scope) {
3503 // Looks good, remember this. If there
3504 // is no external macro behind this,
3505 // we found the right one already.
3506 bestPos = it->first;
3507 bestData = &it->second.macro;
3511 // try previous macro if there is one
3512 if (it == nameIt->second.begin())
3519 // find macros in included files
3520 PositionScopeBufferMap::const_iterator it
3521 = greatest_below(position_to_children, pos);
3522 if (it == position_to_children.end())
3523 // no children before
3527 // do we know something better (i.e. later) already?
3528 if (it->first < bestPos )
3531 // scope ends behind pos?
3532 if (pos < it->second.scope
3533 && (cloned_buffer_ ||
3534 theBufferList().isLoaded(it->second.buffer))) {
3535 // look for macro in external file
3537 MacroData const * data
3538 = it->second.buffer->getMacro(name, false);
3541 bestPos = it->first;
3547 // try previous file if there is one
3548 if (it == position_to_children.begin())
3553 // return the best macro we have found
3558 MacroData const * Buffer::getMacro(docstring const & name,
3559 DocIterator const & pos, bool global) const
3564 // query buffer macros
3565 MacroData const * data = d->getBufferMacro(name, pos);
3569 // If there is a master buffer, query that
3570 Buffer const * const pbuf = d->parent();
3572 d->macro_lock = true;
3573 MacroData const * macro = pbuf->getMacro(
3574 name, *this, false);
3575 d->macro_lock = false;
3581 data = MacroTable::globalMacros().get(name);
3590 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3592 // set scope end behind the last paragraph
3593 DocIterator scope = par_iterator_begin();
3594 scope.pit() = scope.lastpit() + 1;
3596 return getMacro(name, scope, global);
3600 MacroData const * Buffer::getMacro(docstring const & name,
3601 Buffer const & child, bool global) const
3603 // look where the child buffer is included first
3604 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3605 if (it == d->children_positions.end())
3608 // check for macros at the inclusion position
3609 return getMacro(name, it->second, global);
3613 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3615 pit_type const lastpit = it.lastpit();
3617 // look for macros in each paragraph
3618 while (it.pit() <= lastpit) {
3619 Paragraph & par = it.paragraph();
3621 // iterate over the insets of the current paragraph
3622 InsetList const & insets = par.insetList();
3623 InsetList::const_iterator iit = insets.begin();
3624 InsetList::const_iterator end = insets.end();
3625 for (; iit != end; ++iit) {
3626 it.pos() = iit->pos;
3628 // is it a nested text inset?
3629 if (iit->inset->asInsetText()) {
3630 // Inset needs its own scope?
3631 InsetText const * itext = iit->inset->asInsetText();
3632 bool newScope = itext->isMacroScope();
3634 // scope which ends just behind the inset
3635 DocIterator insetScope = it;
3638 // collect macros in inset
3639 it.push_back(CursorSlice(*iit->inset));
3640 updateMacros(it, newScope ? insetScope : scope);
3645 if (iit->inset->asInsetTabular()) {
3646 CursorSlice slice(*iit->inset);
3647 size_t const numcells = slice.nargs();
3648 for (; slice.idx() < numcells; slice.forwardIdx()) {
3649 it.push_back(slice);
3650 updateMacros(it, scope);
3656 // is it an external file?
3657 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3658 // get buffer of external file
3659 InsetInclude const & inset =
3660 static_cast<InsetInclude const &>(*iit->inset);
3662 Buffer * child = inset.getChildBuffer();
3667 // register its position, but only when it is
3668 // included first in the buffer
3669 if (children_positions.find(child) ==
3670 children_positions.end())
3671 children_positions[child] = it;
3673 // register child with its scope
3674 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3678 InsetMath * im = iit->inset->asInsetMath();
3679 if (doing_export && im) {
3680 InsetMathHull * hull = im->asHullInset();
3682 hull->recordLocation(it);
3685 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3689 InsetMathMacroTemplate & macroTemplate =
3690 *iit->inset->asInsetMath()->asMacroTemplate();
3691 MacroContext mc(owner_, it);
3692 macroTemplate.updateToContext(mc);
3695 bool valid = macroTemplate.validMacro();
3696 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3697 // then the BufferView's cursor will be invalid in
3698 // some cases which leads to crashes.
3703 // FIXME (Abdel), I don't understand why we pass 'it' here
3704 // instead of 'macroTemplate' defined above... is this correct?
3705 macros[macroTemplate.name()][it] =
3706 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3716 void Buffer::updateMacros() const
3721 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3723 // start with empty table
3725 d->children_positions.clear();
3726 d->position_to_children.clear();
3728 // Iterate over buffer, starting with first paragraph
3729 // The scope must be bigger than any lookup DocIterator
3730 // later. For the global lookup, lastpit+1 is used, hence
3731 // we use lastpit+2 here.
3732 DocIterator it = par_iterator_begin();
3733 DocIterator outerScope = it;
3734 outerScope.pit() = outerScope.lastpit() + 2;
3735 d->updateMacros(it, outerScope);
3739 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3741 InsetIterator it = inset_iterator_begin(inset());
3742 InsetIterator const end = inset_iterator_end(inset());
3743 for (; it != end; ++it) {
3744 if (it->lyxCode() == BRANCH_CODE) {
3745 InsetBranch & br = static_cast<InsetBranch &>(*it);
3746 docstring const name = br.branch();
3747 if (!from_master && !params().branchlist().find(name))
3748 result.push_back(name);
3749 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3750 result.push_back(name);
3753 if (it->lyxCode() == INCLUDE_CODE) {
3754 // get buffer of external file
3755 InsetInclude const & ins =
3756 static_cast<InsetInclude const &>(*it);
3757 Buffer * child = ins.getChildBuffer();
3760 child->getUsedBranches(result, true);
3763 // remove duplicates
3768 void Buffer::updateMacroInstances(UpdateType utype) const
3770 LYXERR(Debug::MACROS, "updateMacroInstances for "
3771 << d->filename.onlyFileName());
3772 DocIterator it = doc_iterator_begin(this);
3774 DocIterator const end = doc_iterator_end(this);
3775 for (; it != end; it.forwardInset()) {
3776 // look for MathData cells in InsetMathNest insets
3777 InsetMath * minset = it.nextInset()->asInsetMath();
3781 // update macro in all cells of the InsetMathNest
3782 DocIterator::idx_type n = minset->nargs();
3783 MacroContext mc = MacroContext(this, it);
3784 for (DocIterator::idx_type i = 0; i < n; ++i) {
3785 MathData & data = minset->cell(i);
3786 data.updateMacros(0, mc, utype, 0);
3792 void Buffer::listMacroNames(MacroNameSet & macros) const
3797 d->macro_lock = true;
3799 // loop over macro names
3800 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3801 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3802 for (; nameIt != nameEnd; ++nameIt)
3803 macros.insert(nameIt->first);
3805 // loop over children
3806 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3807 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3808 for (; it != end; ++it) {
3809 Buffer * child = const_cast<Buffer *>(it->first);
3810 // The buffer might have been closed (see #10766).
3811 if (theBufferList().isLoaded(child))
3812 child->listMacroNames(macros);
3816 Buffer const * const pbuf = d->parent();
3818 pbuf->listMacroNames(macros);
3820 d->macro_lock = false;
3824 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3826 Buffer const * const pbuf = d->parent();
3831 pbuf->listMacroNames(names);
3834 MacroNameSet::iterator it = names.begin();
3835 MacroNameSet::iterator end = names.end();
3836 for (; it != end; ++it) {
3838 MacroData const * data =
3839 pbuf->getMacro(*it, *this, false);
3841 macros.insert(data);
3843 // we cannot access the original InsetMathMacroTemplate anymore
3844 // here to calls validate method. So we do its work here manually.
3845 // FIXME: somehow make the template accessible here.
3846 if (data->optionals() > 0)
3847 features.require("xargs");
3853 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3856 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3858 RefCache::iterator it = d->ref_cache_.find(label);
3859 if (it != d->ref_cache_.end())
3860 return it->second.second;
3862 static InsetLabel const * dummy_il = 0;
3863 static References const dummy_refs = References();
3864 it = d->ref_cache_.insert(
3865 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3866 return it->second.second;
3870 Buffer::References const & Buffer::references(docstring const & label) const
3872 return const_cast<Buffer *>(this)->getReferenceCache(label);
3876 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3878 References & refs = getReferenceCache(label);
3879 refs.push_back(make_pair(inset, it));
3883 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3885 masterBuffer()->d->ref_cache_[label].first = il;
3889 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3891 return masterBuffer()->d->ref_cache_[label].first;
3895 void Buffer::clearReferenceCache() const
3898 d->ref_cache_.clear();
3902 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3904 //FIXME: This does not work for child documents yet.
3905 reloadBibInfoCache();
3907 // Check if the label 'from' appears more than once
3908 BiblioInfo const & keys = masterBibInfo();
3909 BiblioInfo::const_iterator bit = keys.begin();
3910 BiblioInfo::const_iterator bend = keys.end();
3911 vector<docstring> labels;
3913 for (; bit != bend; ++bit)
3915 labels.push_back(bit->first);
3917 if (count(labels.begin(), labels.end(), from) > 1)
3920 string const paramName = "key";
3921 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3922 if (it->lyxCode() != CITE_CODE)
3924 InsetCommand * inset = it->asInsetCommand();
3925 docstring const oldValue = inset->getParam(paramName);
3926 if (oldValue == from)
3927 inset->setParam(paramName, to);
3931 // returns NULL if id-to-row conversion is unsupported
3932 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3933 pit_type par_begin, pit_type par_end,
3934 OutputWhat output, bool master) const
3936 unique_ptr<TexRow> texrow;
3937 OutputParams runparams(¶ms().encoding());
3938 runparams.nice = true;
3939 runparams.flavor = params().getOutputFlavor(format);
3940 runparams.linelen = lyxrc.plaintext_linelen;
3941 // No side effect of file copying and image conversion
3942 runparams.dryrun = true;
3944 if (output == CurrentParagraph) {
3945 runparams.par_begin = par_begin;
3946 runparams.par_end = par_end;
3947 if (par_begin + 1 == par_end) {
3949 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3953 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3954 convert<docstring>(par_begin),
3955 convert<docstring>(par_end - 1))
3958 // output paragraphs
3959 if (runparams.flavor == OutputParams::LYX) {
3960 Paragraph const & par = text().paragraphs()[par_begin];
3962 depth_type dt = par.getDepth();
3963 par.write(ods, params(), dt);
3964 os << from_utf8(ods.str());
3965 } else if (runparams.flavor == OutputParams::HTML) {
3967 setMathFlavor(runparams);
3968 xhtmlParagraphs(text(), *this, xs, runparams);
3969 } else if (runparams.flavor == OutputParams::TEXT) {
3971 // FIXME Handles only one paragraph, unlike the others.
3972 // Probably should have some routine with a signature like them.
3973 writePlaintextParagraph(*this,
3974 text().paragraphs()[par_begin], os, runparams, dummy);
3975 } else if (params().isDocBook()) {
3976 docbookParagraphs(text(), *this, os, runparams);
3978 // If we are previewing a paragraph, even if this is the
3979 // child of some other buffer, let's cut the link here,
3980 // so that no concurring settings from the master
3981 // (e.g. branch state) interfere (see #8101).
3983 d->ignore_parent = true;
3984 // We need to validate the Buffer params' features here
3985 // in order to know if we should output polyglossia
3986 // macros (instead of babel macros)
3987 LaTeXFeatures features(*this, params(), runparams);
3989 runparams.use_polyglossia = features.usePolyglossia();
3990 // latex or literate
3993 ots.texrow().newlines(2);
3995 latexParagraphs(*this, text(), ots, runparams);
3996 texrow = ots.releaseTexRow();
3998 // Restore the parenthood
4000 d->ignore_parent = false;
4004 if (output == FullSource)
4005 os << _("Preview source code");
4006 else if (output == OnlyPreamble)
4007 os << _("Preview preamble");
4008 else if (output == OnlyBody)
4009 os << _("Preview body");
4011 if (runparams.flavor == OutputParams::LYX) {
4013 if (output == FullSource)
4015 else if (output == OnlyPreamble)
4016 params().writeFile(ods, this);
4017 else if (output == OnlyBody)
4019 os << from_utf8(ods.str());
4020 } else if (runparams.flavor == OutputParams::HTML) {
4021 writeLyXHTMLSource(os, runparams, output);
4022 } else if (runparams.flavor == OutputParams::TEXT) {
4023 if (output == OnlyPreamble) {
4024 os << "% "<< _("Plain text does not have a preamble.");
4026 writePlaintextFile(*this, os, runparams);
4027 } else if (params().isDocBook()) {
4028 writeDocBookSource(os, absFileName(), runparams, output);
4030 // latex or literate
4033 ots.texrow().newlines(2);
4035 runparams.is_child = true;
4037 writeLaTeXSource(ots, string(), runparams, output);
4038 texrow = ots.releaseTexRow();
4045 ErrorList & Buffer::errorList(string const & type) const
4047 return d->errorLists[type];
4051 void Buffer::updateTocItem(std::string const & type,
4052 DocIterator const & dit) const
4055 d->gui_->updateTocItem(type, dit);
4059 void Buffer::structureChanged() const
4062 d->gui_->structureChanged();
4066 void Buffer::errors(string const & err, bool from_master) const
4069 d->gui_->errors(err, from_master);
4073 void Buffer::message(docstring const & msg) const
4076 d->gui_->message(msg);
4080 void Buffer::setBusy(bool on) const
4083 d->gui_->setBusy(on);
4087 void Buffer::updateTitles() const
4090 d->wa_->updateTitles();
4094 void Buffer::resetAutosaveTimers() const
4097 d->gui_->resetAutosaveTimers();
4101 bool Buffer::hasGuiDelegate() const
4107 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4116 class AutoSaveBuffer : public ForkedProcess {
4119 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4120 : buffer_(buffer), fname_(fname) {}
4122 virtual shared_ptr<ForkedProcess> clone() const
4124 return make_shared<AutoSaveBuffer>(*this);
4129 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4130 from_utf8(fname_.absFileName())));
4131 return run(DontWait);
4135 virtual int generateChild();
4137 Buffer const & buffer_;
4142 int AutoSaveBuffer::generateChild()
4144 #if defined(__APPLE__)
4145 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4146 * We should use something else like threads.
4148 * Since I do not know how to determine at run time what is the OS X
4149 * version, I just disable forking altogether for now (JMarc)
4151 pid_t const pid = -1;
4153 // tmp_ret will be located (usually) in /tmp
4154 // will that be a problem?
4155 // Note that this calls ForkedCalls::fork(), so it's
4156 // ok cross-platform.
4157 pid_t const pid = fork();
4158 // If you want to debug the autosave
4159 // you should set pid to -1, and comment out the fork.
4160 if (pid != 0 && pid != -1)
4164 // pid = -1 signifies that lyx was unable
4165 // to fork. But we will do the save
4167 bool failed = false;
4168 TempFile tempfile("lyxautoXXXXXX.lyx");
4169 tempfile.setAutoRemove(false);
4170 FileName const tmp_ret = tempfile.name();
4171 if (!tmp_ret.empty()) {
4172 if (!buffer_.writeFile(tmp_ret))
4174 else if (!tmp_ret.moveTo(fname_))
4180 // failed to write/rename tmp_ret so try writing direct
4181 if (!buffer_.writeFile(fname_)) {
4182 // It is dangerous to do this in the child,
4183 // but safe in the parent, so...
4184 if (pid == -1) // emit message signal.
4185 buffer_.message(_("Autosave failed!"));
4189 if (pid == 0) // we are the child so...
4198 FileName Buffer::getEmergencyFileName() const
4200 return FileName(d->filename.absFileName() + ".emergency");
4204 FileName Buffer::getAutosaveFileName() const
4206 // if the document is unnamed try to save in the backup dir, else
4207 // in the default document path, and as a last try in the filePath,
4208 // which will most often be the temporary directory
4211 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4212 : lyxrc.backupdir_path;
4213 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4216 string const fname = "#" + d->filename.onlyFileName() + "#";
4218 return makeAbsPath(fname, fpath);
4222 void Buffer::removeAutosaveFile() const
4224 FileName const f = getAutosaveFileName();
4230 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4232 FileName const newauto = getAutosaveFileName();
4234 if (newauto != oldauto && oldauto.exists())
4235 if (!oldauto.moveTo(newauto))
4236 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4240 bool Buffer::autoSave() const
4242 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4243 if (buf->d->bak_clean || hasReadonlyFlag())
4246 message(_("Autosaving current document..."));
4247 buf->d->bak_clean = true;
4249 FileName const fname = getAutosaveFileName();
4250 LASSERT(d->cloned_buffer_, return false);
4252 // If this buffer is cloned, we assume that
4253 // we are running in a separate thread already.
4254 TempFile tempfile("lyxautoXXXXXX.lyx");
4255 tempfile.setAutoRemove(false);
4256 FileName const tmp_ret = tempfile.name();
4257 if (!tmp_ret.empty()) {
4259 // assume successful write of tmp_ret
4260 if (tmp_ret.moveTo(fname))
4263 // failed to write/rename tmp_ret so try writing direct
4264 return writeFile(fname);
4268 void Buffer::setExportStatus(bool e) const
4270 d->doing_export = e;
4271 ListOfBuffers clist = getDescendents();
4272 ListOfBuffers::const_iterator cit = clist.begin();
4273 ListOfBuffers::const_iterator const cen = clist.end();
4274 for (; cit != cen; ++cit)
4275 (*cit)->d->doing_export = e;
4279 bool Buffer::isExporting() const
4281 return d->doing_export;
4285 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4289 return doExport(target, put_in_tempdir, result_file);
4292 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4293 string & result_file) const
4295 bool const update_unincluded =
4296 params().maintain_unincluded_children
4297 && !params().getIncludedChildren().empty();
4299 // (1) export with all included children (omit \includeonly)
4300 if (update_unincluded) {
4301 ExportStatus const status =
4302 doExport(target, put_in_tempdir, true, result_file);
4303 if (status != ExportSuccess)
4306 // (2) export with included children only
4307 return doExport(target, put_in_tempdir, false, result_file);
4311 void Buffer::setMathFlavor(OutputParams & op) const
4313 switch (params().html_math_output) {
4314 case BufferParams::MathML:
4315 op.math_flavor = OutputParams::MathAsMathML;
4317 case BufferParams::HTML:
4318 op.math_flavor = OutputParams::MathAsHTML;
4320 case BufferParams::Images:
4321 op.math_flavor = OutputParams::MathAsImages;
4323 case BufferParams::LaTeX:
4324 op.math_flavor = OutputParams::MathAsLaTeX;
4330 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4331 bool includeall, string & result_file) const
4333 LYXERR(Debug::FILES, "target=" << target);
4334 OutputParams runparams(¶ms().encoding());
4335 string format = target;
4336 string dest_filename;
4337 size_t pos = target.find(' ');
4338 if (pos != string::npos) {
4339 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4340 format = target.substr(0, pos);
4341 if (format == "default")
4342 format = params().getDefaultOutputFormat();
4343 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4344 FileName(dest_filename).onlyPath().createPath();
4345 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4347 MarkAsExporting exporting(this);
4348 string backend_format;
4349 runparams.flavor = OutputParams::LATEX;
4350 runparams.linelen = lyxrc.plaintext_linelen;
4351 runparams.includeall = includeall;
4352 vector<string> backs = params().backends();
4353 Converters converters = theConverters();
4354 bool need_nice_file = false;
4355 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4356 // Get shortest path to format
4357 converters.buildGraph();
4358 Graph::EdgePath path;
4359 for (vector<string>::const_iterator it = backs.begin();
4360 it != backs.end(); ++it) {
4361 Graph::EdgePath p = converters.getPath(*it, format);
4362 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4363 backend_format = *it;
4368 if (!put_in_tempdir) {
4369 // Only show this alert if this is an export to a non-temporary
4370 // file (not for previewing).
4371 Alert::error(_("Couldn't export file"), bformat(
4372 _("No information for exporting the format %1$s."),
4373 theFormats().prettyName(format)));
4375 return ExportNoPathToFormat;
4377 runparams.flavor = converters.getFlavor(path, this);
4378 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4379 Graph::EdgePath::const_iterator it = path.begin();
4380 Graph::EdgePath::const_iterator en = path.end();
4381 for (; it != en; ++it)
4382 if (theConverters().get(*it).nice()) {
4383 need_nice_file = true;
4388 backend_format = format;
4389 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4390 // FIXME: Don't hardcode format names here, but use a flag
4391 if (backend_format == "pdflatex")
4392 runparams.flavor = OutputParams::PDFLATEX;
4393 else if (backend_format == "luatex")
4394 runparams.flavor = OutputParams::LUATEX;
4395 else if (backend_format == "dviluatex")
4396 runparams.flavor = OutputParams::DVILUATEX;
4397 else if (backend_format == "xetex")
4398 runparams.flavor = OutputParams::XETEX;
4401 string filename = latexName(false);
4402 filename = addName(temppath(), filename);
4403 filename = changeExtension(filename,
4404 theFormats().extension(backend_format));
4405 LYXERR(Debug::FILES, "filename=" << filename);
4407 // Plain text backend
4408 if (backend_format == "text") {
4409 runparams.flavor = OutputParams::TEXT;
4410 writePlaintextFile(*this, FileName(filename), runparams);
4413 else if (backend_format == "xhtml") {
4414 runparams.flavor = OutputParams::HTML;
4415 setMathFlavor(runparams);
4416 makeLyXHTMLFile(FileName(filename), runparams);
4417 } else if (backend_format == "lyx")
4418 writeFile(FileName(filename));
4420 else if (params().isDocBook()) {
4421 runparams.nice = !put_in_tempdir;
4422 makeDocBookFile(FileName(filename), runparams);
4425 else if (backend_format == format || need_nice_file) {
4426 runparams.nice = true;
4427 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4428 if (d->cloned_buffer_)
4429 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4432 } else if (!lyxrc.tex_allows_spaces
4433 && contains(filePath(), ' ')) {
4434 Alert::error(_("File name error"),
4435 bformat(_("The directory path to the document\n%1$s\n"
4436 "contains spaces, but your TeX installation does "
4437 "not allow them. You should save the file to a directory "
4438 "whose name does not contain spaces."), from_ascii(filePath())));
4439 return ExportTexPathHasSpaces;
4441 runparams.nice = false;
4442 bool const success = makeLaTeXFile(
4443 FileName(filename), filePath(), runparams);
4444 if (d->cloned_buffer_)
4445 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4450 string const error_type = (format == "program")
4451 ? "Build" : params().bufferFormat();
4452 ErrorList & error_list = d->errorLists[error_type];
4453 string const ext = theFormats().extension(format);
4454 FileName const tmp_result_file(changeExtension(filename, ext));
4455 bool const success = converters.convert(this, FileName(filename),
4456 tmp_result_file, FileName(absFileName()), backend_format, format,
4459 // Emit the signal to show the error list or copy it back to the
4460 // cloned Buffer so that it can be emitted afterwards.
4461 if (format != backend_format) {
4462 if (runparams.silent)
4464 else if (d->cloned_buffer_)
4465 d->cloned_buffer_->d->errorLists[error_type] =
4466 d->errorLists[error_type];
4469 // also to the children, in case of master-buffer-view
4470 ListOfBuffers clist = getDescendents();
4471 ListOfBuffers::const_iterator cit = clist.begin();
4472 ListOfBuffers::const_iterator const cen = clist.end();
4473 for (; cit != cen; ++cit) {
4474 if (runparams.silent)
4475 (*cit)->d->errorLists[error_type].clear();
4476 else if (d->cloned_buffer_) {
4477 // Enable reverse search by copying back the
4478 // texrow object to the cloned buffer.
4479 // FIXME: this is not thread safe.
4480 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4481 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4482 (*cit)->d->errorLists[error_type];
4484 (*cit)->errors(error_type, true);
4488 if (d->cloned_buffer_) {
4489 // Enable reverse dvi or pdf to work by copying back the texrow
4490 // object to the cloned buffer.
4491 // FIXME: There is a possibility of concurrent access to texrow
4492 // here from the main GUI thread that should be securized.
4493 d->cloned_buffer_->d->texrow = d->texrow;
4494 string const error_type = params().bufferFormat();
4495 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4499 if (put_in_tempdir) {
4500 result_file = tmp_result_file.absFileName();
4501 return success ? ExportSuccess : ExportConverterError;
4504 if (dest_filename.empty())
4505 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4507 result_file = dest_filename;
4508 // We need to copy referenced files (e. g. included graphics
4509 // if format == "dvi") to the result dir.
4510 vector<ExportedFile> const files =
4511 runparams.exportdata->externalFiles(format);
4512 string const dest = runparams.export_folder.empty() ?
4513 onlyPath(result_file) : runparams.export_folder;
4514 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4515 : force_overwrite == ALL_FILES;
4516 CopyStatus status = use_force ? FORCE : SUCCESS;
4518 vector<ExportedFile>::const_iterator it = files.begin();
4519 vector<ExportedFile>::const_iterator const en = files.end();
4520 for (; it != en && status != CANCEL; ++it) {
4521 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4522 string fixedName = it->exportName;
4523 if (!runparams.export_folder.empty()) {
4524 // Relative pathnames starting with ../ will be sanitized
4525 // if exporting to a different folder
4526 while (fixedName.substr(0, 3) == "../")
4527 fixedName = fixedName.substr(3, fixedName.length() - 3);
4529 FileName fixedFileName = makeAbsPath(fixedName, dest);
4530 fixedFileName.onlyPath().createPath();
4531 status = copyFile(fmt, it->sourceName,
4533 it->exportName, status == FORCE,
4534 runparams.export_folder.empty());
4537 if (status == CANCEL) {
4538 message(_("Document export cancelled."));
4539 return ExportCancel;
4542 if (tmp_result_file.exists()) {
4543 // Finally copy the main file
4544 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4545 : force_overwrite != NO_FILES;
4546 if (status == SUCCESS && use_force)
4548 status = copyFile(format, tmp_result_file,
4549 FileName(result_file), result_file,
4551 if (status == CANCEL) {
4552 message(_("Document export cancelled."));
4553 return ExportCancel;
4555 message(bformat(_("Document exported as %1$s "
4557 theFormats().prettyName(format),
4558 makeDisplayPath(result_file)));
4561 // This must be a dummy converter like fax (bug 1888)
4562 message(bformat(_("Document exported as %1$s"),
4563 theFormats().prettyName(format)));
4566 return success ? ExportSuccess : ExportConverterError;
4570 Buffer::ExportStatus Buffer::preview(string const & format) const
4572 bool const update_unincluded =
4573 params().maintain_unincluded_children
4574 && !params().getIncludedChildren().empty();
4575 return preview(format, update_unincluded);
4579 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4581 MarkAsExporting exporting(this);
4583 // (1) export with all included children (omit \includeonly)
4585 ExportStatus const status = doExport(format, true, true, result_file);
4586 if (status != ExportSuccess)
4589 // (2) export with included children only
4590 ExportStatus const status = doExport(format, true, false, result_file);
4591 FileName const previewFile(result_file);
4593 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4594 theimpl->preview_file_ = previewFile;
4595 theimpl->preview_format_ = format;
4596 theimpl->preview_error_ = (status != ExportSuccess);
4598 if (status != ExportSuccess)
4601 if (previewFile.exists())
4602 return theFormats().view(*this, previewFile, format) ?
4603 PreviewSuccess : PreviewError;
4605 // Successful export but no output file?
4606 // Probably a bug in error detection.
4607 LATTEST(status != ExportSuccess);
4612 Buffer::ReadStatus Buffer::extractFromVC()
4614 bool const found = LyXVC::file_not_found_hook(d->filename);
4616 return ReadFileNotFound;
4617 if (!d->filename.isReadableFile())
4623 Buffer::ReadStatus Buffer::loadEmergency()
4625 FileName const emergencyFile = getEmergencyFileName();
4626 if (!emergencyFile.exists()
4627 || emergencyFile.lastModified() <= d->filename.lastModified())
4628 return ReadFileNotFound;
4630 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4631 docstring const text = bformat(_("An emergency save of the document "
4632 "%1$s exists.\n\nRecover emergency save?"), file);
4634 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4635 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4641 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4642 bool const success = (ret_llf == ReadSuccess);
4644 if (hasReadonlyFlag()) {
4645 Alert::warning(_("File is read-only"),
4646 bformat(_("An emergency file is successfully loaded, "
4647 "but the original file %1$s is marked read-only. "
4648 "Please make sure to save the document as a different "
4649 "file."), from_utf8(d->filename.absFileName())));
4652 lyxvc().file_found_hook(d->filename);
4653 str = _("Document was successfully recovered.");
4655 str = _("Document was NOT successfully recovered.");
4656 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4657 makeDisplayPath(emergencyFile.absFileName()));
4659 int const del_emerg =
4660 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4661 _("&Remove"), _("&Keep"));
4662 if (del_emerg == 0) {
4663 emergencyFile.removeFile();
4665 Alert::warning(_("Emergency file deleted"),
4666 _("Do not forget to save your file now!"), true);
4668 return success ? ReadSuccess : ReadEmergencyFailure;
4671 int const del_emerg =
4672 Alert::prompt(_("Delete emergency file?"),
4673 _("Remove emergency file now?"), 1, 1,
4674 _("&Remove"), _("&Keep"));
4676 emergencyFile.removeFile();
4677 return ReadOriginal;
4687 Buffer::ReadStatus Buffer::loadAutosave()
4689 // Now check if autosave file is newer.
4690 FileName const autosaveFile = getAutosaveFileName();
4691 if (!autosaveFile.exists()
4692 || autosaveFile.lastModified() <= d->filename.lastModified())
4693 return ReadFileNotFound;
4695 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4696 docstring const text = bformat(_("The backup of the document %1$s "
4697 "is newer.\n\nLoad the backup instead?"), file);
4698 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4699 _("&Load backup"), _("Load &original"), _("&Cancel"));
4704 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4705 // the file is not saved if we load the autosave file.
4706 if (ret_llf == ReadSuccess) {
4707 if (hasReadonlyFlag()) {
4708 Alert::warning(_("File is read-only"),
4709 bformat(_("A backup file is successfully loaded, "
4710 "but the original file %1$s is marked read-only. "
4711 "Please make sure to save the document as a "
4713 from_utf8(d->filename.absFileName())));
4716 lyxvc().file_found_hook(d->filename);
4719 return ReadAutosaveFailure;
4722 // Here we delete the autosave
4723 autosaveFile.removeFile();
4724 return ReadOriginal;
4732 Buffer::ReadStatus Buffer::loadLyXFile()
4734 if (!d->filename.isReadableFile()) {
4735 ReadStatus const ret_rvc = extractFromVC();
4736 if (ret_rvc != ReadSuccess)
4740 ReadStatus const ret_re = loadEmergency();
4741 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4744 ReadStatus const ret_ra = loadAutosave();
4745 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4748 return loadThisLyXFile(d->filename);
4752 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4754 return readFile(fn);
4758 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4760 for (auto const & err : terr) {
4761 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4762 int errorRow = err.error_in_line;
4763 Buffer const * buf = 0;
4765 if (err.child_name.empty())
4766 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4768 // The error occurred in a child
4769 for (Buffer const * child : getDescendents()) {
4770 string const child_name =
4771 DocFileName(changeExtension(child->absFileName(), "tex")).
4773 if (err.child_name != child_name)
4775 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4776 if (!TexRow::isNone(start)) {
4777 buf = d->cloned_buffer_
4778 ? child->d->cloned_buffer_->d->owner_
4785 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4791 void Buffer::setBuffersForInsets() const
4793 inset().setBuffer(const_cast<Buffer &>(*this));
4797 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4799 LBUFERR(!text().paragraphs().empty());
4801 // Use the master text class also for child documents
4802 Buffer const * const master = masterBuffer();
4803 DocumentClass const & textclass = master->params().documentClass();
4805 docstring_list old_bibfiles;
4806 // Do this only if we are the top-level Buffer. We also need to account
4807 // for the case of a previewed child with ignored parent here.
4808 if (master == this && !d->ignore_parent) {
4809 textclass.counters().reset(from_ascii("bibitem"));
4810 reloadBibInfoCache();
4813 // keep the buffers to be children in this set. If the call from the
4814 // master comes back we can see which of them were actually seen (i.e.
4815 // via an InsetInclude). The remaining ones in the set need still be updated.
4816 static std::set<Buffer const *> bufToUpdate;
4817 if (scope == UpdateMaster) {
4818 // If this is a child document start with the master
4819 if (master != this) {
4820 bufToUpdate.insert(this);
4821 master->updateBuffer(UpdateMaster, utype);
4822 // If the master buffer has no gui associated with it, then the TocModel is
4823 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4824 // (bug 5699). The same happens if the master buffer is open in a different
4825 // window. This test catches both possibilities.
4826 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4827 // There remains a problem here: If there is another child open in yet a third
4828 // window, that TOC is not updated. So some more general solution is needed at
4830 if (master->d->gui_ != d->gui_)
4833 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4834 if (bufToUpdate.find(this) == bufToUpdate.end())
4838 // start over the counters in the master
4839 textclass.counters().reset();
4842 // update will be done below for this buffer
4843 bufToUpdate.erase(this);
4845 // update all caches
4846 clearReferenceCache();
4848 setChangesPresent(false);
4850 Buffer & cbuf = const_cast<Buffer &>(*this);
4853 ParIterator parit = cbuf.par_iterator_begin();
4854 updateBuffer(parit, utype);
4857 // If this document has siblings, then update the TocBackend later. The
4858 // reason is to ensure that later siblings are up to date when e.g. the
4859 // broken or not status of references is computed. The update is called
4860 // in InsetInclude::addToToc.
4863 // if the bibfiles changed, the cache of bibinfo is invalid
4864 docstring_list new_bibfiles = d->bibfiles_cache_;
4865 // this is a trick to determine whether the two vectors have
4866 // the same elements.
4867 sort(new_bibfiles.begin(), new_bibfiles.end());
4868 sort(old_bibfiles.begin(), old_bibfiles.end());
4869 if (old_bibfiles != new_bibfiles) {
4870 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4871 invalidateBibinfoCache();
4872 reloadBibInfoCache();
4873 // We relied upon the bibinfo cache when recalculating labels. But that
4874 // cache was invalid, although we didn't find that out until now. So we
4875 // have to do it all again.
4876 // That said, the only thing we really need to do is update the citation
4877 // labels. Nothing else will have changed. So we could create a new
4878 // UpdateType that would signal that fact, if we needed to do so.
4879 parit = cbuf.par_iterator_begin();
4880 // we will be re-doing the counters and references and such.
4881 textclass.counters().reset();
4882 clearReferenceCache();
4883 // we should not need to do this again?
4885 setChangesPresent(false);
4886 updateBuffer(parit, utype);
4887 // this will already have been done by reloadBibInfoCache();
4888 // d->bibinfo_cache_valid_ = true;
4891 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4892 // this is also set to true on the other path, by reloadBibInfoCache.
4893 d->bibinfo_cache_valid_ = true;
4895 d->cite_labels_valid_ = true;
4897 cbuf.tocBackend().update(true, utype);
4898 if (scope == UpdateMaster)
4899 cbuf.structureChanged();
4903 static depth_type getDepth(DocIterator const & it)
4905 depth_type depth = 0;
4906 for (size_t i = 0 ; i < it.depth() ; ++i)
4907 if (!it[i].inset().inMathed())
4908 depth += it[i].paragraph().getDepth() + 1;
4909 // remove 1 since the outer inset does not count
4910 // we should have at least one non-math inset, so
4911 // depth should nevery be 0. but maybe it is worth
4912 // marking this, just in case.
4914 // coverity[INTEGER_OVERFLOW]
4918 static depth_type getItemDepth(ParIterator const & it)
4920 Paragraph const & par = *it;
4921 LabelType const labeltype = par.layout().labeltype;
4923 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4926 // this will hold the lowest depth encountered up to now.
4927 depth_type min_depth = getDepth(it);
4928 ParIterator prev_it = it;
4931 --prev_it.top().pit();
4933 // start of nested inset: go to outer par
4935 if (prev_it.empty()) {
4936 // start of document: nothing to do
4941 // We search for the first paragraph with same label
4942 // that is not more deeply nested.
4943 Paragraph & prev_par = *prev_it;
4944 depth_type const prev_depth = getDepth(prev_it);
4945 if (labeltype == prev_par.layout().labeltype) {
4946 if (prev_depth < min_depth)
4947 return prev_par.itemdepth + 1;
4948 if (prev_depth == min_depth)
4949 return prev_par.itemdepth;
4951 min_depth = min(min_depth, prev_depth);
4952 // small optimization: if we are at depth 0, we won't
4953 // find anything else
4954 if (prev_depth == 0)
4960 static bool needEnumCounterReset(ParIterator const & it)
4962 Paragraph const & par = *it;
4963 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4964 depth_type const cur_depth = par.getDepth();
4965 ParIterator prev_it = it;
4966 while (prev_it.pit()) {
4967 --prev_it.top().pit();
4968 Paragraph const & prev_par = *prev_it;
4969 if (prev_par.getDepth() <= cur_depth)
4970 return prev_par.layout().name() != par.layout().name();
4972 // start of nested inset: reset
4977 // set the label of a paragraph. This includes the counters.
4978 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4980 BufferParams const & bp = owner_->masterBuffer()->params();
4981 DocumentClass const & textclass = bp.documentClass();
4982 Paragraph & par = it.paragraph();
4983 Layout const & layout = par.layout();
4984 Counters & counters = textclass.counters();
4986 if (par.params().startOfAppendix()) {
4987 // We want to reset the counter corresponding to toplevel sectioning
4988 Layout const & lay = textclass.getTOCLayout();
4989 docstring const cnt = lay.counter;
4991 counters.reset(cnt);
4992 counters.appendix(true);
4994 par.params().appendix(counters.appendix());
4996 // Compute the item depth of the paragraph
4997 par.itemdepth = getItemDepth(it);
4999 if (layout.margintype == MARGIN_MANUAL) {
5000 if (par.params().labelWidthString().empty())
5001 par.params().labelWidthString(par.expandLabel(layout, bp));
5002 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5003 // we do not need to do anything here, since the empty case is
5004 // handled during export.
5006 par.params().labelWidthString(docstring());
5009 switch(layout.labeltype) {
5010 case LABEL_ITEMIZE: {
5011 // At some point of time we should do something more
5012 // clever here, like:
5013 // par.params().labelString(
5014 // bp.user_defined_bullet(par.itemdepth).getText());
5015 // for now, use a simple hardcoded label
5016 docstring itemlabel;
5017 switch (par.itemdepth) {
5019 itemlabel = char_type(0x2022);
5022 itemlabel = char_type(0x2013);
5025 itemlabel = char_type(0x2217);
5028 itemlabel = char_type(0x2219); // or 0x00b7
5031 par.params().labelString(itemlabel);
5035 case LABEL_ENUMERATE: {
5036 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5038 switch (par.itemdepth) {
5049 enumcounter += "iv";
5052 // not a valid enumdepth...
5056 // Increase the master counter?
5057 if (layout.stepmastercounter && needEnumCounterReset(it))
5058 counters.stepMaster(enumcounter, utype);
5060 // Maybe we have to reset the enumeration counter.
5061 if (!layout.resumecounter && needEnumCounterReset(it))
5062 counters.reset(enumcounter);
5063 counters.step(enumcounter, utype);
5065 string const & lang = par.getParLanguage(bp)->code();
5066 par.params().labelString(counters.theCounter(enumcounter, lang));
5071 case LABEL_SENSITIVE: {
5072 string const & type = counters.current_float();
5073 docstring full_label;
5075 full_label = owner_->B_("Senseless!!! ");
5077 docstring name = owner_->B_(textclass.floats().getType(type).name());
5078 if (counters.hasCounter(from_utf8(type))) {
5079 string const & lang = par.getParLanguage(bp)->code();
5080 counters.step(from_utf8(type), utype);
5081 full_label = bformat(from_ascii("%1$s %2$s:"),
5083 counters.theCounter(from_utf8(type), lang));
5085 full_label = bformat(from_ascii("%1$s #:"), name);
5087 par.params().labelString(full_label);
5091 case LABEL_NO_LABEL:
5092 par.params().labelString(docstring());
5096 case LABEL_CENTERED:
5097 case LABEL_STATIC: {
5098 docstring const & lcounter = layout.counter;
5099 if (!lcounter.empty()) {
5100 if (layout.toclevel <= bp.secnumdepth
5101 && (layout.latextype != LATEX_ENVIRONMENT
5102 || it.text()->isFirstInSequence(it.pit()))) {
5103 if (counters.hasCounter(lcounter))
5104 counters.step(lcounter, utype);
5105 par.params().labelString(par.expandLabel(layout, bp));
5107 par.params().labelString(docstring());
5109 par.params().labelString(par.expandLabel(layout, bp));
5115 par.params().labelString(par.expandLabel(layout, bp));
5120 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5122 // LASSERT: Is it safe to continue here, or should we just return?
5123 LASSERT(parit.pit() == 0, /**/);
5125 // Set the position of the text in the buffer to be able
5126 // to resolve macros in it.
5127 parit.text()->setMacrocontextPosition(parit);
5129 depth_type maxdepth = 0;
5130 pit_type const lastpit = parit.lastpit();
5131 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5132 // reduce depth if necessary
5133 if (parit->params().depth() > maxdepth) {
5134 /** FIXME: this function is const, but
5135 * nevertheless it modifies the buffer. To be
5136 * cleaner, one should modify the buffer in
5137 * another function, which is actually
5138 * non-const. This would however be costly in
5139 * terms of code duplication.
5141 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5142 parit->params().depth(maxdepth);
5144 maxdepth = parit->getMaxDepthAfter();
5146 if (utype == OutputUpdate) {
5147 // track the active counters
5148 // we have to do this for the master buffer, since the local
5149 // buffer isn't tracking anything.
5150 masterBuffer()->params().documentClass().counters().
5151 setActiveLayout(parit->layout());
5154 // set the counter for this paragraph
5155 d->setLabel(parit, utype);
5157 // update change-tracking flag
5158 parit->addChangesToBuffer(*this);
5161 InsetList::const_iterator iit = parit->insetList().begin();
5162 InsetList::const_iterator end = parit->insetList().end();
5163 for (; iit != end; ++iit) {
5164 parit.pos() = iit->pos;
5165 iit->inset->updateBuffer(parit, utype);
5171 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5172 WordLangTuple & word_lang, docstring_list & suggestions) const
5176 suggestions.clear();
5177 word_lang = WordLangTuple();
5178 bool const to_end = to.empty();
5179 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5180 // OK, we start from here.
5181 for (; from != end; from.forwardPos()) {
5182 // This skips all insets with spell check disabled.
5183 while (!from.allowSpellCheck()) {
5187 // If from is at the end of the document (which is possible
5188 // when "from" was changed above) LyX will crash later otherwise.
5189 if (from.atEnd() || (!to_end && from >= end))
5192 from.paragraph().spellCheck();
5193 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5194 if (SpellChecker::misspelled(res)) {
5198 // Do not increase progress when from == to, otherwise the word
5199 // count will be wrong.
5209 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5211 bool inword = false;
5216 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5217 if (!dit.inTexted()) {
5222 Paragraph const & par = dit.paragraph();
5223 pos_type const pos = dit.pos();
5225 // Copied and adapted from isWordSeparator() in Paragraph
5226 if (pos == dit.lastpos()) {
5229 Inset const * ins = par.getInset(pos);
5230 if (ins && skipNoOutput && !ins->producesOutput()) {
5233 // stop if end of range was skipped
5234 if (!to.atEnd() && dit >= to)
5237 } else if (!par.isDeleted(pos)) {
5238 if (par.isWordSeparator(pos))
5244 if (ins && ins->isLetter())
5246 else if (ins && ins->isSpace())
5249 char_type const c = par.getChar(pos);
5250 if (isPrintableNonspace(c))
5252 else if (isSpace(c))
5262 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5264 d->updateStatistics(from, to, skipNoOutput);
5268 int Buffer::wordCount() const
5270 return d->wordCount();
5274 int Buffer::charCount(bool with_blanks) const
5276 return d->charCount(with_blanks);
5280 Buffer::ReadStatus Buffer::reload()
5283 // c.f. bug https://www.lyx.org/trac/ticket/6587
5284 removeAutosaveFile();
5285 // e.g., read-only status could have changed due to version control
5286 d->filename.refresh();
5287 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5289 // clear parent. this will get reset if need be.
5291 ReadStatus const status = loadLyXFile();
5292 if (status == ReadSuccess) {
5297 message(bformat(_("Document %1$s reloaded."), disp_fn));
5300 message(bformat(_("Could not reload document %1$s."), disp_fn));
5310 bool Buffer::saveAs(FileName const & fn)
5312 FileName const old_name = fileName();
5313 FileName const old_auto = getAutosaveFileName();
5314 bool const old_unnamed = isUnnamed();
5315 bool success = true;
5316 d->old_position = filePath();
5323 // bring the autosave file with us, just in case.
5324 moveAutosaveFile(old_auto);
5325 // validate version control data and
5326 // correct buffer title
5327 lyxvc().file_found_hook(fileName());
5329 // the file has now been saved to the new location.
5330 // we need to check that the locations of child buffers
5332 checkChildBuffers();
5333 checkMasterBuffer();
5336 // reset the old filename and unnamed state
5337 setFileName(old_name);
5338 setUnnamed(old_unnamed);
5342 d->old_position.clear();
5347 void Buffer::checkChildBuffers()
5349 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5350 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5351 for (; it != en; ++it) {
5352 DocIterator dit = it->second;
5353 Buffer * cbuf = const_cast<Buffer *>(it->first);
5354 if (!cbuf || !theBufferList().isLoaded(cbuf))
5356 Inset * inset = dit.nextInset();
5357 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5358 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5359 docstring const & incfile = inset_inc->getParam("filename");
5360 string oldloc = cbuf->absFileName();
5361 string newloc = makeAbsPath(to_utf8(incfile),
5362 onlyPath(absFileName())).absFileName();
5363 if (oldloc == newloc)
5365 // the location of the child file is incorrect.
5367 inset_inc->setChildBuffer(0);
5369 // invalidate cache of children
5370 d->children_positions.clear();
5371 d->position_to_children.clear();
5375 // If a child has been saved under a different name/path, it might have been
5376 // orphaned. Therefore the master needs to be reset (bug 8161).
5377 void Buffer::checkMasterBuffer()
5379 Buffer const * const master = masterBuffer();
5383 // necessary to re-register the child (bug 5873)
5384 // FIXME: clean up updateMacros (here, only
5385 // child registering is needed).
5386 master->updateMacros();
5387 // (re)set master as master buffer, but only
5388 // if we are a real child
5389 if (master->isChild(this))
5396 string Buffer::includedFilePath(string const & name, string const & ext) const
5398 if (d->old_position.empty() ||
5399 equivalent(FileName(d->old_position), FileName(filePath())))
5402 bool isabsolute = FileName::isAbsolute(name);
5403 // both old_position and filePath() end with a path separator
5404 string absname = isabsolute ? name : d->old_position + name;
5406 // if old_position is set to origin, we need to do the equivalent of
5407 // getReferencedFileName() (see readDocument())
5408 if (!isabsolute && d->old_position == params().origin) {
5409 FileName const test(addExtension(filePath() + name, ext));
5411 absname = filePath() + name;
5414 if (!FileName(addExtension(absname, ext)).exists())
5418 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5420 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5421 from_utf8(filePath())));
5425 void Buffer::setChangesPresent(bool b) const
5427 d->tracked_changes_present_ = b;
5431 bool Buffer::areChangesPresent() const
5433 return d->tracked_changes_present_;
5437 void Buffer::updateChangesPresent() const
5439 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5440 setChangesPresent(false);
5441 ParConstIterator it = par_iterator_begin();
5442 ParConstIterator const end = par_iterator_end();
5443 for (; !areChangesPresent() && it != end; ++it)
5444 it->addChangesToBuffer(*this);
5448 void Buffer::Impl::refreshFileMonitor()
5450 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5451 file_monitor_->refresh();
5455 // The previous file monitor is invalid
5456 // This also destroys the previous file monitor and all its connections
5457 file_monitor_ = FileSystemWatcher::monitor(filename);
5458 // file_monitor_ will be destroyed with *this, so it is not going to call a
5459 // destroyed object method.
5460 file_monitor_->connect([this](bool exists) {
5461 fileExternallyModified(exists);
5466 void Buffer::Impl::fileExternallyModified(bool const exists)
5468 // ignore notifications after our own saving operations
5469 if (checksum_ == filename.checksum()) {
5470 LYXERR(Debug::FILES, "External modification but "
5471 "checksum unchanged: " << filename);
5474 // If the file has been deleted, only mark the file as dirty since it is
5475 // pointless to prompt for reloading. If later a file is moved into this
5476 // location, then the externally modified warning will appear then.
5478 externally_modified_ = true;
5479 // Update external modification notification.
5480 // Dirty buffers must be visible at all times.
5481 if (wa_ && wa_->unhide(owner_))
5482 wa_->updateTitles();
5484 // Unable to unhide the buffer (e.g. no GUI or not current View)
5489 bool Buffer::notifiesExternalModification() const
5491 return d->externally_modified_;
5495 void Buffer::clearExternalModification() const
5497 d->externally_modified_ = false;
5499 d->wa_->updateTitles();