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 support::FileNamePairList bibfiles_cache_;
284 // FIXME The caching mechanism could be improved. At present, we have a
285 // cache for each Buffer, that caches all the bibliography info for that
286 // Buffer. A more efficient solution would be to have a global cache per
287 // file, and then to construct the Buffer's bibinfo from that.
288 /// A cache for bibliography info
289 mutable BiblioInfo bibinfo_;
290 /// whether the bibinfo cache is valid
291 mutable bool bibinfo_cache_valid_;
292 /// Cache of timestamps of .bib files
293 map<FileName, time_t> bibfile_status_;
294 /// Indicates whether the bibinfo has changed since the last time
295 /// we ran updateBuffer(), i.e., whether citation labels may need
297 mutable bool cite_labels_valid_;
299 /// These two hold the file name and format, written to by
300 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
301 FileName preview_file_;
302 string preview_format_;
303 /// If there was an error when previewing, on the next preview we do
304 /// a fresh compile (e.g. in case the user installed a package that
308 mutable RefCache ref_cache_;
310 /// our Text that should be wrapped in an InsetText
314 PreviewLoader * preview_loader_;
316 /// This is here to force the test to be done whenever parent_buffer
318 Buffer const * parent() const
320 // ignore_parent temporarily "orphans" a buffer
321 // (e.g. if a child is compiled standalone)
324 // if parent_buffer is not loaded, then it has been unloaded,
325 // which means that parent_buffer is an invalid pointer. So we
326 // set it to null in that case.
327 // however, the BufferList doesn't know about cloned buffers, so
328 // they will always be regarded as unloaded. in that case, we hope
330 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
332 return parent_buffer;
336 void setParent(Buffer const * pb)
338 if (parent_buffer == pb)
341 if (!cloned_buffer_ && parent_buffer && pb)
342 LYXERR0("Warning: a buffer should not have two parents!");
344 if (!cloned_buffer_ && parent_buffer)
345 parent_buffer->invalidateBibinfoCache();
348 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
349 /// This one is useful for preview detached in a thread.
350 Buffer const * cloned_buffer_;
352 CloneList * clone_list_;
353 /// are we in the process of exporting this buffer?
354 mutable bool doing_export;
356 /// compute statistics
357 /// \p from initial position
358 /// \p to points to the end position
359 void updateStatistics(DocIterator & from, DocIterator & to,
360 bool skipNoOutput = true);
361 /// statistics accessor functions
362 int wordCount() const
366 int charCount(bool with_blanks) const
369 + (with_blanks ? blank_count_ : 0);
372 // does the buffer contain tracked changes? (if so, we automatically
373 // display the review toolbar, for instance)
374 mutable bool tracked_changes_present_;
376 // Make sure the file monitor monitors the good file.
377 void refreshFileMonitor();
379 /// Notify or clear of external modification
380 void fileExternallyModified(bool exists);
382 /// has been externally modified? Can be reset by the user.
383 mutable bool externally_modified_;
386 /// So we can force access via the accessors.
387 mutable Buffer const * parent_buffer;
393 FileMonitorPtr file_monitor_;
397 /// Creates the per buffer temporary directory
398 static FileName createBufferTmpDir()
400 // FIXME This would be the ideal application for a TempDir class (like
401 // TempFile but for directories)
406 Mutex::Locker locker(&mutex);
407 counter = convert<string>(count++);
409 // We are in our own directory. Why bother to mangle name?
410 // In fact I wrote this code to circumvent a problematic behaviour
411 // (bug?) of EMX mkstemp().
412 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
415 if (!tmpfl.createDirectory(0777)) {
416 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
417 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
418 from_utf8(tmpfl.absFileName())));
424 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
425 Buffer const * cloned_buffer)
426 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
427 internal_buffer(false), read_only(readonly_), filename(file),
428 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
429 ignore_parent(false), toc_backend(owner), macro_lock(false),
430 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
431 cite_labels_valid_(false), preview_error_(false),
432 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
433 clone_list_(0), doing_export(false),
434 tracked_changes_present_(0), externally_modified_(false), parent_buffer(0),
435 word_count_(0), char_count_(0), blank_count_(0)
437 refreshFileMonitor();
438 if (!cloned_buffer_) {
439 temppath = createBufferTmpDir();
440 lyxvc.setBuffer(owner_);
442 wa_ = new frontend::WorkAreaManager;
445 temppath = cloned_buffer_->d->temppath;
446 file_fully_loaded = true;
447 params = cloned_buffer_->d->params;
448 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
449 bibinfo_ = cloned_buffer_->d->bibinfo_;
450 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
451 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
452 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
453 unnamed = cloned_buffer_->d->unnamed;
454 internal_buffer = cloned_buffer_->d->internal_buffer;
455 layout_position = cloned_buffer_->d->layout_position;
456 preview_file_ = cloned_buffer_->d->preview_file_;
457 preview_format_ = cloned_buffer_->d->preview_format_;
458 preview_error_ = cloned_buffer_->d->preview_error_;
459 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
463 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
464 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
466 LYXERR(Debug::INFO, "Buffer::Buffer()");
468 d->inset = new InsetText(*cloned_buffer->d->inset);
469 d->inset->setBuffer(*this);
470 // FIXME: optimize this loop somewhat, maybe by creating a new
471 // general recursive Inset::setId().
472 DocIterator it = doc_iterator_begin(this);
473 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
474 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
475 it.paragraph().setId(cloned_it.paragraph().id());
477 d->inset = new InsetText(this);
478 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
484 LYXERR(Debug::INFO, "Buffer::~Buffer()");
485 // here the buffer should take care that it is
486 // saved properly, before it goes into the void.
488 // GuiView already destroyed
492 // No need to do additional cleanups for internal buffer.
498 // this is in case of recursive includes: we won't try to delete
499 // ourselves as a child.
500 d->clone_list_->erase(this);
501 // loop over children
502 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
503 Impl::BufferPositionMap::iterator end = d->children_positions.end();
504 for (; it != end; ++it) {
505 Buffer * child = const_cast<Buffer *>(it->first);
506 if (d->clone_list_->erase(child))
509 // if we're the master buffer, then we should get rid of the list
512 // If this is not empty, we have leaked something. Worse, one of the
513 // children still has a reference to this list. But we will try to
514 // continue, rather than shut down.
515 LATTEST(d->clone_list_->empty());
516 list<CloneList *>::iterator it =
517 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
518 if (it == cloned_buffers.end()) {
519 // We will leak in this case, but it is safe to continue.
522 cloned_buffers.erase(it);
523 delete d->clone_list_;
525 // FIXME Do we really need to do this right before we delete d?
526 // clear references to children in macro tables
527 d->children_positions.clear();
528 d->position_to_children.clear();
530 // loop over children
531 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
532 Impl::BufferPositionMap::iterator end = d->children_positions.end();
533 for (; it != end; ++it) {
534 Buffer * child = const_cast<Buffer *>(it->first);
535 if (theBufferList().isLoaded(child)) {
536 if (theBufferList().isOthersChild(this, child))
539 theBufferList().release(child);
544 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
546 msg += emergencyWrite();
548 msg += " " + _("Save failed! Document is lost.");
550 Alert::warning(_("Attempting to close changed document!"), msg);
553 // FIXME Do we really need to do this right before we delete d?
554 // clear references to children in macro tables
555 d->children_positions.clear();
556 d->position_to_children.clear();
558 if (!d->temppath.destroyDirectory()) {
559 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
560 from_utf8(d->temppath.absFileName())));
569 Buffer * Buffer::cloneFromMaster() const
572 cloned_buffers.push_back(new CloneList);
573 CloneList * clones = cloned_buffers.back();
575 masterBuffer()->cloneWithChildren(bufmap, clones);
577 // make sure we got cloned
578 BufferMap::const_iterator bit = bufmap.find(this);
579 LASSERT(bit != bufmap.end(), return 0);
580 Buffer * cloned_buffer = bit->second;
582 return cloned_buffer;
586 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
588 // have we already been cloned?
589 if (bufmap.find(this) != bufmap.end())
592 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
594 // The clone needs its own DocumentClass, since running updateBuffer() will
595 // modify it, and we would otherwise be sharing it with the original Buffer.
596 buffer_clone->params().makeDocumentClass(true);
598 cap::switchBetweenClasses(
599 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
600 static_cast<InsetText &>(buffer_clone->inset()), el);
602 bufmap[this] = buffer_clone;
603 clones->insert(buffer_clone);
604 buffer_clone->d->clone_list_ = clones;
605 buffer_clone->d->macro_lock = true;
606 buffer_clone->d->children_positions.clear();
608 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
609 // math macro caches need to be rethought and simplified.
610 // I am not sure wether we should handle Buffer cloning here or in BufferList.
611 // Right now BufferList knows nothing about buffer clones.
612 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
613 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
614 for (; it != end; ++it) {
615 DocIterator dit = it->first.clone(buffer_clone);
616 dit.setBuffer(buffer_clone);
617 Buffer * child = const_cast<Buffer *>(it->second.buffer);
619 child->cloneWithChildren(bufmap, clones);
620 BufferMap::iterator const bit = bufmap.find(child);
621 LASSERT(bit != bufmap.end(), continue);
622 Buffer * child_clone = bit->second;
624 Inset * inset = dit.nextInset();
625 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
626 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
627 inset_inc->setChildBuffer(child_clone);
628 child_clone->d->setParent(buffer_clone);
629 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
630 buffer_clone->setChild(dit, child_clone);
632 buffer_clone->d->macro_lock = false;
637 Buffer * Buffer::cloneBufferOnly() const {
638 cloned_buffers.push_back(new CloneList);
639 CloneList * clones = cloned_buffers.back();
640 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
642 // The clone needs its own DocumentClass, since running updateBuffer() will
643 // modify it, and we would otherwise be sharing it with the original Buffer.
644 buffer_clone->params().makeDocumentClass(true);
646 cap::switchBetweenClasses(
647 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
648 static_cast<InsetText &>(buffer_clone->inset()), el);
650 clones->insert(buffer_clone);
651 buffer_clone->d->clone_list_ = clones;
653 // we won't be cloning the children
654 buffer_clone->d->children_positions.clear();
659 bool Buffer::isClone() const
661 return d->cloned_buffer_;
665 void Buffer::changed(bool update_metrics) const
668 d->wa_->redrawAll(update_metrics);
672 frontend::WorkAreaManager & Buffer::workAreaManager() const
679 Text & Buffer::text() const
681 return d->inset->text();
685 Inset & Buffer::inset() const
691 BufferParams & Buffer::params()
697 BufferParams const & Buffer::params() const
703 BufferParams const & Buffer::masterParams() const
705 if (masterBuffer() == this)
708 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
709 // Copy child authors to the params. We need those pointers.
710 AuthorList const & child_authors = params().authors();
711 AuthorList::Authors::const_iterator it = child_authors.begin();
712 for (; it != child_authors.end(); ++it)
713 mparams.authors().record(*it);
718 double Buffer::fontScalingFactor() const
720 return isExporting() ? 75.0 * params().html_math_img_scale
721 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
725 ParagraphList & Buffer::paragraphs()
727 return text().paragraphs();
731 ParagraphList const & Buffer::paragraphs() const
733 return text().paragraphs();
737 LyXVC & Buffer::lyxvc()
743 LyXVC const & Buffer::lyxvc() const
749 string const Buffer::temppath() const
751 return d->temppath.absFileName();
755 TexRow & Buffer::texrow()
761 TexRow const & Buffer::texrow() const
767 TocBackend & Buffer::tocBackend() const
769 return d->toc_backend;
773 Undo & Buffer::undo()
779 void Buffer::setChild(DocIterator const & dit, Buffer * child)
781 d->children_positions[child] = dit;
785 string Buffer::latexName(bool const no_path) const
787 FileName latex_name =
788 makeLatexName(d->exportFileName());
789 return no_path ? latex_name.onlyFileName()
790 : latex_name.absFileName();
794 FileName Buffer::Impl::exportFileName() const
796 docstring const branch_suffix =
797 params.branchlist().getFileNameSuffix();
798 if (branch_suffix.empty())
801 string const name = filename.onlyFileNameWithoutExt()
802 + to_utf8(branch_suffix);
803 FileName res(filename.onlyPath().absFileName() + "/" + name);
804 res.changeExtension(filename.extension());
810 string Buffer::logName(LogType * type) const
812 string const filename = latexName(false);
814 if (filename.empty()) {
820 string const path = temppath();
822 FileName const fname(addName(temppath(),
823 onlyFileName(changeExtension(filename,
826 // FIXME: how do we know this is the name of the build log?
827 FileName const bname(
828 addName(path, onlyFileName(
829 changeExtension(filename,
830 theFormats().extension(params().bufferFormat()) + ".out"))));
832 // Also consider the master buffer log file
833 FileName masterfname = fname;
834 LogType mtype = latexlog;
835 if (masterBuffer() != this) {
836 string const mlogfile = masterBuffer()->logName(&mtype);
837 masterfname = FileName(mlogfile);
840 // If no Latex log or Build log is newer, show Build log
841 if (bname.exists() &&
842 ((!fname.exists() && !masterfname.exists())
843 || (fname.lastModified() < bname.lastModified()
844 && masterfname.lastModified() < bname.lastModified()))) {
845 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
848 return bname.absFileName();
849 // If we have a newer master file log or only a master log, show this
850 } else if (fname != masterfname
851 && (!fname.exists() && (masterfname.exists()
852 || fname.lastModified() < masterfname.lastModified()))) {
853 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
856 return masterfname.absFileName();
858 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
861 return fname.absFileName();
865 void Buffer::setReadonly(bool const flag)
867 if (d->read_only != flag) {
874 void Buffer::setFileName(FileName const & fname)
876 bool const changed = fname != d->filename;
878 d->refreshFileMonitor();
880 lyxvc().file_found_hook(fname);
881 setReadonly(d->filename.isReadOnly());
887 int Buffer::readHeader(Lexer & lex)
889 int unknown_tokens = 0;
891 int begin_header_line = -1;
893 // Initialize parameters that may be/go lacking in header:
894 params().branchlist().clear();
895 params().preamble.erase();
896 params().options.erase();
897 params().master.erase();
898 params().float_placement.erase();
899 params().paperwidth.erase();
900 params().paperheight.erase();
901 params().leftmargin.erase();
902 params().rightmargin.erase();
903 params().topmargin.erase();
904 params().bottommargin.erase();
905 params().headheight.erase();
906 params().headsep.erase();
907 params().footskip.erase();
908 params().columnsep.erase();
909 params().fonts_cjk.erase();
910 params().listings_params.clear();
911 params().clearLayoutModules();
912 params().clearRemovedModules();
913 params().clearIncludedChildren();
914 params().pdfoptions().clear();
915 params().indiceslist().clear();
916 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
917 params().isbackgroundcolor = false;
918 params().fontcolor = RGBColor(0, 0, 0);
919 params().isfontcolor = false;
920 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
921 params().boxbgcolor = RGBColor(0xFF, 0, 0);
922 params().html_latex_start.clear();
923 params().html_latex_end.clear();
924 params().html_math_img_scale = 1.0;
925 params().output_sync_macro.erase();
926 params().setLocalLayout(docstring(), false);
927 params().setLocalLayout(docstring(), true);
928 params().biblio_opts.erase();
929 params().biblatex_bibstyle.erase();
930 params().biblatex_citestyle.erase();
931 params().multibib.erase();
933 for (int i = 0; i < 4; ++i) {
934 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
935 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
938 ErrorList & errorList = d->errorLists["Parse"];
947 if (token == "\\end_header")
951 if (token == "\\begin_header") {
952 begin_header_line = line;
956 LYXERR(Debug::PARSER, "Handling document header token: `"
959 string const result =
960 params().readToken(lex, token, d->filename.onlyPath());
961 if (!result.empty()) {
962 if (token == "\\textclass") {
963 d->layout_position = result;
966 docstring const s = bformat(_("Unknown token: "
970 errorList.push_back(ErrorItem(_("Document header error"), s));
974 if (begin_header_line) {
975 docstring const s = _("\\begin_header is missing");
976 errorList.push_back(ErrorItem(_("Document header error"), s));
979 params().shell_escape = theSession().shellescapeFiles().find(absFileName());
981 params().makeDocumentClass();
983 return unknown_tokens;
988 // changed to be public and have one parameter
989 // Returns true if "\end_document" is not read (Asger)
990 bool Buffer::readDocument(Lexer & lex)
992 ErrorList & errorList = d->errorLists["Parse"];
995 // remove dummy empty par
996 paragraphs().clear();
998 if (!lex.checkFor("\\begin_document")) {
999 docstring const s = _("\\begin_document is missing");
1000 errorList.push_back(ErrorItem(_("Document header error"), s));
1005 if (params().output_changes) {
1006 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1007 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1008 LaTeXFeatures::isAvailable("xcolor");
1010 if (!dvipost && !xcolorulem) {
1011 Alert::warning(_("Changes not shown in LaTeX output"),
1012 _("Changes will not be highlighted in LaTeX output, "
1013 "because neither dvipost nor xcolor/ulem are installed.\n"
1014 "Please install these packages or redefine "
1015 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1016 } else if (!xcolorulem) {
1017 Alert::warning(_("Changes not shown in LaTeX output"),
1018 _("Changes will not be highlighted in LaTeX output "
1019 "when using pdflatex, because xcolor and ulem are not installed.\n"
1020 "Please install both packages or redefine "
1021 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1025 if (!parent() && !params().master.empty()) {
1026 FileName const master_file = makeAbsPath(params().master,
1027 onlyPath(absFileName()));
1028 if (isLyXFileName(master_file.absFileName())) {
1030 checkAndLoadLyXFile(master_file, true);
1032 // necessary e.g. after a reload
1033 // to re-register the child (bug 5873)
1034 // FIXME: clean up updateMacros (here, only
1035 // child registering is needed).
1036 master->updateMacros();
1037 // set master as master buffer, but only
1038 // if we are a real child
1039 if (master->isChild(this))
1041 // if the master is not fully loaded
1042 // it is probably just loading this
1043 // child. No warning needed then.
1044 else if (master->isFullyLoaded())
1045 LYXERR0("The master '"
1047 << "' assigned to this document ("
1049 << ") does not include "
1050 "this document. Ignoring the master assignment.");
1055 // assure we have a default index
1056 params().indiceslist().addDefault(B_("Index"));
1059 if (FileName::isAbsolute(params().origin))
1060 d->old_position = params().origin;
1062 d->old_position = filePath();
1063 bool const res = text().read(lex, errorList, d->inset);
1064 d->old_position.clear();
1066 // inform parent buffer about local macros
1068 Buffer const * pbuf = parent();
1069 UserMacroSet::const_iterator cit = usermacros.begin();
1070 UserMacroSet::const_iterator end = usermacros.end();
1071 for (; cit != end; ++cit)
1072 pbuf->usermacros.insert(*cit);
1076 updateMacroInstances(InternalUpdate);
1081 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1083 Format const * fmt = theFormats().getFormat(format);
1086 // It is important to use the correct extension here, since some
1087 // converters create a wrong output file otherwise (e.g. html2latex)
1088 FileName const name = tempFileName("Buffer_importStringXXXXXX." + fmt->extension());
1089 ofdocstream os(name.toFilesystemEncoding().c_str());
1090 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1091 bool const success = !(os << contents).fail();
1094 bool converted = false;
1096 params().compressed = false;
1098 // remove dummy empty par
1099 paragraphs().clear();
1101 converted = importFile(format, name, errorList);
1104 removeTempFile(name);
1109 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1111 if (!theConverters().isReachable(format, "lyx"))
1114 FileName const lyx = tempFileName("Buffer_importFileXXXXXX.lyx");
1115 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList)) {
1116 bool const success = readFile(lyx) == ReadSuccess;
1117 removeTempFile(lyx);
1125 bool Buffer::readString(string const & s)
1127 params().compressed = false;
1130 istringstream is(s);
1132 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1133 FileName const fn = tempfile.name();
1136 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1138 if (success && file_format != LYX_FORMAT) {
1139 // We need to call lyx2lyx, so write the input to a file
1140 ofstream os(fn.toFilesystemEncoding().c_str());
1143 // lyxvc in readFile
1144 if (readFile(fn) != ReadSuccess)
1148 if (readDocument(lex))
1154 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1158 if (!lex.setFile(fname)) {
1159 Alert::error(_("File Not Found"),
1160 bformat(_("Unable to open file `%1$s'."),
1161 from_utf8(fn.absFileName())));
1162 return ReadFileNotFound;
1166 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1167 if (ret_plf != ReadSuccess)
1170 if (file_format != LYX_FORMAT) {
1172 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1173 if (ret_clf != ReadSuccess)
1175 ret_clf = readFile(tmpFile);
1176 if (ret_clf == ReadSuccess) {
1177 d->file_format = file_format;
1178 d->need_format_backup = true;
1183 // FIXME: InsetInfo needs to know whether the file is under VCS
1184 // during the parse process, so this has to be done before.
1185 lyxvc().file_found_hook(d->filename);
1187 if (readDocument(lex)) {
1188 Alert::error(_("Document format failure"),
1189 bformat(_("%1$s ended unexpectedly, which means"
1190 " that it is probably corrupted."),
1191 from_utf8(fn.absFileName())));
1192 return ReadDocumentFailure;
1195 d->file_fully_loaded = true;
1196 d->read_only = !d->filename.isWritable();
1197 params().compressed = theFormats().isZippedFile(d->filename);
1203 bool Buffer::isFullyLoaded() const
1205 return d->file_fully_loaded;
1209 void Buffer::setFullyLoaded(bool value)
1211 d->file_fully_loaded = value;
1215 bool Buffer::lastPreviewError() const
1217 return d->preview_error_;
1221 PreviewLoader * Buffer::loader() const
1223 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1225 if (!d->preview_loader_)
1226 d->preview_loader_ = new PreviewLoader(*this);
1227 return d->preview_loader_;
1231 void Buffer::removePreviews() const
1233 delete d->preview_loader_;
1234 d->preview_loader_ = 0;
1238 void Buffer::updatePreviews() const
1240 PreviewLoader * ploader = loader();
1244 InsetIterator it = inset_iterator_begin(*d->inset);
1245 InsetIterator const end = inset_iterator_end(*d->inset);
1246 for (; it != end; ++it)
1247 it->addPreview(it, *ploader);
1249 ploader->startLoading();
1253 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1254 FileName const & fn, int & file_format) const
1256 if(!lex.checkFor("\\lyxformat")) {
1257 Alert::error(_("Document format failure"),
1258 bformat(_("%1$s is not a readable LyX document."),
1259 from_utf8(fn.absFileName())));
1260 return ReadNoLyXFormat;
1266 // LyX formats 217 and earlier were written as 2.17. This corresponds
1267 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1268 // these cases. See also: www.lyx.org/trac/changeset/1313.
1269 size_t dot = tmp_format.find_first_of(".,");
1270 if (dot != string::npos)
1271 tmp_format.erase(dot, 1);
1273 file_format = convert<int>(tmp_format);
1278 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1279 FileName & tmpfile, int from_format)
1281 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1282 tempfile.setAutoRemove(false);
1283 tmpfile = tempfile.name();
1284 if(tmpfile.empty()) {
1285 Alert::error(_("Conversion failed"),
1286 bformat(_("%1$s is from a different"
1287 " version of LyX, but a temporary"
1288 " file for converting it could"
1289 " not be created."),
1290 from_utf8(fn.absFileName())));
1291 return LyX2LyXNoTempFile;
1294 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1295 if (lyx2lyx.empty()) {
1296 Alert::error(_("Conversion script not found"),
1297 bformat(_("%1$s is from a different"
1298 " version of LyX, but the"
1299 " conversion script lyx2lyx"
1300 " could not be found."),
1301 from_utf8(fn.absFileName())));
1302 return LyX2LyXNotFound;
1306 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1307 ostringstream command;
1308 command << os::python()
1309 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1310 << " -t " << convert<string>(LYX_FORMAT)
1311 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1312 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1313 string const command_str = command.str();
1315 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1317 cmd_ret const ret = runCommand(command_str);
1318 if (ret.first != 0) {
1319 if (from_format < LYX_FORMAT) {
1320 Alert::error(_("Conversion script failed"),
1321 bformat(_("%1$s is from an older version"
1322 " of LyX and the lyx2lyx script"
1323 " failed to convert it."),
1324 from_utf8(fn.absFileName())));
1325 return LyX2LyXOlderFormat;
1327 Alert::error(_("Conversion script failed"),
1328 bformat(_("%1$s is from a newer version"
1329 " of LyX and the lyx2lyx script"
1330 " failed to convert it."),
1331 from_utf8(fn.absFileName())));
1332 return LyX2LyXNewerFormat;
1339 FileName Buffer::getBackupName() const {
1340 FileName const & fn = fileName();
1341 string const fname = fn.onlyFileNameWithoutExt();
1342 string const fext = fn.extension() + "~";
1343 string const fpath = lyxrc.backupdir_path.empty() ?
1344 fn.onlyPath().absFileName() :
1345 lyxrc.backupdir_path;
1346 string const fform = convert<string>(d->file_format);
1347 string const backname = fname + "-lyxformat-" + fform;
1348 FileName backup(addName(fpath, addExtension(backname, fext)));
1350 // limit recursion, just in case
1352 unsigned long orig_checksum = 0;
1353 while (backup.exists() && v < 100) {
1354 if (orig_checksum == 0)
1355 orig_checksum = fn.checksum();
1356 unsigned long new_checksum = backup.checksum();
1357 if (orig_checksum == new_checksum) {
1358 LYXERR(Debug::FILES, "Not backing up " << fn <<
1359 "since " << backup << "has the same checksum.");
1360 // a bit of a hack, but we have to check this anyway
1361 // below, and setting this is simpler than introducing
1362 // a special boolean for this purpose.
1366 string const newbackname = backname + "-" + convert<string>(v);
1367 backup.set(addName(fpath, addExtension(newbackname, fext)));
1370 return v < 100 ? backup : FileName();
1374 // Should probably be moved to somewhere else: BufferView? GuiView?
1375 bool Buffer::save() const
1377 docstring const file = makeDisplayPath(absFileName(), 20);
1378 d->filename.refresh();
1380 // check the read-only status before moving the file as a backup
1381 if (d->filename.exists()) {
1382 bool const read_only = !d->filename.isWritable();
1384 Alert::warning(_("File is read-only"),
1385 bformat(_("The file %1$s cannot be written because it "
1386 "is marked as read-only."), file));
1391 // ask if the disk file has been externally modified (use checksum method)
1392 if (fileName().exists() && isChecksumModified()) {
1394 bformat(_("Document %1$s has been externally modified. "
1395 "Are you sure you want to overwrite this file?"), file);
1396 int const ret = Alert::prompt(_("Overwrite modified file?"),
1397 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1402 // We don't need autosaves in the immediate future. (Asger)
1403 resetAutosaveTimers();
1405 // if the file does not yet exist, none of the backup activity
1406 // that follows is necessary
1407 if (!fileName().exists()) {
1408 if (!writeFile(fileName()))
1414 // we first write the file to a new name, then move it to its
1415 // proper location once that has been done successfully. that
1416 // way we preserve the original file if something goes wrong.
1417 string const justname = fileName().onlyFileNameWithoutExt();
1418 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1419 justname + "-XXXXXX.lyx");
1420 bool const symlink = fileName().isSymLink();
1422 tempfile->setAutoRemove(false);
1424 FileName savefile(tempfile->name());
1425 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1426 if (!writeFile(savefile))
1429 // we will set this to false if we fail
1430 bool made_backup = true;
1432 FileName backupName;
1433 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1435 if (d->need_format_backup)
1436 backupName = getBackupName();
1438 // If we for some reason failed to find a backup name in case of
1439 // a format change, this will still set one. It's the best we can
1441 if (backupName.empty()) {
1442 backupName.set(fileName().absFileName() + "~");
1443 if (!lyxrc.backupdir_path.empty()) {
1444 string const mangledName =
1445 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1446 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1450 LYXERR(Debug::FILES, "Backing up original file to " <<
1451 backupName.absFileName());
1452 // Except file is symlink do not copy because of #6587.
1453 // Hard links have bad luck.
1454 made_backup = symlink ?
1455 fileName().copyTo(backupName):
1456 fileName().moveTo(backupName);
1459 Alert::error(_("Backup failure"),
1460 bformat(_("Cannot create backup file %1$s.\n"
1461 "Please check whether the directory exists and is writable."),
1462 from_utf8(backupName.absFileName())));
1463 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1464 } else if (d->need_format_backup) {
1465 // the original file has been backed up successfully, so we
1466 // will not need to do that again
1467 d->need_format_backup = false;
1471 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1472 // Only do this if tempfile is not in autoremove mode
1475 // If we have no symlink, we can simply rename the temp file.
1476 // Otherwise, we need to copy it so the symlink stays intact.
1477 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1478 savefile.moveTo(fileName()))
1480 // saveCheckSum() was already called by writeFile(), but the
1481 // time stamp is invalidated by copying/moving
1484 if (d->file_format != LYX_FORMAT)
1485 // the file associated with this buffer is now in the current format
1486 d->file_format = LYX_FORMAT;
1489 // else we saved the file, but failed to move it to the right location.
1491 if (needBackup && made_backup && !symlink) {
1492 // the original file was moved to some new location, so it will look
1493 // to the user as if it was deleted. (see bug #9234.) we could try
1494 // to restore it, but that would basically mean trying to do again
1495 // what we just failed to do. better to leave things as they are.
1496 Alert::error(_("Write failure"),
1497 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1498 "But LyX could not move it to:\n %2$s.\n"
1499 "Your original file has been backed up to:\n %3$s"),
1500 from_utf8(savefile.absFileName()),
1501 from_utf8(fileName().absFileName()),
1502 from_utf8(backupName.absFileName())));
1504 // either we did not try to make a backup, or else we tried and failed,
1505 // or else the original file was a symlink, in which case it was copied,
1506 // not moved. so the original file is intact.
1507 Alert::error(_("Write failure"),
1508 bformat(_("Cannot move saved file to:\n %1$s.\n"
1509 "But the file has successfully been saved as:\n %2$s."),
1510 from_utf8(fileName().absFileName()),
1511 from_utf8(savefile.absFileName())));
1517 bool Buffer::writeFile(FileName const & fname) const
1519 if (d->read_only && fname == d->filename)
1522 bool retval = false;
1524 docstring const str = bformat(_("Saving document %1$s..."),
1525 makeDisplayPath(fname.absFileName()));
1528 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1530 if (params().compressed) {
1531 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1532 retval = ofs && write(ofs);
1534 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1535 retval = ofs && write(ofs);
1539 message(str + _(" could not write file!"));
1544 // removeAutosaveFile();
1547 message(str + _(" done."));
1553 docstring Buffer::emergencyWrite()
1555 // No need to save if the buffer has not changed.
1559 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1561 docstring user_message = bformat(
1562 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1564 // We try to save three places:
1565 // 1) Same place as document. Unless it is an unnamed doc.
1567 string s = absFileName();
1570 if (writeFile(FileName(s))) {
1572 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1573 return user_message;
1575 user_message += " " + _("Save failed! Trying again...\n");
1579 // 2) In HOME directory.
1580 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1582 lyxerr << ' ' << s << endl;
1583 if (writeFile(FileName(s))) {
1585 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1586 return user_message;
1589 user_message += " " + _("Save failed! Trying yet again...\n");
1591 // 3) In "/tmp" directory.
1592 // MakeAbsPath to prepend the current
1593 // drive letter on OS/2
1594 s = addName(package().temp_dir().absFileName(), absFileName());
1596 lyxerr << ' ' << s << endl;
1597 if (writeFile(FileName(s))) {
1599 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1600 return user_message;
1603 user_message += " " + _("Save failed! Document is lost.");
1606 return user_message;
1610 bool Buffer::write(ostream & ofs) const
1613 // Use the standard "C" locale for file output.
1614 ofs.imbue(locale::classic());
1617 // The top of the file should not be written by params().
1619 // write out a comment in the top of the file
1620 // Important: Keep the version formatting in sync with lyx2lyx and
1621 // tex2lyx (bug 7951)
1622 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1623 << " created this file. For more info see http://www.lyx.org/\n"
1624 << "\\lyxformat " << LYX_FORMAT << "\n"
1625 << "\\begin_document\n";
1627 /// For each author, set 'used' to true if there is a change
1628 /// by this author in the document; otherwise set it to 'false'.
1629 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1630 AuthorList::Authors::const_iterator a_end = params().authors().end();
1631 for (; a_it != a_end; ++a_it)
1632 a_it->setUsed(false);
1634 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1635 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1636 for ( ; it != end; ++it)
1637 it->checkAuthors(params().authors());
1639 // now write out the buffer parameters.
1640 ofs << "\\begin_header\n";
1641 params().writeFile(ofs, this);
1642 ofs << "\\end_header\n";
1645 ofs << "\n\\begin_body\n";
1647 ofs << "\n\\end_body\n";
1649 // Write marker that shows file is complete
1650 ofs << "\\end_document" << endl;
1652 // Shouldn't really be needed....
1655 // how to check if close went ok?
1656 // Following is an attempt... (BE 20001011)
1658 // good() returns false if any error occurred, including some
1659 // formatting error.
1660 // bad() returns true if something bad happened in the buffer,
1661 // which should include file system full errors.
1666 lyxerr << "File was not closed properly." << endl;
1673 bool Buffer::makeLaTeXFile(FileName const & fname,
1674 string const & original_path,
1675 OutputParams const & runparams_in,
1676 OutputWhat output) const
1678 OutputParams runparams = runparams_in;
1680 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1681 // Check here, because the "flavor" is not known in BufferParams::encoding()
1682 // (power users can override this safety measure selecting "utf8-plain").
1683 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1684 && (runparams.encoding->name() != "utf8-plain"))
1685 runparams.encoding = encodings.fromLyXName("ascii");
1687 string const encoding = runparams.encoding->iconvName();
1688 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1691 try { ofs.reset(encoding); }
1692 catch (iconv_codecvt_facet_exception const & e) {
1693 lyxerr << "Caught iconv exception: " << e.what() << endl;
1694 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1695 "verify that the support software for your encoding (%1$s) is "
1696 "properly installed"), from_ascii(encoding)));
1699 if (!openFileWrite(ofs, fname))
1702 ErrorList & errorList = d->errorLists["Export"];
1704 bool failed_export = false;
1707 // make sure we are ready to export
1708 // this needs to be done before we validate
1709 // FIXME Do we need to do this all the time? I.e., in children
1710 // of a master we are exporting?
1712 updateMacroInstances(OutputUpdate);
1715 writeLaTeXSource(os, original_path, runparams, output);
1717 catch (EncodingException const & e) {
1718 docstring const failed(1, e.failed_char);
1720 oss << "0x" << hex << e.failed_char << dec;
1721 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1722 " (code point %2$s)"),
1723 failed, from_utf8(oss.str()));
1724 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1725 "representable in the chosen encoding.\n"
1726 "Changing the document encoding to utf8 could help."),
1727 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1728 failed_export = true;
1730 catch (iconv_codecvt_facet_exception const & e) {
1731 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1733 failed_export = true;
1735 catch (exception const & e) {
1736 errorList.push_back(ErrorItem(_("conversion failed"),
1738 lyxerr << e.what() << endl;
1739 failed_export = true;
1742 lyxerr << "Caught some really weird exception..." << endl;
1746 d->texrow = move(os.texrow());
1750 failed_export = true;
1751 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1754 if (runparams_in.silent)
1758 return !failed_export;
1762 void Buffer::writeLaTeXSource(otexstream & os,
1763 string const & original_path,
1764 OutputParams const & runparams_in,
1765 OutputWhat output) const
1767 // The child documents, if any, shall be already loaded at this point.
1769 OutputParams runparams = runparams_in;
1771 // XeTeX with TeX fonts is only safe with ASCII encoding,
1772 // Check here, because the "flavor" is not known in BufferParams::encoding()
1773 // (power users can override this safety measure selecting "utf8-plain").
1774 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1775 && (runparams.encoding->name() != "utf8-plain"))
1776 runparams.encoding = encodings.fromLyXName("ascii");
1777 // FIXME: when only the current paragraph is shown, this is ignored
1778 // (or not reached) and characters encodable in the current
1779 // encoding are not converted to ASCII-representation.
1781 // If we are compiling a file standalone, even if this is the
1782 // child of some other buffer, let's cut the link here, so the
1783 // file is really independent and no concurring settings from
1784 // the master (e.g. branch state) interfere (see #8100).
1785 if (!runparams.is_child)
1786 d->ignore_parent = true;
1788 // Classify the unicode characters appearing in math insets
1789 BufferEncodings::initUnicodeMath(*this);
1791 // validate the buffer.
1792 LYXERR(Debug::LATEX, " Validating buffer...");
1793 LaTeXFeatures features(*this, params(), runparams);
1795 // This is only set once per document (in master)
1796 if (!runparams.is_child)
1797 runparams.use_polyglossia = features.usePolyglossia();
1798 LYXERR(Debug::LATEX, " Buffer validation done.");
1800 bool const output_preamble =
1801 output == FullSource || output == OnlyPreamble;
1802 bool const output_body =
1803 output == FullSource || output == OnlyBody;
1805 // The starting paragraph of the coming rows is the
1806 // first paragraph of the document. (Asger)
1807 if (output_preamble && runparams.nice) {
1808 os << "%% LyX " << lyx_version << " created this file. "
1809 "For more info, see http://www.lyx.org/.\n"
1810 "%% Do not edit unless you really know what "
1813 LYXERR(Debug::INFO, "lyx document header finished");
1815 // There are a few differences between nice LaTeX and usual files:
1816 // usual files have \batchmode and special input@path to allow
1817 // inclusion of figures specified by an explicitly relative path
1818 // (i.e., a path starting with './' or '../') with either \input or
1819 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1820 // input@path is set when the actual parameter original_path is set.
1821 // This is done for usual tex-file, but not for nice-latex-file.
1822 // (Matthias 250696)
1823 // Note that input@path is only needed for something the user does
1824 // in the preamble, included .tex files or ERT, files included by
1825 // LyX work without it.
1826 if (output_preamble) {
1827 if (!runparams.nice) {
1828 // code for usual, NOT nice-latex-file
1829 os << "\\batchmode\n"; // changed from \nonstopmode
1831 if (!original_path.empty()) {
1833 // We don't know the encoding of inputpath
1834 docstring const inputpath = from_utf8(original_path);
1835 docstring uncodable_glyphs;
1836 Encoding const * const enc = runparams.encoding;
1838 for (size_t n = 0; n < inputpath.size(); ++n) {
1839 if (!enc->encodable(inputpath[n])) {
1840 docstring const glyph(1, inputpath[n]);
1841 LYXERR0("Uncodable character '"
1843 << "' in input path!");
1844 uncodable_glyphs += glyph;
1849 // warn user if we found uncodable glyphs.
1850 if (!uncodable_glyphs.empty()) {
1851 frontend::Alert::warning(
1852 _("Uncodable character in file path"),
1854 _("The path of your document\n"
1856 "contains glyphs that are unknown "
1857 "in the current document encoding "
1858 "(namely %2$s). This may result in "
1859 "incomplete output, unless "
1860 "TEXINPUTS contains the document "
1861 "directory and you don't use "
1862 "explicitly relative paths (i.e., "
1863 "paths starting with './' or "
1864 "'../') in the preamble or in ERT."
1865 "\n\nIn case of problems, choose "
1866 "an appropriate document encoding\n"
1867 "(such as utf8) or change the "
1869 inputpath, uncodable_glyphs));
1872 support::latex_path(original_path);
1873 if (contains(docdir, '#')) {
1874 docdir = subst(docdir, "#", "\\#");
1875 os << "\\catcode`\\#=11"
1876 "\\def\\#{#}\\catcode`\\#=6\n";
1878 if (contains(docdir, '%')) {
1879 docdir = subst(docdir, "%", "\\%");
1880 os << "\\catcode`\\%=11"
1881 "\\def\\%{%}\\catcode`\\%=14\n";
1883 os << "\\makeatletter\n"
1884 << "\\def\\input@path{{"
1886 << "\\makeatother\n";
1890 // get parent macros (if this buffer has a parent) which will be
1891 // written at the document begin further down.
1892 MacroSet parentMacros;
1893 listParentMacros(parentMacros, features);
1895 // Write the preamble
1896 runparams.use_babel = params().writeLaTeX(os, features,
1897 d->filename.onlyPath());
1899 // Biblatex bibliographies are loaded here
1900 if (params().useBiblatex()) {
1901 vector<docstring> const bibfiles =
1902 prepareBibFilePaths(runparams, getBibfiles(), true);
1903 for (docstring const & file: bibfiles)
1904 os << "\\addbibresource{" << file << "}\n";
1907 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1908 && !features.hasOnlyPolyglossiaLanguages()) {
1911 vector<string> bll = features.getBabelExclusiveLanguages();
1912 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1915 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1920 blangs = bll.size() > 1 ?
1921 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1922 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1926 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1931 plangs = pll.size() > 1 ?
1932 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1933 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1934 if (!blangs.empty())
1938 frontend::Alert::warning(
1939 _("Incompatible Languages!"),
1941 _("You cannot use the following languages "
1942 "together in one LaTeX document because "
1943 "they require conflicting language packages:\n"
1948 // Japanese might be required only in some children of a document,
1949 // but once required, we must keep use_japanese true.
1950 runparams.use_japanese |= features.isRequired("japanese");
1953 // Restore the parenthood if needed
1954 if (!runparams.is_child)
1955 d->ignore_parent = false;
1960 // mark the beginning of the body to separate it from InPreamble insets
1961 os.texrow().start(TexRow::beginDocument());
1962 os << "\\begin{document}\n";
1964 // mark the start of a new paragraph by simulating a newline,
1965 // so that os.afterParbreak() returns true at document start
1968 // output the parent macros
1969 MacroSet::iterator it = parentMacros.begin();
1970 MacroSet::iterator end = parentMacros.end();
1971 for (; it != end; ++it) {
1972 int num_lines = (*it)->write(os.os(), true);
1973 os.texrow().newlines(num_lines);
1976 } // output_preamble
1978 LYXERR(Debug::INFO, "preamble finished, now the body.");
1981 latexParagraphs(*this, text(), os, runparams);
1983 // Restore the parenthood if needed
1984 if (!runparams.is_child)
1985 d->ignore_parent = false;
1987 // add this just in case after all the paragraphs
1990 if (output_preamble) {
1991 os << "\\end{document}\n";
1992 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1994 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1996 runparams_in.encoding = runparams.encoding;
1998 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1999 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2003 void Buffer::makeDocBookFile(FileName const & fname,
2004 OutputParams const & runparams,
2005 OutputWhat output) const
2007 LYXERR(Debug::LATEX, "makeDocBookFile...");
2010 if (!openFileWrite(ofs, fname))
2013 // make sure we are ready to export
2014 // this needs to be done before we validate
2016 updateMacroInstances(OutputUpdate);
2018 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2022 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2026 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2027 OutputParams const & runparams,
2028 OutputWhat output) const
2030 LaTeXFeatures features(*this, params(), runparams);
2035 DocumentClass const & tclass = params().documentClass();
2036 string const & top_element = tclass.latexname();
2038 bool const output_preamble =
2039 output == FullSource || output == OnlyPreamble;
2040 bool const output_body =
2041 output == FullSource || output == OnlyBody;
2043 if (output_preamble) {
2044 if (runparams.flavor == OutputParams::XML)
2045 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2048 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2051 if (! tclass.class_header().empty())
2052 os << from_ascii(tclass.class_header());
2053 else if (runparams.flavor == OutputParams::XML)
2054 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2055 << "\"https://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2057 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2059 docstring preamble = params().preamble;
2060 if (runparams.flavor != OutputParams::XML ) {
2061 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2062 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2063 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2064 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2067 string const name = runparams.nice
2068 ? changeExtension(absFileName(), ".sgml") : fname;
2069 preamble += features.getIncludedFiles(name);
2070 preamble += features.getLyXSGMLEntities();
2072 if (!preamble.empty()) {
2073 os << "\n [ " << preamble << " ]";
2079 string top = top_element;
2081 if (runparams.flavor == OutputParams::XML)
2082 top += params().language->code();
2084 top += params().language->code().substr(0, 2);
2087 if (!params().options.empty()) {
2089 top += params().options;
2092 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2093 << " file was created by LyX " << lyx_version
2094 << "\n See http://www.lyx.org/ for more information -->\n";
2096 params().documentClass().counters().reset();
2098 sgml::openTag(os, top);
2100 docbookParagraphs(text(), *this, os, runparams);
2101 sgml::closeTag(os, top_element);
2106 void Buffer::makeLyXHTMLFile(FileName const & fname,
2107 OutputParams const & runparams) const
2109 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2112 if (!openFileWrite(ofs, fname))
2115 // make sure we are ready to export
2116 // this has to be done before we validate
2117 updateBuffer(UpdateMaster, OutputUpdate);
2118 updateMacroInstances(OutputUpdate);
2120 writeLyXHTMLSource(ofs, runparams, FullSource);
2124 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2128 void Buffer::writeLyXHTMLSource(odocstream & os,
2129 OutputParams const & runparams,
2130 OutputWhat output) const
2132 LaTeXFeatures features(*this, params(), runparams);
2134 d->bibinfo_.makeCitationLabels(*this);
2136 bool const output_preamble =
2137 output == FullSource || output == OnlyPreamble;
2138 bool const output_body =
2139 output == FullSource || output == OnlyBody || output == IncludedFile;
2141 if (output_preamble) {
2142 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2143 << "<!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"
2144 // FIXME Language should be set properly.
2145 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2147 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2148 // FIXME Presumably need to set this right
2149 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2151 docstring const & doctitle = features.htmlTitle();
2153 << (doctitle.empty() ?
2154 from_ascii("LyX Document") :
2155 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2158 docstring styles = features.getTClassHTMLPreamble();
2159 if (!styles.empty())
2160 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2162 styles = features.getPreambleSnippets().str;
2163 if (!styles.empty())
2164 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2166 // we will collect CSS information in a stream, and then output it
2167 // either here, as part of the header, or else in a separate file.
2168 odocstringstream css;
2169 styles = features.getCSSSnippets();
2170 if (!styles.empty())
2171 css << "/* LyX Provided Styles */\n" << styles << '\n';
2173 styles = features.getTClassHTMLStyles();
2174 if (!styles.empty())
2175 css << "/* Layout-provided Styles */\n" << styles << '\n';
2177 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2178 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2179 if (needfg || needbg) {
2180 css << "\nbody {\n";
2183 << from_ascii(X11hexname(params().fontcolor))
2186 css << " background-color: "
2187 << from_ascii(X11hexname(params().backgroundcolor))
2192 docstring const dstyles = css.str();
2193 if (!dstyles.empty()) {
2194 bool written = false;
2195 if (params().html_css_as_file) {
2196 // open a file for CSS info
2198 string const fcssname = addName(temppath(), "docstyle.css");
2199 FileName const fcssfile = FileName(fcssname);
2200 if (openFileWrite(ocss, fcssfile)) {
2204 // write link to header
2205 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2207 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2210 // we are here if the CSS is supposed to be written to the header
2211 // or if we failed to write it to an external file.
2213 os << "<style type='text/css'>\n"
2222 bool const output_body_tag = (output != IncludedFile);
2223 if (output_body_tag)
2224 os << "<body dir=\"auto\">\n";
2226 if (output != IncludedFile)
2227 // if we're an included file, the counters are in the master.
2228 params().documentClass().counters().reset();
2229 xhtmlParagraphs(text(), *this, xs, runparams);
2230 if (output_body_tag)
2234 if (output_preamble)
2239 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2240 // Other flags: -wall -v0 -x
2241 int Buffer::runChktex()
2245 // get LaTeX-Filename
2246 FileName const path(temppath());
2247 string const name = addName(path.absFileName(), latexName());
2248 string const org_path = filePath();
2250 PathChanger p(path); // path to LaTeX file
2251 message(_("Running chktex..."));
2253 // Generate the LaTeX file if neccessary
2254 OutputParams runparams(¶ms().encoding());
2255 runparams.flavor = OutputParams::LATEX;
2256 runparams.nice = false;
2257 runparams.linelen = lyxrc.plaintext_linelen;
2258 makeLaTeXFile(FileName(name), org_path, runparams);
2261 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2262 int const res = chktex.run(terr); // run chktex
2265 Alert::error(_("chktex failure"),
2266 _("Could not run chktex successfully."));
2268 ErrorList & errlist = d->errorLists["ChkTeX"];
2270 bufferErrors(terr, errlist);
2275 if (runparams.silent)
2276 d->errorLists["ChkTeX"].clear();
2284 void Buffer::validate(LaTeXFeatures & features) const
2286 // Validate the buffer params, but not for included
2287 // files, since they also use the parent buffer's
2289 if (!features.runparams().is_child)
2290 params().validate(features);
2292 for (Paragraph const & p : paragraphs())
2293 p.validate(features);
2295 if (lyxerr.debugging(Debug::LATEX)) {
2296 features.showStruct();
2301 void Buffer::getLabelList(vector<docstring> & list) const
2303 // If this is a child document, use the master's list instead.
2305 masterBuffer()->getLabelList(list);
2310 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2311 Toc::const_iterator toc_it = toc->begin();
2312 Toc::const_iterator end = toc->end();
2313 for (; toc_it != end; ++toc_it) {
2314 if (toc_it->depth() == 0)
2315 list.push_back(toc_it->str());
2320 void Buffer::invalidateBibinfoCache() const
2322 d->bibinfo_cache_valid_ = false;
2323 d->cite_labels_valid_ = false;
2324 removeBiblioTempFiles();
2325 // also invalidate the cache for the parent buffer
2326 Buffer const * const pbuf = d->parent();
2328 pbuf->invalidateBibinfoCache();
2332 FileNamePairList const & Buffer::getBibfiles(UpdateScope scope) const
2334 // FIXME This is probably unnecessary, given where we call this.
2335 // If this is a child document, use the master instead.
2336 Buffer const * const pbuf = masterBuffer();
2337 if (pbuf != this && scope != UpdateChildOnly)
2338 return pbuf->getBibfiles();
2339 return d->bibfiles_cache_;
2343 BiblioInfo const & Buffer::masterBibInfo() const
2345 Buffer const * const tmp = masterBuffer();
2347 return tmp->masterBibInfo();
2352 BiblioInfo const & Buffer::bibInfo() const
2358 void Buffer::registerBibfiles(FileNamePairList const & bf) const {
2359 // We register the bib files in the master buffer,
2360 // if there is one, but also in every single buffer,
2361 // in case a child is compiled alone.
2362 Buffer const * const tmp = masterBuffer();
2364 tmp->registerBibfiles(bf);
2366 for (auto const & p : bf) {
2367 FileNamePairList::const_iterator tmp =
2368 find(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end(), p);
2369 if (tmp == d->bibfiles_cache_.end())
2370 d->bibfiles_cache_.push_back(p);
2375 void Buffer::checkIfBibInfoCacheIsValid() const
2377 // use the master's cache
2378 Buffer const * const tmp = masterBuffer();
2380 tmp->checkIfBibInfoCacheIsValid();
2384 // if we already know the cache is invalid, no need to check
2386 if (!d->bibinfo_cache_valid_)
2389 // compare the cached timestamps with the actual ones.
2390 FileNamePairList const & bibfiles_cache = getBibfiles();
2391 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2392 FileNamePairList::const_iterator en = bibfiles_cache.end();
2393 for (; ei != en; ++ ei) {
2394 FileName const fn = ei->second;
2395 time_t lastw = fn.lastModified();
2396 time_t prevw = d->bibfile_status_[fn];
2397 if (lastw != prevw) {
2398 d->bibinfo_cache_valid_ = false;
2399 d->cite_labels_valid_ = false;
2400 d->bibfile_status_[fn] = lastw;
2406 void Buffer::reloadBibInfoCache() const
2408 // use the master's cache
2409 Buffer const * const tmp = masterBuffer();
2411 tmp->reloadBibInfoCache();
2415 checkIfBibInfoCacheIsValid();
2416 if (d->bibinfo_cache_valid_)
2419 d->bibinfo_.clear();
2420 FileNameList checkedFiles;
2421 collectBibKeys(checkedFiles);
2422 d->bibinfo_cache_valid_ = true;
2426 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2428 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2429 it->collectBibKeys(it, checkedFiles);
2433 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2435 // We add the biblio info to the master buffer,
2436 // if there is one, but also to every single buffer,
2437 // in case a child is compiled alone.
2438 BiblioInfo & bi = d->bibinfo_;
2439 bi.mergeBiblioInfo(bin);
2441 if (parent() != 0) {
2442 BiblioInfo & masterbi = parent()->d->bibinfo_;
2443 masterbi.mergeBiblioInfo(bin);
2448 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2450 // We add the bibtex info to the master buffer,
2451 // if there is one, but also to every single buffer,
2452 // in case a child is compiled alone.
2453 BiblioInfo & bi = d->bibinfo_;
2456 if (parent() != 0) {
2457 BiblioInfo & masterbi = parent()->d->bibinfo_;
2458 masterbi[key] = bin;
2463 void Buffer::makeCitationLabels() const
2465 Buffer const * const master = masterBuffer();
2466 return d->bibinfo_.makeCitationLabels(*master);
2470 void Buffer::invalidateCiteLabels() const
2472 masterBuffer()->d->cite_labels_valid_ = false;
2475 bool Buffer::citeLabelsValid() const
2477 return masterBuffer()->d->cite_labels_valid_;
2481 void Buffer::removeBiblioTempFiles() const
2483 // We remove files that contain LaTeX commands specific to the
2484 // particular bibliographic style being used, in order to avoid
2485 // LaTeX errors when we switch style.
2486 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2487 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2488 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2489 aux_file.removeFile();
2490 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2491 bbl_file.removeFile();
2492 // Also for the parent buffer
2493 Buffer const * const pbuf = parent();
2495 pbuf->removeBiblioTempFiles();
2499 bool Buffer::isDepClean(string const & name) const
2501 DepClean::const_iterator const it = d->dep_clean.find(name);
2502 if (it == d->dep_clean.end())
2508 void Buffer::markDepClean(string const & name)
2510 d->dep_clean[name] = true;
2514 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2517 // FIXME? if there is an Buffer LFUN that can be dispatched even
2518 // if internal, put a switch '(cmd.action)' here.
2524 switch (cmd.action()) {
2526 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2527 flag.setOnOff(hasReadonlyFlag());
2530 // FIXME: There is need for a command-line import.
2531 //case LFUN_BUFFER_IMPORT:
2533 case LFUN_BUFFER_AUTO_SAVE:
2536 case LFUN_BUFFER_EXPORT_CUSTOM:
2537 // FIXME: Nothing to check here?
2540 case LFUN_BUFFER_EXPORT: {
2541 docstring const arg = cmd.argument();
2542 if (arg == "custom") {
2546 string format = (arg.empty() || arg == "default") ?
2547 params().getDefaultOutputFormat() : to_utf8(arg);
2548 size_t pos = format.find(' ');
2549 if (pos != string::npos)
2550 format = format.substr(0, pos);
2551 enable = params().isExportable(format, false);
2553 flag.message(bformat(
2554 _("Don't know how to export to format: %1$s"), arg));
2558 case LFUN_BUILD_PROGRAM:
2559 enable = params().isExportable("program", false);
2562 case LFUN_BRANCH_ACTIVATE:
2563 case LFUN_BRANCH_DEACTIVATE:
2564 case LFUN_BRANCH_MASTER_ACTIVATE:
2565 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2566 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2567 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2568 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2569 : params().branchlist();
2570 docstring const branchName = cmd.argument();
2571 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2575 case LFUN_BRANCH_ADD:
2576 case LFUN_BRANCHES_RENAME:
2577 // if no Buffer is present, then of course we won't be called!
2580 case LFUN_BUFFER_LANGUAGE:
2581 enable = !isReadonly();
2584 case LFUN_BUFFER_VIEW_CACHE:
2585 (d->preview_file_).refresh();
2586 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2589 case LFUN_CHANGES_TRACK:
2590 flag.setEnabled(true);
2591 flag.setOnOff(params().track_changes);
2594 case LFUN_CHANGES_OUTPUT:
2595 flag.setEnabled(true);
2596 flag.setOnOff(params().output_changes);
2599 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2600 flag.setOnOff(params().compressed);
2603 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2604 flag.setOnOff(params().output_sync);
2607 case LFUN_BUFFER_ANONYMIZE:
2613 flag.setEnabled(enable);
2618 void Buffer::dispatch(string const & command, DispatchResult & result)
2620 return dispatch(lyxaction.lookupFunc(command), result);
2624 // NOTE We can end up here even if we have no GUI, because we are called
2625 // by LyX::exec to handled command-line requests. So we may need to check
2626 // whether we have a GUI or not. The boolean use_gui holds this information.
2627 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2630 // FIXME? if there is an Buffer LFUN that can be dispatched even
2631 // if internal, put a switch '(cmd.action())' here.
2632 dr.dispatched(false);
2635 string const argument = to_utf8(func.argument());
2636 // We'll set this back to false if need be.
2637 bool dispatched = true;
2638 // This handles undo groups automagically
2639 UndoGroupHelper ugh(this);
2641 switch (func.action()) {
2642 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2643 if (lyxvc().inUse()) {
2644 string log = lyxvc().toggleReadOnly();
2649 setReadonly(!hasReadonlyFlag());
2652 case LFUN_BUFFER_EXPORT: {
2653 string const format = (argument.empty() || argument == "default") ?
2654 params().getDefaultOutputFormat() : argument;
2655 ExportStatus const status = doExport(format, false);
2656 dr.setError(status != ExportSuccess);
2657 if (status != ExportSuccess)
2658 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2659 from_utf8(format)));
2663 case LFUN_BUILD_PROGRAM: {
2664 ExportStatus const status = doExport("program", true);
2665 dr.setError(status != ExportSuccess);
2666 if (status != ExportSuccess)
2667 dr.setMessage(_("Error generating literate programming code."));
2671 case LFUN_BUFFER_EXPORT_CUSTOM: {
2673 string command = split(argument, format_name, ' ');
2674 Format const * format = theFormats().getFormat(format_name);
2676 lyxerr << "Format \"" << format_name
2677 << "\" not recognized!"
2682 // The name of the file created by the conversion process
2685 // Output to filename
2686 if (format->name() == "lyx") {
2687 string const latexname = latexName(false);
2688 filename = changeExtension(latexname,
2689 format->extension());
2690 filename = addName(temppath(), filename);
2692 if (!writeFile(FileName(filename)))
2696 doExport(format_name, true, filename);
2699 // Substitute $$FName for filename
2700 if (!contains(command, "$$FName"))
2701 command = "( " + command + " ) < $$FName";
2702 command = subst(command, "$$FName", filename);
2704 // Execute the command in the background
2706 call.startscript(Systemcall::DontWait, command,
2707 filePath(), layoutPos());
2711 // FIXME: There is need for a command-line import.
2713 case LFUN_BUFFER_IMPORT:
2718 case LFUN_BUFFER_AUTO_SAVE:
2720 resetAutosaveTimers();
2723 case LFUN_BRANCH_ACTIVATE:
2724 case LFUN_BRANCH_DEACTIVATE:
2725 case LFUN_BRANCH_MASTER_ACTIVATE:
2726 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2727 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2728 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2729 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2732 docstring const branch_name = func.argument();
2733 // the case without a branch name is handled elsewhere
2734 if (branch_name.empty()) {
2738 Branch * branch = buf->params().branchlist().find(branch_name);
2740 LYXERR0("Branch " << branch_name << " does not exist.");
2742 docstring const msg =
2743 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2747 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2748 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2749 if (branch->isSelected() != activate) {
2750 buf->undo().recordUndoBufferParams(CursorData());
2751 branch->setSelected(activate);
2753 dr.screenUpdate(Update::Force);
2754 dr.forceBufferUpdate();
2759 case LFUN_BRANCH_ADD: {
2760 docstring branch_name = func.argument();
2761 if (branch_name.empty()) {
2765 BranchList & branch_list = params().branchlist();
2766 vector<docstring> const branches =
2767 getVectorFromString(branch_name, branch_list.separator());
2769 for (vector<docstring>::const_iterator it = branches.begin();
2770 it != branches.end(); ++it) {
2772 Branch * branch = branch_list.find(branch_name);
2774 LYXERR0("Branch " << branch_name << " already exists.");
2778 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2780 undo().recordUndoBufferParams(CursorData());
2781 branch_list.add(branch_name);
2782 branch = branch_list.find(branch_name);
2783 string const x11hexname = X11hexname(branch->color());
2784 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2785 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2787 dr.screenUpdate(Update::Force);
2795 case LFUN_BRANCHES_RENAME: {
2796 if (func.argument().empty())
2799 docstring const oldname = from_utf8(func.getArg(0));
2800 docstring const newname = from_utf8(func.getArg(1));
2801 InsetIterator it = inset_iterator_begin(inset());
2802 InsetIterator const end = inset_iterator_end(inset());
2803 bool success = false;
2804 for (; it != end; ++it) {
2805 if (it->lyxCode() == BRANCH_CODE) {
2806 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2807 if (ins.branch() == oldname) {
2808 undo().recordUndo(CursorData(it));
2809 ins.rename(newname);
2814 if (it->lyxCode() == INCLUDE_CODE) {
2815 // get buffer of external file
2816 InsetInclude const & ins =
2817 static_cast<InsetInclude const &>(*it);
2818 Buffer * child = ins.getChildBuffer();
2821 child->dispatch(func, dr);
2826 dr.screenUpdate(Update::Force);
2827 dr.forceBufferUpdate();
2832 case LFUN_BUFFER_VIEW_CACHE:
2833 if (!theFormats().view(*this, d->preview_file_,
2834 d->preview_format_))
2835 dr.setMessage(_("Error viewing the output file."));
2838 case LFUN_CHANGES_TRACK:
2839 if (params().save_transient_properties)
2840 undo().recordUndoBufferParams(CursorData());
2841 params().track_changes = !params().track_changes;
2842 if (!params().track_changes)
2843 dr.forceChangesUpdate();
2846 case LFUN_CHANGES_OUTPUT:
2847 if (params().save_transient_properties)
2848 undo().recordUndoBufferParams(CursorData());
2849 params().output_changes = !params().output_changes;
2850 if (params().output_changes) {
2851 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2852 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2853 LaTeXFeatures::isAvailable("xcolor");
2855 if (!dvipost && !xcolorulem) {
2856 Alert::warning(_("Changes not shown in LaTeX output"),
2857 _("Changes will not be highlighted in LaTeX output, "
2858 "because neither dvipost nor xcolor/ulem are installed.\n"
2859 "Please install these packages or redefine "
2860 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2861 } else if (!xcolorulem) {
2862 Alert::warning(_("Changes not shown in LaTeX output"),
2863 _("Changes will not be highlighted in LaTeX output "
2864 "when using pdflatex, because xcolor and ulem are not installed.\n"
2865 "Please install both packages or redefine "
2866 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2871 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2872 // turn compression on/off
2873 undo().recordUndoBufferParams(CursorData());
2874 params().compressed = !params().compressed;
2877 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2878 undo().recordUndoBufferParams(CursorData());
2879 params().output_sync = !params().output_sync;
2882 case LFUN_BUFFER_ANONYMIZE: {
2883 undo().recordUndoFullBuffer(CursorData());
2884 CursorData cur(doc_iterator_begin(this));
2885 for ( ; cur ; cur.forwardPar())
2886 cur.paragraph().anonymize();
2887 dr.forceBufferUpdate();
2895 dr.dispatched(dispatched);
2899 void Buffer::changeLanguage(Language const * from, Language const * to)
2901 LASSERT(from, return);
2902 LASSERT(to, return);
2904 for_each(par_iterator_begin(),
2906 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2910 bool Buffer::isMultiLingual() const
2912 ParConstIterator end = par_iterator_end();
2913 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2914 if (it->isMultiLingual(params()))
2921 std::set<Language const *> Buffer::getLanguages() const
2923 std::set<Language const *> languages;
2924 getLanguages(languages);
2929 void Buffer::getLanguages(std::set<Language const *> & languages) const
2931 ParConstIterator end = par_iterator_end();
2932 // add the buffer language, even if it's not actively used
2933 languages.insert(language());
2934 // iterate over the paragraphs
2935 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2936 it->getLanguages(languages);
2938 ListOfBuffers clist = getDescendents();
2939 ListOfBuffers::const_iterator cit = clist.begin();
2940 ListOfBuffers::const_iterator const cen = clist.end();
2941 for (; cit != cen; ++cit)
2942 (*cit)->getLanguages(languages);
2946 DocIterator Buffer::getParFromID(int const id) const
2948 Buffer * buf = const_cast<Buffer *>(this);
2950 // This means non-existent
2951 return doc_iterator_end(buf);
2953 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2954 if (it.paragraph().id() == id)
2957 return doc_iterator_end(buf);
2961 bool Buffer::hasParWithID(int const id) const
2963 return !getParFromID(id).atEnd();
2967 ParIterator Buffer::par_iterator_begin()
2969 return ParIterator(doc_iterator_begin(this));
2973 ParIterator Buffer::par_iterator_end()
2975 return ParIterator(doc_iterator_end(this));
2979 ParConstIterator Buffer::par_iterator_begin() const
2981 return ParConstIterator(doc_iterator_begin(this));
2985 ParConstIterator Buffer::par_iterator_end() const
2987 return ParConstIterator(doc_iterator_end(this));
2991 Language const * Buffer::language() const
2993 return params().language;
2997 docstring const Buffer::B_(string const & l10n) const
2999 return params().B_(l10n);
3003 bool Buffer::isClean() const
3005 return d->lyx_clean;
3009 bool Buffer::isChecksumModified() const
3011 LASSERT(d->filename.exists(), return false);
3012 return d->checksum_ != d->filename.checksum();
3016 void Buffer::saveCheckSum() const
3018 FileName const & file = d->filename;
3020 d->checksum_ = file.exists() ? file.checksum()
3021 : 0; // in the case of save to a new file.
3025 void Buffer::markClean() const
3027 if (!d->lyx_clean) {
3028 d->lyx_clean = true;
3031 // if the .lyx file has been saved, we don't need an
3033 d->bak_clean = true;
3034 d->undo_.markDirty();
3035 clearExternalModification();
3039 void Buffer::setUnnamed(bool flag)
3045 bool Buffer::isUnnamed() const
3052 /// Don't check unnamed, here: isInternal() is used in
3053 /// newBuffer(), where the unnamed flag has not been set by anyone
3054 /// yet. Also, for an internal buffer, there should be no need for
3055 /// retrieving fileName() nor for checking if it is unnamed or not.
3056 bool Buffer::isInternal() const
3058 return d->internal_buffer;
3062 void Buffer::setInternal(bool flag)
3064 d->internal_buffer = flag;
3068 void Buffer::markDirty()
3071 d->lyx_clean = false;
3074 d->bak_clean = false;
3076 DepClean::iterator it = d->dep_clean.begin();
3077 DepClean::const_iterator const end = d->dep_clean.end();
3079 for (; it != end; ++it)
3084 FileName Buffer::fileName() const
3090 string Buffer::absFileName() const
3092 return d->filename.absFileName();
3096 string Buffer::filePath() const
3098 string const abs = d->filename.onlyPath().absFileName();
3101 int last = abs.length() - 1;
3103 return abs[last] == '/' ? abs : abs + '/';
3107 DocFileName Buffer::getReferencedFileName(string const & fn) const
3110 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3111 result.set(fn, filePath());
3113 // filePath() ends with a path separator
3114 FileName const test(filePath() + fn);
3116 result.set(fn, filePath());
3118 result.set(fn, params().origin);
3125 string const Buffer::prepareFileNameForLaTeX(string const & name,
3126 string const & ext, bool nice) const
3128 string const fname = makeAbsPath(name, filePath()).absFileName();
3129 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3135 return to_utf8(makeRelPath(from_utf8(fname),
3136 from_utf8(masterBuffer()->filePath())));
3140 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3141 FileNamePairList const bibfilelist,
3142 bool const add_extension) const
3144 // If we are processing the LaTeX file in a temp directory then
3145 // copy the .bib databases to this temp directory, mangling their
3146 // names in the process. Store this mangled name in the list of
3148 // (We need to do all this because BibTeX *really*, *really*
3149 // can't handle "files with spaces" and Windows users tend to
3150 // use such filenames.)
3151 // Otherwise, store the (maybe absolute) path to the original,
3152 // unmangled database name.
3154 vector<docstring> res;
3156 // determine the export format
3157 string const tex_format = flavor2format(runparams.flavor);
3159 // check for spaces in paths
3160 bool found_space = false;
3162 FileNamePairList::const_iterator it = bibfilelist.begin();
3163 FileNamePairList::const_iterator en = bibfilelist.end();
3164 for (; it != en; ++it) {
3165 string utf8input = to_utf8(it->first);
3167 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3168 FileName try_in_file =
3169 makeAbsPath(database + ".bib", filePath());
3170 bool not_from_texmf = try_in_file.isReadableFile();
3171 // If the file has not been found, try with the real file name
3172 // (it might come from a child in a sub-directory)
3173 if (!not_from_texmf) {
3174 try_in_file = it->second;
3175 if (try_in_file.isReadableFile()) {
3176 // Check if the file is in texmf
3177 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3178 not_from_texmf = kpsefile.empty()
3179 || kpsefile.absFileName() != try_in_file.absFileName();
3181 // If this exists, make path relative to the master
3183 database = removeExtension(
3184 prepareFileNameForLaTeX(to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3185 from_utf8(filePath()))),
3186 ".bib", runparams.nice));
3190 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3192 // mangledFileName() needs the extension
3193 DocFileName const in_file = DocFileName(try_in_file);
3194 database = removeExtension(in_file.mangledFileName());
3195 FileName const out_file = makeAbsPath(database + ".bib",
3196 masterBuffer()->temppath());
3197 bool const success = in_file.copyTo(out_file);
3199 LYXERR0("Failed to copy '" << in_file
3200 << "' to '" << out_file << "'");
3202 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3203 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3204 if (!isValidLaTeXFileName(database)) {
3205 frontend::Alert::warning(_("Invalid filename"),
3206 _("The following filename will cause troubles "
3207 "when running the exported file through LaTeX: ") +
3208 from_utf8(database));
3210 if (!isValidDVIFileName(database)) {
3211 frontend::Alert::warning(_("Problematic filename for DVI"),
3212 _("The following filename can cause troubles "
3213 "when running the exported file through LaTeX "
3214 "and opening the resulting DVI: ") +
3215 from_utf8(database), true);
3223 docstring const path = from_utf8(latex_path(database));
3225 if (contains(path, ' '))
3228 if (find(res.begin(), res.end(), path) == res.end())
3229 res.push_back(path);
3232 // Check if there are spaces in the path and warn BibTeX users, if so.
3233 // (biber can cope with such paths)
3234 if (!prefixIs(runparams.bibtex_command, "biber")) {
3235 // Post this warning only once.
3236 static bool warned_about_spaces = false;
3237 if (!warned_about_spaces &&
3238 runparams.nice && found_space) {
3239 warned_about_spaces = true;
3240 Alert::warning(_("Export Warning!"),
3241 _("There are spaces in the paths to your BibTeX databases.\n"
3242 "BibTeX will be unable to find them."));
3251 string Buffer::layoutPos() const
3253 return d->layout_position;
3257 void Buffer::setLayoutPos(string const & path)
3260 d->layout_position.clear();
3264 LATTEST(FileName::isAbsolute(path));
3266 d->layout_position =
3267 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3269 if (d->layout_position.empty())
3270 d->layout_position = ".";
3274 bool Buffer::hasReadonlyFlag() const
3276 return d->read_only;
3280 bool Buffer::isReadonly() const
3282 return hasReadonlyFlag() || notifiesExternalModification();
3286 void Buffer::setParent(Buffer const * buffer)
3288 // Avoids recursive include.
3289 d->setParent(buffer == this ? 0 : buffer);
3294 Buffer const * Buffer::parent() const
3300 ListOfBuffers Buffer::allRelatives() const
3302 ListOfBuffers lb = masterBuffer()->getDescendents();
3303 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3308 Buffer const * Buffer::masterBuffer() const
3310 // FIXME Should be make sure we are not in some kind
3311 // of recursive include? A -> B -> A will crash this.
3312 Buffer const * const pbuf = d->parent();
3316 return pbuf->masterBuffer();
3320 bool Buffer::isChild(Buffer * child) const
3322 return d->children_positions.find(child) != d->children_positions.end();
3326 DocIterator Buffer::firstChildPosition(Buffer const * child)
3328 Impl::BufferPositionMap::iterator it;
3329 it = d->children_positions.find(child);
3330 if (it == d->children_positions.end())
3331 return DocIterator(this);
3336 bool Buffer::hasChildren() const
3338 return !d->children_positions.empty();
3342 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3344 // loop over children
3345 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3346 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3347 for (; it != end; ++it) {
3348 Buffer * child = const_cast<Buffer *>(it->first);
3350 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3351 if (bit != clist.end())
3353 clist.push_back(child);
3355 // there might be grandchildren
3356 child->collectChildren(clist, true);
3361 ListOfBuffers Buffer::getChildren() const
3364 collectChildren(v, false);
3365 // Make sure we have not included ourselves.
3366 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3367 if (bit != v.end()) {
3368 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3375 ListOfBuffers Buffer::getDescendents() const
3378 collectChildren(v, true);
3379 // Make sure we have not included ourselves.
3380 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3381 if (bit != v.end()) {
3382 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3389 template<typename M>
3390 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3395 typename M::const_iterator it = m.lower_bound(x);
3396 if (it == m.begin())
3404 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3405 DocIterator const & pos) const
3407 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3409 // if paragraphs have no macro context set, pos will be empty
3413 // we haven't found anything yet
3414 DocIterator bestPos = owner_->par_iterator_begin();
3415 MacroData const * bestData = 0;
3417 // find macro definitions for name
3418 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3419 if (nameIt != macros.end()) {
3420 // find last definition in front of pos or at pos itself
3421 PositionScopeMacroMap::const_iterator it
3422 = greatest_below(nameIt->second, pos);
3423 if (it != nameIt->second.end()) {
3425 // scope ends behind pos?
3426 if (pos < it->second.scope) {
3427 // Looks good, remember this. If there
3428 // is no external macro behind this,
3429 // we found the right one already.
3430 bestPos = it->first;
3431 bestData = &it->second.macro;
3435 // try previous macro if there is one
3436 if (it == nameIt->second.begin())
3443 // find macros in included files
3444 PositionScopeBufferMap::const_iterator it
3445 = greatest_below(position_to_children, pos);
3446 if (it == position_to_children.end())
3447 // no children before
3451 // do we know something better (i.e. later) already?
3452 if (it->first < bestPos )
3455 // scope ends behind pos?
3456 if (pos < it->second.scope
3457 && (cloned_buffer_ ||
3458 theBufferList().isLoaded(it->second.buffer))) {
3459 // look for macro in external file
3461 MacroData const * data
3462 = it->second.buffer->getMacro(name, false);
3465 bestPos = it->first;
3471 // try previous file if there is one
3472 if (it == position_to_children.begin())
3477 // return the best macro we have found
3482 MacroData const * Buffer::getMacro(docstring const & name,
3483 DocIterator const & pos, bool global) const
3488 // query buffer macros
3489 MacroData const * data = d->getBufferMacro(name, pos);
3493 // If there is a master buffer, query that
3494 Buffer const * const pbuf = d->parent();
3496 d->macro_lock = true;
3497 MacroData const * macro = pbuf->getMacro(
3498 name, *this, false);
3499 d->macro_lock = false;
3505 data = MacroTable::globalMacros().get(name);
3514 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3516 // set scope end behind the last paragraph
3517 DocIterator scope = par_iterator_begin();
3518 scope.pit() = scope.lastpit() + 1;
3520 return getMacro(name, scope, global);
3524 MacroData const * Buffer::getMacro(docstring const & name,
3525 Buffer const & child, bool global) const
3527 // look where the child buffer is included first
3528 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3529 if (it == d->children_positions.end())
3532 // check for macros at the inclusion position
3533 return getMacro(name, it->second, global);
3537 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3539 pit_type const lastpit = it.lastpit();
3541 // look for macros in each paragraph
3542 while (it.pit() <= lastpit) {
3543 Paragraph & par = it.paragraph();
3545 // iterate over the insets of the current paragraph
3546 InsetList const & insets = par.insetList();
3547 InsetList::const_iterator iit = insets.begin();
3548 InsetList::const_iterator end = insets.end();
3549 for (; iit != end; ++iit) {
3550 it.pos() = iit->pos;
3552 // is it a nested text inset?
3553 if (iit->inset->asInsetText()) {
3554 // Inset needs its own scope?
3555 InsetText const * itext = iit->inset->asInsetText();
3556 bool newScope = itext->isMacroScope();
3558 // scope which ends just behind the inset
3559 DocIterator insetScope = it;
3562 // collect macros in inset
3563 it.push_back(CursorSlice(*iit->inset));
3564 updateMacros(it, newScope ? insetScope : scope);
3569 if (iit->inset->asInsetTabular()) {
3570 CursorSlice slice(*iit->inset);
3571 size_t const numcells = slice.nargs();
3572 for (; slice.idx() < numcells; slice.forwardIdx()) {
3573 it.push_back(slice);
3574 updateMacros(it, scope);
3580 // is it an external file?
3581 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3582 // get buffer of external file
3583 InsetInclude const & inset =
3584 static_cast<InsetInclude const &>(*iit->inset);
3586 Buffer * child = inset.getChildBuffer();
3591 // register its position, but only when it is
3592 // included first in the buffer
3593 if (children_positions.find(child) ==
3594 children_positions.end())
3595 children_positions[child] = it;
3597 // register child with its scope
3598 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3602 InsetMath * im = iit->inset->asInsetMath();
3603 if (doing_export && im) {
3604 InsetMathHull * hull = im->asHullInset();
3606 hull->recordLocation(it);
3609 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3613 InsetMathMacroTemplate & macroTemplate =
3614 *iit->inset->asInsetMath()->asMacroTemplate();
3615 MacroContext mc(owner_, it);
3616 macroTemplate.updateToContext(mc);
3619 bool valid = macroTemplate.validMacro();
3620 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3621 // then the BufferView's cursor will be invalid in
3622 // some cases which leads to crashes.
3627 // FIXME (Abdel), I don't understand why we pass 'it' here
3628 // instead of 'macroTemplate' defined above... is this correct?
3629 macros[macroTemplate.name()][it] =
3630 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3640 void Buffer::updateMacros() const
3645 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3647 // start with empty table
3649 d->children_positions.clear();
3650 d->position_to_children.clear();
3652 // Iterate over buffer, starting with first paragraph
3653 // The scope must be bigger than any lookup DocIterator
3654 // later. For the global lookup, lastpit+1 is used, hence
3655 // we use lastpit+2 here.
3656 DocIterator it = par_iterator_begin();
3657 DocIterator outerScope = it;
3658 outerScope.pit() = outerScope.lastpit() + 2;
3659 d->updateMacros(it, outerScope);
3663 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3665 InsetIterator it = inset_iterator_begin(inset());
3666 InsetIterator const end = inset_iterator_end(inset());
3667 for (; it != end; ++it) {
3668 if (it->lyxCode() == BRANCH_CODE) {
3669 InsetBranch & br = static_cast<InsetBranch &>(*it);
3670 docstring const name = br.branch();
3671 if (!from_master && !params().branchlist().find(name))
3672 result.push_back(name);
3673 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3674 result.push_back(name);
3677 if (it->lyxCode() == INCLUDE_CODE) {
3678 // get buffer of external file
3679 InsetInclude const & ins =
3680 static_cast<InsetInclude const &>(*it);
3681 Buffer * child = ins.getChildBuffer();
3684 child->getUsedBranches(result, true);
3687 // remove duplicates
3692 void Buffer::updateMacroInstances(UpdateType utype) const
3694 LYXERR(Debug::MACROS, "updateMacroInstances for "
3695 << d->filename.onlyFileName());
3696 DocIterator it = doc_iterator_begin(this);
3698 DocIterator const end = doc_iterator_end(this);
3699 for (; it != end; it.forwardInset()) {
3700 // look for MathData cells in InsetMathNest insets
3701 InsetMath * minset = it.nextInset()->asInsetMath();
3705 // update macro in all cells of the InsetMathNest
3706 DocIterator::idx_type n = minset->nargs();
3707 MacroContext mc = MacroContext(this, it);
3708 for (DocIterator::idx_type i = 0; i < n; ++i) {
3709 MathData & data = minset->cell(i);
3710 data.updateMacros(0, mc, utype, 0);
3716 void Buffer::listMacroNames(MacroNameSet & macros) const
3721 d->macro_lock = true;
3723 // loop over macro names
3724 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3725 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3726 for (; nameIt != nameEnd; ++nameIt)
3727 macros.insert(nameIt->first);
3729 // loop over children
3730 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3731 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3732 for (; it != end; ++it) {
3733 Buffer * child = const_cast<Buffer *>(it->first);
3734 // The buffer might have been closed (see #10766).
3735 if (theBufferList().isLoaded(child))
3736 child->listMacroNames(macros);
3740 Buffer const * const pbuf = d->parent();
3742 pbuf->listMacroNames(macros);
3744 d->macro_lock = false;
3748 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3750 Buffer const * const pbuf = d->parent();
3755 pbuf->listMacroNames(names);
3758 MacroNameSet::iterator it = names.begin();
3759 MacroNameSet::iterator end = names.end();
3760 for (; it != end; ++it) {
3762 MacroData const * data =
3763 pbuf->getMacro(*it, *this, false);
3765 macros.insert(data);
3767 // we cannot access the original InsetMathMacroTemplate anymore
3768 // here to calls validate method. So we do its work here manually.
3769 // FIXME: somehow make the template accessible here.
3770 if (data->optionals() > 0)
3771 features.require("xargs");
3777 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3780 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3782 RefCache::iterator it = d->ref_cache_.find(label);
3783 if (it != d->ref_cache_.end())
3784 return it->second.second;
3786 static InsetLabel const * dummy_il = 0;
3787 static References const dummy_refs = References();
3788 it = d->ref_cache_.insert(
3789 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3790 return it->second.second;
3794 Buffer::References const & Buffer::references(docstring const & label) const
3796 return const_cast<Buffer *>(this)->getReferenceCache(label);
3800 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3802 References & refs = getReferenceCache(label);
3803 refs.push_back(make_pair(inset, it));
3807 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3809 masterBuffer()->d->ref_cache_[label].first = il;
3813 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3815 return masterBuffer()->d->ref_cache_[label].first;
3819 void Buffer::clearReferenceCache() const
3822 d->ref_cache_.clear();
3826 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3828 //FIXME: This does not work for child documents yet.
3829 reloadBibInfoCache();
3831 // Check if the label 'from' appears more than once
3832 BiblioInfo const & keys = masterBibInfo();
3833 BiblioInfo::const_iterator bit = keys.begin();
3834 BiblioInfo::const_iterator bend = keys.end();
3835 vector<docstring> labels;
3837 for (; bit != bend; ++bit)
3839 labels.push_back(bit->first);
3841 if (count(labels.begin(), labels.end(), from) > 1)
3844 string const paramName = "key";
3845 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3846 if (it->lyxCode() != CITE_CODE)
3848 InsetCommand * inset = it->asInsetCommand();
3849 docstring const oldValue = inset->getParam(paramName);
3850 if (oldValue == from)
3851 inset->setParam(paramName, to);
3855 // returns NULL if id-to-row conversion is unsupported
3856 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3857 pit_type par_begin, pit_type par_end,
3858 OutputWhat output, bool master) const
3860 unique_ptr<TexRow> texrow;
3861 OutputParams runparams(¶ms().encoding());
3862 runparams.nice = true;
3863 runparams.flavor = params().getOutputFlavor(format);
3864 runparams.linelen = lyxrc.plaintext_linelen;
3865 // No side effect of file copying and image conversion
3866 runparams.dryrun = true;
3868 if (output == CurrentParagraph) {
3869 runparams.par_begin = par_begin;
3870 runparams.par_end = par_end;
3871 if (par_begin + 1 == par_end) {
3873 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3877 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3878 convert<docstring>(par_begin),
3879 convert<docstring>(par_end - 1))
3882 // output paragraphs
3883 if (runparams.flavor == OutputParams::LYX) {
3884 Paragraph const & par = text().paragraphs()[par_begin];
3886 depth_type dt = par.getDepth();
3887 par.write(ods, params(), dt);
3888 os << from_utf8(ods.str());
3889 } else if (runparams.flavor == OutputParams::HTML) {
3891 setMathFlavor(runparams);
3892 xhtmlParagraphs(text(), *this, xs, runparams);
3893 } else if (runparams.flavor == OutputParams::TEXT) {
3895 // FIXME Handles only one paragraph, unlike the others.
3896 // Probably should have some routine with a signature like them.
3897 writePlaintextParagraph(*this,
3898 text().paragraphs()[par_begin], os, runparams, dummy);
3899 } else if (params().isDocBook()) {
3900 docbookParagraphs(text(), *this, os, runparams);
3902 // If we are previewing a paragraph, even if this is the
3903 // child of some other buffer, let's cut the link here,
3904 // so that no concurring settings from the master
3905 // (e.g. branch state) interfere (see #8101).
3907 d->ignore_parent = true;
3908 // We need to validate the Buffer params' features here
3909 // in order to know if we should output polyglossia
3910 // macros (instead of babel macros)
3911 LaTeXFeatures features(*this, params(), runparams);
3913 runparams.use_polyglossia = features.usePolyglossia();
3914 // latex or literate
3917 ots.texrow().newlines(2);
3919 latexParagraphs(*this, text(), ots, runparams);
3920 texrow = ots.releaseTexRow();
3922 // Restore the parenthood
3924 d->ignore_parent = false;
3928 if (output == FullSource)
3929 os << _("Preview source code");
3930 else if (output == OnlyPreamble)
3931 os << _("Preview preamble");
3932 else if (output == OnlyBody)
3933 os << _("Preview body");
3935 if (runparams.flavor == OutputParams::LYX) {
3937 if (output == FullSource)
3939 else if (output == OnlyPreamble)
3940 params().writeFile(ods, this);
3941 else if (output == OnlyBody)
3943 os << from_utf8(ods.str());
3944 } else if (runparams.flavor == OutputParams::HTML) {
3945 writeLyXHTMLSource(os, runparams, output);
3946 } else if (runparams.flavor == OutputParams::TEXT) {
3947 if (output == OnlyPreamble) {
3948 os << "% "<< _("Plain text does not have a preamble.");
3950 writePlaintextFile(*this, os, runparams);
3951 } else if (params().isDocBook()) {
3952 writeDocBookSource(os, absFileName(), runparams, output);
3954 // latex or literate
3957 ots.texrow().newlines(2);
3959 runparams.is_child = true;
3961 writeLaTeXSource(ots, string(), runparams, output);
3962 texrow = ots.releaseTexRow();
3969 ErrorList & Buffer::errorList(string const & type) const
3971 return d->errorLists[type];
3975 void Buffer::updateTocItem(std::string const & type,
3976 DocIterator const & dit) const
3979 d->gui_->updateTocItem(type, dit);
3983 void Buffer::structureChanged() const
3986 d->gui_->structureChanged();
3990 void Buffer::errors(string const & err, bool from_master) const
3993 d->gui_->errors(err, from_master);
3997 void Buffer::message(docstring const & msg) const
4000 d->gui_->message(msg);
4004 void Buffer::setBusy(bool on) const
4007 d->gui_->setBusy(on);
4011 void Buffer::updateTitles() const
4014 d->wa_->updateTitles();
4018 void Buffer::resetAutosaveTimers() const
4021 d->gui_->resetAutosaveTimers();
4025 bool Buffer::hasGuiDelegate() const
4031 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4040 class AutoSaveBuffer : public ForkedProcess {
4043 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4044 : buffer_(buffer), fname_(fname) {}
4046 virtual shared_ptr<ForkedProcess> clone() const
4048 return make_shared<AutoSaveBuffer>(*this);
4053 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4054 from_utf8(fname_.absFileName())));
4055 return run(DontWait);
4059 virtual int generateChild();
4061 Buffer const & buffer_;
4066 int AutoSaveBuffer::generateChild()
4068 #if defined(__APPLE__)
4069 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4070 * We should use something else like threads.
4072 * Since I do not know how to determine at run time what is the OS X
4073 * version, I just disable forking altogether for now (JMarc)
4075 pid_t const pid = -1;
4077 // tmp_ret will be located (usually) in /tmp
4078 // will that be a problem?
4079 // Note that this calls ForkedCalls::fork(), so it's
4080 // ok cross-platform.
4081 pid_t const pid = fork();
4082 // If you want to debug the autosave
4083 // you should set pid to -1, and comment out the fork.
4084 if (pid != 0 && pid != -1)
4088 // pid = -1 signifies that lyx was unable
4089 // to fork. But we will do the save
4091 bool failed = false;
4092 TempFile tempfile("lyxautoXXXXXX.lyx");
4093 tempfile.setAutoRemove(false);
4094 FileName const tmp_ret = tempfile.name();
4095 if (!tmp_ret.empty()) {
4096 if (!buffer_.writeFile(tmp_ret))
4098 else if (!tmp_ret.moveTo(fname_))
4104 // failed to write/rename tmp_ret so try writing direct
4105 if (!buffer_.writeFile(fname_)) {
4106 // It is dangerous to do this in the child,
4107 // but safe in the parent, so...
4108 if (pid == -1) // emit message signal.
4109 buffer_.message(_("Autosave failed!"));
4113 if (pid == 0) // we are the child so...
4122 FileName Buffer::getEmergencyFileName() const
4124 return FileName(d->filename.absFileName() + ".emergency");
4128 FileName Buffer::getAutosaveFileName() const
4130 // if the document is unnamed try to save in the backup dir, else
4131 // in the default document path, and as a last try in the filePath,
4132 // which will most often be the temporary directory
4135 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4136 : lyxrc.backupdir_path;
4137 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4140 string const fname = "#" + d->filename.onlyFileName() + "#";
4142 return makeAbsPath(fname, fpath);
4146 void Buffer::removeAutosaveFile() const
4148 FileName const f = getAutosaveFileName();
4154 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4156 FileName const newauto = getAutosaveFileName();
4158 if (newauto != oldauto && oldauto.exists())
4159 if (!oldauto.moveTo(newauto))
4160 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4164 bool Buffer::autoSave() const
4166 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4167 if (buf->d->bak_clean || hasReadonlyFlag())
4170 message(_("Autosaving current document..."));
4171 buf->d->bak_clean = true;
4173 FileName const fname = getAutosaveFileName();
4174 LASSERT(d->cloned_buffer_, return false);
4176 // If this buffer is cloned, we assume that
4177 // we are running in a separate thread already.
4178 TempFile tempfile("lyxautoXXXXXX.lyx");
4179 tempfile.setAutoRemove(false);
4180 FileName const tmp_ret = tempfile.name();
4181 if (!tmp_ret.empty()) {
4183 // assume successful write of tmp_ret
4184 if (tmp_ret.moveTo(fname))
4187 // failed to write/rename tmp_ret so try writing direct
4188 return writeFile(fname);
4192 void Buffer::setExportStatus(bool e) const
4194 d->doing_export = e;
4195 ListOfBuffers clist = getDescendents();
4196 ListOfBuffers::const_iterator cit = clist.begin();
4197 ListOfBuffers::const_iterator const cen = clist.end();
4198 for (; cit != cen; ++cit)
4199 (*cit)->d->doing_export = e;
4203 bool Buffer::isExporting() const
4205 return d->doing_export;
4209 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4213 return doExport(target, put_in_tempdir, result_file);
4216 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4217 string & result_file) const
4219 bool const update_unincluded =
4220 params().maintain_unincluded_children
4221 && !params().getIncludedChildren().empty();
4223 // (1) export with all included children (omit \includeonly)
4224 if (update_unincluded) {
4225 ExportStatus const status =
4226 doExport(target, put_in_tempdir, true, result_file);
4227 if (status != ExportSuccess)
4230 // (2) export with included children only
4231 return doExport(target, put_in_tempdir, false, result_file);
4235 void Buffer::setMathFlavor(OutputParams & op) const
4237 switch (params().html_math_output) {
4238 case BufferParams::MathML:
4239 op.math_flavor = OutputParams::MathAsMathML;
4241 case BufferParams::HTML:
4242 op.math_flavor = OutputParams::MathAsHTML;
4244 case BufferParams::Images:
4245 op.math_flavor = OutputParams::MathAsImages;
4247 case BufferParams::LaTeX:
4248 op.math_flavor = OutputParams::MathAsLaTeX;
4254 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4255 bool includeall, string & result_file) const
4257 LYXERR(Debug::FILES, "target=" << target);
4258 OutputParams runparams(¶ms().encoding());
4259 string format = target;
4260 string dest_filename;
4261 size_t pos = target.find(' ');
4262 if (pos != string::npos) {
4263 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4264 format = target.substr(0, pos);
4265 if (format == "default")
4266 format = params().getDefaultOutputFormat();
4267 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4268 FileName(dest_filename).onlyPath().createPath();
4269 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4271 MarkAsExporting exporting(this);
4272 string backend_format;
4273 runparams.flavor = OutputParams::LATEX;
4274 runparams.linelen = lyxrc.plaintext_linelen;
4275 runparams.includeall = includeall;
4276 vector<string> backs = params().backends();
4277 Converters converters = theConverters();
4278 bool need_nice_file = false;
4279 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4280 // Get shortest path to format
4281 converters.buildGraph();
4282 Graph::EdgePath path;
4283 for (vector<string>::const_iterator it = backs.begin();
4284 it != backs.end(); ++it) {
4285 Graph::EdgePath p = converters.getPath(*it, format);
4286 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4287 backend_format = *it;
4292 if (!put_in_tempdir) {
4293 // Only show this alert if this is an export to a non-temporary
4294 // file (not for previewing).
4295 Alert::error(_("Couldn't export file"), bformat(
4296 _("No information for exporting the format %1$s."),
4297 theFormats().prettyName(format)));
4299 return ExportNoPathToFormat;
4301 runparams.flavor = converters.getFlavor(path, this);
4302 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4303 Graph::EdgePath::const_iterator it = path.begin();
4304 Graph::EdgePath::const_iterator en = path.end();
4305 for (; it != en; ++it)
4306 if (theConverters().get(*it).nice()) {
4307 need_nice_file = true;
4312 backend_format = format;
4313 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4314 // FIXME: Don't hardcode format names here, but use a flag
4315 if (backend_format == "pdflatex")
4316 runparams.flavor = OutputParams::PDFLATEX;
4317 else if (backend_format == "luatex")
4318 runparams.flavor = OutputParams::LUATEX;
4319 else if (backend_format == "dviluatex")
4320 runparams.flavor = OutputParams::DVILUATEX;
4321 else if (backend_format == "xetex")
4322 runparams.flavor = OutputParams::XETEX;
4325 string filename = latexName(false);
4326 filename = addName(temppath(), filename);
4327 filename = changeExtension(filename,
4328 theFormats().extension(backend_format));
4329 LYXERR(Debug::FILES, "filename=" << filename);
4331 // Plain text backend
4332 if (backend_format == "text") {
4333 runparams.flavor = OutputParams::TEXT;
4334 writePlaintextFile(*this, FileName(filename), runparams);
4337 else if (backend_format == "xhtml") {
4338 runparams.flavor = OutputParams::HTML;
4339 setMathFlavor(runparams);
4340 makeLyXHTMLFile(FileName(filename), runparams);
4341 } else if (backend_format == "lyx")
4342 writeFile(FileName(filename));
4344 else if (params().isDocBook()) {
4345 runparams.nice = !put_in_tempdir;
4346 makeDocBookFile(FileName(filename), runparams);
4349 else if (backend_format == format || need_nice_file) {
4350 runparams.nice = true;
4351 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4352 if (d->cloned_buffer_)
4353 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4356 } else if (!lyxrc.tex_allows_spaces
4357 && contains(filePath(), ' ')) {
4358 Alert::error(_("File name error"),
4359 _("The directory path to the document cannot contain spaces."));
4360 return ExportTexPathHasSpaces;
4362 runparams.nice = false;
4363 bool const success = makeLaTeXFile(
4364 FileName(filename), filePath(), runparams);
4365 if (d->cloned_buffer_)
4366 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4371 string const error_type = (format == "program")
4372 ? "Build" : params().bufferFormat();
4373 ErrorList & error_list = d->errorLists[error_type];
4374 string const ext = theFormats().extension(format);
4375 FileName const tmp_result_file(changeExtension(filename, ext));
4376 bool const success = converters.convert(this, FileName(filename),
4377 tmp_result_file, FileName(absFileName()), backend_format, format,
4380 // Emit the signal to show the error list or copy it back to the
4381 // cloned Buffer so that it can be emitted afterwards.
4382 if (format != backend_format) {
4383 if (runparams.silent)
4385 else if (d->cloned_buffer_)
4386 d->cloned_buffer_->d->errorLists[error_type] =
4387 d->errorLists[error_type];
4390 // also to the children, in case of master-buffer-view
4391 ListOfBuffers clist = getDescendents();
4392 ListOfBuffers::const_iterator cit = clist.begin();
4393 ListOfBuffers::const_iterator const cen = clist.end();
4394 for (; cit != cen; ++cit) {
4395 if (runparams.silent)
4396 (*cit)->d->errorLists[error_type].clear();
4397 else if (d->cloned_buffer_) {
4398 // Enable reverse search by copying back the
4399 // texrow object to the cloned buffer.
4400 // FIXME: this is not thread safe.
4401 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4402 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4403 (*cit)->d->errorLists[error_type];
4405 (*cit)->errors(error_type, true);
4409 if (d->cloned_buffer_) {
4410 // Enable reverse dvi or pdf to work by copying back the texrow
4411 // object to the cloned buffer.
4412 // FIXME: There is a possibility of concurrent access to texrow
4413 // here from the main GUI thread that should be securized.
4414 d->cloned_buffer_->d->texrow = d->texrow;
4415 string const error_type = params().bufferFormat();
4416 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4420 if (put_in_tempdir) {
4421 result_file = tmp_result_file.absFileName();
4422 return success ? ExportSuccess : ExportConverterError;
4425 if (dest_filename.empty())
4426 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4428 result_file = dest_filename;
4429 // We need to copy referenced files (e. g. included graphics
4430 // if format == "dvi") to the result dir.
4431 vector<ExportedFile> const files =
4432 runparams.exportdata->externalFiles(format);
4433 string const dest = runparams.export_folder.empty() ?
4434 onlyPath(result_file) : runparams.export_folder;
4435 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4436 : force_overwrite == ALL_FILES;
4437 CopyStatus status = use_force ? FORCE : SUCCESS;
4439 vector<ExportedFile>::const_iterator it = files.begin();
4440 vector<ExportedFile>::const_iterator const en = files.end();
4441 for (; it != en && status != CANCEL; ++it) {
4442 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4443 string fixedName = it->exportName;
4444 if (!runparams.export_folder.empty()) {
4445 // Relative pathnames starting with ../ will be sanitized
4446 // if exporting to a different folder
4447 while (fixedName.substr(0, 3) == "../")
4448 fixedName = fixedName.substr(3, fixedName.length() - 3);
4450 FileName fixedFileName = makeAbsPath(fixedName, dest);
4451 fixedFileName.onlyPath().createPath();
4452 status = copyFile(fmt, it->sourceName,
4454 it->exportName, status == FORCE,
4455 runparams.export_folder.empty());
4458 if (status == CANCEL) {
4459 message(_("Document export cancelled."));
4460 return ExportCancel;
4463 if (tmp_result_file.exists()) {
4464 // Finally copy the main file
4465 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4466 : force_overwrite != NO_FILES;
4467 if (status == SUCCESS && use_force)
4469 status = copyFile(format, tmp_result_file,
4470 FileName(result_file), result_file,
4472 if (status == CANCEL) {
4473 message(_("Document export cancelled."));
4474 return ExportCancel;
4476 message(bformat(_("Document exported as %1$s "
4478 theFormats().prettyName(format),
4479 makeDisplayPath(result_file)));
4482 // This must be a dummy converter like fax (bug 1888)
4483 message(bformat(_("Document exported as %1$s"),
4484 theFormats().prettyName(format)));
4487 return success ? ExportSuccess : ExportConverterError;
4491 Buffer::ExportStatus Buffer::preview(string const & format) const
4493 bool const update_unincluded =
4494 params().maintain_unincluded_children
4495 && !params().getIncludedChildren().empty();
4496 return preview(format, update_unincluded);
4500 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4502 MarkAsExporting exporting(this);
4504 // (1) export with all included children (omit \includeonly)
4506 ExportStatus const status = doExport(format, true, true, result_file);
4507 if (status != ExportSuccess)
4510 // (2) export with included children only
4511 ExportStatus const status = doExport(format, true, false, result_file);
4512 FileName const previewFile(result_file);
4514 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4515 theimpl->preview_file_ = previewFile;
4516 theimpl->preview_format_ = format;
4517 theimpl->preview_error_ = (status != ExportSuccess);
4519 if (status != ExportSuccess)
4522 if (previewFile.exists())
4523 return theFormats().view(*this, previewFile, format) ?
4524 PreviewSuccess : PreviewError;
4526 // Successful export but no output file?
4527 // Probably a bug in error detection.
4528 LATTEST(status != ExportSuccess);
4533 Buffer::ReadStatus Buffer::extractFromVC()
4535 bool const found = LyXVC::file_not_found_hook(d->filename);
4537 return ReadFileNotFound;
4538 if (!d->filename.isReadableFile())
4544 Buffer::ReadStatus Buffer::loadEmergency()
4546 FileName const emergencyFile = getEmergencyFileName();
4547 if (!emergencyFile.exists()
4548 || emergencyFile.lastModified() <= d->filename.lastModified())
4549 return ReadFileNotFound;
4551 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4552 docstring const text = bformat(_("An emergency save of the document "
4553 "%1$s exists.\n\nRecover emergency save?"), file);
4555 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4556 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4562 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4563 bool const success = (ret_llf == ReadSuccess);
4565 if (hasReadonlyFlag()) {
4566 Alert::warning(_("File is read-only"),
4567 bformat(_("An emergency file is successfully loaded, "
4568 "but the original file %1$s is marked read-only. "
4569 "Please make sure to save the document as a different "
4570 "file."), from_utf8(d->filename.absFileName())));
4573 lyxvc().file_found_hook(d->filename);
4574 str = _("Document was successfully recovered.");
4576 str = _("Document was NOT successfully recovered.");
4577 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4578 makeDisplayPath(emergencyFile.absFileName()));
4580 int const del_emerg =
4581 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4582 _("&Remove"), _("&Keep"));
4583 if (del_emerg == 0) {
4584 emergencyFile.removeFile();
4586 Alert::warning(_("Emergency file deleted"),
4587 _("Do not forget to save your file now!"), true);
4589 return success ? ReadSuccess : ReadEmergencyFailure;
4592 int const del_emerg =
4593 Alert::prompt(_("Delete emergency file?"),
4594 _("Remove emergency file now?"), 1, 1,
4595 _("&Remove"), _("&Keep"));
4597 emergencyFile.removeFile();
4598 return ReadOriginal;
4608 Buffer::ReadStatus Buffer::loadAutosave()
4610 // Now check if autosave file is newer.
4611 FileName const autosaveFile = getAutosaveFileName();
4612 if (!autosaveFile.exists()
4613 || autosaveFile.lastModified() <= d->filename.lastModified())
4614 return ReadFileNotFound;
4616 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4617 docstring const text = bformat(_("The backup of the document %1$s "
4618 "is newer.\n\nLoad the backup instead?"), file);
4619 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4620 _("&Load backup"), _("Load &original"), _("&Cancel"));
4625 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4626 // the file is not saved if we load the autosave file.
4627 if (ret_llf == ReadSuccess) {
4628 if (hasReadonlyFlag()) {
4629 Alert::warning(_("File is read-only"),
4630 bformat(_("A backup file is successfully loaded, "
4631 "but the original file %1$s is marked read-only. "
4632 "Please make sure to save the document as a "
4634 from_utf8(d->filename.absFileName())));
4637 lyxvc().file_found_hook(d->filename);
4640 return ReadAutosaveFailure;
4643 // Here we delete the autosave
4644 autosaveFile.removeFile();
4645 return ReadOriginal;
4653 Buffer::ReadStatus Buffer::loadLyXFile()
4655 if (!d->filename.isReadableFile()) {
4656 ReadStatus const ret_rvc = extractFromVC();
4657 if (ret_rvc != ReadSuccess)
4661 ReadStatus const ret_re = loadEmergency();
4662 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4665 ReadStatus const ret_ra = loadAutosave();
4666 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4669 return loadThisLyXFile(d->filename);
4673 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4675 return readFile(fn);
4679 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4681 for (auto const & err : terr) {
4682 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4683 int errorRow = err.error_in_line;
4684 Buffer const * buf = 0;
4686 if (err.child_name.empty())
4687 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4689 // The error occurred in a child
4690 for (Buffer const * child : getDescendents()) {
4691 string const child_name =
4692 DocFileName(changeExtension(child->absFileName(), "tex")).
4694 if (err.child_name != child_name)
4696 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4697 if (!TexRow::isNone(start)) {
4698 buf = d->cloned_buffer_
4699 ? child->d->cloned_buffer_->d->owner_
4706 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4712 void Buffer::setBuffersForInsets() const
4714 inset().setBuffer(const_cast<Buffer &>(*this));
4718 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4720 LBUFERR(!text().paragraphs().empty());
4722 // Use the master text class also for child documents
4723 Buffer const * const master = masterBuffer();
4724 DocumentClass const & textclass = master->params().documentClass();
4726 FileNamePairList old_bibfiles;
4727 // Do this only if we are the top-level Buffer. We also need to account
4728 // for the case of a previewed child with ignored parent here.
4729 if (master == this && !d->ignore_parent) {
4730 textclass.counters().reset(from_ascii("bibitem"));
4731 reloadBibInfoCache();
4732 // we will re-read this cache as we go through, but we need
4733 // to know whether it's changed to know whether we need to
4734 // update the bibinfo cache.
4735 old_bibfiles = d->bibfiles_cache_;
4736 d->bibfiles_cache_.clear();
4739 // keep the buffers to be children in this set. If the call from the
4740 // master comes back we can see which of them were actually seen (i.e.
4741 // via an InsetInclude). The remaining ones in the set need still be updated.
4742 static std::set<Buffer const *> bufToUpdate;
4743 if (scope == UpdateMaster) {
4744 // If this is a child document start with the master
4745 if (master != this) {
4746 bufToUpdate.insert(this);
4747 master->updateBuffer(UpdateMaster, utype);
4748 // If the master buffer has no gui associated with it, then the TocModel is
4749 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4750 // (bug 5699). The same happens if the master buffer is open in a different
4751 // window. This test catches both possibilities.
4752 // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4753 // There remains a problem here: If there is another child open in yet a third
4754 // window, that TOC is not updated. So some more general solution is needed at
4756 if (master->d->gui_ != d->gui_)
4759 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4760 if (bufToUpdate.find(this) == bufToUpdate.end())
4764 // start over the counters in the master
4765 textclass.counters().reset();
4768 // update will be done below for this buffer
4769 bufToUpdate.erase(this);
4771 // update all caches
4772 clearReferenceCache();
4774 setChangesPresent(false);
4776 Buffer & cbuf = const_cast<Buffer &>(*this);
4779 ParIterator parit = cbuf.par_iterator_begin();
4780 updateBuffer(parit, utype);
4782 // If this document has siblings, then update the TocBackend later. The
4783 // reason is to ensure that later siblings are up to date when e.g. the
4784 // broken or not status of references is computed. The update is called
4785 // in InsetInclude::addToToc.
4789 // if the bibfiles changed, the cache of bibinfo is invalid
4790 sort(d->bibfiles_cache_.begin(), d->bibfiles_cache_.end());
4791 // the old one should already be sorted
4792 if (old_bibfiles != d->bibfiles_cache_) {
4793 invalidateBibinfoCache();
4794 reloadBibInfoCache();
4795 // We relied upon the bibinfo cache when recalculating labels. But that
4796 // cache was invalid, although we didn't find that out until now. So we
4797 // have to do it all again.
4798 // That said, the only thing we really need to do is update the citation
4799 // labels. Nothing else will have changed. So we could create a new
4800 // UpdateType that would signal that fact, if we needed to do so.
4801 parit = cbuf.par_iterator_begin();
4802 updateBuffer(parit, utype);
4805 d->bibinfo_cache_valid_ = true;
4806 d->cite_labels_valid_ = true;
4808 cbuf.tocBackend().update(true, utype);
4809 if (scope == UpdateMaster)
4810 cbuf.structureChanged();
4814 static depth_type getDepth(DocIterator const & it)
4816 depth_type depth = 0;
4817 for (size_t i = 0 ; i < it.depth() ; ++i)
4818 if (!it[i].inset().inMathed())
4819 depth += it[i].paragraph().getDepth() + 1;
4820 // remove 1 since the outer inset does not count
4821 // we should have at least one non-math inset, so
4822 // depth should nevery be 0. but maybe it is worth
4823 // marking this, just in case.
4825 // coverity[INTEGER_OVERFLOW]
4829 static depth_type getItemDepth(ParIterator const & it)
4831 Paragraph const & par = *it;
4832 LabelType const labeltype = par.layout().labeltype;
4834 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4837 // this will hold the lowest depth encountered up to now.
4838 depth_type min_depth = getDepth(it);
4839 ParIterator prev_it = it;
4842 --prev_it.top().pit();
4844 // start of nested inset: go to outer par
4846 if (prev_it.empty()) {
4847 // start of document: nothing to do
4852 // We search for the first paragraph with same label
4853 // that is not more deeply nested.
4854 Paragraph & prev_par = *prev_it;
4855 depth_type const prev_depth = getDepth(prev_it);
4856 if (labeltype == prev_par.layout().labeltype) {
4857 if (prev_depth < min_depth)
4858 return prev_par.itemdepth + 1;
4859 if (prev_depth == min_depth)
4860 return prev_par.itemdepth;
4862 min_depth = min(min_depth, prev_depth);
4863 // small optimization: if we are at depth 0, we won't
4864 // find anything else
4865 if (prev_depth == 0)
4871 static bool needEnumCounterReset(ParIterator const & it)
4873 Paragraph const & par = *it;
4874 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4875 depth_type const cur_depth = par.getDepth();
4876 ParIterator prev_it = it;
4877 while (prev_it.pit()) {
4878 --prev_it.top().pit();
4879 Paragraph const & prev_par = *prev_it;
4880 if (prev_par.getDepth() <= cur_depth)
4881 return prev_par.layout().name() != par.layout().name();
4883 // start of nested inset: reset
4888 // set the label of a paragraph. This includes the counters.
4889 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4891 BufferParams const & bp = owner_->masterBuffer()->params();
4892 DocumentClass const & textclass = bp.documentClass();
4893 Paragraph & par = it.paragraph();
4894 Layout const & layout = par.layout();
4895 Counters & counters = textclass.counters();
4897 if (par.params().startOfAppendix()) {
4898 // We want to reset the counter corresponding to toplevel sectioning
4899 Layout const & lay = textclass.getTOCLayout();
4900 docstring const cnt = lay.counter;
4902 counters.reset(cnt);
4903 counters.appendix(true);
4905 par.params().appendix(counters.appendix());
4907 // Compute the item depth of the paragraph
4908 par.itemdepth = getItemDepth(it);
4910 if (layout.margintype == MARGIN_MANUAL) {
4911 if (par.params().labelWidthString().empty())
4912 par.params().labelWidthString(par.expandLabel(layout, bp));
4913 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4914 // we do not need to do anything here, since the empty case is
4915 // handled during export.
4917 par.params().labelWidthString(docstring());
4920 switch(layout.labeltype) {
4921 case LABEL_ITEMIZE: {
4922 // At some point of time we should do something more
4923 // clever here, like:
4924 // par.params().labelString(
4925 // bp.user_defined_bullet(par.itemdepth).getText());
4926 // for now, use a simple hardcoded label
4927 docstring itemlabel;
4928 switch (par.itemdepth) {
4930 itemlabel = char_type(0x2022);
4933 itemlabel = char_type(0x2013);
4936 itemlabel = char_type(0x2217);
4939 itemlabel = char_type(0x2219); // or 0x00b7
4942 par.params().labelString(itemlabel);
4946 case LABEL_ENUMERATE: {
4947 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4949 switch (par.itemdepth) {
4960 enumcounter += "iv";
4963 // not a valid enumdepth...
4967 // Increase the master counter?
4968 if (layout.stepmastercounter && needEnumCounterReset(it))
4969 counters.stepMaster(enumcounter, utype);
4971 // Maybe we have to reset the enumeration counter.
4972 if (!layout.resumecounter && needEnumCounterReset(it))
4973 counters.reset(enumcounter);
4974 counters.step(enumcounter, utype);
4976 string const & lang = par.getParLanguage(bp)->code();
4977 par.params().labelString(counters.theCounter(enumcounter, lang));
4982 case LABEL_SENSITIVE: {
4983 string const & type = counters.current_float();
4984 docstring full_label;
4986 full_label = owner_->B_("Senseless!!! ");
4988 docstring name = owner_->B_(textclass.floats().getType(type).name());
4989 if (counters.hasCounter(from_utf8(type))) {
4990 string const & lang = par.getParLanguage(bp)->code();
4991 counters.step(from_utf8(type), utype);
4992 full_label = bformat(from_ascii("%1$s %2$s:"),
4994 counters.theCounter(from_utf8(type), lang));
4996 full_label = bformat(from_ascii("%1$s #:"), name);
4998 par.params().labelString(full_label);
5002 case LABEL_NO_LABEL:
5003 par.params().labelString(docstring());
5007 case LABEL_CENTERED:
5008 case LABEL_STATIC: {
5009 docstring const & lcounter = layout.counter;
5010 if (!lcounter.empty()) {
5011 if (layout.toclevel <= bp.secnumdepth
5012 && (layout.latextype != LATEX_ENVIRONMENT
5013 || it.text()->isFirstInSequence(it.pit()))) {
5014 if (counters.hasCounter(lcounter))
5015 counters.step(lcounter, utype);
5016 par.params().labelString(par.expandLabel(layout, bp));
5018 par.params().labelString(docstring());
5020 par.params().labelString(par.expandLabel(layout, bp));
5026 par.params().labelString(par.expandLabel(layout, bp));
5031 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5033 // LASSERT: Is it safe to continue here, or should we just return?
5034 LASSERT(parit.pit() == 0, /**/);
5036 // Set the position of the text in the buffer to be able
5037 // to resolve macros in it.
5038 parit.text()->setMacrocontextPosition(parit);
5040 depth_type maxdepth = 0;
5041 pit_type const lastpit = parit.lastpit();
5042 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5043 // reduce depth if necessary
5044 if (parit->params().depth() > maxdepth) {
5045 /** FIXME: this function is const, but
5046 * nevertheless it modifies the buffer. To be
5047 * cleaner, one should modify the buffer in
5048 * another function, which is actually
5049 * non-const. This would however be costly in
5050 * terms of code duplication.
5052 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5053 parit->params().depth(maxdepth);
5055 maxdepth = parit->getMaxDepthAfter();
5057 if (utype == OutputUpdate) {
5058 // track the active counters
5059 // we have to do this for the master buffer, since the local
5060 // buffer isn't tracking anything.
5061 masterBuffer()->params().documentClass().counters().
5062 setActiveLayout(parit->layout());
5065 // set the counter for this paragraph
5066 d->setLabel(parit, utype);
5068 // update change-tracking flag
5069 parit->addChangesToBuffer(*this);
5072 InsetList::const_iterator iit = parit->insetList().begin();
5073 InsetList::const_iterator end = parit->insetList().end();
5074 for (; iit != end; ++iit) {
5075 parit.pos() = iit->pos;
5076 iit->inset->updateBuffer(parit, utype);
5082 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5083 WordLangTuple & word_lang, docstring_list & suggestions) const
5087 suggestions.clear();
5088 word_lang = WordLangTuple();
5089 bool const to_end = to.empty();
5090 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5091 // OK, we start from here.
5092 for (; from != end; from.forwardPos()) {
5093 // This skips all insets with spell check disabled.
5094 while (!from.allowSpellCheck()) {
5098 // If from is at the end of the document (which is possible
5099 // when "from" was changed above) LyX will crash later otherwise.
5100 if (from.atEnd() || (!to_end && from >= end))
5103 from.paragraph().spellCheck();
5104 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5105 if (SpellChecker::misspelled(res)) {
5109 // Do not increase progress when from == to, otherwise the word
5110 // count will be wrong.
5120 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5122 bool inword = false;
5127 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5128 if (!dit.inTexted()) {
5133 Paragraph const & par = dit.paragraph();
5134 pos_type const pos = dit.pos();
5136 // Copied and adapted from isWordSeparator() in Paragraph
5137 if (pos == dit.lastpos()) {
5140 Inset const * ins = par.getInset(pos);
5141 if (ins && skipNoOutput && !ins->producesOutput()) {
5144 // stop if end of range was skipped
5145 if (!to.atEnd() && dit >= to)
5148 } else if (!par.isDeleted(pos)) {
5149 if (par.isWordSeparator(pos))
5155 if (ins && ins->isLetter())
5157 else if (ins && ins->isSpace())
5160 char_type const c = par.getChar(pos);
5161 if (isPrintableNonspace(c))
5163 else if (isSpace(c))
5173 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5175 d->updateStatistics(from, to, skipNoOutput);
5179 int Buffer::wordCount() const
5181 return d->wordCount();
5185 int Buffer::charCount(bool with_blanks) const
5187 return d->charCount(with_blanks);
5191 Buffer::ReadStatus Buffer::reload()
5194 // c.f. bug https://www.lyx.org/trac/ticket/6587
5195 removeAutosaveFile();
5196 // e.g., read-only status could have changed due to version control
5197 d->filename.refresh();
5198 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5200 // clear parent. this will get reset if need be.
5202 ReadStatus const status = loadLyXFile();
5203 if (status == ReadSuccess) {
5208 message(bformat(_("Document %1$s reloaded."), disp_fn));
5211 message(bformat(_("Could not reload document %1$s."), disp_fn));
5221 bool Buffer::saveAs(FileName const & fn)
5223 FileName const old_name = fileName();
5224 FileName const old_auto = getAutosaveFileName();
5225 bool const old_unnamed = isUnnamed();
5226 bool success = true;
5227 d->old_position = filePath();
5234 // bring the autosave file with us, just in case.
5235 moveAutosaveFile(old_auto);
5236 // validate version control data and
5237 // correct buffer title
5238 lyxvc().file_found_hook(fileName());
5240 // the file has now been saved to the new location.
5241 // we need to check that the locations of child buffers
5243 checkChildBuffers();
5244 checkMasterBuffer();
5247 // reset the old filename and unnamed state
5248 setFileName(old_name);
5249 setUnnamed(old_unnamed);
5253 d->old_position.clear();
5258 void Buffer::checkChildBuffers()
5260 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5261 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5262 for (; it != en; ++it) {
5263 DocIterator dit = it->second;
5264 Buffer * cbuf = const_cast<Buffer *>(it->first);
5265 if (!cbuf || !theBufferList().isLoaded(cbuf))
5267 Inset * inset = dit.nextInset();
5268 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5269 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5270 docstring const & incfile = inset_inc->getParam("filename");
5271 string oldloc = cbuf->absFileName();
5272 string newloc = makeAbsPath(to_utf8(incfile),
5273 onlyPath(absFileName())).absFileName();
5274 if (oldloc == newloc)
5276 // the location of the child file is incorrect.
5278 inset_inc->setChildBuffer(0);
5280 // invalidate cache of children
5281 d->children_positions.clear();
5282 d->position_to_children.clear();
5286 // If a child has been saved under a different name/path, it might have been
5287 // orphaned. Therefore the master needs to be reset (bug 8161).
5288 void Buffer::checkMasterBuffer()
5290 Buffer const * const master = masterBuffer();
5294 // necessary to re-register the child (bug 5873)
5295 // FIXME: clean up updateMacros (here, only
5296 // child registering is needed).
5297 master->updateMacros();
5298 // (re)set master as master buffer, but only
5299 // if we are a real child
5300 if (master->isChild(this))
5307 string Buffer::includedFilePath(string const & name, string const & ext) const
5309 if (d->old_position.empty() ||
5310 equivalent(FileName(d->old_position), FileName(filePath())))
5313 bool isabsolute = FileName::isAbsolute(name);
5314 // both old_position and filePath() end with a path separator
5315 string absname = isabsolute ? name : d->old_position + name;
5317 // if old_position is set to origin, we need to do the equivalent of
5318 // getReferencedFileName() (see readDocument())
5319 if (!isabsolute && d->old_position == params().origin) {
5320 FileName const test(addExtension(filePath() + name, ext));
5322 absname = filePath() + name;
5325 if (!FileName(addExtension(absname, ext)).exists())
5329 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5331 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5332 from_utf8(filePath())));
5336 void Buffer::setChangesPresent(bool b) const
5338 d->tracked_changes_present_ = b;
5342 bool Buffer::areChangesPresent() const
5344 return d->tracked_changes_present_;
5348 void Buffer::updateChangesPresent() const
5350 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5351 setChangesPresent(false);
5352 ParConstIterator it = par_iterator_begin();
5353 ParConstIterator const end = par_iterator_end();
5354 for (; !areChangesPresent() && it != end; ++it)
5355 it->addChangesToBuffer(*this);
5359 void Buffer::Impl::refreshFileMonitor()
5361 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5362 file_monitor_->refresh();
5366 // The previous file monitor is invalid
5367 // This also destroys the previous file monitor and all its connections
5368 file_monitor_ = FileSystemWatcher::monitor(filename);
5369 // file_monitor_ will be destroyed with *this, so it is not going to call a
5370 // destroyed object method.
5371 file_monitor_->connect([this](bool exists) {
5372 fileExternallyModified(exists);
5377 void Buffer::Impl::fileExternallyModified(bool const exists)
5379 // ignore notifications after our own saving operations
5380 if (checksum_ == filename.checksum()) {
5381 LYXERR(Debug::FILES, "External modification but "
5382 "checksum unchanged: " << filename);
5385 // If the file has been deleted, only mark the file as dirty since it is
5386 // pointless to prompt for reloading. If later a file is moved into this
5387 // location, then the externally modified warning will appear then.
5389 externally_modified_ = true;
5390 // Update external modification notification.
5391 // Dirty buffers must be visible at all times.
5392 if (wa_ && wa_->unhide(owner_))
5393 wa_->updateTitles();
5395 // Unable to unhide the buffer (e.g. no GUI or not current View)
5400 bool Buffer::notifiesExternalModification() const
5402 return d->externally_modified_;
5406 void Buffer::clearExternalModification() const
5408 d->externally_modified_ = false;
5410 d->wa_->updateTitles();