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::cloneFromMaster() const
576 cloned_buffers.push_back(new CloneList);
577 CloneList * clones = cloned_buffers.back();
579 masterBuffer()->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.");
1059 // assure we have a default index
1060 params().indiceslist().addDefault(B_("Index"));
1063 if (FileName::isAbsolute(params().origin))
1064 d->old_position = params().origin;
1066 d->old_position = filePath();
1067 bool const res = text().read(lex, errorList, d->inset);
1068 d->old_position.clear();
1070 // inform parent buffer about local macros
1072 Buffer const * pbuf = parent();
1073 UserMacroSet::const_iterator cit = usermacros.begin();
1074 UserMacroSet::const_iterator end = usermacros.end();
1075 for (; cit != end; ++cit)
1076 pbuf->usermacros.insert(*cit);
1080 updateMacroInstances(InternalUpdate);
1085 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1087 Format const * fmt = theFormats().getFormat(format);
1090 // It is important to use the correct extension here, since some
1091 // converters create a wrong output file otherwise (e.g. html2latex)
1092 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1093 ofdocstream os(name.toFilesystemEncoding().c_str());
1094 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1095 bool const success = !(os << contents).fail();
1098 bool converted = false;
1100 params().compressed = false;
1102 // remove dummy empty par
1103 paragraphs().clear();
1105 converted = importFile(format, name, errorList);
1108 removeTempFile(name);
1113 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1115 if (!theConverters().isReachable(format, "lyx"))
1118 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1119 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList)) {
1120 bool const success = readFile(lyx) == ReadSuccess;
1121 removeTempFile(lyx);
1129 bool Buffer::readString(string const & s)
1131 params().compressed = false;
1134 istringstream is(s);
1136 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1137 FileName const fn = tempfile.name();
1140 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1142 if (success && file_format != LYX_FORMAT) {
1143 // We need to call lyx2lyx, so write the input to a file
1144 ofstream os(fn.toFilesystemEncoding().c_str());
1147 // lyxvc in readFile
1148 if (readFile(fn) != ReadSuccess)
1152 if (readDocument(lex))
1158 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1162 if (!lex.setFile(fname)) {
1163 Alert::error(_("File Not Found"),
1164 bformat(_("Unable to open file `%1$s'."),
1165 from_utf8(fn.absFileName())));
1166 return ReadFileNotFound;
1170 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1171 if (ret_plf != ReadSuccess)
1174 if (file_format != LYX_FORMAT) {
1176 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1177 if (ret_clf != ReadSuccess)
1179 ret_clf = readFile(tmpFile);
1180 if (ret_clf == ReadSuccess) {
1181 d->file_format = file_format;
1182 d->need_format_backup = true;
1187 // FIXME: InsetInfo needs to know whether the file is under VCS
1188 // during the parse process, so this has to be done before.
1189 lyxvc().file_found_hook(d->filename);
1191 if (readDocument(lex)) {
1192 Alert::error(_("Document format failure"),
1193 bformat(_("%1$s ended unexpectedly, which means"
1194 " that it is probably corrupted."),
1195 from_utf8(fn.absFileName())));
1196 return ReadDocumentFailure;
1199 d->file_fully_loaded = true;
1200 d->read_only = !d->filename.isWritable();
1201 params().compressed = theFormats().isZippedFile(d->filename);
1207 bool Buffer::isFullyLoaded() const
1209 return d->file_fully_loaded;
1213 void Buffer::setFullyLoaded(bool value)
1215 d->file_fully_loaded = value;
1219 bool Buffer::lastPreviewError() const
1221 return d->preview_error_;
1225 PreviewLoader * Buffer::loader() const
1227 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1229 if (!d->preview_loader_)
1230 d->preview_loader_ = new PreviewLoader(*this);
1231 return d->preview_loader_;
1235 void Buffer::removePreviews() const
1237 delete d->preview_loader_;
1238 d->preview_loader_ = 0;
1242 void Buffer::updatePreviews() const
1244 PreviewLoader * ploader = loader();
1248 InsetIterator it = inset_iterator_begin(*d->inset);
1249 InsetIterator const end = inset_iterator_end(*d->inset);
1250 for (; it != end; ++it)
1251 it->addPreview(it, *ploader);
1253 ploader->startLoading();
1257 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1258 FileName const & fn, int & file_format) const
1260 if(!lex.checkFor("\\lyxformat")) {
1261 Alert::error(_("Document format failure"),
1262 bformat(_("%1$s is not a readable LyX document."),
1263 from_utf8(fn.absFileName())));
1264 return ReadNoLyXFormat;
1270 // LyX formats 217 and earlier were written as 2.17. This corresponds
1271 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1272 // these cases. See also: www.lyx.org/trac/changeset/1313.
1273 size_t dot = tmp_format.find_first_of(".,");
1274 if (dot != string::npos)
1275 tmp_format.erase(dot, 1);
1277 file_format = convert<int>(tmp_format);
1282 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1283 FileName & tmpfile, int from_format)
1285 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1286 tempfile.setAutoRemove(false);
1287 tmpfile = tempfile.name();
1288 if(tmpfile.empty()) {
1289 Alert::error(_("Conversion failed"),
1290 bformat(_("%1$s is from a different"
1291 " version of LyX, but a temporary"
1292 " file for converting it could"
1293 " not be created."),
1294 from_utf8(fn.absFileName())));
1295 return LyX2LyXNoTempFile;
1298 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1299 if (lyx2lyx.empty()) {
1300 Alert::error(_("Conversion script not found"),
1301 bformat(_("%1$s is from a different"
1302 " version of LyX, but the"
1303 " conversion script lyx2lyx"
1304 " could not be found."),
1305 from_utf8(fn.absFileName())));
1306 return LyX2LyXNotFound;
1310 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1311 ostringstream command;
1312 command << os::python()
1313 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1314 << " -t " << convert<string>(LYX_FORMAT)
1315 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1316 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1317 string const command_str = command.str();
1319 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1321 cmd_ret const ret = runCommand(command_str);
1322 if (ret.first != 0) {
1323 if (from_format < LYX_FORMAT) {
1324 Alert::error(_("Conversion script failed"),
1325 bformat(_("%1$s is from an older version"
1326 " of LyX and the lyx2lyx script"
1327 " failed to convert it."),
1328 from_utf8(fn.absFileName())));
1329 return LyX2LyXOlderFormat;
1331 Alert::error(_("Conversion script failed"),
1332 bformat(_("%1$s is from a newer version"
1333 " of LyX and the lyx2lyx script"
1334 " failed to convert it."),
1335 from_utf8(fn.absFileName())));
1336 return LyX2LyXNewerFormat;
1343 FileName Buffer::getBackupName() const {
1344 FileName const & fn = fileName();
1345 string const fname = fn.onlyFileNameWithoutExt();
1346 string const fext = fn.extension() + "~";
1347 string const fpath = lyxrc.backupdir_path.empty() ?
1348 fn.onlyPath().absFileName() :
1349 lyxrc.backupdir_path;
1350 string const fform = convert<string>(d->file_format);
1351 string const backname = fname + "-lyxformat-" + fform;
1352 FileName backup(addName(fpath, addExtension(backname, fext)));
1354 // limit recursion, just in case
1356 unsigned long orig_checksum = 0;
1357 while (backup.exists() && v < 100) {
1358 if (orig_checksum == 0)
1359 orig_checksum = fn.checksum();
1360 unsigned long new_checksum = backup.checksum();
1361 if (orig_checksum == new_checksum) {
1362 LYXERR(Debug::FILES, "Not backing up " << fn <<
1363 "since " << backup << "has the same checksum.");
1364 // a bit of a hack, but we have to check this anyway
1365 // below, and setting this is simpler than introducing
1366 // a special boolean for this purpose.
1370 string const newbackname = backname + "-" + convert<string>(v);
1371 backup.set(addName(fpath, addExtension(newbackname, fext)));
1374 return v < 100 ? backup : FileName();
1378 // Should probably be moved to somewhere else: BufferView? GuiView?
1379 bool Buffer::save() const
1381 docstring const file = makeDisplayPath(absFileName(), 20);
1382 d->filename.refresh();
1384 // check the read-only status before moving the file as a backup
1385 if (d->filename.exists()) {
1386 bool const read_only = !d->filename.isWritable();
1388 Alert::warning(_("File is read-only"),
1389 bformat(_("The file %1$s cannot be written because it "
1390 "is marked as read-only."), file));
1395 // ask if the disk file has been externally modified (use checksum method)
1396 if (fileName().exists() && isChecksumModified()) {
1398 bformat(_("Document %1$s has been externally modified. "
1399 "Are you sure you want to overwrite this file?"), file);
1400 int const ret = Alert::prompt(_("Overwrite modified file?"),
1401 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1406 // We don't need autosaves in the immediate future. (Asger)
1407 resetAutosaveTimers();
1409 // if the file does not yet exist, none of the backup activity
1410 // that follows is necessary
1411 if (!fileName().exists()) {
1412 if (!writeFile(fileName()))
1418 // we first write the file to a new name, then move it to its
1419 // proper location once that has been done successfully. that
1420 // way we preserve the original file if something goes wrong.
1421 string const justname = fileName().onlyFileNameWithoutExt();
1422 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1423 justname + "-XXXXXX.lyx");
1424 bool const symlink = fileName().isSymLink();
1426 tempfile->setAutoRemove(false);
1428 FileName savefile(tempfile->name());
1429 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1430 if (!writeFile(savefile))
1433 // we will set this to false if we fail
1434 bool made_backup = true;
1436 FileName backupName;
1437 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1439 if (d->need_format_backup)
1440 backupName = getBackupName();
1442 // If we for some reason failed to find a backup name in case of
1443 // a format change, this will still set one. It's the best we can
1445 if (backupName.empty()) {
1446 backupName.set(fileName().absFileName() + "~");
1447 if (!lyxrc.backupdir_path.empty()) {
1448 string const mangledName =
1449 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1450 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1454 LYXERR(Debug::FILES, "Backing up original file to " <<
1455 backupName.absFileName());
1456 // Except file is symlink do not copy because of #6587.
1457 // Hard links have bad luck.
1458 made_backup = symlink ?
1459 fileName().copyTo(backupName):
1460 fileName().moveTo(backupName);
1463 Alert::error(_("Backup failure"),
1464 bformat(_("Cannot create backup file %1$s.\n"
1465 "Please check whether the directory exists and is writable."),
1466 from_utf8(backupName.absFileName())));
1467 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1468 } else if (d->need_format_backup) {
1469 // the original file has been backed up successfully, so we
1470 // will not need to do that again
1471 d->need_format_backup = false;
1475 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1476 // Only do this if tempfile is not in autoremove mode
1479 // If we have no symlink, we can simply rename the temp file.
1480 // Otherwise, we need to copy it so the symlink stays intact.
1481 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1482 savefile.moveTo(fileName()))
1484 // saveCheckSum() was already called by writeFile(), but the
1485 // time stamp is invalidated by copying/moving
1488 if (d->file_format != LYX_FORMAT)
1489 // the file associated with this buffer is now in the current format
1490 d->file_format = LYX_FORMAT;
1493 // else we saved the file, but failed to move it to the right location.
1495 if (needBackup && made_backup && !symlink) {
1496 // the original file was moved to some new location, so it will look
1497 // to the user as if it was deleted. (see bug #9234.) we could try
1498 // to restore it, but that would basically mean trying to do again
1499 // what we just failed to do. better to leave things as they are.
1500 Alert::error(_("Write failure"),
1501 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1502 "But LyX could not move it to:\n %2$s.\n"
1503 "Your original file has been backed up to:\n %3$s"),
1504 from_utf8(savefile.absFileName()),
1505 from_utf8(fileName().absFileName()),
1506 from_utf8(backupName.absFileName())));
1508 // either we did not try to make a backup, or else we tried and failed,
1509 // or else the original file was a symlink, in which case it was copied,
1510 // not moved. so the original file is intact.
1511 Alert::error(_("Write failure"),
1512 bformat(_("Cannot move saved file to:\n %1$s.\n"
1513 "But the file has successfully been saved as:\n %2$s."),
1514 from_utf8(fileName().absFileName()),
1515 from_utf8(savefile.absFileName())));
1521 bool Buffer::writeFile(FileName const & fname) const
1523 if (d->read_only && fname == d->filename)
1526 bool retval = false;
1528 docstring const str = bformat(_("Saving document %1$s..."),
1529 makeDisplayPath(fname.absFileName()));
1532 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1534 if (params().compressed) {
1535 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1536 retval = ofs && write(ofs);
1538 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1539 retval = ofs && write(ofs);
1543 message(str + _(" could not write file!"));
1548 // removeAutosaveFile();
1551 message(str + _(" done."));
1557 docstring Buffer::emergencyWrite()
1559 // No need to save if the buffer has not changed.
1563 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1565 docstring user_message = bformat(
1566 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1568 // We try to save three places:
1569 // 1) Same place as document. Unless it is an unnamed doc.
1571 string s = absFileName();
1574 if (writeFile(FileName(s))) {
1576 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1577 return user_message;
1579 user_message += " " + _("Save failed! Trying again...\n");
1583 // 2) In HOME directory.
1584 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1586 lyxerr << ' ' << s << endl;
1587 if (writeFile(FileName(s))) {
1589 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1590 return user_message;
1593 user_message += " " + _("Save failed! Trying yet again...\n");
1595 // 3) In "/tmp" directory.
1596 // MakeAbsPath to prepend the current
1597 // drive letter on OS/2
1598 s = addName(package().temp_dir().absFileName(), absFileName());
1600 lyxerr << ' ' << s << endl;
1601 if (writeFile(FileName(s))) {
1603 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1604 return user_message;
1607 user_message += " " + _("Save failed! Document is lost.");
1610 return user_message;
1614 bool Buffer::write(ostream & ofs) const
1617 // Use the standard "C" locale for file output.
1618 ofs.imbue(locale::classic());
1621 // The top of the file should not be written by params().
1623 // write out a comment in the top of the file
1624 // Important: Keep the version formatting in sync with lyx2lyx and
1625 // tex2lyx (bug 7951)
1626 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1627 << " created this file. For more info see http://www.lyx.org/\n"
1628 << "\\lyxformat " << LYX_FORMAT << "\n"
1629 << "\\begin_document\n";
1631 /// For each author, set 'used' to true if there is a change
1632 /// by this author in the document; otherwise set it to 'false'.
1633 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1634 AuthorList::Authors::const_iterator a_end = params().authors().end();
1635 for (; a_it != a_end; ++a_it)
1636 a_it->setUsed(false);
1638 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1639 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1640 for ( ; it != end; ++it)
1641 it->checkAuthors(params().authors());
1643 // now write out the buffer parameters.
1644 ofs << "\\begin_header\n";
1645 params().writeFile(ofs, this);
1646 ofs << "\\end_header\n";
1649 ofs << "\n\\begin_body\n";
1651 ofs << "\n\\end_body\n";
1653 // Write marker that shows file is complete
1654 ofs << "\\end_document" << endl;
1656 // Shouldn't really be needed....
1659 // how to check if close went ok?
1660 // Following is an attempt... (BE 20001011)
1662 // good() returns false if any error occurred, including some
1663 // formatting error.
1664 // bad() returns true if something bad happened in the buffer,
1665 // which should include file system full errors.
1670 lyxerr << "File was not closed properly." << endl;
1677 bool Buffer::makeLaTeXFile(FileName const & fname,
1678 string const & original_path,
1679 OutputParams const & runparams_in,
1680 OutputWhat output) const
1682 OutputParams runparams = runparams_in;
1684 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1685 // Check here, because the "flavor" is not known in BufferParams::encoding()
1686 // (power users can override this safety measure selecting "utf8-plain").
1687 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1688 && (runparams.encoding->name() != "utf8-plain"))
1689 runparams.encoding = encodings.fromLyXName("ascii");
1691 string const encoding = runparams.encoding->iconvName();
1692 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1695 try { ofs.reset(encoding); }
1696 catch (iconv_codecvt_facet_exception const & e) {
1697 lyxerr << "Caught iconv exception: " << e.what() << endl;
1698 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1699 "verify that the support software for your encoding (%1$s) is "
1700 "properly installed"), from_ascii(encoding)));
1703 if (!openFileWrite(ofs, fname))
1706 ErrorList & errorList = d->errorLists["Export"];
1708 bool failed_export = false;
1711 // make sure we are ready to export
1712 // this needs to be done before we validate
1713 // FIXME Do we need to do this all the time? I.e., in children
1714 // of a master we are exporting?
1716 updateMacroInstances(OutputUpdate);
1719 writeLaTeXSource(os, original_path, runparams, output);
1721 catch (EncodingException const & e) {
1722 docstring const failed(1, e.failed_char);
1724 oss << "0x" << hex << e.failed_char << dec;
1725 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1726 " (code point %2$s)"),
1727 failed, from_utf8(oss.str()));
1728 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1729 "representable in the chosen encoding.\n"
1730 "Changing the document encoding to utf8 could help."),
1731 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1732 failed_export = true;
1734 catch (iconv_codecvt_facet_exception const & e) {
1735 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1737 failed_export = true;
1739 catch (exception const & e) {
1740 errorList.push_back(ErrorItem(_("conversion failed"),
1742 lyxerr << e.what() << endl;
1743 failed_export = true;
1746 lyxerr << "Caught some really weird exception..." << endl;
1750 d->texrow = move(os.texrow());
1754 failed_export = true;
1755 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1758 if (runparams_in.silent)
1762 return !failed_export;
1766 void Buffer::writeLaTeXSource(otexstream & os,
1767 string const & original_path,
1768 OutputParams const & runparams_in,
1769 OutputWhat output) const
1771 // The child documents, if any, shall be already loaded at this point.
1773 OutputParams runparams = runparams_in;
1775 // XeTeX with TeX fonts is only safe with ASCII encoding,
1776 // Check here, because the "flavor" is not known in BufferParams::encoding()
1777 // (power users can override this safety measure selecting "utf8-plain").
1778 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1779 && (runparams.encoding->name() != "utf8-plain"))
1780 runparams.encoding = encodings.fromLyXName("ascii");
1781 // FIXME: when only the current paragraph is shown, this is ignored
1782 // (or not reached) and characters encodable in the current
1783 // encoding are not converted to ASCII-representation.
1785 // If we are compiling a file standalone, even if this is the
1786 // child of some other buffer, let's cut the link here, so the
1787 // file is really independent and no concurring settings from
1788 // the master (e.g. branch state) interfere (see #8100).
1789 if (!runparams.is_child)
1790 d->ignore_parent = true;
1792 // Classify the unicode characters appearing in math insets
1793 BufferEncodings::initUnicodeMath(*this);
1795 // validate the buffer.
1796 LYXERR(Debug::LATEX, " Validating buffer...");
1797 LaTeXFeatures features(*this, params(), runparams);
1799 // This is only set once per document (in master)
1800 if (!runparams.is_child)
1801 runparams.use_polyglossia = features.usePolyglossia();
1802 LYXERR(Debug::LATEX, " Buffer validation done.");
1804 bool const output_preamble =
1805 output == FullSource || output == OnlyPreamble;
1806 bool const output_body =
1807 output == FullSource || output == OnlyBody;
1809 // The starting paragraph of the coming rows is the
1810 // first paragraph of the document. (Asger)
1811 if (output_preamble && runparams.nice) {
1812 os << "%% LyX " << lyx_version << " created this file. "
1813 "For more info, see http://www.lyx.org/.\n"
1814 "%% Do not edit unless you really know what "
1817 LYXERR(Debug::INFO, "lyx document header finished");
1819 // There are a few differences between nice LaTeX and usual files:
1820 // usual files have \batchmode and special input@path to allow
1821 // inclusion of figures specified by an explicitly relative path
1822 // (i.e., a path starting with './' or '../') with either \input or
1823 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1824 // input@path is set when the actual parameter original_path is set.
1825 // This is done for usual tex-file, but not for nice-latex-file.
1826 // (Matthias 250696)
1827 // Note that input@path is only needed for something the user does
1828 // in the preamble, included .tex files or ERT, files included by
1829 // LyX work without it.
1830 if (output_preamble) {
1831 if (!runparams.nice) {
1832 // code for usual, NOT nice-latex-file
1833 os << "\\batchmode\n"; // changed from \nonstopmode
1835 if (!original_path.empty()) {
1837 // We don't know the encoding of inputpath
1838 docstring const inputpath = from_utf8(original_path);
1839 docstring uncodable_glyphs;
1840 Encoding const * const enc = runparams.encoding;
1842 for (size_t n = 0; n < inputpath.size(); ++n) {
1843 if (!enc->encodable(inputpath[n])) {
1844 docstring const glyph(1, inputpath[n]);
1845 LYXERR0("Uncodable character '"
1847 << "' in input path!");
1848 uncodable_glyphs += glyph;
1853 // warn user if we found uncodable glyphs.
1854 if (!uncodable_glyphs.empty()) {
1855 frontend::Alert::warning(
1856 _("Uncodable character in file path"),
1858 _("The path of your document\n"
1860 "contains glyphs that are unknown "
1861 "in the current document encoding "
1862 "(namely %2$s). This may result in "
1863 "incomplete output, unless "
1864 "TEXINPUTS contains the document "
1865 "directory and you don't use "
1866 "explicitly relative paths (i.e., "
1867 "paths starting with './' or "
1868 "'../') in the preamble or in ERT."
1869 "\n\nIn case of problems, choose "
1870 "an appropriate document encoding\n"
1871 "(such as utf8) or change the "
1873 inputpath, uncodable_glyphs));
1876 support::latex_path(original_path);
1877 if (contains(docdir, '#')) {
1878 docdir = subst(docdir, "#", "\\#");
1879 os << "\\catcode`\\#=11"
1880 "\\def\\#{#}\\catcode`\\#=6\n";
1882 if (contains(docdir, '%')) {
1883 docdir = subst(docdir, "%", "\\%");
1884 os << "\\catcode`\\%=11"
1885 "\\def\\%{%}\\catcode`\\%=14\n";
1887 os << "\\makeatletter\n"
1888 << "\\def\\input@path{{"
1890 << "\\makeatother\n";
1894 // get parent macros (if this buffer has a parent) which will be
1895 // written at the document begin further down.
1896 MacroSet parentMacros;
1897 listParentMacros(parentMacros, features);
1899 // Write the preamble
1900 runparams.use_babel = params().writeLaTeX(os, features,
1901 d->filename.onlyPath());
1903 // Biblatex bibliographies are loaded here
1904 if (params().useBiblatex()) {
1905 vector<docstring> const bibfiles =
1906 prepareBibFilePaths(runparams, getBibfiles(), true);
1907 for (docstring const & file: bibfiles)
1908 os << "\\addbibresource{" << file << "}\n";
1911 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1912 && !features.hasOnlyPolyglossiaLanguages()) {
1915 vector<string> bll = features.getBabelExclusiveLanguages();
1916 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1919 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1924 blangs = bll.size() > 1 ?
1925 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1926 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1930 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1935 plangs = pll.size() > 1 ?
1936 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1937 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1938 if (!blangs.empty())
1942 frontend::Alert::warning(
1943 _("Incompatible Languages!"),
1945 _("You cannot use the following languages "
1946 "together in one LaTeX document because "
1947 "they require conflicting language packages:\n"
1952 // Japanese might be required only in some children of a document,
1953 // but once required, we must keep use_japanese true.
1954 runparams.use_japanese |= features.isRequired("japanese");
1957 // Restore the parenthood if needed
1958 if (!runparams.is_child)
1959 d->ignore_parent = false;
1964 // mark the beginning of the body to separate it from InPreamble insets
1965 os.texrow().start(TexRow::beginDocument());
1966 os << "\\begin{document}\n";
1968 // mark the start of a new paragraph by simulating a newline,
1969 // so that os.afterParbreak() returns true at document start
1972 // output the parent macros
1973 MacroSet::iterator it = parentMacros.begin();
1974 MacroSet::iterator end = parentMacros.end();
1975 for (; it != end; ++it) {
1976 int num_lines = (*it)->write(os.os(), true);
1977 os.texrow().newlines(num_lines);
1980 } // output_preamble
1982 LYXERR(Debug::INFO, "preamble finished, now the body.");
1985 latexParagraphs(*this, text(), os, runparams);
1987 // Restore the parenthood if needed
1988 if (!runparams.is_child)
1989 d->ignore_parent = false;
1991 // add this just in case after all the paragraphs
1994 if (output_preamble) {
1995 os << "\\end{document}\n";
1996 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1998 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2000 runparams_in.encoding = runparams.encoding;
2002 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2003 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2007 void Buffer::makeDocBookFile(FileName const & fname,
2008 OutputParams const & runparams,
2009 OutputWhat output) const
2011 LYXERR(Debug::LATEX, "makeDocBookFile...");
2014 if (!openFileWrite(ofs, fname))
2017 // make sure we are ready to export
2018 // this needs to be done before we validate
2020 updateMacroInstances(OutputUpdate);
2022 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2026 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2030 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2031 OutputParams const & runparams,
2032 OutputWhat output) const
2034 LaTeXFeatures features(*this, params(), runparams);
2039 DocumentClass const & tclass = params().documentClass();
2040 string const & top_element = tclass.latexname();
2042 bool const output_preamble =
2043 output == FullSource || output == OnlyPreamble;
2044 bool const output_body =
2045 output == FullSource || output == OnlyBody;
2047 if (output_preamble) {
2048 if (runparams.flavor == OutputParams::XML)
2049 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2052 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2055 if (! tclass.class_header().empty())
2056 os << from_ascii(tclass.class_header());
2057 else if (runparams.flavor == OutputParams::XML)
2058 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2059 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2061 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2063 docstring preamble = params().preamble;
2064 if (runparams.flavor != OutputParams::XML ) {
2065 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2066 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2067 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2068 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2071 string const name = runparams.nice
2072 ? changeExtension(absFileName(), ".sgml") : fname;
2073 preamble += features.getIncludedFiles(name);
2074 preamble += features.getLyXSGMLEntities();
2076 if (!preamble.empty()) {
2077 os << "\n [ " << preamble << " ]";
2083 string top = top_element;
2085 if (runparams.flavor == OutputParams::XML)
2086 top += params().language->code();
2088 top += params().language->code().substr(0, 2);
2091 if (!params().options.empty()) {
2093 top += params().options;
2096 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2097 << " file was created by LyX " << lyx_version
2098 << "\n See http://www.lyx.org/ for more information -->\n";
2100 params().documentClass().counters().reset();
2102 sgml::openTag(os, top);
2104 docbookParagraphs(text(), *this, os, runparams);
2105 sgml::closeTag(os, top_element);
2110 void Buffer::makeLyXHTMLFile(FileName const & fname,
2111 OutputParams const & runparams) const
2113 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2116 if (!openFileWrite(ofs, fname))
2119 // make sure we are ready to export
2120 // this has to be done before we validate
2121 updateBuffer(UpdateMaster, OutputUpdate);
2122 updateMacroInstances(OutputUpdate);
2124 writeLyXHTMLSource(ofs, runparams, FullSource);
2128 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2132 void Buffer::writeLyXHTMLSource(odocstream & os,
2133 OutputParams const & runparams,
2134 OutputWhat output) const
2136 LaTeXFeatures features(*this, params(), runparams);
2138 d->bibinfo_.makeCitationLabels(*this);
2140 bool const output_preamble =
2141 output == FullSource || output == OnlyPreamble;
2142 bool const output_body =
2143 output == FullSource || output == OnlyBody || output == IncludedFile;
2145 if (output_preamble) {
2146 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2147 << "<!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"
2148 // FIXME Language should be set properly.
2149 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2151 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2152 // FIXME Presumably need to set this right
2153 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2155 docstring const & doctitle = features.htmlTitle();
2157 << (doctitle.empty() ?
2158 from_ascii("LyX Document") :
2159 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2162 docstring styles = features.getTClassHTMLPreamble();
2163 if (!styles.empty())
2164 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2166 styles = features.getPreambleSnippets().str;
2167 if (!styles.empty())
2168 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2170 // we will collect CSS information in a stream, and then output it
2171 // either here, as part of the header, or else in a separate file.
2172 odocstringstream css;
2173 styles = features.getCSSSnippets();
2174 if (!styles.empty())
2175 css << "/* LyX Provided Styles */\n" << styles << '\n';
2177 styles = features.getTClassHTMLStyles();
2178 if (!styles.empty())
2179 css << "/* Layout-provided Styles */\n" << styles << '\n';
2181 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2182 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2183 if (needfg || needbg) {
2184 css << "\nbody {\n";
2187 << from_ascii(X11hexname(params().fontcolor))
2190 css << " background-color: "
2191 << from_ascii(X11hexname(params().backgroundcolor))
2196 docstring const dstyles = css.str();
2197 if (!dstyles.empty()) {
2198 bool written = false;
2199 if (params().html_css_as_file) {
2200 // open a file for CSS info
2202 string const fcssname = addName(temppath(), "docstyle.css");
2203 FileName const fcssfile = FileName(fcssname);
2204 if (openFileWrite(ocss, fcssfile)) {
2208 // write link to header
2209 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2211 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2214 // we are here if the CSS is supposed to be written to the header
2215 // or if we failed to write it to an external file.
2217 os << "<style type='text/css'>\n"
2226 bool const output_body_tag = (output != IncludedFile);
2227 if (output_body_tag)
2228 os << "<body dir=\"auto\">\n";
2230 if (output != IncludedFile)
2231 // if we're an included file, the counters are in the master.
2232 params().documentClass().counters().reset();
2233 xhtmlParagraphs(text(), *this, xs, runparams);
2234 if (output_body_tag)
2238 if (output_preamble)
2243 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2244 // Other flags: -wall -v0 -x
2245 int Buffer::runChktex()
2249 // get LaTeX-Filename
2250 FileName const path(temppath());
2251 string const name = addName(path.absFileName(), latexName());
2252 string const org_path = filePath();
2254 PathChanger p(path); // path to LaTeX file
2255 message(_("Running chktex..."));
2257 // Generate the LaTeX file if neccessary
2258 OutputParams runparams(¶ms().encoding());
2259 runparams.flavor = OutputParams::LATEX;
2260 runparams.nice = false;
2261 runparams.linelen = lyxrc.plaintext_linelen;
2262 makeLaTeXFile(FileName(name), org_path, runparams);
2265 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2266 int const res = chktex.run(terr); // run chktex
2269 Alert::error(_("chktex failure"),
2270 _("Could not run chktex successfully."));
2272 ErrorList & errlist = d->errorLists["ChkTeX"];
2274 bufferErrors(terr, errlist);
2279 if (runparams.silent)
2280 d->errorLists["ChkTeX"].clear();
2288 void Buffer::validate(LaTeXFeatures & features) const
2290 // Validate the buffer params, but not for included
2291 // files, since they also use the parent buffer's
2293 if (!features.runparams().is_child)
2294 params().validate(features);
2296 for (Paragraph const & p : paragraphs())
2297 p.validate(features);
2299 if (lyxerr.debugging(Debug::LATEX)) {
2300 features.showStruct();
2305 void Buffer::getLabelList(vector<docstring> & list) const
2307 // If this is a child document, use the master's list instead.
2309 masterBuffer()->getLabelList(list);
2314 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2315 Toc::const_iterator toc_it = toc->begin();
2316 Toc::const_iterator end = toc->end();
2317 for (; toc_it != end; ++toc_it) {
2318 if (toc_it->depth() == 0)
2319 list.push_back(toc_it->str());
2324 void Buffer::updateBibfilesCache(UpdateScope scope) const
2326 // FIXME This is probably unnecssary, given where we call this.
2327 // If this is a child document, use the parent's cache instead.
2328 if (parent() && scope != UpdateChildOnly) {
2329 masterBuffer()->updateBibfilesCache();
2333 d->bibfiles_cache_.clear();
2334 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2335 if (it->lyxCode() == BIBTEX_CODE) {
2336 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2337 docstring_list const bibfiles = inset.getBibFiles();
2338 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2341 } else if (it->lyxCode() == INCLUDE_CODE) {
2342 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2343 Buffer const * const incbuf = inset.getChildBuffer();
2346 docstring_list const & bibfiles =
2347 incbuf->getBibfiles(UpdateChildOnly);
2348 if (!bibfiles.empty()) {
2349 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2355 d->bibfile_cache_valid_ = true;
2356 d->bibinfo_cache_valid_ = false;
2357 d->cite_labels_valid_ = false;
2361 void Buffer::invalidateBibinfoCache() const
2363 d->bibinfo_cache_valid_ = false;
2364 d->cite_labels_valid_ = false;
2365 // also invalidate the cache for the parent buffer
2366 Buffer const * const pbuf = d->parent();
2368 pbuf->invalidateBibinfoCache();
2372 docstring_list const & Buffer::getBibfiles(UpdateScope scope) const
2374 // FIXME This is probably unnecessary, given where we call this.
2375 // If this is a child document, use the master's cache instead.
2376 Buffer const * const pbuf = masterBuffer();
2377 if (pbuf != this && scope != UpdateChildOnly)
2378 return pbuf->getBibfiles();
2380 if (!d->bibfile_cache_valid_)
2381 this->updateBibfilesCache(scope);
2383 return d->bibfiles_cache_;
2387 BiblioInfo const & Buffer::masterBibInfo() const
2389 Buffer const * const tmp = masterBuffer();
2391 return tmp->masterBibInfo();
2396 BiblioInfo const & Buffer::bibInfo() const
2402 void Buffer::registerBibfiles(const docstring_list & bf) const
2404 // We register the bib files in the master buffer,
2405 // if there is one, but also in every single buffer,
2406 // in case a child is compiled alone.
2407 Buffer const * const tmp = masterBuffer();
2409 tmp->registerBibfiles(bf);
2411 for (auto const & p : bf) {
2412 docstring_list::const_iterator temp =
2413 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2414 if (temp == d->bibfiles_cache_.end())
2415 d->bibfiles_cache_.push_back(p);
2420 static map<docstring, FileName> bibfileCache;
2422 FileName Buffer::getBibfilePath(docstring const & bibid) const
2424 map<docstring, FileName>::const_iterator it =
2425 bibfileCache.find(bibid);
2426 if (it != bibfileCache.end()) {
2427 // i.e., bibfileCache[bibid]
2431 LYXERR(Debug::FILES, "Reading file location for " << bibid);
2432 string texfile = changeExtension(to_utf8(bibid), "bib");
2433 // note that, if the filename can be found directly from the path,
2434 // findtexfile will just return a FileName object for that path.
2435 FileName file(findtexfile(texfile, "bib"));
2437 file = FileName(makeAbsPath(texfile, filePath()));
2438 LYXERR(Debug::FILES, "Found at: " << file);
2440 bibfileCache[bibid] = file;
2441 return bibfileCache[bibid];
2445 void Buffer::checkIfBibInfoCacheIsValid() const
2447 // use the master's cache
2448 Buffer const * const tmp = masterBuffer();
2450 tmp->checkIfBibInfoCacheIsValid();
2454 // compare the cached timestamps with the actual ones.
2455 docstring_list const & bibfiles_cache = getBibfiles();
2456 for (auto const & bf : bibfiles_cache) {
2457 FileName const fn = getBibfilePath(bf);
2458 time_t lastw = fn.lastModified();
2459 time_t prevw = d->bibfile_status_[fn];
2460 if (lastw != prevw) {
2461 d->bibinfo_cache_valid_ = false;
2462 d->cite_labels_valid_ = false;
2463 d->bibfile_status_[fn] = lastw;
2469 void Buffer::reloadBibInfoCache() const
2471 // use the master's cache
2472 Buffer const * const tmp = masterBuffer();
2474 tmp->reloadBibInfoCache();
2478 checkIfBibInfoCacheIsValid();
2479 if (d->bibinfo_cache_valid_)
2482 // re-read file locations when this info changes
2483 // FIXME Is this sufficient? Or should we also force that
2484 // in some other cases? If so, then it is easy enough to
2485 // add the following line in some other places.
2486 bibfileCache.clear();
2487 d->bibinfo_.clear();
2488 FileNameList checkedFiles;
2489 collectBibKeys(checkedFiles);
2490 d->bibinfo_cache_valid_ = true;
2494 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2496 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2497 it->collectBibKeys(it, checkedFiles);
2501 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2503 // We add the biblio info to the master buffer,
2504 // if there is one, but also to every single buffer,
2505 // in case a child is compiled alone.
2506 BiblioInfo & bi = d->bibinfo_;
2507 bi.mergeBiblioInfo(bin);
2509 if (parent() != 0) {
2510 BiblioInfo & masterbi = parent()->d->bibinfo_;
2511 masterbi.mergeBiblioInfo(bin);
2516 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2518 // We add the bibtex info to the master buffer,
2519 // if there is one, but also to every single buffer,
2520 // in case a child is compiled alone.
2521 BiblioInfo & bi = d->bibinfo_;
2524 if (parent() != 0) {
2525 BiblioInfo & masterbi = parent()->d->bibinfo_;
2526 masterbi[key] = bin;
2531 void Buffer::makeCitationLabels() const
2533 Buffer const * const master = masterBuffer();
2534 return d->bibinfo_.makeCitationLabels(*master);
2538 void Buffer::invalidateCiteLabels() const
2540 masterBuffer()->d->cite_labels_valid_ = false;
2543 bool Buffer::citeLabelsValid() const
2545 return masterBuffer()->d->cite_labels_valid_;
2549 void Buffer::removeBiblioTempFiles() const
2551 // We remove files that contain LaTeX commands specific to the
2552 // particular bibliographic style being used, in order to avoid
2553 // LaTeX errors when we switch style.
2554 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2555 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2556 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2557 aux_file.removeFile();
2558 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2559 bbl_file.removeFile();
2560 // Also for the parent buffer
2561 Buffer const * const pbuf = parent();
2563 pbuf->removeBiblioTempFiles();
2567 bool Buffer::isDepClean(string const & name) const
2569 DepClean::const_iterator const it = d->dep_clean.find(name);
2570 if (it == d->dep_clean.end())
2576 void Buffer::markDepClean(string const & name)
2578 d->dep_clean[name] = true;
2582 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2585 // FIXME? if there is an Buffer LFUN that can be dispatched even
2586 // if internal, put a switch '(cmd.action)' here.
2592 switch (cmd.action()) {
2594 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2595 flag.setOnOff(hasReadonlyFlag());
2598 // FIXME: There is need for a command-line import.
2599 //case LFUN_BUFFER_IMPORT:
2601 case LFUN_BUFFER_AUTO_SAVE:
2604 case LFUN_BUFFER_EXPORT_CUSTOM:
2605 // FIXME: Nothing to check here?
2608 case LFUN_BUFFER_EXPORT: {
2609 docstring const arg = cmd.argument();
2610 if (arg == "custom") {
2614 string format = (arg.empty() || arg == "default") ?
2615 params().getDefaultOutputFormat() : to_utf8(arg);
2616 size_t pos = format.find(' ');
2617 if (pos != string::npos)
2618 format = format.substr(0, pos);
2619 enable = params().isExportable(format, false);
2621 flag.message(bformat(
2622 _("Don't know how to export to format: %1$s"), arg));
2626 case LFUN_BUILD_PROGRAM:
2627 enable = params().isExportable("program", false);
2630 case LFUN_BRANCH_ACTIVATE:
2631 case LFUN_BRANCH_DEACTIVATE:
2632 case LFUN_BRANCH_MASTER_ACTIVATE:
2633 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2634 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2635 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2636 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2637 : params().branchlist();
2638 docstring const branchName = cmd.argument();
2639 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2643 case LFUN_BRANCH_ADD:
2644 case LFUN_BRANCHES_RENAME:
2645 // if no Buffer is present, then of course we won't be called!
2648 case LFUN_BUFFER_LANGUAGE:
2649 enable = !isReadonly();
2652 case LFUN_BUFFER_VIEW_CACHE:
2653 (d->preview_file_).refresh();
2654 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2657 case LFUN_CHANGES_TRACK:
2658 flag.setEnabled(true);
2659 flag.setOnOff(params().track_changes);
2662 case LFUN_CHANGES_OUTPUT:
2663 flag.setEnabled(true);
2664 flag.setOnOff(params().output_changes);
2667 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2668 flag.setOnOff(params().compressed);
2671 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2672 flag.setOnOff(params().output_sync);
2675 case LFUN_BUFFER_ANONYMIZE:
2681 flag.setEnabled(enable);
2686 void Buffer::dispatch(string const & command, DispatchResult & result)
2688 return dispatch(lyxaction.lookupFunc(command), result);
2692 // NOTE We can end up here even if we have no GUI, because we are called
2693 // by LyX::exec to handled command-line requests. So we may need to check
2694 // whether we have a GUI or not. The boolean use_gui holds this information.
2695 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2698 // FIXME? if there is an Buffer LFUN that can be dispatched even
2699 // if internal, put a switch '(cmd.action())' here.
2700 dr.dispatched(false);
2703 string const argument = to_utf8(func.argument());
2704 // We'll set this back to false if need be.
2705 bool dispatched = true;
2706 // This handles undo groups automagically
2707 UndoGroupHelper ugh(this);
2709 switch (func.action()) {
2710 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2711 if (lyxvc().inUse()) {
2712 string log = lyxvc().toggleReadOnly();
2717 setReadonly(!hasReadonlyFlag());
2720 case LFUN_BUFFER_EXPORT: {
2721 string const format = (argument.empty() || argument == "default") ?
2722 params().getDefaultOutputFormat() : argument;
2723 ExportStatus const status = doExport(format, false);
2724 dr.setError(status != ExportSuccess);
2725 if (status != ExportSuccess)
2726 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2727 from_utf8(format)));
2731 case LFUN_BUILD_PROGRAM: {
2732 ExportStatus const status = doExport("program", true);
2733 dr.setError(status != ExportSuccess);
2734 if (status != ExportSuccess)
2735 dr.setMessage(_("Error generating literate programming code."));
2739 case LFUN_BUFFER_EXPORT_CUSTOM: {
2741 string command = split(argument, format_name, ' ');
2742 Format const * format = theFormats().getFormat(format_name);
2744 lyxerr << "Format \"" << format_name
2745 << "\" not recognized!"
2750 // The name of the file created by the conversion process
2753 // Output to filename
2754 if (format->name() == "lyx") {
2755 string const latexname = latexName(false);
2756 filename = changeExtension(latexname,
2757 format->extension());
2758 filename = addName(temppath(), filename);
2760 if (!writeFile(FileName(filename)))
2764 doExport(format_name, true, filename);
2767 // Substitute $$FName for filename
2768 if (!contains(command, "$$FName"))
2769 command = "( " + command + " ) < $$FName";
2770 command = subst(command, "$$FName", filename);
2772 // Execute the command in the background
2774 call.startscript(Systemcall::DontWait, command,
2775 filePath(), layoutPos());
2779 // FIXME: There is need for a command-line import.
2781 case LFUN_BUFFER_IMPORT:
2786 case LFUN_BUFFER_AUTO_SAVE:
2788 resetAutosaveTimers();
2791 case LFUN_BRANCH_ACTIVATE:
2792 case LFUN_BRANCH_DEACTIVATE:
2793 case LFUN_BRANCH_MASTER_ACTIVATE:
2794 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2795 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2796 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2797 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2800 docstring const branch_name = func.argument();
2801 // the case without a branch name is handled elsewhere
2802 if (branch_name.empty()) {
2806 Branch * branch = buf->params().branchlist().find(branch_name);
2808 LYXERR0("Branch " << branch_name << " does not exist.");
2810 docstring const msg =
2811 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2815 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2816 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2817 if (branch->isSelected() != activate) {
2818 buf->undo().recordUndoBufferParams(CursorData());
2819 branch->setSelected(activate);
2821 dr.screenUpdate(Update::Force);
2822 dr.forceBufferUpdate();
2827 case LFUN_BRANCH_ADD: {
2828 docstring branch_name = func.argument();
2829 if (branch_name.empty()) {
2833 BranchList & branch_list = params().branchlist();
2834 vector<docstring> const branches =
2835 getVectorFromString(branch_name, branch_list.separator());
2837 for (vector<docstring>::const_iterator it = branches.begin();
2838 it != branches.end(); ++it) {
2840 Branch * branch = branch_list.find(branch_name);
2842 LYXERR0("Branch " << branch_name << " already exists.");
2846 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2848 undo().recordUndoBufferParams(CursorData());
2849 branch_list.add(branch_name);
2850 branch = branch_list.find(branch_name);
2851 string const x11hexname = X11hexname(branch->color());
2852 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2853 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2855 dr.screenUpdate(Update::Force);
2863 case LFUN_BRANCHES_RENAME: {
2864 if (func.argument().empty())
2867 docstring const oldname = from_utf8(func.getArg(0));
2868 docstring const newname = from_utf8(func.getArg(1));
2869 InsetIterator it = inset_iterator_begin(inset());
2870 InsetIterator const end = inset_iterator_end(inset());
2871 bool success = false;
2872 for (; it != end; ++it) {
2873 if (it->lyxCode() == BRANCH_CODE) {
2874 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2875 if (ins.branch() == oldname) {
2876 undo().recordUndo(CursorData(it));
2877 ins.rename(newname);
2882 if (it->lyxCode() == INCLUDE_CODE) {
2883 // get buffer of external file
2884 InsetInclude const & ins =
2885 static_cast<InsetInclude const &>(*it);
2886 Buffer * child = ins.getChildBuffer();
2889 child->dispatch(func, dr);
2894 dr.screenUpdate(Update::Force);
2895 dr.forceBufferUpdate();
2900 case LFUN_BUFFER_VIEW_CACHE:
2901 if (!theFormats().view(*this, d->preview_file_,
2902 d->preview_format_))
2903 dr.setMessage(_("Error viewing the output file."));
2906 case LFUN_CHANGES_TRACK:
2907 if (params().save_transient_properties)
2908 undo().recordUndoBufferParams(CursorData());
2909 params().track_changes = !params().track_changes;
2910 if (!params().track_changes)
2911 dr.forceChangesUpdate();
2914 case LFUN_CHANGES_OUTPUT:
2915 if (params().save_transient_properties)
2916 undo().recordUndoBufferParams(CursorData());
2917 params().output_changes = !params().output_changes;
2918 if (params().output_changes) {
2919 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2920 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2921 LaTeXFeatures::isAvailable("xcolor");
2923 if (!dvipost && !xcolorulem) {
2924 Alert::warning(_("Changes not shown in LaTeX output"),
2925 _("Changes will not be highlighted in LaTeX output, "
2926 "because neither dvipost nor xcolor/ulem are installed.\n"
2927 "Please install these packages or redefine "
2928 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2929 } else if (!xcolorulem) {
2930 Alert::warning(_("Changes not shown in LaTeX output"),
2931 _("Changes will not be highlighted in LaTeX output "
2932 "when using pdflatex, because xcolor and ulem are not installed.\n"
2933 "Please install both packages or redefine "
2934 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2939 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2940 // turn compression on/off
2941 undo().recordUndoBufferParams(CursorData());
2942 params().compressed = !params().compressed;
2945 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2946 undo().recordUndoBufferParams(CursorData());
2947 params().output_sync = !params().output_sync;
2950 case LFUN_BUFFER_ANONYMIZE: {
2951 undo().recordUndoFullBuffer(CursorData());
2952 CursorData cur(doc_iterator_begin(this));
2953 for ( ; cur ; cur.forwardPar())
2954 cur.paragraph().anonymize();
2955 dr.forceBufferUpdate();
2963 dr.dispatched(dispatched);
2967 void Buffer::changeLanguage(Language const * from, Language const * to)
2969 LASSERT(from, return);
2970 LASSERT(to, return);
2972 for_each(par_iterator_begin(),
2974 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2978 bool Buffer::isMultiLingual() const
2980 ParConstIterator end = par_iterator_end();
2981 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2982 if (it->isMultiLingual(params()))
2989 std::set<Language const *> Buffer::getLanguages() const
2991 std::set<Language const *> languages;
2992 getLanguages(languages);
2997 void Buffer::getLanguages(std::set<Language const *> & languages) const
2999 ParConstIterator end = par_iterator_end();
3000 // add the buffer language, even if it's not actively used
3001 languages.insert(language());
3002 // iterate over the paragraphs
3003 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3004 it->getLanguages(languages);
3006 ListOfBuffers clist = getDescendents();
3007 ListOfBuffers::const_iterator cit = clist.begin();
3008 ListOfBuffers::const_iterator const cen = clist.end();
3009 for (; cit != cen; ++cit)
3010 (*cit)->getLanguages(languages);
3014 DocIterator Buffer::getParFromID(int const id) const
3016 Buffer * buf = const_cast<Buffer *>(this);
3018 // This means non-existent
3019 return doc_iterator_end(buf);
3021 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3022 if (it.paragraph().id() == id)
3025 return doc_iterator_end(buf);
3029 bool Buffer::hasParWithID(int const id) const
3031 return !getParFromID(id).atEnd();
3035 ParIterator Buffer::par_iterator_begin()
3037 return ParIterator(doc_iterator_begin(this));
3041 ParIterator Buffer::par_iterator_end()
3043 return ParIterator(doc_iterator_end(this));
3047 ParConstIterator Buffer::par_iterator_begin() const
3049 return ParConstIterator(doc_iterator_begin(this));
3053 ParConstIterator Buffer::par_iterator_end() const
3055 return ParConstIterator(doc_iterator_end(this));
3059 Language const * Buffer::language() const
3061 return params().language;
3065 docstring const Buffer::B_(string const & l10n) const
3067 return params().B_(l10n);
3071 bool Buffer::isClean() const
3073 return d->lyx_clean;
3077 bool Buffer::isChecksumModified() const
3079 LASSERT(d->filename.exists(), return false);
3080 return d->checksum_ != d->filename.checksum();
3084 void Buffer::saveCheckSum() const
3086 FileName const & file = d->filename;
3088 d->checksum_ = file.exists() ? file.checksum()
3089 : 0; // in the case of save to a new file.
3093 void Buffer::markClean() const
3095 if (!d->lyx_clean) {
3096 d->lyx_clean = true;
3099 // if the .lyx file has been saved, we don't need an
3101 d->bak_clean = true;
3102 d->undo_.markDirty();
3103 clearExternalModification();
3107 void Buffer::setUnnamed(bool flag)
3113 bool Buffer::isUnnamed() const
3120 /// Don't check unnamed, here: isInternal() is used in
3121 /// newBuffer(), where the unnamed flag has not been set by anyone
3122 /// yet. Also, for an internal buffer, there should be no need for
3123 /// retrieving fileName() nor for checking if it is unnamed or not.
3124 bool Buffer::isInternal() const
3126 return d->internal_buffer;
3130 void Buffer::setInternal(bool flag)
3132 d->internal_buffer = flag;
3136 void Buffer::markDirty()
3139 d->lyx_clean = false;
3142 d->bak_clean = false;
3144 DepClean::iterator it = d->dep_clean.begin();
3145 DepClean::const_iterator const end = d->dep_clean.end();
3147 for (; it != end; ++it)
3152 FileName Buffer::fileName() const
3158 string Buffer::absFileName() const
3160 return d->filename.absFileName();
3164 string Buffer::filePath() const
3166 string const abs = d->filename.onlyPath().absFileName();
3169 int last = abs.length() - 1;
3171 return abs[last] == '/' ? abs : abs + '/';
3175 DocFileName Buffer::getReferencedFileName(string const & fn) const
3178 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3179 result.set(fn, filePath());
3181 // filePath() ends with a path separator
3182 FileName const test(filePath() + fn);
3184 result.set(fn, filePath());
3186 result.set(fn, params().origin);
3193 string const Buffer::prepareFileNameForLaTeX(string const & name,
3194 string const & ext, bool nice) const
3196 string const fname = makeAbsPath(name, filePath()).absFileName();
3197 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3203 return to_utf8(makeRelPath(from_utf8(fname),
3204 from_utf8(masterBuffer()->filePath())));
3208 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3209 docstring_list const & bibfilelist,
3210 bool const add_extension) const
3212 // If we are processing the LaTeX file in a temp directory then
3213 // copy the .bib databases to this temp directory, mangling their
3214 // names in the process. Store this mangled name in the list of
3216 // (We need to do all this because BibTeX *really*, *really*
3217 // can't handle "files with spaces" and Windows users tend to
3218 // use such filenames.)
3219 // Otherwise, store the (maybe absolute) path to the original,
3220 // unmangled database name.
3222 vector<docstring> res;
3224 // determine the export format
3225 string const tex_format = flavor2format(runparams.flavor);
3227 // check for spaces in paths
3228 bool found_space = false;
3230 for (auto const & bit : bibfilelist) {
3231 string utf8input = to_utf8(bit);
3233 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3234 FileName try_in_file =
3235 makeAbsPath(database + ".bib", filePath());
3236 bool not_from_texmf = try_in_file.isReadableFile();
3237 // If the file has not been found, try with the real file name
3238 // (it might come from a child in a sub-directory)
3239 if (!not_from_texmf) {
3240 try_in_file = getBibfilePath(bit);
3241 if (try_in_file.isReadableFile()) {
3242 // Check if the file is in texmf
3243 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3244 not_from_texmf = kpsefile.empty()
3245 || kpsefile.absFileName() != try_in_file.absFileName();
3247 // If this exists, make path relative to the master
3249 database = removeExtension(
3250 prepareFileNameForLaTeX(to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3251 from_utf8(filePath()))),
3252 ".bib", runparams.nice));
3256 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3258 // mangledFileName() needs the extension
3259 DocFileName const in_file = DocFileName(try_in_file);
3260 database = removeExtension(in_file.mangledFileName());
3261 FileName const out_file = makeAbsPath(database + ".bib",
3262 masterBuffer()->temppath());
3263 bool const success = in_file.copyTo(out_file);
3265 LYXERR0("Failed to copy '" << in_file
3266 << "' to '" << out_file << "'");
3268 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3269 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3270 if (!isValidLaTeXFileName(database)) {
3271 frontend::Alert::warning(_("Invalid filename"),
3272 _("The following filename will cause troubles "
3273 "when running the exported file through LaTeX: ") +
3274 from_utf8(database));
3276 if (!isValidDVIFileName(database)) {
3277 frontend::Alert::warning(_("Problematic filename for DVI"),
3278 _("The following filename can cause troubles "
3279 "when running the exported file through LaTeX "
3280 "and opening the resulting DVI: ") +
3281 from_utf8(database), true);
3289 docstring const path = from_utf8(latex_path(database));
3291 if (contains(path, ' '))
3294 if (find(res.begin(), res.end(), path) == res.end())
3295 res.push_back(path);
3298 // Check if there are spaces in the path and warn BibTeX users, if so.
3299 // (biber can cope with such paths)
3300 if (!prefixIs(runparams.bibtex_command, "biber")) {
3301 // Post this warning only once.
3302 static bool warned_about_spaces = false;
3303 if (!warned_about_spaces &&
3304 runparams.nice && found_space) {
3305 warned_about_spaces = true;
3306 Alert::warning(_("Export Warning!"),
3307 _("There are spaces in the paths to your BibTeX databases.\n"
3308 "BibTeX will be unable to find them."));
3317 string Buffer::layoutPos() const
3319 return d->layout_position;
3323 void Buffer::setLayoutPos(string const & path)
3326 d->layout_position.clear();
3330 LATTEST(FileName::isAbsolute(path));
3332 d->layout_position =
3333 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3335 if (d->layout_position.empty())
3336 d->layout_position = ".";
3340 bool Buffer::hasReadonlyFlag() const
3342 return d->read_only;
3346 bool Buffer::isReadonly() const
3348 return hasReadonlyFlag() || notifiesExternalModification();
3352 void Buffer::setParent(Buffer const * buffer)
3354 // Avoids recursive include.
3355 d->setParent(buffer == this ? 0 : buffer);
3360 Buffer const * Buffer::parent() const
3366 ListOfBuffers Buffer::allRelatives() const
3368 ListOfBuffers lb = masterBuffer()->getDescendents();
3369 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3374 Buffer const * Buffer::masterBuffer() const
3376 // FIXME Should be make sure we are not in some kind
3377 // of recursive include? A -> B -> A will crash this.
3378 Buffer const * const pbuf = d->parent();
3382 return pbuf->masterBuffer();
3386 bool Buffer::isChild(Buffer * child) const
3388 return d->children_positions.find(child) != d->children_positions.end();
3392 DocIterator Buffer::firstChildPosition(Buffer const * child)
3394 Impl::BufferPositionMap::iterator it;
3395 it = d->children_positions.find(child);
3396 if (it == d->children_positions.end())
3397 return DocIterator(this);
3402 bool Buffer::hasChildren() const
3404 return !d->children_positions.empty();
3408 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3410 // loop over children
3411 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3412 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3413 for (; it != end; ++it) {
3414 Buffer * child = const_cast<Buffer *>(it->first);
3416 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3417 if (bit != clist.end())
3419 clist.push_back(child);
3421 // there might be grandchildren
3422 child->collectChildren(clist, true);
3427 ListOfBuffers Buffer::getChildren() const
3430 collectChildren(v, false);
3431 // Make sure we have not included ourselves.
3432 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3433 if (bit != v.end()) {
3434 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3441 ListOfBuffers Buffer::getDescendents() const
3444 collectChildren(v, true);
3445 // Make sure we have not included ourselves.
3446 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3447 if (bit != v.end()) {
3448 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3455 template<typename M>
3456 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3461 typename M::const_iterator it = m.lower_bound(x);
3462 if (it == m.begin())
3470 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3471 DocIterator const & pos) const
3473 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3475 // if paragraphs have no macro context set, pos will be empty
3479 // we haven't found anything yet
3480 DocIterator bestPos = owner_->par_iterator_begin();
3481 MacroData const * bestData = 0;
3483 // find macro definitions for name
3484 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3485 if (nameIt != macros.end()) {
3486 // find last definition in front of pos or at pos itself
3487 PositionScopeMacroMap::const_iterator it
3488 = greatest_below(nameIt->second, pos);
3489 if (it != nameIt->second.end()) {
3491 // scope ends behind pos?
3492 if (pos < it->second.scope) {
3493 // Looks good, remember this. If there
3494 // is no external macro behind this,
3495 // we found the right one already.
3496 bestPos = it->first;
3497 bestData = &it->second.macro;
3501 // try previous macro if there is one
3502 if (it == nameIt->second.begin())
3509 // find macros in included files
3510 PositionScopeBufferMap::const_iterator it
3511 = greatest_below(position_to_children, pos);
3512 if (it == position_to_children.end())
3513 // no children before
3517 // do we know something better (i.e. later) already?
3518 if (it->first < bestPos )
3521 // scope ends behind pos?
3522 if (pos < it->second.scope
3523 && (cloned_buffer_ ||
3524 theBufferList().isLoaded(it->second.buffer))) {
3525 // look for macro in external file
3527 MacroData const * data
3528 = it->second.buffer->getMacro(name, false);
3531 bestPos = it->first;
3537 // try previous file if there is one
3538 if (it == position_to_children.begin())
3543 // return the best macro we have found
3548 MacroData const * Buffer::getMacro(docstring const & name,
3549 DocIterator const & pos, bool global) const
3554 // query buffer macros
3555 MacroData const * data = d->getBufferMacro(name, pos);
3559 // If there is a master buffer, query that
3560 Buffer const * const pbuf = d->parent();
3562 d->macro_lock = true;
3563 MacroData const * macro = pbuf->getMacro(
3564 name, *this, false);
3565 d->macro_lock = false;
3571 data = MacroTable::globalMacros().get(name);
3580 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3582 // set scope end behind the last paragraph
3583 DocIterator scope = par_iterator_begin();
3584 scope.pit() = scope.lastpit() + 1;
3586 return getMacro(name, scope, global);
3590 MacroData const * Buffer::getMacro(docstring const & name,
3591 Buffer const & child, bool global) const
3593 // look where the child buffer is included first
3594 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3595 if (it == d->children_positions.end())
3598 // check for macros at the inclusion position
3599 return getMacro(name, it->second, global);
3603 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3605 pit_type const lastpit = it.lastpit();
3607 // look for macros in each paragraph
3608 while (it.pit() <= lastpit) {
3609 Paragraph & par = it.paragraph();
3611 // iterate over the insets of the current paragraph
3612 InsetList const & insets = par.insetList();
3613 InsetList::const_iterator iit = insets.begin();
3614 InsetList::const_iterator end = insets.end();
3615 for (; iit != end; ++iit) {
3616 it.pos() = iit->pos;
3618 // is it a nested text inset?
3619 if (iit->inset->asInsetText()) {
3620 // Inset needs its own scope?
3621 InsetText const * itext = iit->inset->asInsetText();
3622 bool newScope = itext->isMacroScope();
3624 // scope which ends just behind the inset
3625 DocIterator insetScope = it;
3628 // collect macros in inset
3629 it.push_back(CursorSlice(*iit->inset));
3630 updateMacros(it, newScope ? insetScope : scope);
3635 if (iit->inset->asInsetTabular()) {
3636 CursorSlice slice(*iit->inset);
3637 size_t const numcells = slice.nargs();
3638 for (; slice.idx() < numcells; slice.forwardIdx()) {
3639 it.push_back(slice);
3640 updateMacros(it, scope);
3646 // is it an external file?
3647 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3648 // get buffer of external file
3649 InsetInclude const & inset =
3650 static_cast<InsetInclude const &>(*iit->inset);
3652 Buffer * child = inset.getChildBuffer();
3657 // register its position, but only when it is
3658 // included first in the buffer
3659 if (children_positions.find(child) ==
3660 children_positions.end())
3661 children_positions[child] = it;
3663 // register child with its scope
3664 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3668 InsetMath * im = iit->inset->asInsetMath();
3669 if (doing_export && im) {
3670 InsetMathHull * hull = im->asHullInset();
3672 hull->recordLocation(it);
3675 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3679 InsetMathMacroTemplate & macroTemplate =
3680 *iit->inset->asInsetMath()->asMacroTemplate();
3681 MacroContext mc(owner_, it);
3682 macroTemplate.updateToContext(mc);
3685 bool valid = macroTemplate.validMacro();
3686 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3687 // then the BufferView's cursor will be invalid in
3688 // some cases which leads to crashes.
3693 // FIXME (Abdel), I don't understand why we pass 'it' here
3694 // instead of 'macroTemplate' defined above... is this correct?
3695 macros[macroTemplate.name()][it] =
3696 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3706 void Buffer::updateMacros() const
3711 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3713 // start with empty table
3715 d->children_positions.clear();
3716 d->position_to_children.clear();
3718 // Iterate over buffer, starting with first paragraph
3719 // The scope must be bigger than any lookup DocIterator
3720 // later. For the global lookup, lastpit+1 is used, hence
3721 // we use lastpit+2 here.
3722 DocIterator it = par_iterator_begin();
3723 DocIterator outerScope = it;
3724 outerScope.pit() = outerScope.lastpit() + 2;
3725 d->updateMacros(it, outerScope);
3729 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3731 InsetIterator it = inset_iterator_begin(inset());
3732 InsetIterator const end = inset_iterator_end(inset());
3733 for (; it != end; ++it) {
3734 if (it->lyxCode() == BRANCH_CODE) {
3735 InsetBranch & br = static_cast<InsetBranch &>(*it);
3736 docstring const name = br.branch();
3737 if (!from_master && !params().branchlist().find(name))
3738 result.push_back(name);
3739 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3740 result.push_back(name);
3743 if (it->lyxCode() == INCLUDE_CODE) {
3744 // get buffer of external file
3745 InsetInclude const & ins =
3746 static_cast<InsetInclude const &>(*it);
3747 Buffer * child = ins.getChildBuffer();
3750 child->getUsedBranches(result, true);
3753 // remove duplicates
3758 void Buffer::updateMacroInstances(UpdateType utype) const
3760 LYXERR(Debug::MACROS, "updateMacroInstances for "
3761 << d->filename.onlyFileName());
3762 DocIterator it = doc_iterator_begin(this);
3764 DocIterator const end = doc_iterator_end(this);
3765 for (; it != end; it.forwardInset()) {
3766 // look for MathData cells in InsetMathNest insets
3767 InsetMath * minset = it.nextInset()->asInsetMath();
3771 // update macro in all cells of the InsetMathNest
3772 DocIterator::idx_type n = minset->nargs();
3773 MacroContext mc = MacroContext(this, it);
3774 for (DocIterator::idx_type i = 0; i < n; ++i) {
3775 MathData & data = minset->cell(i);
3776 data.updateMacros(0, mc, utype, 0);
3782 void Buffer::listMacroNames(MacroNameSet & macros) const
3787 d->macro_lock = true;
3789 // loop over macro names
3790 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3791 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3792 for (; nameIt != nameEnd; ++nameIt)
3793 macros.insert(nameIt->first);
3795 // loop over children
3796 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3797 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3798 for (; it != end; ++it) {
3799 Buffer * child = const_cast<Buffer *>(it->first);
3800 // The buffer might have been closed (see #10766).
3801 if (theBufferList().isLoaded(child))
3802 child->listMacroNames(macros);
3806 Buffer const * const pbuf = d->parent();
3808 pbuf->listMacroNames(macros);
3810 d->macro_lock = false;
3814 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3816 Buffer const * const pbuf = d->parent();
3821 pbuf->listMacroNames(names);
3824 MacroNameSet::iterator it = names.begin();
3825 MacroNameSet::iterator end = names.end();
3826 for (; it != end; ++it) {
3828 MacroData const * data =
3829 pbuf->getMacro(*it, *this, false);
3831 macros.insert(data);
3833 // we cannot access the original InsetMathMacroTemplate anymore
3834 // here to calls validate method. So we do its work here manually.
3835 // FIXME: somehow make the template accessible here.
3836 if (data->optionals() > 0)
3837 features.require("xargs");
3843 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3846 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3848 RefCache::iterator it = d->ref_cache_.find(label);
3849 if (it != d->ref_cache_.end())
3850 return it->second.second;
3852 static InsetLabel const * dummy_il = 0;
3853 static References const dummy_refs = References();
3854 it = d->ref_cache_.insert(
3855 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3856 return it->second.second;
3860 Buffer::References const & Buffer::references(docstring const & label) const
3862 return const_cast<Buffer *>(this)->getReferenceCache(label);
3866 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3868 References & refs = getReferenceCache(label);
3869 refs.push_back(make_pair(inset, it));
3873 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3875 masterBuffer()->d->ref_cache_[label].first = il;
3879 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3881 return masterBuffer()->d->ref_cache_[label].first;
3885 void Buffer::clearReferenceCache() const
3888 d->ref_cache_.clear();
3892 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3894 //FIXME: This does not work for child documents yet.
3895 reloadBibInfoCache();
3897 // Check if the label 'from' appears more than once
3898 BiblioInfo const & keys = masterBibInfo();
3899 BiblioInfo::const_iterator bit = keys.begin();
3900 BiblioInfo::const_iterator bend = keys.end();
3901 vector<docstring> labels;
3903 for (; bit != bend; ++bit)
3905 labels.push_back(bit->first);
3907 if (count(labels.begin(), labels.end(), from) > 1)
3910 string const paramName = "key";
3911 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3912 if (it->lyxCode() != CITE_CODE)
3914 InsetCommand * inset = it->asInsetCommand();
3915 docstring const oldValue = inset->getParam(paramName);
3916 if (oldValue == from)
3917 inset->setParam(paramName, to);
3921 // returns NULL if id-to-row conversion is unsupported
3922 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3923 pit_type par_begin, pit_type par_end,
3924 OutputWhat output, bool master) const
3926 unique_ptr<TexRow> texrow;
3927 OutputParams runparams(¶ms().encoding());
3928 runparams.nice = true;
3929 runparams.flavor = params().getOutputFlavor(format);
3930 runparams.linelen = lyxrc.plaintext_linelen;
3931 // No side effect of file copying and image conversion
3932 runparams.dryrun = true;
3934 if (output == CurrentParagraph) {
3935 runparams.par_begin = par_begin;
3936 runparams.par_end = par_end;
3937 if (par_begin + 1 == par_end) {
3939 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3943 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3944 convert<docstring>(par_begin),
3945 convert<docstring>(par_end - 1))
3948 // output paragraphs
3949 if (runparams.flavor == OutputParams::LYX) {
3950 Paragraph const & par = text().paragraphs()[par_begin];
3952 depth_type dt = par.getDepth();
3953 par.write(ods, params(), dt);
3954 os << from_utf8(ods.str());
3955 } else if (runparams.flavor == OutputParams::HTML) {
3957 setMathFlavor(runparams);
3958 xhtmlParagraphs(text(), *this, xs, runparams);
3959 } else if (runparams.flavor == OutputParams::TEXT) {
3961 // FIXME Handles only one paragraph, unlike the others.
3962 // Probably should have some routine with a signature like them.
3963 writePlaintextParagraph(*this,
3964 text().paragraphs()[par_begin], os, runparams, dummy);
3965 } else if (params().isDocBook()) {
3966 docbookParagraphs(text(), *this, os, runparams);
3968 // If we are previewing a paragraph, even if this is the
3969 // child of some other buffer, let's cut the link here,
3970 // so that no concurring settings from the master
3971 // (e.g. branch state) interfere (see #8101).
3973 d->ignore_parent = true;
3974 // We need to validate the Buffer params' features here
3975 // in order to know if we should output polyglossia
3976 // macros (instead of babel macros)
3977 LaTeXFeatures features(*this, params(), runparams);
3979 runparams.use_polyglossia = features.usePolyglossia();
3980 // latex or literate
3983 ots.texrow().newlines(2);
3985 latexParagraphs(*this, text(), ots, runparams);
3986 texrow = ots.releaseTexRow();
3988 // Restore the parenthood
3990 d->ignore_parent = false;
3994 if (output == FullSource)
3995 os << _("Preview source code");
3996 else if (output == OnlyPreamble)
3997 os << _("Preview preamble");
3998 else if (output == OnlyBody)
3999 os << _("Preview body");
4001 if (runparams.flavor == OutputParams::LYX) {
4003 if (output == FullSource)
4005 else if (output == OnlyPreamble)
4006 params().writeFile(ods, this);
4007 else if (output == OnlyBody)
4009 os << from_utf8(ods.str());
4010 } else if (runparams.flavor == OutputParams::HTML) {
4011 writeLyXHTMLSource(os, runparams, output);
4012 } else if (runparams.flavor == OutputParams::TEXT) {
4013 if (output == OnlyPreamble) {
4014 os << "% "<< _("Plain text does not have a preamble.");
4016 writePlaintextFile(*this, os, runparams);
4017 } else if (params().isDocBook()) {
4018 writeDocBookSource(os, absFileName(), runparams, output);
4020 // latex or literate
4023 ots.texrow().newlines(2);
4025 runparams.is_child = true;
4027 writeLaTeXSource(ots, string(), runparams, output);
4028 texrow = ots.releaseTexRow();
4035 ErrorList & Buffer::errorList(string const & type) const
4037 return d->errorLists[type];
4041 void Buffer::updateTocItem(std::string const & type,
4042 DocIterator const & dit) const
4045 d->gui_->updateTocItem(type, dit);
4049 void Buffer::structureChanged() const
4052 d->gui_->structureChanged();
4056 void Buffer::errors(string const & err, bool from_master) const
4059 d->gui_->errors(err, from_master);
4063 void Buffer::message(docstring const & msg) const
4066 d->gui_->message(msg);
4070 void Buffer::setBusy(bool on) const
4073 d->gui_->setBusy(on);
4077 void Buffer::updateTitles() const
4080 d->wa_->updateTitles();
4084 void Buffer::resetAutosaveTimers() const
4087 d->gui_->resetAutosaveTimers();
4091 bool Buffer::hasGuiDelegate() const
4097 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4106 class AutoSaveBuffer : public ForkedProcess {
4109 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4110 : buffer_(buffer), fname_(fname) {}
4112 virtual shared_ptr<ForkedProcess> clone() const
4114 return make_shared<AutoSaveBuffer>(*this);
4119 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4120 from_utf8(fname_.absFileName())));
4121 return run(DontWait);
4125 virtual int generateChild();
4127 Buffer const & buffer_;
4132 int AutoSaveBuffer::generateChild()
4134 #if defined(__APPLE__)
4135 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4136 * We should use something else like threads.
4138 * Since I do not know how to determine at run time what is the OS X
4139 * version, I just disable forking altogether for now (JMarc)
4141 pid_t const pid = -1;
4143 // tmp_ret will be located (usually) in /tmp
4144 // will that be a problem?
4145 // Note that this calls ForkedCalls::fork(), so it's
4146 // ok cross-platform.
4147 pid_t const pid = fork();
4148 // If you want to debug the autosave
4149 // you should set pid to -1, and comment out the fork.
4150 if (pid != 0 && pid != -1)
4154 // pid = -1 signifies that lyx was unable
4155 // to fork. But we will do the save
4157 bool failed = false;
4158 TempFile tempfile("lyxautoXXXXXX.lyx");
4159 tempfile.setAutoRemove(false);
4160 FileName const tmp_ret = tempfile.name();
4161 if (!tmp_ret.empty()) {
4162 if (!buffer_.writeFile(tmp_ret))
4164 else if (!tmp_ret.moveTo(fname_))
4170 // failed to write/rename tmp_ret so try writing direct
4171 if (!buffer_.writeFile(fname_)) {
4172 // It is dangerous to do this in the child,
4173 // but safe in the parent, so...
4174 if (pid == -1) // emit message signal.
4175 buffer_.message(_("Autosave failed!"));
4179 if (pid == 0) // we are the child so...
4188 FileName Buffer::getEmergencyFileName() const
4190 return FileName(d->filename.absFileName() + ".emergency");
4194 FileName Buffer::getAutosaveFileName() const
4196 // if the document is unnamed try to save in the backup dir, else
4197 // in the default document path, and as a last try in the filePath,
4198 // which will most often be the temporary directory
4201 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4202 : lyxrc.backupdir_path;
4203 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4206 string const fname = "#" + d->filename.onlyFileName() + "#";
4208 return makeAbsPath(fname, fpath);
4212 void Buffer::removeAutosaveFile() const
4214 FileName const f = getAutosaveFileName();
4220 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4222 FileName const newauto = getAutosaveFileName();
4224 if (newauto != oldauto && oldauto.exists())
4225 if (!oldauto.moveTo(newauto))
4226 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4230 bool Buffer::autoSave() const
4232 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4233 if (buf->d->bak_clean || hasReadonlyFlag())
4236 message(_("Autosaving current document..."));
4237 buf->d->bak_clean = true;
4239 FileName const fname = getAutosaveFileName();
4240 LASSERT(d->cloned_buffer_, return false);
4242 // If this buffer is cloned, we assume that
4243 // we are running in a separate thread already.
4244 TempFile tempfile("lyxautoXXXXXX.lyx");
4245 tempfile.setAutoRemove(false);
4246 FileName const tmp_ret = tempfile.name();
4247 if (!tmp_ret.empty()) {
4249 // assume successful write of tmp_ret
4250 if (tmp_ret.moveTo(fname))
4253 // failed to write/rename tmp_ret so try writing direct
4254 return writeFile(fname);
4258 void Buffer::setExportStatus(bool e) const
4260 d->doing_export = e;
4261 ListOfBuffers clist = getDescendents();
4262 ListOfBuffers::const_iterator cit = clist.begin();
4263 ListOfBuffers::const_iterator const cen = clist.end();
4264 for (; cit != cen; ++cit)
4265 (*cit)->d->doing_export = e;
4269 bool Buffer::isExporting() const
4271 return d->doing_export;
4275 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4279 return doExport(target, put_in_tempdir, result_file);
4282 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4283 string & result_file) const
4285 bool const update_unincluded =
4286 params().maintain_unincluded_children
4287 && !params().getIncludedChildren().empty();
4289 // (1) export with all included children (omit \includeonly)
4290 if (update_unincluded) {
4291 ExportStatus const status =
4292 doExport(target, put_in_tempdir, true, result_file);
4293 if (status != ExportSuccess)
4296 // (2) export with included children only
4297 return doExport(target, put_in_tempdir, false, result_file);
4301 void Buffer::setMathFlavor(OutputParams & op) const
4303 switch (params().html_math_output) {
4304 case BufferParams::MathML:
4305 op.math_flavor = OutputParams::MathAsMathML;
4307 case BufferParams::HTML:
4308 op.math_flavor = OutputParams::MathAsHTML;
4310 case BufferParams::Images:
4311 op.math_flavor = OutputParams::MathAsImages;
4313 case BufferParams::LaTeX:
4314 op.math_flavor = OutputParams::MathAsLaTeX;
4320 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4321 bool includeall, string & result_file) const
4323 LYXERR(Debug::FILES, "target=" << target);
4324 OutputParams runparams(¶ms().encoding());
4325 string format = target;
4326 string dest_filename;
4327 size_t pos = target.find(' ');
4328 if (pos != string::npos) {
4329 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4330 format = target.substr(0, pos);
4331 if (format == "default")
4332 format = params().getDefaultOutputFormat();
4333 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4334 FileName(dest_filename).onlyPath().createPath();
4335 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4337 MarkAsExporting exporting(this);
4338 string backend_format;
4339 runparams.flavor = OutputParams::LATEX;
4340 runparams.linelen = lyxrc.plaintext_linelen;
4341 runparams.includeall = includeall;
4342 vector<string> backs = params().backends();
4343 Converters converters = theConverters();
4344 bool need_nice_file = false;
4345 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4346 // Get shortest path to format
4347 converters.buildGraph();
4348 Graph::EdgePath path;
4349 for (vector<string>::const_iterator it = backs.begin();
4350 it != backs.end(); ++it) {
4351 Graph::EdgePath p = converters.getPath(*it, format);
4352 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4353 backend_format = *it;
4358 if (!put_in_tempdir) {
4359 // Only show this alert if this is an export to a non-temporary
4360 // file (not for previewing).
4361 Alert::error(_("Couldn't export file"), bformat(
4362 _("No information for exporting the format %1$s."),
4363 theFormats().prettyName(format)));
4365 return ExportNoPathToFormat;
4367 runparams.flavor = converters.getFlavor(path, this);
4368 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4369 Graph::EdgePath::const_iterator it = path.begin();
4370 Graph::EdgePath::const_iterator en = path.end();
4371 for (; it != en; ++it)
4372 if (theConverters().get(*it).nice()) {
4373 need_nice_file = true;
4378 backend_format = format;
4379 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4380 // FIXME: Don't hardcode format names here, but use a flag
4381 if (backend_format == "pdflatex")
4382 runparams.flavor = OutputParams::PDFLATEX;
4383 else if (backend_format == "luatex")
4384 runparams.flavor = OutputParams::LUATEX;
4385 else if (backend_format == "dviluatex")
4386 runparams.flavor = OutputParams::DVILUATEX;
4387 else if (backend_format == "xetex")
4388 runparams.flavor = OutputParams::XETEX;
4391 string filename = latexName(false);
4392 filename = addName(temppath(), filename);
4393 filename = changeExtension(filename,
4394 theFormats().extension(backend_format));
4395 LYXERR(Debug::FILES, "filename=" << filename);
4397 // Plain text backend
4398 if (backend_format == "text") {
4399 runparams.flavor = OutputParams::TEXT;
4400 writePlaintextFile(*this, FileName(filename), runparams);
4403 else if (backend_format == "xhtml") {
4404 runparams.flavor = OutputParams::HTML;
4405 setMathFlavor(runparams);
4406 makeLyXHTMLFile(FileName(filename), runparams);
4407 } else if (backend_format == "lyx")
4408 writeFile(FileName(filename));
4410 else if (params().isDocBook()) {
4411 runparams.nice = !put_in_tempdir;
4412 makeDocBookFile(FileName(filename), runparams);
4415 else if (backend_format == format || need_nice_file) {
4416 runparams.nice = true;
4417 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4418 if (d->cloned_buffer_)
4419 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4422 } else if (!lyxrc.tex_allows_spaces
4423 && contains(filePath(), ' ')) {
4424 Alert::error(_("File name error"),
4425 bformat(_("The directory path to the document\n%1$s\n"
4426 "contains spaces, but your TeX installation does "
4427 "not allow them. You should save the file to a directory "
4428 "whose name does not contain spaces."), from_ascii(filePath())));
4429 return ExportTexPathHasSpaces;
4431 runparams.nice = false;
4432 bool const success = makeLaTeXFile(
4433 FileName(filename), filePath(), runparams);
4434 if (d->cloned_buffer_)
4435 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4440 string const error_type = (format == "program")
4441 ? "Build" : params().bufferFormat();
4442 ErrorList & error_list = d->errorLists[error_type];
4443 string const ext = theFormats().extension(format);
4444 FileName const tmp_result_file(changeExtension(filename, ext));
4445 bool const success = converters.convert(this, FileName(filename),
4446 tmp_result_file, FileName(absFileName()), backend_format, format,
4449 // Emit the signal to show the error list or copy it back to the
4450 // cloned Buffer so that it can be emitted afterwards.
4451 if (format != backend_format) {
4452 if (runparams.silent)
4454 else if (d->cloned_buffer_)
4455 d->cloned_buffer_->d->errorLists[error_type] =
4456 d->errorLists[error_type];
4459 // also to the children, in case of master-buffer-view
4460 ListOfBuffers clist = getDescendents();
4461 ListOfBuffers::const_iterator cit = clist.begin();
4462 ListOfBuffers::const_iterator const cen = clist.end();
4463 for (; cit != cen; ++cit) {
4464 if (runparams.silent)
4465 (*cit)->d->errorLists[error_type].clear();
4466 else if (d->cloned_buffer_) {
4467 // Enable reverse search by copying back the
4468 // texrow object to the cloned buffer.
4469 // FIXME: this is not thread safe.
4470 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4471 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4472 (*cit)->d->errorLists[error_type];
4474 (*cit)->errors(error_type, true);
4478 if (d->cloned_buffer_) {
4479 // Enable reverse dvi or pdf to work by copying back the texrow
4480 // object to the cloned buffer.
4481 // FIXME: There is a possibility of concurrent access to texrow
4482 // here from the main GUI thread that should be securized.
4483 d->cloned_buffer_->d->texrow = d->texrow;
4484 string const error_type = params().bufferFormat();
4485 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4489 if (put_in_tempdir) {
4490 result_file = tmp_result_file.absFileName();
4491 return success ? ExportSuccess : ExportConverterError;
4494 if (dest_filename.empty())
4495 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4497 result_file = dest_filename;
4498 // We need to copy referenced files (e. g. included graphics
4499 // if format == "dvi") to the result dir.
4500 vector<ExportedFile> const files =
4501 runparams.exportdata->externalFiles(format);
4502 string const dest = runparams.export_folder.empty() ?
4503 onlyPath(result_file) : runparams.export_folder;
4504 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4505 : force_overwrite == ALL_FILES;
4506 CopyStatus status = use_force ? FORCE : SUCCESS;
4508 vector<ExportedFile>::const_iterator it = files.begin();
4509 vector<ExportedFile>::const_iterator const en = files.end();
4510 for (; it != en && status != CANCEL; ++it) {
4511 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4512 string fixedName = it->exportName;
4513 if (!runparams.export_folder.empty()) {
4514 // Relative pathnames starting with ../ will be sanitized
4515 // if exporting to a different folder
4516 while (fixedName.substr(0, 3) == "../")
4517 fixedName = fixedName.substr(3, fixedName.length() - 3);
4519 FileName fixedFileName = makeAbsPath(fixedName, dest);
4520 fixedFileName.onlyPath().createPath();
4521 status = copyFile(fmt, it->sourceName,
4523 it->exportName, status == FORCE,
4524 runparams.export_folder.empty());
4527 if (status == CANCEL) {
4528 message(_("Document export cancelled."));
4529 return ExportCancel;
4532 if (tmp_result_file.exists()) {
4533 // Finally copy the main file
4534 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4535 : force_overwrite != NO_FILES;
4536 if (status == SUCCESS && use_force)
4538 status = copyFile(format, tmp_result_file,
4539 FileName(result_file), result_file,
4541 if (status == CANCEL) {
4542 message(_("Document export cancelled."));
4543 return ExportCancel;
4545 message(bformat(_("Document exported as %1$s "
4547 theFormats().prettyName(format),
4548 makeDisplayPath(result_file)));
4551 // This must be a dummy converter like fax (bug 1888)
4552 message(bformat(_("Document exported as %1$s"),
4553 theFormats().prettyName(format)));
4556 return success ? ExportSuccess : ExportConverterError;
4560 Buffer::ExportStatus Buffer::preview(string const & format) const
4562 bool const update_unincluded =
4563 params().maintain_unincluded_children
4564 && !params().getIncludedChildren().empty();
4565 return preview(format, update_unincluded);
4569 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4571 MarkAsExporting exporting(this);
4573 // (1) export with all included children (omit \includeonly)
4575 ExportStatus const status = doExport(format, true, true, result_file);
4576 if (status != ExportSuccess)
4579 // (2) export with included children only
4580 ExportStatus const status = doExport(format, true, false, result_file);
4581 FileName const previewFile(result_file);
4583 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4584 theimpl->preview_file_ = previewFile;
4585 theimpl->preview_format_ = format;
4586 theimpl->preview_error_ = (status != ExportSuccess);
4588 if (status != ExportSuccess)
4591 if (previewFile.exists())
4592 return theFormats().view(*this, previewFile, format) ?
4593 PreviewSuccess : PreviewError;
4595 // Successful export but no output file?
4596 // Probably a bug in error detection.
4597 LATTEST(status != ExportSuccess);
4602 Buffer::ReadStatus Buffer::extractFromVC()
4604 bool const found = LyXVC::file_not_found_hook(d->filename);
4606 return ReadFileNotFound;
4607 if (!d->filename.isReadableFile())
4613 Buffer::ReadStatus Buffer::loadEmergency()
4615 FileName const emergencyFile = getEmergencyFileName();
4616 if (!emergencyFile.exists()
4617 || emergencyFile.lastModified() <= d->filename.lastModified())
4618 return ReadFileNotFound;
4620 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4621 docstring const text = bformat(_("An emergency save of the document "
4622 "%1$s exists.\n\nRecover emergency save?"), file);
4624 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4625 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4631 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4632 bool const success = (ret_llf == ReadSuccess);
4634 if (hasReadonlyFlag()) {
4635 Alert::warning(_("File is read-only"),
4636 bformat(_("An emergency file is successfully loaded, "
4637 "but the original file %1$s is marked read-only. "
4638 "Please make sure to save the document as a different "
4639 "file."), from_utf8(d->filename.absFileName())));
4642 lyxvc().file_found_hook(d->filename);
4643 str = _("Document was successfully recovered.");
4645 str = _("Document was NOT successfully recovered.");
4646 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4647 makeDisplayPath(emergencyFile.absFileName()));
4649 int const del_emerg =
4650 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4651 _("&Remove"), _("&Keep"));
4652 if (del_emerg == 0) {
4653 emergencyFile.removeFile();
4655 Alert::warning(_("Emergency file deleted"),
4656 _("Do not forget to save your file now!"), true);
4658 return success ? ReadSuccess : ReadEmergencyFailure;
4661 int const del_emerg =
4662 Alert::prompt(_("Delete emergency file?"),
4663 _("Remove emergency file now?"), 1, 1,
4664 _("&Remove"), _("&Keep"));
4666 emergencyFile.removeFile();
4667 return ReadOriginal;
4677 Buffer::ReadStatus Buffer::loadAutosave()
4679 // Now check if autosave file is newer.
4680 FileName const autosaveFile = getAutosaveFileName();
4681 if (!autosaveFile.exists()
4682 || autosaveFile.lastModified() <= d->filename.lastModified())
4683 return ReadFileNotFound;
4685 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4686 docstring const text = bformat(_("The backup of the document %1$s "
4687 "is newer.\n\nLoad the backup instead?"), file);
4688 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4689 _("&Load backup"), _("Load &original"), _("&Cancel"));
4694 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4695 // the file is not saved if we load the autosave file.
4696 if (ret_llf == ReadSuccess) {
4697 if (hasReadonlyFlag()) {
4698 Alert::warning(_("File is read-only"),
4699 bformat(_("A backup file is successfully loaded, "
4700 "but the original file %1$s is marked read-only. "
4701 "Please make sure to save the document as a "
4703 from_utf8(d->filename.absFileName())));
4706 lyxvc().file_found_hook(d->filename);
4709 return ReadAutosaveFailure;
4712 // Here we delete the autosave
4713 autosaveFile.removeFile();
4714 return ReadOriginal;
4722 Buffer::ReadStatus Buffer::loadLyXFile()
4724 if (!d->filename.isReadableFile()) {
4725 ReadStatus const ret_rvc = extractFromVC();
4726 if (ret_rvc != ReadSuccess)
4730 ReadStatus const ret_re = loadEmergency();
4731 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4734 ReadStatus const ret_ra = loadAutosave();
4735 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4738 return loadThisLyXFile(d->filename);
4742 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4744 return readFile(fn);
4748 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4750 for (auto const & err : terr) {
4751 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4752 int errorRow = err.error_in_line;
4753 Buffer const * buf = 0;
4755 if (err.child_name.empty())
4756 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4758 // The error occurred in a child
4759 for (Buffer const * child : getDescendents()) {
4760 string const child_name =
4761 DocFileName(changeExtension(child->absFileName(), "tex")).
4763 if (err.child_name != child_name)
4765 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4766 if (!TexRow::isNone(start)) {
4767 buf = d->cloned_buffer_
4768 ? child->d->cloned_buffer_->d->owner_
4775 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4781 void Buffer::setBuffersForInsets() const
4783 inset().setBuffer(const_cast<Buffer &>(*this));
4787 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4789 LBUFERR(!text().paragraphs().empty());
4791 // Use the master text class also for child documents
4792 Buffer const * const master = masterBuffer();
4793 DocumentClass const & textclass = master->params().documentClass();
4795 docstring_list old_bibfiles;
4796 // Do this only if we are the top-level Buffer. We also need to account
4797 // for the case of a previewed child with ignored parent here.
4798 if (master == this && !d->ignore_parent) {
4799 textclass.counters().reset(from_ascii("bibitem"));
4800 reloadBibInfoCache();
4803 // keep the buffers to be children in this set. If the call from the
4804 // master comes back we can see which of them were actually seen (i.e.
4805 // via an InsetInclude). The remaining ones in the set need still be updated.
4806 static std::set<Buffer const *> bufToUpdate;
4807 if (scope == UpdateMaster) {
4808 // If this is a child document start with the master
4809 if (master != this) {
4810 bufToUpdate.insert(this);
4811 master->updateBuffer(UpdateMaster, utype);
4812 // If the master buffer has no gui associated with it, then the TocModel is
4813 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4814 // (bug 5699). The same happens if the master buffer is open in a different
4815 // window. This test catches both possibilities.
4816 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4817 // There remains a problem here: If there is another child open in yet a third
4818 // window, that TOC is not updated. So some more general solution is needed at
4820 if (master->d->gui_ != d->gui_)
4823 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4824 if (bufToUpdate.find(this) == bufToUpdate.end())
4828 // start over the counters in the master
4829 textclass.counters().reset();
4832 // update will be done below for this buffer
4833 bufToUpdate.erase(this);
4835 // update all caches
4836 clearReferenceCache();
4838 setChangesPresent(false);
4840 Buffer & cbuf = const_cast<Buffer &>(*this);
4843 ParIterator parit = cbuf.par_iterator_begin();
4844 updateBuffer(parit, utype);
4847 // If this document has siblings, then update the TocBackend later. The
4848 // reason is to ensure that later siblings are up to date when e.g. the
4849 // broken or not status of references is computed. The update is called
4850 // in InsetInclude::addToToc.
4853 // if the bibfiles changed, the cache of bibinfo is invalid
4854 docstring_list new_bibfiles = d->bibfiles_cache_;
4855 // this is a trick to determine whether the two vectors have
4856 // the same elements.
4857 sort(new_bibfiles.begin(), new_bibfiles.end());
4858 sort(old_bibfiles.begin(), old_bibfiles.end());
4859 if (old_bibfiles != new_bibfiles) {
4860 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4861 invalidateBibinfoCache();
4862 reloadBibInfoCache();
4863 // We relied upon the bibinfo cache when recalculating labels. But that
4864 // cache was invalid, although we didn't find that out until now. So we
4865 // have to do it all again.
4866 // That said, the only thing we really need to do is update the citation
4867 // labels. Nothing else will have changed. So we could create a new
4868 // UpdateType that would signal that fact, if we needed to do so.
4869 parit = cbuf.par_iterator_begin();
4870 // we will be re-doing the counters and references and such.
4871 textclass.counters().reset();
4872 clearReferenceCache();
4873 // we should not need to do this again?
4875 setChangesPresent(false);
4876 updateBuffer(parit, utype);
4877 // this will already have been done by reloadBibInfoCache();
4878 // d->bibinfo_cache_valid_ = true;
4881 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4882 // this is also set to true on the other path, by reloadBibInfoCache.
4883 d->bibinfo_cache_valid_ = true;
4885 d->cite_labels_valid_ = true;
4887 cbuf.tocBackend().update(true, utype);
4888 if (scope == UpdateMaster)
4889 cbuf.structureChanged();
4893 static depth_type getDepth(DocIterator const & it)
4895 depth_type depth = 0;
4896 for (size_t i = 0 ; i < it.depth() ; ++i)
4897 if (!it[i].inset().inMathed())
4898 depth += it[i].paragraph().getDepth() + 1;
4899 // remove 1 since the outer inset does not count
4900 // we should have at least one non-math inset, so
4901 // depth should nevery be 0. but maybe it is worth
4902 // marking this, just in case.
4904 // coverity[INTEGER_OVERFLOW]
4908 static depth_type getItemDepth(ParIterator const & it)
4910 Paragraph const & par = *it;
4911 LabelType const labeltype = par.layout().labeltype;
4913 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4916 // this will hold the lowest depth encountered up to now.
4917 depth_type min_depth = getDepth(it);
4918 ParIterator prev_it = it;
4921 --prev_it.top().pit();
4923 // start of nested inset: go to outer par
4925 if (prev_it.empty()) {
4926 // start of document: nothing to do
4931 // We search for the first paragraph with same label
4932 // that is not more deeply nested.
4933 Paragraph & prev_par = *prev_it;
4934 depth_type const prev_depth = getDepth(prev_it);
4935 if (labeltype == prev_par.layout().labeltype) {
4936 if (prev_depth < min_depth)
4937 return prev_par.itemdepth + 1;
4938 if (prev_depth == min_depth)
4939 return prev_par.itemdepth;
4941 min_depth = min(min_depth, prev_depth);
4942 // small optimization: if we are at depth 0, we won't
4943 // find anything else
4944 if (prev_depth == 0)
4950 static bool needEnumCounterReset(ParIterator const & it)
4952 Paragraph const & par = *it;
4953 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4954 depth_type const cur_depth = par.getDepth();
4955 ParIterator prev_it = it;
4956 while (prev_it.pit()) {
4957 --prev_it.top().pit();
4958 Paragraph const & prev_par = *prev_it;
4959 if (prev_par.getDepth() <= cur_depth)
4960 return prev_par.layout().name() != par.layout().name();
4962 // start of nested inset: reset
4967 // set the label of a paragraph. This includes the counters.
4968 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4970 BufferParams const & bp = owner_->masterBuffer()->params();
4971 DocumentClass const & textclass = bp.documentClass();
4972 Paragraph & par = it.paragraph();
4973 Layout const & layout = par.layout();
4974 Counters & counters = textclass.counters();
4976 if (par.params().startOfAppendix()) {
4977 // We want to reset the counter corresponding to toplevel sectioning
4978 Layout const & lay = textclass.getTOCLayout();
4979 docstring const cnt = lay.counter;
4981 counters.reset(cnt);
4982 counters.appendix(true);
4984 par.params().appendix(counters.appendix());
4986 // Compute the item depth of the paragraph
4987 par.itemdepth = getItemDepth(it);
4989 if (layout.margintype == MARGIN_MANUAL) {
4990 if (par.params().labelWidthString().empty())
4991 par.params().labelWidthString(par.expandLabel(layout, bp));
4992 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4993 // we do not need to do anything here, since the empty case is
4994 // handled during export.
4996 par.params().labelWidthString(docstring());
4999 switch(layout.labeltype) {
5000 case LABEL_ITEMIZE: {
5001 // At some point of time we should do something more
5002 // clever here, like:
5003 // par.params().labelString(
5004 // bp.user_defined_bullet(par.itemdepth).getText());
5005 // for now, use a simple hardcoded label
5006 docstring itemlabel;
5007 switch (par.itemdepth) {
5009 itemlabel = char_type(0x2022);
5012 itemlabel = char_type(0x2013);
5015 itemlabel = char_type(0x2217);
5018 itemlabel = char_type(0x2219); // or 0x00b7
5021 par.params().labelString(itemlabel);
5025 case LABEL_ENUMERATE: {
5026 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5028 switch (par.itemdepth) {
5039 enumcounter += "iv";
5042 // not a valid enumdepth...
5046 // Increase the master counter?
5047 if (layout.stepmastercounter && needEnumCounterReset(it))
5048 counters.stepMaster(enumcounter, utype);
5050 // Maybe we have to reset the enumeration counter.
5051 if (!layout.resumecounter && needEnumCounterReset(it))
5052 counters.reset(enumcounter);
5053 counters.step(enumcounter, utype);
5055 string const & lang = par.getParLanguage(bp)->code();
5056 par.params().labelString(counters.theCounter(enumcounter, lang));
5061 case LABEL_SENSITIVE: {
5062 string const & type = counters.current_float();
5063 docstring full_label;
5065 full_label = owner_->B_("Senseless!!! ");
5067 docstring name = owner_->B_(textclass.floats().getType(type).name());
5068 if (counters.hasCounter(from_utf8(type))) {
5069 string const & lang = par.getParLanguage(bp)->code();
5070 counters.step(from_utf8(type), utype);
5071 full_label = bformat(from_ascii("%1$s %2$s:"),
5073 counters.theCounter(from_utf8(type), lang));
5075 full_label = bformat(from_ascii("%1$s #:"), name);
5077 par.params().labelString(full_label);
5081 case LABEL_NO_LABEL:
5082 par.params().labelString(docstring());
5086 case LABEL_CENTERED:
5087 case LABEL_STATIC: {
5088 docstring const & lcounter = layout.counter;
5089 if (!lcounter.empty()) {
5090 if (layout.toclevel <= bp.secnumdepth
5091 && (layout.latextype != LATEX_ENVIRONMENT
5092 || it.text()->isFirstInSequence(it.pit()))) {
5093 if (counters.hasCounter(lcounter))
5094 counters.step(lcounter, utype);
5095 par.params().labelString(par.expandLabel(layout, bp));
5097 par.params().labelString(docstring());
5099 par.params().labelString(par.expandLabel(layout, bp));
5105 par.params().labelString(par.expandLabel(layout, bp));
5110 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5112 // LASSERT: Is it safe to continue here, or should we just return?
5113 LASSERT(parit.pit() == 0, /**/);
5115 // Set the position of the text in the buffer to be able
5116 // to resolve macros in it.
5117 parit.text()->setMacrocontextPosition(parit);
5119 depth_type maxdepth = 0;
5120 pit_type const lastpit = parit.lastpit();
5121 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5122 // reduce depth if necessary
5123 if (parit->params().depth() > maxdepth) {
5124 /** FIXME: this function is const, but
5125 * nevertheless it modifies the buffer. To be
5126 * cleaner, one should modify the buffer in
5127 * another function, which is actually
5128 * non-const. This would however be costly in
5129 * terms of code duplication.
5131 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5132 parit->params().depth(maxdepth);
5134 maxdepth = parit->getMaxDepthAfter();
5136 if (utype == OutputUpdate) {
5137 // track the active counters
5138 // we have to do this for the master buffer, since the local
5139 // buffer isn't tracking anything.
5140 masterBuffer()->params().documentClass().counters().
5141 setActiveLayout(parit->layout());
5144 // set the counter for this paragraph
5145 d->setLabel(parit, utype);
5147 // update change-tracking flag
5148 parit->addChangesToBuffer(*this);
5151 InsetList::const_iterator iit = parit->insetList().begin();
5152 InsetList::const_iterator end = parit->insetList().end();
5153 for (; iit != end; ++iit) {
5154 parit.pos() = iit->pos;
5155 iit->inset->updateBuffer(parit, utype);
5161 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5162 WordLangTuple & word_lang, docstring_list & suggestions) const
5166 suggestions.clear();
5167 word_lang = WordLangTuple();
5168 bool const to_end = to.empty();
5169 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5170 // OK, we start from here.
5171 for (; from != end; from.forwardPos()) {
5172 // This skips all insets with spell check disabled.
5173 while (!from.allowSpellCheck()) {
5177 // If from is at the end of the document (which is possible
5178 // when "from" was changed above) LyX will crash later otherwise.
5179 if (from.atEnd() || (!to_end && from >= end))
5182 from.paragraph().spellCheck();
5183 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5184 if (SpellChecker::misspelled(res)) {
5188 // Do not increase progress when from == to, otherwise the word
5189 // count will be wrong.
5199 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5201 bool inword = false;
5206 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5207 if (!dit.inTexted()) {
5212 Paragraph const & par = dit.paragraph();
5213 pos_type const pos = dit.pos();
5215 // Copied and adapted from isWordSeparator() in Paragraph
5216 if (pos == dit.lastpos()) {
5219 Inset const * ins = par.getInset(pos);
5220 if (ins && skipNoOutput && !ins->producesOutput()) {
5223 // stop if end of range was skipped
5224 if (!to.atEnd() && dit >= to)
5227 } else if (!par.isDeleted(pos)) {
5228 if (par.isWordSeparator(pos))
5234 if (ins && ins->isLetter())
5236 else if (ins && ins->isSpace())
5239 char_type const c = par.getChar(pos);
5240 if (isPrintableNonspace(c))
5242 else if (isSpace(c))
5252 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5254 d->updateStatistics(from, to, skipNoOutput);
5258 int Buffer::wordCount() const
5260 return d->wordCount();
5264 int Buffer::charCount(bool with_blanks) const
5266 return d->charCount(with_blanks);
5270 Buffer::ReadStatus Buffer::reload()
5273 // c.f. bug https://www.lyx.org/trac/ticket/6587
5274 removeAutosaveFile();
5275 // e.g., read-only status could have changed due to version control
5276 d->filename.refresh();
5277 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5279 // clear parent. this will get reset if need be.
5281 ReadStatus const status = loadLyXFile();
5282 if (status == ReadSuccess) {
5287 message(bformat(_("Document %1$s reloaded."), disp_fn));
5290 message(bformat(_("Could not reload document %1$s."), disp_fn));
5300 bool Buffer::saveAs(FileName const & fn)
5302 FileName const old_name = fileName();
5303 FileName const old_auto = getAutosaveFileName();
5304 bool const old_unnamed = isUnnamed();
5305 bool success = true;
5306 d->old_position = filePath();
5313 // bring the autosave file with us, just in case.
5314 moveAutosaveFile(old_auto);
5315 // validate version control data and
5316 // correct buffer title
5317 lyxvc().file_found_hook(fileName());
5319 // the file has now been saved to the new location.
5320 // we need to check that the locations of child buffers
5322 checkChildBuffers();
5323 checkMasterBuffer();
5326 // reset the old filename and unnamed state
5327 setFileName(old_name);
5328 setUnnamed(old_unnamed);
5332 d->old_position.clear();
5337 void Buffer::checkChildBuffers()
5339 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5340 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5341 for (; it != en; ++it) {
5342 DocIterator dit = it->second;
5343 Buffer * cbuf = const_cast<Buffer *>(it->first);
5344 if (!cbuf || !theBufferList().isLoaded(cbuf))
5346 Inset * inset = dit.nextInset();
5347 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5348 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5349 docstring const & incfile = inset_inc->getParam("filename");
5350 string oldloc = cbuf->absFileName();
5351 string newloc = makeAbsPath(to_utf8(incfile),
5352 onlyPath(absFileName())).absFileName();
5353 if (oldloc == newloc)
5355 // the location of the child file is incorrect.
5357 inset_inc->setChildBuffer(0);
5359 // invalidate cache of children
5360 d->children_positions.clear();
5361 d->position_to_children.clear();
5365 // If a child has been saved under a different name/path, it might have been
5366 // orphaned. Therefore the master needs to be reset (bug 8161).
5367 void Buffer::checkMasterBuffer()
5369 Buffer const * const master = masterBuffer();
5373 // necessary to re-register the child (bug 5873)
5374 // FIXME: clean up updateMacros (here, only
5375 // child registering is needed).
5376 master->updateMacros();
5377 // (re)set master as master buffer, but only
5378 // if we are a real child
5379 if (master->isChild(this))
5386 string Buffer::includedFilePath(string const & name, string const & ext) const
5388 if (d->old_position.empty() ||
5389 equivalent(FileName(d->old_position), FileName(filePath())))
5392 bool isabsolute = FileName::isAbsolute(name);
5393 // both old_position and filePath() end with a path separator
5394 string absname = isabsolute ? name : d->old_position + name;
5396 // if old_position is set to origin, we need to do the equivalent of
5397 // getReferencedFileName() (see readDocument())
5398 if (!isabsolute && d->old_position == params().origin) {
5399 FileName const test(addExtension(filePath() + name, ext));
5401 absname = filePath() + name;
5404 if (!FileName(addExtension(absname, ext)).exists())
5408 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5410 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5411 from_utf8(filePath())));
5415 void Buffer::setChangesPresent(bool b) const
5417 d->tracked_changes_present_ = b;
5421 bool Buffer::areChangesPresent() const
5423 return d->tracked_changes_present_;
5427 void Buffer::updateChangesPresent() const
5429 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5430 setChangesPresent(false);
5431 ParConstIterator it = par_iterator_begin();
5432 ParConstIterator const end = par_iterator_end();
5433 for (; !areChangesPresent() && it != end; ++it)
5434 it->addChangesToBuffer(*this);
5438 void Buffer::Impl::refreshFileMonitor()
5440 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5441 file_monitor_->refresh();
5445 // The previous file monitor is invalid
5446 // This also destroys the previous file monitor and all its connections
5447 file_monitor_ = FileSystemWatcher::monitor(filename);
5448 // file_monitor_ will be destroyed with *this, so it is not going to call a
5449 // destroyed object method.
5450 file_monitor_->connect([this](bool exists) {
5451 fileExternallyModified(exists);
5456 void Buffer::Impl::fileExternallyModified(bool const exists)
5458 // ignore notifications after our own saving operations
5459 if (checksum_ == filename.checksum()) {
5460 LYXERR(Debug::FILES, "External modification but "
5461 "checksum unchanged: " << filename);
5464 // If the file has been deleted, only mark the file as dirty since it is
5465 // pointless to prompt for reloading. If later a file is moved into this
5466 // location, then the externally modified warning will appear then.
5468 externally_modified_ = true;
5469 // Update external modification notification.
5470 // Dirty buffers must be visible at all times.
5471 if (wa_ && wa_->unhide(owner_))
5472 wa_->updateTitles();
5474 // Unable to unhide the buffer (e.g. no GUI or not current View)
5479 bool Buffer::notifiesExternalModification() const
5481 return d->externally_modified_;
5485 void Buffer::clearExternalModification() const
5487 d->externally_modified_ = false;
5489 d->wa_->updateTitles();