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();
2966 dr.screenUpdate(Update::Force);
2974 dr.dispatched(dispatched);
2978 void Buffer::changeLanguage(Language const * from, Language const * to)
2980 LASSERT(from, return);
2981 LASSERT(to, return);
2983 for_each(par_iterator_begin(),
2985 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2989 bool Buffer::isMultiLingual() const
2991 ParConstIterator end = par_iterator_end();
2992 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2993 if (it->isMultiLingual(params()))
3000 std::set<Language const *> Buffer::getLanguages() const
3002 std::set<Language const *> languages;
3003 getLanguages(languages);
3008 void Buffer::getLanguages(std::set<Language const *> & languages) const
3010 ParConstIterator end = par_iterator_end();
3011 // add the buffer language, even if it's not actively used
3012 languages.insert(language());
3013 // iterate over the paragraphs
3014 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3015 it->getLanguages(languages);
3017 ListOfBuffers clist = getDescendents();
3018 ListOfBuffers::const_iterator cit = clist.begin();
3019 ListOfBuffers::const_iterator const cen = clist.end();
3020 for (; cit != cen; ++cit)
3021 (*cit)->getLanguages(languages);
3025 DocIterator Buffer::getParFromID(int const id) const
3027 Buffer * buf = const_cast<Buffer *>(this);
3029 // This means non-existent
3030 return doc_iterator_end(buf);
3032 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3033 if (it.paragraph().id() == id)
3036 return doc_iterator_end(buf);
3040 bool Buffer::hasParWithID(int const id) const
3042 return !getParFromID(id).atEnd();
3046 ParIterator Buffer::par_iterator_begin()
3048 return ParIterator(doc_iterator_begin(this));
3052 ParIterator Buffer::par_iterator_end()
3054 return ParIterator(doc_iterator_end(this));
3058 ParConstIterator Buffer::par_iterator_begin() const
3060 return ParConstIterator(doc_iterator_begin(this));
3064 ParConstIterator Buffer::par_iterator_end() const
3066 return ParConstIterator(doc_iterator_end(this));
3070 Language const * Buffer::language() const
3072 return params().language;
3076 docstring const Buffer::B_(string const & l10n) const
3078 return params().B_(l10n);
3082 bool Buffer::isClean() const
3084 return d->lyx_clean;
3088 bool Buffer::isChecksumModified() const
3090 LASSERT(d->filename.exists(), return false);
3091 return d->checksum_ != d->filename.checksum();
3095 void Buffer::saveCheckSum() const
3097 FileName const & file = d->filename;
3099 d->checksum_ = file.exists() ? file.checksum()
3100 : 0; // in the case of save to a new file.
3104 void Buffer::markClean() const
3106 if (!d->lyx_clean) {
3107 d->lyx_clean = true;
3110 // if the .lyx file has been saved, we don't need an
3112 d->bak_clean = true;
3113 d->undo_.markDirty();
3114 clearExternalModification();
3118 void Buffer::setUnnamed(bool flag)
3124 bool Buffer::isUnnamed() const
3131 /// Don't check unnamed, here: isInternal() is used in
3132 /// newBuffer(), where the unnamed flag has not been set by anyone
3133 /// yet. Also, for an internal buffer, there should be no need for
3134 /// retrieving fileName() nor for checking if it is unnamed or not.
3135 bool Buffer::isInternal() const
3137 return d->internal_buffer;
3141 void Buffer::setInternal(bool flag)
3143 d->internal_buffer = flag;
3147 void Buffer::markDirty()
3150 d->lyx_clean = false;
3153 d->bak_clean = false;
3155 DepClean::iterator it = d->dep_clean.begin();
3156 DepClean::const_iterator const end = d->dep_clean.end();
3158 for (; it != end; ++it)
3163 FileName Buffer::fileName() const
3169 string Buffer::absFileName() const
3171 return d->filename.absFileName();
3175 string Buffer::filePath() const
3177 string const abs = d->filename.onlyPath().absFileName();
3180 int last = abs.length() - 1;
3182 return abs[last] == '/' ? abs : abs + '/';
3186 DocFileName Buffer::getReferencedFileName(string const & fn) const
3189 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3190 result.set(fn, filePath());
3192 // filePath() ends with a path separator
3193 FileName const test(filePath() + fn);
3195 result.set(fn, filePath());
3197 result.set(fn, params().origin);
3204 string const Buffer::prepareFileNameForLaTeX(string const & name,
3205 string const & ext, bool nice) const
3207 string const fname = makeAbsPath(name, filePath()).absFileName();
3208 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3214 return to_utf8(makeRelPath(from_utf8(fname),
3215 from_utf8(masterBuffer()->filePath())));
3219 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3220 docstring_list const & bibfilelist,
3221 bool const add_extension) const
3223 // If we are processing the LaTeX file in a temp directory then
3224 // copy the .bib databases to this temp directory, mangling their
3225 // names in the process. Store this mangled name in the list of
3227 // (We need to do all this because BibTeX *really*, *really*
3228 // can't handle "files with spaces" and Windows users tend to
3229 // use such filenames.)
3230 // Otherwise, store the (maybe absolute) path to the original,
3231 // unmangled database name.
3233 vector<docstring> res;
3235 // determine the export format
3236 string const tex_format = flavor2format(runparams.flavor);
3238 // check for spaces in paths
3239 bool found_space = false;
3241 for (auto const & bit : bibfilelist) {
3242 string utf8input = to_utf8(bit);
3244 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3245 FileName try_in_file =
3246 makeAbsPath(database + ".bib", filePath());
3247 bool not_from_texmf = try_in_file.isReadableFile();
3248 // If the file has not been found, try with the real file name
3249 // (it might come from a child in a sub-directory)
3250 if (!not_from_texmf) {
3251 try_in_file = getBibfilePath(bit);
3252 if (try_in_file.isReadableFile()) {
3253 // Check if the file is in texmf
3254 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3255 not_from_texmf = kpsefile.empty()
3256 || kpsefile.absFileName() != try_in_file.absFileName();
3258 // If this exists, make path relative to the master
3260 database = removeExtension(
3261 prepareFileNameForLaTeX(to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3262 from_utf8(filePath()))),
3263 ".bib", runparams.nice));
3267 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3269 // mangledFileName() needs the extension
3270 DocFileName const in_file = DocFileName(try_in_file);
3271 database = removeExtension(in_file.mangledFileName());
3272 FileName const out_file = makeAbsPath(database + ".bib",
3273 masterBuffer()->temppath());
3274 bool const success = in_file.copyTo(out_file);
3276 LYXERR0("Failed to copy '" << in_file
3277 << "' to '" << out_file << "'");
3279 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3280 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3281 if (!isValidLaTeXFileName(database)) {
3282 frontend::Alert::warning(_("Invalid filename"),
3283 _("The following filename will cause troubles "
3284 "when running the exported file through LaTeX: ") +
3285 from_utf8(database));
3287 if (!isValidDVIFileName(database)) {
3288 frontend::Alert::warning(_("Problematic filename for DVI"),
3289 _("The following filename can cause troubles "
3290 "when running the exported file through LaTeX "
3291 "and opening the resulting DVI: ") +
3292 from_utf8(database), true);
3300 docstring const path = from_utf8(latex_path(database));
3302 if (contains(path, ' '))
3305 if (find(res.begin(), res.end(), path) == res.end())
3306 res.push_back(path);
3309 // Check if there are spaces in the path and warn BibTeX users, if so.
3310 // (biber can cope with such paths)
3311 if (!prefixIs(runparams.bibtex_command, "biber")) {
3312 // Post this warning only once.
3313 static bool warned_about_spaces = false;
3314 if (!warned_about_spaces &&
3315 runparams.nice && found_space) {
3316 warned_about_spaces = true;
3317 Alert::warning(_("Export Warning!"),
3318 _("There are spaces in the paths to your BibTeX databases.\n"
3319 "BibTeX will be unable to find them."));
3328 string Buffer::layoutPos() const
3330 return d->layout_position;
3334 void Buffer::setLayoutPos(string const & path)
3337 d->layout_position.clear();
3341 LATTEST(FileName::isAbsolute(path));
3343 d->layout_position =
3344 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3346 if (d->layout_position.empty())
3347 d->layout_position = ".";
3351 bool Buffer::hasReadonlyFlag() const
3353 return d->read_only;
3357 bool Buffer::isReadonly() const
3359 return hasReadonlyFlag() || notifiesExternalModification();
3363 void Buffer::setParent(Buffer const * buffer)
3365 // Avoids recursive include.
3366 d->setParent(buffer == this ? 0 : buffer);
3371 Buffer const * Buffer::parent() const
3377 ListOfBuffers Buffer::allRelatives() const
3379 ListOfBuffers lb = masterBuffer()->getDescendents();
3380 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3385 Buffer const * Buffer::masterBuffer() const
3387 // FIXME Should be make sure we are not in some kind
3388 // of recursive include? A -> B -> A will crash this.
3389 Buffer const * const pbuf = d->parent();
3393 return pbuf->masterBuffer();
3397 bool Buffer::isChild(Buffer * child) const
3399 return d->children_positions.find(child) != d->children_positions.end();
3403 DocIterator Buffer::firstChildPosition(Buffer const * child)
3405 Impl::BufferPositionMap::iterator it;
3406 it = d->children_positions.find(child);
3407 if (it == d->children_positions.end())
3408 return DocIterator(this);
3413 bool Buffer::hasChildren() const
3415 return !d->children_positions.empty();
3419 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3421 // loop over children
3422 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3423 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3424 for (; it != end; ++it) {
3425 Buffer * child = const_cast<Buffer *>(it->first);
3427 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3428 if (bit != clist.end())
3430 clist.push_back(child);
3432 // there might be grandchildren
3433 child->collectChildren(clist, true);
3438 ListOfBuffers Buffer::getChildren() const
3441 collectChildren(v, false);
3442 // Make sure we have not included ourselves.
3443 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3444 if (bit != v.end()) {
3445 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3452 ListOfBuffers Buffer::getDescendents() const
3455 collectChildren(v, true);
3456 // Make sure we have not included ourselves.
3457 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3458 if (bit != v.end()) {
3459 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3466 template<typename M>
3467 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3472 typename M::const_iterator it = m.lower_bound(x);
3473 if (it == m.begin())
3481 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3482 DocIterator const & pos) const
3484 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3486 // if paragraphs have no macro context set, pos will be empty
3490 // we haven't found anything yet
3491 DocIterator bestPos = owner_->par_iterator_begin();
3492 MacroData const * bestData = 0;
3494 // find macro definitions for name
3495 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3496 if (nameIt != macros.end()) {
3497 // find last definition in front of pos or at pos itself
3498 PositionScopeMacroMap::const_iterator it
3499 = greatest_below(nameIt->second, pos);
3500 if (it != nameIt->second.end()) {
3502 // scope ends behind pos?
3503 if (pos < it->second.scope) {
3504 // Looks good, remember this. If there
3505 // is no external macro behind this,
3506 // we found the right one already.
3507 bestPos = it->first;
3508 bestData = &it->second.macro;
3512 // try previous macro if there is one
3513 if (it == nameIt->second.begin())
3520 // find macros in included files
3521 PositionScopeBufferMap::const_iterator it
3522 = greatest_below(position_to_children, pos);
3523 if (it == position_to_children.end())
3524 // no children before
3528 // do we know something better (i.e. later) already?
3529 if (it->first < bestPos )
3532 // scope ends behind pos?
3533 if (pos < it->second.scope
3534 && (cloned_buffer_ ||
3535 theBufferList().isLoaded(it->second.buffer))) {
3536 // look for macro in external file
3538 MacroData const * data
3539 = it->second.buffer->getMacro(name, false);
3542 bestPos = it->first;
3548 // try previous file if there is one
3549 if (it == position_to_children.begin())
3554 // return the best macro we have found
3559 MacroData const * Buffer::getMacro(docstring const & name,
3560 DocIterator const & pos, bool global) const
3565 // query buffer macros
3566 MacroData const * data = d->getBufferMacro(name, pos);
3570 // If there is a master buffer, query that
3571 Buffer const * const pbuf = d->parent();
3573 d->macro_lock = true;
3574 MacroData const * macro = pbuf->getMacro(
3575 name, *this, false);
3576 d->macro_lock = false;
3582 data = MacroTable::globalMacros().get(name);
3591 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3593 // set scope end behind the last paragraph
3594 DocIterator scope = par_iterator_begin();
3595 scope.pit() = scope.lastpit() + 1;
3597 return getMacro(name, scope, global);
3601 MacroData const * Buffer::getMacro(docstring const & name,
3602 Buffer const & child, bool global) const
3604 // look where the child buffer is included first
3605 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3606 if (it == d->children_positions.end())
3609 // check for macros at the inclusion position
3610 return getMacro(name, it->second, global);
3614 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3616 pit_type const lastpit = it.lastpit();
3618 // look for macros in each paragraph
3619 while (it.pit() <= lastpit) {
3620 Paragraph & par = it.paragraph();
3622 // iterate over the insets of the current paragraph
3623 InsetList const & insets = par.insetList();
3624 InsetList::const_iterator iit = insets.begin();
3625 InsetList::const_iterator end = insets.end();
3626 for (; iit != end; ++iit) {
3627 it.pos() = iit->pos;
3629 // is it a nested text inset?
3630 if (iit->inset->asInsetText()) {
3631 // Inset needs its own scope?
3632 InsetText const * itext = iit->inset->asInsetText();
3633 bool newScope = itext->isMacroScope();
3635 // scope which ends just behind the inset
3636 DocIterator insetScope = it;
3639 // collect macros in inset
3640 it.push_back(CursorSlice(*iit->inset));
3641 updateMacros(it, newScope ? insetScope : scope);
3646 if (iit->inset->asInsetTabular()) {
3647 CursorSlice slice(*iit->inset);
3648 size_t const numcells = slice.nargs();
3649 for (; slice.idx() < numcells; slice.forwardIdx()) {
3650 it.push_back(slice);
3651 updateMacros(it, scope);
3657 // is it an external file?
3658 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3659 // get buffer of external file
3660 InsetInclude const & inset =
3661 static_cast<InsetInclude const &>(*iit->inset);
3663 Buffer * child = inset.getChildBuffer();
3668 // register its position, but only when it is
3669 // included first in the buffer
3670 if (children_positions.find(child) ==
3671 children_positions.end())
3672 children_positions[child] = it;
3674 // register child with its scope
3675 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3679 InsetMath * im = iit->inset->asInsetMath();
3680 if (doing_export && im) {
3681 InsetMathHull * hull = im->asHullInset();
3683 hull->recordLocation(it);
3686 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3690 InsetMathMacroTemplate & macroTemplate =
3691 *iit->inset->asInsetMath()->asMacroTemplate();
3692 MacroContext mc(owner_, it);
3693 macroTemplate.updateToContext(mc);
3696 bool valid = macroTemplate.validMacro();
3697 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3698 // then the BufferView's cursor will be invalid in
3699 // some cases which leads to crashes.
3704 // FIXME (Abdel), I don't understand why we pass 'it' here
3705 // instead of 'macroTemplate' defined above... is this correct?
3706 macros[macroTemplate.name()][it] =
3707 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3717 void Buffer::updateMacros() const
3722 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3724 // start with empty table
3726 d->children_positions.clear();
3727 d->position_to_children.clear();
3729 // Iterate over buffer, starting with first paragraph
3730 // The scope must be bigger than any lookup DocIterator
3731 // later. For the global lookup, lastpit+1 is used, hence
3732 // we use lastpit+2 here.
3733 DocIterator it = par_iterator_begin();
3734 DocIterator outerScope = it;
3735 outerScope.pit() = outerScope.lastpit() + 2;
3736 d->updateMacros(it, outerScope);
3740 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3742 InsetIterator it = inset_iterator_begin(inset());
3743 InsetIterator const end = inset_iterator_end(inset());
3744 for (; it != end; ++it) {
3745 if (it->lyxCode() == BRANCH_CODE) {
3746 InsetBranch & br = static_cast<InsetBranch &>(*it);
3747 docstring const name = br.branch();
3748 if (!from_master && !params().branchlist().find(name))
3749 result.push_back(name);
3750 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3751 result.push_back(name);
3754 if (it->lyxCode() == INCLUDE_CODE) {
3755 // get buffer of external file
3756 InsetInclude const & ins =
3757 static_cast<InsetInclude const &>(*it);
3758 Buffer * child = ins.getChildBuffer();
3761 child->getUsedBranches(result, true);
3764 // remove duplicates
3769 void Buffer::updateMacroInstances(UpdateType utype) const
3771 LYXERR(Debug::MACROS, "updateMacroInstances for "
3772 << d->filename.onlyFileName());
3773 DocIterator it = doc_iterator_begin(this);
3775 DocIterator const end = doc_iterator_end(this);
3776 for (; it != end; it.forwardInset()) {
3777 // look for MathData cells in InsetMathNest insets
3778 InsetMath * minset = it.nextInset()->asInsetMath();
3782 // update macro in all cells of the InsetMathNest
3783 DocIterator::idx_type n = minset->nargs();
3784 MacroContext mc = MacroContext(this, it);
3785 for (DocIterator::idx_type i = 0; i < n; ++i) {
3786 MathData & data = minset->cell(i);
3787 data.updateMacros(0, mc, utype, 0);
3793 void Buffer::listMacroNames(MacroNameSet & macros) const
3798 d->macro_lock = true;
3800 // loop over macro names
3801 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3802 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3803 for (; nameIt != nameEnd; ++nameIt)
3804 macros.insert(nameIt->first);
3806 // loop over children
3807 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3808 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3809 for (; it != end; ++it) {
3810 Buffer * child = const_cast<Buffer *>(it->first);
3811 // The buffer might have been closed (see #10766).
3812 if (theBufferList().isLoaded(child))
3813 child->listMacroNames(macros);
3817 Buffer const * const pbuf = d->parent();
3819 pbuf->listMacroNames(macros);
3821 d->macro_lock = false;
3825 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3827 Buffer const * const pbuf = d->parent();
3832 pbuf->listMacroNames(names);
3835 MacroNameSet::iterator it = names.begin();
3836 MacroNameSet::iterator end = names.end();
3837 for (; it != end; ++it) {
3839 MacroData const * data =
3840 pbuf->getMacro(*it, *this, false);
3842 macros.insert(data);
3844 // we cannot access the original InsetMathMacroTemplate anymore
3845 // here to calls validate method. So we do its work here manually.
3846 // FIXME: somehow make the template accessible here.
3847 if (data->optionals() > 0)
3848 features.require("xargs");
3854 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3857 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3859 RefCache::iterator it = d->ref_cache_.find(label);
3860 if (it != d->ref_cache_.end())
3861 return it->second.second;
3863 static InsetLabel const * dummy_il = 0;
3864 static References const dummy_refs = References();
3865 it = d->ref_cache_.insert(
3866 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3867 return it->second.second;
3871 Buffer::References const & Buffer::references(docstring const & label) const
3873 return const_cast<Buffer *>(this)->getReferenceCache(label);
3877 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3879 References & refs = getReferenceCache(label);
3880 refs.push_back(make_pair(inset, it));
3884 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3886 masterBuffer()->d->ref_cache_[label].first = il;
3890 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3892 return masterBuffer()->d->ref_cache_[label].first;
3896 void Buffer::clearReferenceCache() const
3899 d->ref_cache_.clear();
3903 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3905 //FIXME: This does not work for child documents yet.
3906 reloadBibInfoCache();
3908 // Check if the label 'from' appears more than once
3909 BiblioInfo const & keys = masterBibInfo();
3910 BiblioInfo::const_iterator bit = keys.begin();
3911 BiblioInfo::const_iterator bend = keys.end();
3912 vector<docstring> labels;
3914 for (; bit != bend; ++bit)
3916 labels.push_back(bit->first);
3918 if (count(labels.begin(), labels.end(), from) > 1)
3921 string const paramName = "key";
3922 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3923 if (it->lyxCode() != CITE_CODE)
3925 InsetCommand * inset = it->asInsetCommand();
3926 docstring const oldValue = inset->getParam(paramName);
3927 if (oldValue == from)
3928 inset->setParam(paramName, to);
3932 // returns NULL if id-to-row conversion is unsupported
3933 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3934 pit_type par_begin, pit_type par_end,
3935 OutputWhat output, bool master) const
3937 unique_ptr<TexRow> texrow;
3938 OutputParams runparams(¶ms().encoding());
3939 runparams.nice = true;
3940 runparams.flavor = params().getOutputFlavor(format);
3941 runparams.linelen = lyxrc.plaintext_linelen;
3942 // No side effect of file copying and image conversion
3943 runparams.dryrun = true;
3945 if (output == CurrentParagraph) {
3946 runparams.par_begin = par_begin;
3947 runparams.par_end = par_end;
3948 if (par_begin + 1 == par_end) {
3950 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3954 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3955 convert<docstring>(par_begin),
3956 convert<docstring>(par_end - 1))
3959 // output paragraphs
3960 if (runparams.flavor == OutputParams::LYX) {
3961 Paragraph const & par = text().paragraphs()[par_begin];
3963 depth_type dt = par.getDepth();
3964 par.write(ods, params(), dt);
3965 os << from_utf8(ods.str());
3966 } else if (runparams.flavor == OutputParams::HTML) {
3968 setMathFlavor(runparams);
3969 xhtmlParagraphs(text(), *this, xs, runparams);
3970 } else if (runparams.flavor == OutputParams::TEXT) {
3972 // FIXME Handles only one paragraph, unlike the others.
3973 // Probably should have some routine with a signature like them.
3974 writePlaintextParagraph(*this,
3975 text().paragraphs()[par_begin], os, runparams, dummy);
3976 } else if (params().isDocBook()) {
3977 docbookParagraphs(text(), *this, os, runparams);
3979 // If we are previewing a paragraph, even if this is the
3980 // child of some other buffer, let's cut the link here,
3981 // so that no concurring settings from the master
3982 // (e.g. branch state) interfere (see #8101).
3984 d->ignore_parent = true;
3985 // We need to validate the Buffer params' features here
3986 // in order to know if we should output polyglossia
3987 // macros (instead of babel macros)
3988 LaTeXFeatures features(*this, params(), runparams);
3990 runparams.use_polyglossia = features.usePolyglossia();
3991 // latex or literate
3994 ots.texrow().newlines(2);
3996 latexParagraphs(*this, text(), ots, runparams);
3997 texrow = ots.releaseTexRow();
3999 // Restore the parenthood
4001 d->ignore_parent = false;
4005 if (output == FullSource)
4006 os << _("Preview source code");
4007 else if (output == OnlyPreamble)
4008 os << _("Preview preamble");
4009 else if (output == OnlyBody)
4010 os << _("Preview body");
4012 if (runparams.flavor == OutputParams::LYX) {
4014 if (output == FullSource)
4016 else if (output == OnlyPreamble)
4017 params().writeFile(ods, this);
4018 else if (output == OnlyBody)
4020 os << from_utf8(ods.str());
4021 } else if (runparams.flavor == OutputParams::HTML) {
4022 writeLyXHTMLSource(os, runparams, output);
4023 } else if (runparams.flavor == OutputParams::TEXT) {
4024 if (output == OnlyPreamble) {
4025 os << "% "<< _("Plain text does not have a preamble.");
4027 writePlaintextFile(*this, os, runparams);
4028 } else if (params().isDocBook()) {
4029 writeDocBookSource(os, absFileName(), runparams, output);
4031 // latex or literate
4034 ots.texrow().newlines(2);
4036 runparams.is_child = true;
4038 writeLaTeXSource(ots, string(), runparams, output);
4039 texrow = ots.releaseTexRow();
4046 ErrorList & Buffer::errorList(string const & type) const
4048 return d->errorLists[type];
4052 void Buffer::updateTocItem(std::string const & type,
4053 DocIterator const & dit) const
4056 d->gui_->updateTocItem(type, dit);
4060 void Buffer::structureChanged() const
4063 d->gui_->structureChanged();
4067 void Buffer::errors(string const & err, bool from_master) const
4070 d->gui_->errors(err, from_master);
4074 void Buffer::message(docstring const & msg) const
4077 d->gui_->message(msg);
4081 void Buffer::setBusy(bool on) const
4084 d->gui_->setBusy(on);
4088 void Buffer::updateTitles() const
4091 d->wa_->updateTitles();
4095 void Buffer::resetAutosaveTimers() const
4098 d->gui_->resetAutosaveTimers();
4102 bool Buffer::hasGuiDelegate() const
4108 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4117 class AutoSaveBuffer : public ForkedProcess {
4120 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4121 : buffer_(buffer), fname_(fname) {}
4123 virtual shared_ptr<ForkedProcess> clone() const
4125 return make_shared<AutoSaveBuffer>(*this);
4130 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4131 from_utf8(fname_.absFileName())));
4132 return run(DontWait);
4136 virtual int generateChild();
4138 Buffer const & buffer_;
4143 int AutoSaveBuffer::generateChild()
4145 #if defined(__APPLE__)
4146 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4147 * We should use something else like threads.
4149 * Since I do not know how to determine at run time what is the OS X
4150 * version, I just disable forking altogether for now (JMarc)
4152 pid_t const pid = -1;
4154 // tmp_ret will be located (usually) in /tmp
4155 // will that be a problem?
4156 // Note that this calls ForkedCalls::fork(), so it's
4157 // ok cross-platform.
4158 pid_t const pid = fork();
4159 // If you want to debug the autosave
4160 // you should set pid to -1, and comment out the fork.
4161 if (pid != 0 && pid != -1)
4165 // pid = -1 signifies that lyx was unable
4166 // to fork. But we will do the save
4168 bool failed = false;
4169 TempFile tempfile("lyxautoXXXXXX.lyx");
4170 tempfile.setAutoRemove(false);
4171 FileName const tmp_ret = tempfile.name();
4172 if (!tmp_ret.empty()) {
4173 if (!buffer_.writeFile(tmp_ret))
4175 else if (!tmp_ret.moveTo(fname_))
4181 // failed to write/rename tmp_ret so try writing direct
4182 if (!buffer_.writeFile(fname_)) {
4183 // It is dangerous to do this in the child,
4184 // but safe in the parent, so...
4185 if (pid == -1) // emit message signal.
4186 buffer_.message(_("Autosave failed!"));
4190 if (pid == 0) // we are the child so...
4199 FileName Buffer::getEmergencyFileName() const
4201 return FileName(d->filename.absFileName() + ".emergency");
4205 FileName Buffer::getAutosaveFileName() const
4207 // if the document is unnamed try to save in the backup dir, else
4208 // in the default document path, and as a last try in the filePath,
4209 // which will most often be the temporary directory
4212 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4213 : lyxrc.backupdir_path;
4214 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4217 string const fname = "#" + d->filename.onlyFileName() + "#";
4219 return makeAbsPath(fname, fpath);
4223 void Buffer::removeAutosaveFile() const
4225 FileName const f = getAutosaveFileName();
4231 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4233 FileName const newauto = getAutosaveFileName();
4235 if (newauto != oldauto && oldauto.exists())
4236 if (!oldauto.moveTo(newauto))
4237 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4241 bool Buffer::autoSave() const
4243 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4244 if (buf->d->bak_clean || hasReadonlyFlag())
4247 message(_("Autosaving current document..."));
4248 buf->d->bak_clean = true;
4250 FileName const fname = getAutosaveFileName();
4251 LASSERT(d->cloned_buffer_, return false);
4253 // If this buffer is cloned, we assume that
4254 // we are running in a separate thread already.
4255 TempFile tempfile("lyxautoXXXXXX.lyx");
4256 tempfile.setAutoRemove(false);
4257 FileName const tmp_ret = tempfile.name();
4258 if (!tmp_ret.empty()) {
4260 // assume successful write of tmp_ret
4261 if (tmp_ret.moveTo(fname))
4264 // failed to write/rename tmp_ret so try writing direct
4265 return writeFile(fname);
4269 void Buffer::setExportStatus(bool e) const
4271 d->doing_export = e;
4272 ListOfBuffers clist = getDescendents();
4273 ListOfBuffers::const_iterator cit = clist.begin();
4274 ListOfBuffers::const_iterator const cen = clist.end();
4275 for (; cit != cen; ++cit)
4276 (*cit)->d->doing_export = e;
4280 bool Buffer::isExporting() const
4282 return d->doing_export;
4286 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4290 return doExport(target, put_in_tempdir, result_file);
4293 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4294 string & result_file) const
4296 bool const update_unincluded =
4297 params().maintain_unincluded_children
4298 && !params().getIncludedChildren().empty();
4300 // (1) export with all included children (omit \includeonly)
4301 if (update_unincluded) {
4302 ExportStatus const status =
4303 doExport(target, put_in_tempdir, true, result_file);
4304 if (status != ExportSuccess)
4307 // (2) export with included children only
4308 return doExport(target, put_in_tempdir, false, result_file);
4312 void Buffer::setMathFlavor(OutputParams & op) const
4314 switch (params().html_math_output) {
4315 case BufferParams::MathML:
4316 op.math_flavor = OutputParams::MathAsMathML;
4318 case BufferParams::HTML:
4319 op.math_flavor = OutputParams::MathAsHTML;
4321 case BufferParams::Images:
4322 op.math_flavor = OutputParams::MathAsImages;
4324 case BufferParams::LaTeX:
4325 op.math_flavor = OutputParams::MathAsLaTeX;
4331 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4332 bool includeall, string & result_file) const
4334 LYXERR(Debug::FILES, "target=" << target);
4335 OutputParams runparams(¶ms().encoding());
4336 string format = target;
4337 string dest_filename;
4338 size_t pos = target.find(' ');
4339 if (pos != string::npos) {
4340 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4341 format = target.substr(0, pos);
4342 if (format == "default")
4343 format = params().getDefaultOutputFormat();
4344 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4345 FileName(dest_filename).onlyPath().createPath();
4346 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4348 MarkAsExporting exporting(this);
4349 string backend_format;
4350 runparams.flavor = OutputParams::LATEX;
4351 runparams.linelen = lyxrc.plaintext_linelen;
4352 runparams.includeall = includeall;
4353 vector<string> backs = params().backends();
4354 Converters converters = theConverters();
4355 bool need_nice_file = false;
4356 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4357 // Get shortest path to format
4358 converters.buildGraph();
4359 Graph::EdgePath path;
4360 for (vector<string>::const_iterator it = backs.begin();
4361 it != backs.end(); ++it) {
4362 Graph::EdgePath p = converters.getPath(*it, format);
4363 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4364 backend_format = *it;
4369 if (!put_in_tempdir) {
4370 // Only show this alert if this is an export to a non-temporary
4371 // file (not for previewing).
4372 Alert::error(_("Couldn't export file"), bformat(
4373 _("No information for exporting the format %1$s."),
4374 theFormats().prettyName(format)));
4376 return ExportNoPathToFormat;
4378 runparams.flavor = converters.getFlavor(path, this);
4379 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4380 Graph::EdgePath::const_iterator it = path.begin();
4381 Graph::EdgePath::const_iterator en = path.end();
4382 for (; it != en; ++it)
4383 if (theConverters().get(*it).nice()) {
4384 need_nice_file = true;
4389 backend_format = format;
4390 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4391 // FIXME: Don't hardcode format names here, but use a flag
4392 if (backend_format == "pdflatex")
4393 runparams.flavor = OutputParams::PDFLATEX;
4394 else if (backend_format == "luatex")
4395 runparams.flavor = OutputParams::LUATEX;
4396 else if (backend_format == "dviluatex")
4397 runparams.flavor = OutputParams::DVILUATEX;
4398 else if (backend_format == "xetex")
4399 runparams.flavor = OutputParams::XETEX;
4402 string filename = latexName(false);
4403 filename = addName(temppath(), filename);
4404 filename = changeExtension(filename,
4405 theFormats().extension(backend_format));
4406 LYXERR(Debug::FILES, "filename=" << filename);
4408 // Plain text backend
4409 if (backend_format == "text") {
4410 runparams.flavor = OutputParams::TEXT;
4411 writePlaintextFile(*this, FileName(filename), runparams);
4414 else if (backend_format == "xhtml") {
4415 runparams.flavor = OutputParams::HTML;
4416 setMathFlavor(runparams);
4417 makeLyXHTMLFile(FileName(filename), runparams);
4418 } else if (backend_format == "lyx")
4419 writeFile(FileName(filename));
4421 else if (params().isDocBook()) {
4422 runparams.nice = !put_in_tempdir;
4423 makeDocBookFile(FileName(filename), runparams);
4426 else if (backend_format == format || need_nice_file) {
4427 runparams.nice = true;
4428 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4429 if (d->cloned_buffer_)
4430 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4433 } else if (!lyxrc.tex_allows_spaces
4434 && contains(filePath(), ' ')) {
4435 Alert::error(_("File name error"),
4436 bformat(_("The directory path to the document\n%1$s\n"
4437 "contains spaces, but your TeX installation does "
4438 "not allow them. You should save the file to a directory "
4439 "whose name does not contain spaces."), from_ascii(filePath())));
4440 return ExportTexPathHasSpaces;
4442 runparams.nice = false;
4443 bool const success = makeLaTeXFile(
4444 FileName(filename), filePath(), runparams);
4445 if (d->cloned_buffer_)
4446 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4451 string const error_type = (format == "program")
4452 ? "Build" : params().bufferFormat();
4453 ErrorList & error_list = d->errorLists[error_type];
4454 string const ext = theFormats().extension(format);
4455 FileName const tmp_result_file(changeExtension(filename, ext));
4456 bool const success = converters.convert(this, FileName(filename),
4457 tmp_result_file, FileName(absFileName()), backend_format, format,
4460 // Emit the signal to show the error list or copy it back to the
4461 // cloned Buffer so that it can be emitted afterwards.
4462 if (format != backend_format) {
4463 if (runparams.silent)
4465 else if (d->cloned_buffer_)
4466 d->cloned_buffer_->d->errorLists[error_type] =
4467 d->errorLists[error_type];
4470 // also to the children, in case of master-buffer-view
4471 ListOfBuffers clist = getDescendents();
4472 ListOfBuffers::const_iterator cit = clist.begin();
4473 ListOfBuffers::const_iterator const cen = clist.end();
4474 for (; cit != cen; ++cit) {
4475 if (runparams.silent)
4476 (*cit)->d->errorLists[error_type].clear();
4477 else if (d->cloned_buffer_) {
4478 // Enable reverse search by copying back the
4479 // texrow object to the cloned buffer.
4480 // FIXME: this is not thread safe.
4481 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4482 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4483 (*cit)->d->errorLists[error_type];
4485 (*cit)->errors(error_type, true);
4489 if (d->cloned_buffer_) {
4490 // Enable reverse dvi or pdf to work by copying back the texrow
4491 // object to the cloned buffer.
4492 // FIXME: There is a possibility of concurrent access to texrow
4493 // here from the main GUI thread that should be securized.
4494 d->cloned_buffer_->d->texrow = d->texrow;
4495 string const error_type = params().bufferFormat();
4496 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4500 if (put_in_tempdir) {
4501 result_file = tmp_result_file.absFileName();
4502 return success ? ExportSuccess : ExportConverterError;
4505 if (dest_filename.empty())
4506 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4508 result_file = dest_filename;
4509 // We need to copy referenced files (e. g. included graphics
4510 // if format == "dvi") to the result dir.
4511 vector<ExportedFile> const files =
4512 runparams.exportdata->externalFiles(format);
4513 string const dest = runparams.export_folder.empty() ?
4514 onlyPath(result_file) : runparams.export_folder;
4515 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4516 : force_overwrite == ALL_FILES;
4517 CopyStatus status = use_force ? FORCE : SUCCESS;
4519 vector<ExportedFile>::const_iterator it = files.begin();
4520 vector<ExportedFile>::const_iterator const en = files.end();
4521 for (; it != en && status != CANCEL; ++it) {
4522 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4523 string fixedName = it->exportName;
4524 if (!runparams.export_folder.empty()) {
4525 // Relative pathnames starting with ../ will be sanitized
4526 // if exporting to a different folder
4527 while (fixedName.substr(0, 3) == "../")
4528 fixedName = fixedName.substr(3, fixedName.length() - 3);
4530 FileName fixedFileName = makeAbsPath(fixedName, dest);
4531 fixedFileName.onlyPath().createPath();
4532 status = copyFile(fmt, it->sourceName,
4534 it->exportName, status == FORCE,
4535 runparams.export_folder.empty());
4538 if (status == CANCEL) {
4539 message(_("Document export cancelled."));
4540 return ExportCancel;
4543 if (tmp_result_file.exists()) {
4544 // Finally copy the main file
4545 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4546 : force_overwrite != NO_FILES;
4547 if (status == SUCCESS && use_force)
4549 status = copyFile(format, tmp_result_file,
4550 FileName(result_file), result_file,
4552 if (status == CANCEL) {
4553 message(_("Document export cancelled."));
4554 return ExportCancel;
4556 message(bformat(_("Document exported as %1$s "
4558 theFormats().prettyName(format),
4559 makeDisplayPath(result_file)));
4562 // This must be a dummy converter like fax (bug 1888)
4563 message(bformat(_("Document exported as %1$s"),
4564 theFormats().prettyName(format)));
4567 return success ? ExportSuccess : ExportConverterError;
4571 Buffer::ExportStatus Buffer::preview(string const & format) const
4573 bool const update_unincluded =
4574 params().maintain_unincluded_children
4575 && !params().getIncludedChildren().empty();
4576 return preview(format, update_unincluded);
4580 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4582 MarkAsExporting exporting(this);
4584 // (1) export with all included children (omit \includeonly)
4586 ExportStatus const status = doExport(format, true, true, result_file);
4587 if (status != ExportSuccess)
4590 // (2) export with included children only
4591 ExportStatus const status = doExport(format, true, false, result_file);
4592 FileName const previewFile(result_file);
4594 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4595 theimpl->preview_file_ = previewFile;
4596 theimpl->preview_format_ = format;
4597 theimpl->preview_error_ = (status != ExportSuccess);
4599 if (status != ExportSuccess)
4602 if (previewFile.exists())
4603 return theFormats().view(*this, previewFile, format) ?
4604 PreviewSuccess : PreviewError;
4606 // Successful export but no output file?
4607 // Probably a bug in error detection.
4608 LATTEST(status != ExportSuccess);
4613 Buffer::ReadStatus Buffer::extractFromVC()
4615 bool const found = LyXVC::file_not_found_hook(d->filename);
4617 return ReadFileNotFound;
4618 if (!d->filename.isReadableFile())
4624 Buffer::ReadStatus Buffer::loadEmergency()
4626 FileName const emergencyFile = getEmergencyFileName();
4627 if (!emergencyFile.exists()
4628 || emergencyFile.lastModified() <= d->filename.lastModified())
4629 return ReadFileNotFound;
4631 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4632 docstring const text = bformat(_("An emergency save of the document "
4633 "%1$s exists.\n\nRecover emergency save?"), file);
4635 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4636 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4642 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4643 bool const success = (ret_llf == ReadSuccess);
4645 if (hasReadonlyFlag()) {
4646 Alert::warning(_("File is read-only"),
4647 bformat(_("An emergency file is successfully loaded, "
4648 "but the original file %1$s is marked read-only. "
4649 "Please make sure to save the document as a different "
4650 "file."), from_utf8(d->filename.absFileName())));
4653 lyxvc().file_found_hook(d->filename);
4654 str = _("Document was successfully recovered.");
4656 str = _("Document was NOT successfully recovered.");
4657 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4658 makeDisplayPath(emergencyFile.absFileName()));
4660 int const del_emerg =
4661 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4662 _("&Remove"), _("&Keep"));
4663 if (del_emerg == 0) {
4664 emergencyFile.removeFile();
4666 Alert::warning(_("Emergency file deleted"),
4667 _("Do not forget to save your file now!"), true);
4669 return success ? ReadSuccess : ReadEmergencyFailure;
4672 int const del_emerg =
4673 Alert::prompt(_("Delete emergency file?"),
4674 _("Remove emergency file now?"), 1, 1,
4675 _("&Remove"), _("&Keep"));
4677 emergencyFile.removeFile();
4678 return ReadOriginal;
4688 Buffer::ReadStatus Buffer::loadAutosave()
4690 // Now check if autosave file is newer.
4691 FileName const autosaveFile = getAutosaveFileName();
4692 if (!autosaveFile.exists()
4693 || autosaveFile.lastModified() <= d->filename.lastModified())
4694 return ReadFileNotFound;
4696 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4697 docstring const text = bformat(_("The backup of the document %1$s "
4698 "is newer.\n\nLoad the backup instead?"), file);
4699 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4700 _("&Load backup"), _("Load &original"), _("&Cancel"));
4705 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4706 // the file is not saved if we load the autosave file.
4707 if (ret_llf == ReadSuccess) {
4708 if (hasReadonlyFlag()) {
4709 Alert::warning(_("File is read-only"),
4710 bformat(_("A backup file is successfully loaded, "
4711 "but the original file %1$s is marked read-only. "
4712 "Please make sure to save the document as a "
4714 from_utf8(d->filename.absFileName())));
4717 lyxvc().file_found_hook(d->filename);
4720 return ReadAutosaveFailure;
4723 // Here we delete the autosave
4724 autosaveFile.removeFile();
4725 return ReadOriginal;
4733 Buffer::ReadStatus Buffer::loadLyXFile()
4735 if (!d->filename.isReadableFile()) {
4736 ReadStatus const ret_rvc = extractFromVC();
4737 if (ret_rvc != ReadSuccess)
4741 ReadStatus const ret_re = loadEmergency();
4742 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4745 ReadStatus const ret_ra = loadAutosave();
4746 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4749 return loadThisLyXFile(d->filename);
4753 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4755 return readFile(fn);
4759 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4761 for (auto const & err : terr) {
4762 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4763 int errorRow = err.error_in_line;
4764 Buffer const * buf = 0;
4766 if (err.child_name.empty())
4767 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4769 // The error occurred in a child
4770 for (Buffer const * child : getDescendents()) {
4771 string const child_name =
4772 DocFileName(changeExtension(child->absFileName(), "tex")).
4774 if (err.child_name != child_name)
4776 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4777 if (!TexRow::isNone(start)) {
4778 buf = d->cloned_buffer_
4779 ? child->d->cloned_buffer_->d->owner_
4786 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4792 void Buffer::setBuffersForInsets() const
4794 inset().setBuffer(const_cast<Buffer &>(*this));
4798 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4800 LBUFERR(!text().paragraphs().empty());
4802 // Use the master text class also for child documents
4803 Buffer const * const master = masterBuffer();
4804 DocumentClass const & textclass = master->params().documentClass();
4806 docstring_list old_bibfiles;
4807 // Do this only if we are the top-level Buffer. We also need to account
4808 // for the case of a previewed child with ignored parent here.
4809 if (master == this && !d->ignore_parent) {
4810 textclass.counters().reset(from_ascii("bibitem"));
4811 reloadBibInfoCache();
4812 // we will re-read this cache as we go through, but we need
4813 // to know whether it's changed to know whether we need to
4814 // update the bibinfo cache.
4815 old_bibfiles = d->bibfiles_cache_;
4816 d->bibfiles_cache_.clear();
4819 // keep the buffers to be children in this set. If the call from the
4820 // master comes back we can see which of them were actually seen (i.e.
4821 // via an InsetInclude). The remaining ones in the set need still be updated.
4822 static std::set<Buffer const *> bufToUpdate;
4823 if (scope == UpdateMaster) {
4824 // If this is a child document start with the master
4825 if (master != this) {
4826 bufToUpdate.insert(this);
4827 master->updateBuffer(UpdateMaster, utype);
4828 // If the master buffer has no gui associated with it, then the TocModel is
4829 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4830 // (bug 5699). The same happens if the master buffer is open in a different
4831 // window. This test catches both possibilities.
4832 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4833 // There remains a problem here: If there is another child open in yet a third
4834 // window, that TOC is not updated. So some more general solution is needed at
4836 if (master->d->gui_ != d->gui_)
4839 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4840 if (bufToUpdate.find(this) == bufToUpdate.end())
4844 // start over the counters in the master
4845 textclass.counters().reset();
4848 // update will be done below for this buffer
4849 bufToUpdate.erase(this);
4851 // update all caches
4852 clearReferenceCache();
4854 setChangesPresent(false);
4856 Buffer & cbuf = const_cast<Buffer &>(*this);
4859 ParIterator parit = cbuf.par_iterator_begin();
4860 updateBuffer(parit, utype);
4863 // If this document has siblings, then update the TocBackend later. The
4864 // reason is to ensure that later siblings are up to date when e.g. the
4865 // broken or not status of references is computed. The update is called
4866 // in InsetInclude::addToToc.
4869 // if the bibfiles changed, the cache of bibinfo is invalid
4870 docstring_list new_bibfiles = d->bibfiles_cache_;
4871 // this is a trick to determine whether the two vectors have
4872 // the same elements.
4873 sort(new_bibfiles.begin(), new_bibfiles.end());
4874 sort(old_bibfiles.begin(), old_bibfiles.end());
4875 if (old_bibfiles != new_bibfiles) {
4876 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4877 invalidateBibinfoCache();
4878 reloadBibInfoCache();
4879 // We relied upon the bibinfo cache when recalculating labels. But that
4880 // cache was invalid, although we didn't find that out until now. So we
4881 // have to do it all again.
4882 // That said, the only thing we really need to do is update the citation
4883 // labels. Nothing else will have changed. So we could create a new
4884 // UpdateType that would signal that fact, if we needed to do so.
4885 parit = cbuf.par_iterator_begin();
4886 // we will be re-doing the counters and references and such.
4887 textclass.counters().reset();
4888 clearReferenceCache();
4889 // we should not need to do this again?
4891 setChangesPresent(false);
4892 updateBuffer(parit, utype);
4893 // this will already have been done by reloadBibInfoCache();
4894 // d->bibinfo_cache_valid_ = true;
4897 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4898 // this is also set to true on the other path, by reloadBibInfoCache.
4899 d->bibinfo_cache_valid_ = true;
4901 d->cite_labels_valid_ = true;
4903 cbuf.tocBackend().update(true, utype);
4904 if (scope == UpdateMaster)
4905 cbuf.structureChanged();
4909 static depth_type getDepth(DocIterator const & it)
4911 depth_type depth = 0;
4912 for (size_t i = 0 ; i < it.depth() ; ++i)
4913 if (!it[i].inset().inMathed())
4914 depth += it[i].paragraph().getDepth() + 1;
4915 // remove 1 since the outer inset does not count
4916 // we should have at least one non-math inset, so
4917 // depth should nevery be 0. but maybe it is worth
4918 // marking this, just in case.
4920 // coverity[INTEGER_OVERFLOW]
4924 static depth_type getItemDepth(ParIterator const & it)
4926 Paragraph const & par = *it;
4927 LabelType const labeltype = par.layout().labeltype;
4929 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4932 // this will hold the lowest depth encountered up to now.
4933 depth_type min_depth = getDepth(it);
4934 ParIterator prev_it = it;
4937 --prev_it.top().pit();
4939 // start of nested inset: go to outer par
4941 if (prev_it.empty()) {
4942 // start of document: nothing to do
4947 // We search for the first paragraph with same label
4948 // that is not more deeply nested.
4949 Paragraph & prev_par = *prev_it;
4950 depth_type const prev_depth = getDepth(prev_it);
4951 if (labeltype == prev_par.layout().labeltype) {
4952 if (prev_depth < min_depth)
4953 return prev_par.itemdepth + 1;
4954 if (prev_depth == min_depth)
4955 return prev_par.itemdepth;
4957 min_depth = min(min_depth, prev_depth);
4958 // small optimization: if we are at depth 0, we won't
4959 // find anything else
4960 if (prev_depth == 0)
4966 static bool needEnumCounterReset(ParIterator const & it)
4968 Paragraph const & par = *it;
4969 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4970 depth_type const cur_depth = par.getDepth();
4971 ParIterator prev_it = it;
4972 while (prev_it.pit()) {
4973 --prev_it.top().pit();
4974 Paragraph const & prev_par = *prev_it;
4975 if (prev_par.getDepth() <= cur_depth)
4976 return prev_par.layout().name() != par.layout().name();
4978 // start of nested inset: reset
4983 // set the label of a paragraph. This includes the counters.
4984 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4986 BufferParams const & bp = owner_->masterBuffer()->params();
4987 DocumentClass const & textclass = bp.documentClass();
4988 Paragraph & par = it.paragraph();
4989 Layout const & layout = par.layout();
4990 Counters & counters = textclass.counters();
4992 if (par.params().startOfAppendix()) {
4993 // We want to reset the counter corresponding to toplevel sectioning
4994 Layout const & lay = textclass.getTOCLayout();
4995 docstring const cnt = lay.counter;
4997 counters.reset(cnt);
4998 counters.appendix(true);
5000 par.params().appendix(counters.appendix());
5002 // Compute the item depth of the paragraph
5003 par.itemdepth = getItemDepth(it);
5005 if (layout.margintype == MARGIN_MANUAL) {
5006 if (par.params().labelWidthString().empty())
5007 par.params().labelWidthString(par.expandLabel(layout, bp));
5008 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5009 // we do not need to do anything here, since the empty case is
5010 // handled during export.
5012 par.params().labelWidthString(docstring());
5015 switch(layout.labeltype) {
5016 case LABEL_ITEMIZE: {
5017 // At some point of time we should do something more
5018 // clever here, like:
5019 // par.params().labelString(
5020 // bp.user_defined_bullet(par.itemdepth).getText());
5021 // for now, use a simple hardcoded label
5022 docstring itemlabel;
5023 switch (par.itemdepth) {
5025 itemlabel = char_type(0x2022);
5028 itemlabel = char_type(0x2013);
5031 itemlabel = char_type(0x2217);
5034 itemlabel = char_type(0x2219); // or 0x00b7
5037 par.params().labelString(itemlabel);
5041 case LABEL_ENUMERATE: {
5042 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5044 switch (par.itemdepth) {
5055 enumcounter += "iv";
5058 // not a valid enumdepth...
5062 // Increase the master counter?
5063 if (layout.stepmastercounter && needEnumCounterReset(it))
5064 counters.stepMaster(enumcounter, utype);
5066 // Maybe we have to reset the enumeration counter.
5067 if (!layout.resumecounter && needEnumCounterReset(it))
5068 counters.reset(enumcounter);
5069 counters.step(enumcounter, utype);
5071 string const & lang = par.getParLanguage(bp)->code();
5072 par.params().labelString(counters.theCounter(enumcounter, lang));
5077 case LABEL_SENSITIVE: {
5078 string const & type = counters.current_float();
5079 docstring full_label;
5081 full_label = owner_->B_("Senseless!!! ");
5083 docstring name = owner_->B_(textclass.floats().getType(type).name());
5084 if (counters.hasCounter(from_utf8(type))) {
5085 string const & lang = par.getParLanguage(bp)->code();
5086 counters.step(from_utf8(type), utype);
5087 full_label = bformat(from_ascii("%1$s %2$s:"),
5089 counters.theCounter(from_utf8(type), lang));
5091 full_label = bformat(from_ascii("%1$s #:"), name);
5093 par.params().labelString(full_label);
5097 case LABEL_NO_LABEL:
5098 par.params().labelString(docstring());
5102 case LABEL_CENTERED:
5103 case LABEL_STATIC: {
5104 docstring const & lcounter = layout.counter;
5105 if (!lcounter.empty()) {
5106 if (layout.toclevel <= bp.secnumdepth
5107 && (layout.latextype != LATEX_ENVIRONMENT
5108 || it.text()->isFirstInSequence(it.pit()))) {
5109 if (counters.hasCounter(lcounter))
5110 counters.step(lcounter, utype);
5111 par.params().labelString(par.expandLabel(layout, bp));
5113 par.params().labelString(docstring());
5115 par.params().labelString(par.expandLabel(layout, bp));
5121 par.params().labelString(par.expandLabel(layout, bp));
5126 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5128 // LASSERT: Is it safe to continue here, or should we just return?
5129 LASSERT(parit.pit() == 0, /**/);
5131 // Set the position of the text in the buffer to be able
5132 // to resolve macros in it.
5133 parit.text()->setMacrocontextPosition(parit);
5135 depth_type maxdepth = 0;
5136 pit_type const lastpit = parit.lastpit();
5137 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5138 // reduce depth if necessary
5139 if (parit->params().depth() > maxdepth) {
5140 /** FIXME: this function is const, but
5141 * nevertheless it modifies the buffer. To be
5142 * cleaner, one should modify the buffer in
5143 * another function, which is actually
5144 * non-const. This would however be costly in
5145 * terms of code duplication.
5147 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5148 parit->params().depth(maxdepth);
5150 maxdepth = parit->getMaxDepthAfter();
5152 if (utype == OutputUpdate) {
5153 // track the active counters
5154 // we have to do this for the master buffer, since the local
5155 // buffer isn't tracking anything.
5156 masterBuffer()->params().documentClass().counters().
5157 setActiveLayout(parit->layout());
5160 // set the counter for this paragraph
5161 d->setLabel(parit, utype);
5163 // update change-tracking flag
5164 parit->addChangesToBuffer(*this);
5167 InsetList::const_iterator iit = parit->insetList().begin();
5168 InsetList::const_iterator end = parit->insetList().end();
5169 for (; iit != end; ++iit) {
5170 parit.pos() = iit->pos;
5171 iit->inset->updateBuffer(parit, utype);
5177 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5178 WordLangTuple & word_lang, docstring_list & suggestions) const
5182 suggestions.clear();
5183 word_lang = WordLangTuple();
5184 bool const to_end = to.empty();
5185 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5186 // OK, we start from here.
5187 for (; from != end; from.forwardPos()) {
5188 // This skips all insets with spell check disabled.
5189 while (!from.allowSpellCheck()) {
5193 // If from is at the end of the document (which is possible
5194 // when "from" was changed above) LyX will crash later otherwise.
5195 if (from.atEnd() || (!to_end && from >= end))
5198 from.paragraph().spellCheck();
5199 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5200 if (SpellChecker::misspelled(res)) {
5204 // Do not increase progress when from == to, otherwise the word
5205 // count will be wrong.
5215 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5217 bool inword = false;
5222 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5223 if (!dit.inTexted()) {
5228 Paragraph const & par = dit.paragraph();
5229 pos_type const pos = dit.pos();
5231 // Copied and adapted from isWordSeparator() in Paragraph
5232 if (pos == dit.lastpos()) {
5235 Inset const * ins = par.getInset(pos);
5236 if (ins && skipNoOutput && !ins->producesOutput()) {
5239 // stop if end of range was skipped
5240 if (!to.atEnd() && dit >= to)
5243 } else if (!par.isDeleted(pos)) {
5244 if (par.isWordSeparator(pos))
5250 if (ins && ins->isLetter())
5252 else if (ins && ins->isSpace())
5255 char_type const c = par.getChar(pos);
5256 if (isPrintableNonspace(c))
5258 else if (isSpace(c))
5268 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5270 d->updateStatistics(from, to, skipNoOutput);
5274 int Buffer::wordCount() const
5276 return d->wordCount();
5280 int Buffer::charCount(bool with_blanks) const
5282 return d->charCount(with_blanks);
5286 Buffer::ReadStatus Buffer::reload()
5289 // c.f. bug https://www.lyx.org/trac/ticket/6587
5290 removeAutosaveFile();
5291 // e.g., read-only status could have changed due to version control
5292 d->filename.refresh();
5293 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5295 // clear parent. this will get reset if need be.
5297 ReadStatus const status = loadLyXFile();
5298 if (status == ReadSuccess) {
5303 message(bformat(_("Document %1$s reloaded."), disp_fn));
5306 message(bformat(_("Could not reload document %1$s."), disp_fn));
5316 bool Buffer::saveAs(FileName const & fn)
5318 FileName const old_name = fileName();
5319 FileName const old_auto = getAutosaveFileName();
5320 bool const old_unnamed = isUnnamed();
5321 bool success = true;
5322 d->old_position = filePath();
5329 // bring the autosave file with us, just in case.
5330 moveAutosaveFile(old_auto);
5331 // validate version control data and
5332 // correct buffer title
5333 lyxvc().file_found_hook(fileName());
5335 // the file has now been saved to the new location.
5336 // we need to check that the locations of child buffers
5338 checkChildBuffers();
5339 checkMasterBuffer();
5342 // reset the old filename and unnamed state
5343 setFileName(old_name);
5344 setUnnamed(old_unnamed);
5348 d->old_position.clear();
5353 void Buffer::checkChildBuffers()
5355 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5356 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5357 for (; it != en; ++it) {
5358 DocIterator dit = it->second;
5359 Buffer * cbuf = const_cast<Buffer *>(it->first);
5360 if (!cbuf || !theBufferList().isLoaded(cbuf))
5362 Inset * inset = dit.nextInset();
5363 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5364 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5365 docstring const & incfile = inset_inc->getParam("filename");
5366 string oldloc = cbuf->absFileName();
5367 string newloc = makeAbsPath(to_utf8(incfile),
5368 onlyPath(absFileName())).absFileName();
5369 if (oldloc == newloc)
5371 // the location of the child file is incorrect.
5373 inset_inc->setChildBuffer(0);
5375 // invalidate cache of children
5376 d->children_positions.clear();
5377 d->position_to_children.clear();
5381 // If a child has been saved under a different name/path, it might have been
5382 // orphaned. Therefore the master needs to be reset (bug 8161).
5383 void Buffer::checkMasterBuffer()
5385 Buffer const * const master = masterBuffer();
5389 // necessary to re-register the child (bug 5873)
5390 // FIXME: clean up updateMacros (here, only
5391 // child registering is needed).
5392 master->updateMacros();
5393 // (re)set master as master buffer, but only
5394 // if we are a real child
5395 if (master->isChild(this))
5402 string Buffer::includedFilePath(string const & name, string const & ext) const
5404 if (d->old_position.empty() ||
5405 equivalent(FileName(d->old_position), FileName(filePath())))
5408 bool isabsolute = FileName::isAbsolute(name);
5409 // both old_position and filePath() end with a path separator
5410 string absname = isabsolute ? name : d->old_position + name;
5412 // if old_position is set to origin, we need to do the equivalent of
5413 // getReferencedFileName() (see readDocument())
5414 if (!isabsolute && d->old_position == params().origin) {
5415 FileName const test(addExtension(filePath() + name, ext));
5417 absname = filePath() + name;
5420 if (!FileName(addExtension(absname, ext)).exists())
5424 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5426 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5427 from_utf8(filePath())));
5431 void Buffer::setChangesPresent(bool b) const
5433 d->tracked_changes_present_ = b;
5437 bool Buffer::areChangesPresent() const
5439 return d->tracked_changes_present_;
5443 void Buffer::updateChangesPresent() const
5445 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5446 setChangesPresent(false);
5447 ParConstIterator it = par_iterator_begin();
5448 ParConstIterator const end = par_iterator_end();
5449 for (; !areChangesPresent() && it != end; ++it)
5450 it->addChangesToBuffer(*this);
5454 void Buffer::Impl::refreshFileMonitor()
5456 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5457 file_monitor_->refresh();
5461 // The previous file monitor is invalid
5462 // This also destroys the previous file monitor and all its connections
5463 file_monitor_ = FileSystemWatcher::monitor(filename);
5464 // file_monitor_ will be destroyed with *this, so it is not going to call a
5465 // destroyed object method.
5466 file_monitor_->connect([this](bool exists) {
5467 fileExternallyModified(exists);
5472 void Buffer::Impl::fileExternallyModified(bool const exists)
5474 // ignore notifications after our own saving operations
5475 if (checksum_ == filename.checksum()) {
5476 LYXERR(Debug::FILES, "External modification but "
5477 "checksum unchanged: " << filename);
5480 // If the file has been deleted, only mark the file as dirty since it is
5481 // pointless to prompt for reloading. If later a file is moved into this
5482 // location, then the externally modified warning will appear then.
5484 externally_modified_ = true;
5485 // Update external modification notification.
5486 // Dirty buffers must be visible at all times.
5487 if (wa_ && wa_->unhide(owner_))
5488 wa_->updateTitles();
5490 // Unable to unhide the buffer (e.g. no GUI or not current View)
5495 bool Buffer::notifiesExternalModification() const
5497 return d->externally_modified_;
5501 void Buffer::clearExternalModification() const
5503 d->externally_modified_ = false;
5505 d->wa_->updateTitles();