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"
58 #include "SpellChecker.h"
60 #include "texstream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
82 #include "graphics/GraphicsCache.h"
83 #include "graphics/PreviewLoader.h"
85 #include "frontends/alert.h"
86 #include "frontends/Delegates.h"
87 #include "frontends/WorkAreaManager.h"
89 #include "support/lassert.h"
90 #include "support/convert.h"
91 #include "support/debug.h"
92 #include "support/docstring_list.h"
93 #include "support/ExceptionMessage.h"
94 #include "support/FileMonitor.h"
95 #include "support/FileName.h"
96 #include "support/FileNameList.h"
97 #include "support/filetools.h"
98 #include "support/ForkedCalls.h"
99 #include "support/gettext.h"
100 #include "support/gzstream.h"
101 #include "support/lstrings.h"
102 #include "support/lyxalgo.h"
103 #include "support/mutex.h"
104 #include "support/os.h"
105 #include "support/Package.h"
106 #include "support/PathChanger.h"
107 #include "support/Systemcall.h"
108 #include "support/TempFile.h"
109 #include "support/textutils.h"
110 #include "support/types.h"
112 #include "support/bind.h"
124 using namespace lyx::support;
125 using namespace lyx::graphics;
129 namespace Alert = frontend::Alert;
130 namespace os = support::os;
134 int const LYX_FORMAT = LYX_FORMAT_LYX;
136 typedef map<string, bool> DepClean;
137 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
142 // A storehouse for the cloned buffers.
143 list<CloneList *> cloned_buffers;
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
153 delete preview_loader_;
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 /** If we have branches that use the file suffix
172 feature, return the file name with suffix appended.
174 support::FileName exportFileName() const;
181 mutable TexRow texrow;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this an unnamed file (New...)?
195 /// is this an internal bufffer?
196 bool internal_buffer;
201 /// name of the file the buffer is associated with.
204 /** Set to true only when the file is fully loaded.
205 * Used to prevent the premature generation of previews
206 * and by the citation inset.
208 bool file_fully_loaded;
210 /// original format of loaded file
213 /// if the file was originally loaded from an older format, do
214 /// we need to back it up still?
215 bool need_format_backup;
217 /// Ignore the parent (e.g. when exporting a child standalone)?
221 mutable TocBackend toc_backend;
226 ScopeMacro(DocIterator const & s, MacroData const & m)
227 : scope(s), macro(m) {}
231 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
232 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
233 /// map from the macro name to the position map,
234 /// which maps the macro definition position to the scope and the MacroData.
235 NamePositionScopeMacroMap macros;
236 /// This seem to change the way Buffer::getMacro() works
237 mutable bool macro_lock;
239 /// positions of child buffers in the buffer
240 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
242 ScopeBuffer() : buffer(0) {}
243 ScopeBuffer(DocIterator const & s, Buffer const * b)
244 : scope(s), buffer(b) {}
246 Buffer const * buffer;
248 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
249 /// position of children buffers in this buffer
250 BufferPositionMap children_positions;
251 /// map from children inclusion positions to their scope and their buffer
252 PositionScopeBufferMap position_to_children;
254 /// Contains the old buffer filePath() while saving-as, or the
255 /// directory where the document was last saved while loading.
258 /** Keeps track of the path of local layout files.
259 * If possible, it is always relative to the buffer path.
260 * Empty for layouts in system or user directory.
262 string layout_position;
264 /// Container for all sort of Buffer dependant errors.
265 map<string, ErrorList> errorLists;
267 /// checksum used to test if the file has been externally modified. Used to
268 /// double check whether the file had been externally modified when saving.
269 unsigned long checksum_;
272 frontend::WorkAreaManager * wa_;
274 frontend::GuiBufferDelegate * gui_;
279 /// A cache for the bibfiles (including bibfiles of loaded child
280 /// documents), needed for appropriate update of natbib labels.
281 mutable support::FileNamePairList bibfiles_cache_;
283 // FIXME The caching mechanism could be improved. At present, we have a
284 // cache for each Buffer, that caches all the bibliography info for that
285 // Buffer. A more efficient solution would be to have a global cache per
286 // file, and then to construct the Buffer's bibinfo from that.
287 /// A cache for bibliography info
288 mutable BiblioInfo bibinfo_;
289 /// whether the bibinfo cache is valid
290 mutable bool bibinfo_cache_valid_;
291 /// whether the bibfile cache is valid
292 mutable bool bibfile_cache_valid_;
293 /// Cache of timestamps of .bib files
294 map<FileName, time_t> bibfile_status_;
295 /// Indicates whether the bibinfo has changed since the last time
296 /// we ran updateBuffer(), i.e., whether citation labels may need
298 mutable bool cite_labels_valid_;
300 /// These two hold the file name and format, written to by
301 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
302 FileName preview_file_;
303 string preview_format_;
304 /// If there was an error when previewing, on the next preview we do
305 /// a fresh compile (e.g. in case the user installed a package that
309 mutable RefCache ref_cache_;
311 /// our Text that should be wrapped in an InsetText
315 PreviewLoader * preview_loader_;
317 /// This is here to force the test to be done whenever parent_buffer
319 Buffer const * parent() const
321 // ignore_parent temporarily "orphans" a buffer
322 // (e.g. if a child is compiled standalone)
325 // if parent_buffer is not loaded, then it has been unloaded,
326 // which means that parent_buffer is an invalid pointer. So we
327 // set it to null in that case.
328 // however, the BufferList doesn't know about cloned buffers, so
329 // they will always be regarded as unloaded. in that case, we hope
331 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
333 return parent_buffer;
337 void setParent(Buffer const * pb)
339 if (parent_buffer == pb)
342 if (!cloned_buffer_ && parent_buffer && pb)
343 LYXERR0("Warning: a buffer should not have two parents!");
345 if (!cloned_buffer_ && parent_buffer) {
346 parent_buffer->invalidateBibfileCache();
347 parent_buffer->invalidateBibinfoCache();
351 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
352 /// This one is useful for preview detached in a thread.
353 Buffer const * cloned_buffer_;
355 CloneList * clone_list_;
356 /// are we in the process of exporting this buffer?
357 mutable bool doing_export;
359 /// compute statistics
360 /// \p from initial position
361 /// \p to points to the end position
362 void updateStatistics(DocIterator & from, DocIterator & to,
363 bool skipNoOutput = true);
364 /// statistics accessor functions
365 int wordCount() const
369 int charCount(bool with_blanks) const
372 + (with_blanks ? blank_count_ : 0);
375 // does the buffer contain tracked changes? (if so, we automatically
376 // display the review toolbar, for instance)
377 mutable bool tracked_changes_present_;
379 // Make sure the file monitor monitors the good file.
380 void refreshFileMonitor();
382 /// has it been notified of an external modification?
383 bool isExternallyModified() const { return externally_modified_; }
385 /// Notify or clear of external modification
386 void fileExternallyModified(bool modified) const;
388 /// Block notifications of external modifications
389 FileMonitorBlocker blockFileMonitor() { return file_monitor_->block(10); }
392 /// So we can force access via the accessors.
393 mutable Buffer const * parent_buffer;
399 /// has been externally modified? Can be reset by the user.
400 mutable bool externally_modified_;
402 FileMonitorPtr file_monitor_;
406 /// Creates the per buffer temporary directory
407 static FileName createBufferTmpDir()
409 // FIXME This would be the ideal application for a TempDir class (like
410 // TempFile but for directories)
415 Mutex::Locker locker(&mutex);
416 counter = convert<string>(count++);
418 // We are in our own directory. Why bother to mangle name?
419 // In fact I wrote this code to circumvent a problematic behaviour
420 // (bug?) of EMX mkstemp().
421 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
424 if (!tmpfl.createDirectory(0777)) {
425 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
426 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
427 from_utf8(tmpfl.absFileName())));
433 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
434 Buffer const * cloned_buffer)
435 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
436 internal_buffer(false), read_only(readonly_), filename(file),
437 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
438 ignore_parent(false), toc_backend(owner), macro_lock(false),
439 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
440 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
441 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
442 clone_list_(0), doing_export(false),
443 tracked_changes_present_(0), parent_buffer(0),
444 word_count_(0), char_count_(0), blank_count_(0),
445 externally_modified_(false)
447 refreshFileMonitor();
448 if (!cloned_buffer_) {
449 temppath = createBufferTmpDir();
450 lyxvc.setBuffer(owner_);
452 wa_ = new frontend::WorkAreaManager;
455 temppath = cloned_buffer_->d->temppath;
456 file_fully_loaded = true;
457 params = cloned_buffer_->d->params;
458 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
459 bibinfo_ = cloned_buffer_->d->bibinfo_;
460 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
461 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
462 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
463 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
464 unnamed = cloned_buffer_->d->unnamed;
465 internal_buffer = cloned_buffer_->d->internal_buffer;
466 layout_position = cloned_buffer_->d->layout_position;
467 preview_file_ = cloned_buffer_->d->preview_file_;
468 preview_format_ = cloned_buffer_->d->preview_format_;
469 preview_error_ = cloned_buffer_->d->preview_error_;
470 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
474 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
475 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
477 LYXERR(Debug::INFO, "Buffer::Buffer()");
479 d->inset = new InsetText(*cloned_buffer->d->inset);
480 d->inset->setBuffer(*this);
481 // FIXME: optimize this loop somewhat, maybe by creating a new
482 // general recursive Inset::setId().
483 DocIterator it = doc_iterator_begin(this);
484 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
485 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
486 it.paragraph().setId(cloned_it.paragraph().id());
488 d->inset = new InsetText(this);
489 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
495 LYXERR(Debug::INFO, "Buffer::~Buffer()");
496 // here the buffer should take care that it is
497 // saved properly, before it goes into the void.
499 // GuiView already destroyed
503 // No need to do additional cleanups for internal buffer.
509 // this is in case of recursive includes: we won't try to delete
510 // ourselves as a child.
511 d->clone_list_->erase(this);
512 // loop over children
513 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
514 Impl::BufferPositionMap::iterator end = d->children_positions.end();
515 for (; it != end; ++it) {
516 Buffer * child = const_cast<Buffer *>(it->first);
517 if (d->clone_list_->erase(child))
520 // if we're the master buffer, then we should get rid of the list
523 // If this is not empty, we have leaked something. Worse, one of the
524 // children still has a reference to this list. But we will try to
525 // continue, rather than shut down.
526 LATTEST(d->clone_list_->empty());
527 list<CloneList *>::iterator it =
528 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
529 if (it == cloned_buffers.end()) {
530 // We will leak in this case, but it is safe to continue.
533 cloned_buffers.erase(it);
534 delete d->clone_list_;
536 // FIXME Do we really need to do this right before we delete d?
537 // clear references to children in macro tables
538 d->children_positions.clear();
539 d->position_to_children.clear();
541 // loop over children
542 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
543 Impl::BufferPositionMap::iterator end = d->children_positions.end();
544 for (; it != end; ++it) {
545 Buffer * child = const_cast<Buffer *>(it->first);
546 if (theBufferList().isLoaded(child)) {
547 if (theBufferList().isOthersChild(this, child))
550 theBufferList().release(child);
555 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
557 msg += emergencyWrite();
559 msg += " " + _("Save failed! Document is lost.");
561 Alert::warning(_("Attempting to close changed document!"), msg);
564 // FIXME Do we really need to do this right before we delete d?
565 // clear references to children in macro tables
566 d->children_positions.clear();
567 d->position_to_children.clear();
569 if (!d->temppath.destroyDirectory()) {
570 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
571 from_utf8(d->temppath.absFileName())));
580 Buffer * Buffer::cloneFromMaster() const
583 cloned_buffers.push_back(new CloneList);
584 CloneList * clones = cloned_buffers.back();
586 masterBuffer()->cloneWithChildren(bufmap, clones);
588 // make sure we got cloned
589 BufferMap::const_iterator bit = bufmap.find(this);
590 LASSERT(bit != bufmap.end(), return 0);
591 Buffer * cloned_buffer = bit->second;
593 return cloned_buffer;
597 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
599 // have we already been cloned?
600 if (bufmap.find(this) != bufmap.end())
603 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
605 // The clone needs its own DocumentClass, since running updateBuffer() will
606 // modify it, and we would otherwise be sharing it with the original Buffer.
607 buffer_clone->params().makeDocumentClass(true);
609 cap::switchBetweenClasses(
610 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
611 static_cast<InsetText &>(buffer_clone->inset()), el);
613 bufmap[this] = buffer_clone;
614 clones->insert(buffer_clone);
615 buffer_clone->d->clone_list_ = clones;
616 buffer_clone->d->macro_lock = true;
617 buffer_clone->d->children_positions.clear();
619 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
620 // math macro caches need to be rethought and simplified.
621 // I am not sure wether we should handle Buffer cloning here or in BufferList.
622 // Right now BufferList knows nothing about buffer clones.
623 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
624 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
625 for (; it != end; ++it) {
626 DocIterator dit = it->first.clone(buffer_clone);
627 dit.setBuffer(buffer_clone);
628 Buffer * child = const_cast<Buffer *>(it->second.buffer);
630 child->cloneWithChildren(bufmap, clones);
631 BufferMap::iterator const bit = bufmap.find(child);
632 LASSERT(bit != bufmap.end(), continue);
633 Buffer * child_clone = bit->second;
635 Inset * inset = dit.nextInset();
636 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
637 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
638 inset_inc->setChildBuffer(child_clone);
639 child_clone->d->setParent(buffer_clone);
640 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
641 buffer_clone->setChild(dit, child_clone);
643 buffer_clone->d->macro_lock = false;
648 Buffer * Buffer::cloneBufferOnly() const {
649 cloned_buffers.push_back(new CloneList);
650 CloneList * clones = cloned_buffers.back();
651 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
653 // The clone needs its own DocumentClass, since running updateBuffer() will
654 // modify it, and we would otherwise be sharing it with the original Buffer.
655 buffer_clone->params().makeDocumentClass(true);
657 cap::switchBetweenClasses(
658 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
659 static_cast<InsetText &>(buffer_clone->inset()), el);
661 clones->insert(buffer_clone);
662 buffer_clone->d->clone_list_ = clones;
664 // we won't be cloning the children
665 buffer_clone->d->children_positions.clear();
670 bool Buffer::isClone() const
672 return d->cloned_buffer_;
676 void Buffer::changed(bool update_metrics) const
679 d->wa_->redrawAll(update_metrics);
683 frontend::WorkAreaManager & Buffer::workAreaManager() const
690 Text & Buffer::text() const
692 return d->inset->text();
696 Inset & Buffer::inset() const
702 BufferParams & Buffer::params()
708 BufferParams const & Buffer::params() const
714 BufferParams const & Buffer::masterParams() const
716 if (masterBuffer() == this)
719 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
720 // Copy child authors to the params. We need those pointers.
721 AuthorList const & child_authors = params().authors();
722 AuthorList::Authors::const_iterator it = child_authors.begin();
723 for (; it != child_authors.end(); ++it)
724 mparams.authors().record(*it);
729 double Buffer::fontScalingFactor() const
731 return isExporting() ? 75.0 * params().html_math_img_scale
732 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
736 ParagraphList & Buffer::paragraphs()
738 return text().paragraphs();
742 ParagraphList const & Buffer::paragraphs() const
744 return text().paragraphs();
748 LyXVC & Buffer::lyxvc()
754 LyXVC const & Buffer::lyxvc() const
760 string const Buffer::temppath() const
762 return d->temppath.absFileName();
766 TexRow & Buffer::texrow()
772 TexRow const & Buffer::texrow() const
778 TocBackend & Buffer::tocBackend() const
780 return d->toc_backend;
784 Undo & Buffer::undo()
790 void Buffer::setChild(DocIterator const & dit, Buffer * child)
792 d->children_positions[child] = dit;
796 string Buffer::latexName(bool const no_path) const
798 FileName latex_name =
799 makeLatexName(d->exportFileName());
800 return no_path ? latex_name.onlyFileName()
801 : latex_name.absFileName();
805 FileName Buffer::Impl::exportFileName() const
807 docstring const branch_suffix =
808 params.branchlist().getFileNameSuffix();
809 if (branch_suffix.empty())
812 string const name = filename.onlyFileNameWithoutExt()
813 + to_utf8(branch_suffix);
814 FileName res(filename.onlyPath().absFileName() + "/" + name);
815 res.changeExtension(filename.extension());
821 string Buffer::logName(LogType * type) const
823 string const filename = latexName(false);
825 if (filename.empty()) {
831 string const path = temppath();
833 FileName const fname(addName(temppath(),
834 onlyFileName(changeExtension(filename,
837 // FIXME: how do we know this is the name of the build log?
838 FileName const bname(
839 addName(path, onlyFileName(
840 changeExtension(filename,
841 theFormats().extension(params().bufferFormat()) + ".out"))));
843 // Also consider the master buffer log file
844 FileName masterfname = fname;
845 LogType mtype = latexlog;
846 if (masterBuffer() != this) {
847 string const mlogfile = masterBuffer()->logName(&mtype);
848 masterfname = FileName(mlogfile);
851 // If no Latex log or Build log is newer, show Build log
852 if (bname.exists() &&
853 ((!fname.exists() && !masterfname.exists())
854 || (fname.lastModified() < bname.lastModified()
855 && masterfname.lastModified() < bname.lastModified()))) {
856 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
859 return bname.absFileName();
860 // If we have a newer master file log or only a master log, show this
861 } else if (fname != masterfname
862 && (!fname.exists() && (masterfname.exists()
863 || fname.lastModified() < masterfname.lastModified()))) {
864 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
867 return masterfname.absFileName();
869 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
872 return fname.absFileName();
876 void Buffer::setReadonly(bool const flag)
878 if (d->read_only != flag) {
885 void Buffer::setFileName(FileName const & fname)
887 bool const changed = fname != d->filename;
889 d->refreshFileMonitor();
891 lyxvc().file_found_hook(fname);
892 setReadonly(d->filename.isReadOnly());
898 int Buffer::readHeader(Lexer & lex)
900 int unknown_tokens = 0;
902 int begin_header_line = -1;
904 // Initialize parameters that may be/go lacking in header:
905 params().branchlist().clear();
906 params().preamble.erase();
907 params().options.erase();
908 params().master.erase();
909 params().float_placement.erase();
910 params().paperwidth.erase();
911 params().paperheight.erase();
912 params().leftmargin.erase();
913 params().rightmargin.erase();
914 params().topmargin.erase();
915 params().bottommargin.erase();
916 params().headheight.erase();
917 params().headsep.erase();
918 params().footskip.erase();
919 params().math_indentation.erase();
920 params().columnsep.erase();
921 params().fonts_cjk.erase();
922 params().listings_params.clear();
923 params().clearLayoutModules();
924 params().clearRemovedModules();
925 params().clearIncludedChildren();
926 params().pdfoptions().clear();
927 params().indiceslist().clear();
928 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
929 params().isbackgroundcolor = false;
930 params().fontcolor = RGBColor(0, 0, 0);
931 params().isfontcolor = false;
932 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
933 params().boxbgcolor = RGBColor(0xFF, 0, 0);
934 params().html_latex_start.clear();
935 params().html_latex_end.clear();
936 params().html_math_img_scale = 1.0;
937 params().output_sync_macro.erase();
938 params().setLocalLayout(docstring(), false);
939 params().setLocalLayout(docstring(), true);
940 params().biblio_opts.erase();
941 params().biblatex_bibstyle.erase();
942 params().biblatex_citestyle.erase();
943 params().multibib.erase();
945 for (int i = 0; i < 4; ++i) {
946 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
947 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
950 ErrorList & errorList = d->errorLists["Parse"];
959 if (token == "\\end_header")
963 if (token == "\\begin_header") {
964 begin_header_line = line;
968 LYXERR(Debug::PARSER, "Handling document header token: `"
971 string const result =
972 params().readToken(lex, token, d->filename.onlyPath());
973 if (!result.empty()) {
974 if (token == "\\textclass") {
975 d->layout_position = result;
978 docstring const s = bformat(_("Unknown token: "
982 errorList.push_back(ErrorItem(_("Document header error"), s));
986 if (begin_header_line) {
987 docstring const s = _("\\begin_header is missing");
988 errorList.push_back(ErrorItem(_("Document header error"), s));
991 params().makeDocumentClass();
993 return unknown_tokens;
998 // changed to be public and have one parameter
999 // Returns true if "\end_document" is not read (Asger)
1000 bool Buffer::readDocument(Lexer & lex)
1002 ErrorList & errorList = d->errorLists["Parse"];
1005 // remove dummy empty par
1006 paragraphs().clear();
1008 if (!lex.checkFor("\\begin_document")) {
1009 docstring const s = _("\\begin_document is missing");
1010 errorList.push_back(ErrorItem(_("Document header error"), s));
1015 if (params().output_changes) {
1016 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1017 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1018 LaTeXFeatures::isAvailable("xcolor");
1020 if (!dvipost && !xcolorulem) {
1021 Alert::warning(_("Changes not shown in LaTeX output"),
1022 _("Changes will not be highlighted in LaTeX output, "
1023 "because neither dvipost nor xcolor/ulem are installed.\n"
1024 "Please install these packages or redefine "
1025 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1026 } else if (!xcolorulem) {
1027 Alert::warning(_("Changes not shown in LaTeX output"),
1028 _("Changes will not be highlighted in LaTeX output "
1029 "when using pdflatex, because xcolor and ulem are not installed.\n"
1030 "Please install both packages or redefine "
1031 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1035 if (!parent() && !params().master.empty()) {
1036 FileName const master_file = makeAbsPath(params().master,
1037 onlyPath(absFileName()));
1038 if (isLyXFileName(master_file.absFileName())) {
1040 checkAndLoadLyXFile(master_file, true);
1042 // necessary e.g. after a reload
1043 // to re-register the child (bug 5873)
1044 // FIXME: clean up updateMacros (here, only
1045 // child registering is needed).
1046 master->updateMacros();
1047 // set master as master buffer, but only
1048 // if we are a real child
1049 if (master->isChild(this))
1051 // if the master is not fully loaded
1052 // it is probably just loading this
1053 // child. No warning needed then.
1054 else if (master->isFullyLoaded())
1055 LYXERR0("The master '"
1057 << "' assigned to this document ("
1059 << ") does not include "
1060 "this document. Ignoring the master assignment.");
1065 // assure we have a default index
1066 params().indiceslist().addDefault(B_("Index"));
1069 if (FileName::isAbsolute(params().origin))
1070 d->old_position = params().origin;
1072 d->old_position = filePath();
1073 bool const res = text().read(lex, errorList, d->inset);
1074 d->old_position.clear();
1076 // inform parent buffer about local macros
1078 Buffer const * pbuf = parent();
1079 UserMacroSet::const_iterator cit = usermacros.begin();
1080 UserMacroSet::const_iterator end = usermacros.end();
1081 for (; cit != end; ++cit)
1082 pbuf->usermacros.insert(*cit);
1086 updateMacroInstances(InternalUpdate);
1091 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1093 Format const * fmt = theFormats().getFormat(format);
1096 // It is important to use the correct extension here, since some
1097 // converters create a wrong output file otherwise (e.g. html2latex)
1098 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1099 FileName const name(tempfile.name());
1100 ofdocstream os(name.toFilesystemEncoding().c_str());
1101 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1102 bool const success = !(os << contents).fail();
1105 bool converted = false;
1107 params().compressed = false;
1109 // remove dummy empty par
1110 paragraphs().clear();
1112 converted = importFile(format, name, errorList);
1121 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1123 if (!theConverters().isReachable(format, "lyx"))
1126 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1127 FileName const lyx(tempfile.name());
1128 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1129 return readFile(lyx) == ReadSuccess;
1135 bool Buffer::readString(string const & s)
1137 params().compressed = false;
1140 istringstream is(s);
1142 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1143 FileName const fn = tempfile.name();
1146 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1148 if (success && file_format != LYX_FORMAT) {
1149 // We need to call lyx2lyx, so write the input to a file
1150 ofstream os(fn.toFilesystemEncoding().c_str());
1153 // lyxvc in readFile
1154 if (readFile(fn) != ReadSuccess)
1158 if (readDocument(lex))
1164 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1168 if (!lex.setFile(fname)) {
1169 Alert::error(_("File Not Found"),
1170 bformat(_("Unable to open file `%1$s'."),
1171 from_utf8(fn.absFileName())));
1172 return ReadFileNotFound;
1176 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1177 if (ret_plf != ReadSuccess)
1180 if (file_format != LYX_FORMAT) {
1182 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1183 if (ret_clf != ReadSuccess)
1185 ret_clf = readFile(tmpFile);
1186 if (ret_clf == ReadSuccess) {
1187 d->file_format = file_format;
1188 d->need_format_backup = true;
1193 // FIXME: InsetInfo needs to know whether the file is under VCS
1194 // during the parse process, so this has to be done before.
1195 lyxvc().file_found_hook(d->filename);
1197 if (readDocument(lex)) {
1198 Alert::error(_("Document format failure"),
1199 bformat(_("%1$s ended unexpectedly, which means"
1200 " that it is probably corrupted."),
1201 from_utf8(fn.absFileName())));
1202 return ReadDocumentFailure;
1205 d->file_fully_loaded = true;
1206 d->read_only = !d->filename.isWritable();
1207 params().compressed = theFormats().isZippedFile(d->filename);
1213 bool Buffer::isFullyLoaded() const
1215 return d->file_fully_loaded;
1219 void Buffer::setFullyLoaded(bool value)
1221 d->file_fully_loaded = value;
1225 bool Buffer::lastPreviewError() const
1227 return d->preview_error_;
1231 PreviewLoader * Buffer::loader() const
1233 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1235 if (!d->preview_loader_)
1236 d->preview_loader_ = new PreviewLoader(*this);
1237 return d->preview_loader_;
1241 void Buffer::removePreviews() const
1243 delete d->preview_loader_;
1244 d->preview_loader_ = 0;
1248 void Buffer::updatePreviews() const
1250 PreviewLoader * ploader = loader();
1254 InsetIterator it = inset_iterator_begin(*d->inset);
1255 InsetIterator const end = inset_iterator_end(*d->inset);
1256 for (; it != end; ++it)
1257 it->addPreview(it, *ploader);
1259 ploader->startLoading();
1263 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1264 FileName const & fn, int & file_format) const
1266 if(!lex.checkFor("\\lyxformat")) {
1267 Alert::error(_("Document format failure"),
1268 bformat(_("%1$s is not a readable LyX document."),
1269 from_utf8(fn.absFileName())));
1270 return ReadNoLyXFormat;
1276 // LyX formats 217 and earlier were written as 2.17. This corresponds
1277 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1278 // these cases. See also: www.lyx.org/trac/changeset/1313.
1279 size_t dot = tmp_format.find_first_of(".,");
1280 if (dot != string::npos)
1281 tmp_format.erase(dot, 1);
1283 file_format = convert<int>(tmp_format);
1288 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1289 FileName & tmpfile, int from_format)
1291 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1292 tempfile.setAutoRemove(false);
1293 tmpfile = tempfile.name();
1294 if(tmpfile.empty()) {
1295 Alert::error(_("Conversion failed"),
1296 bformat(_("%1$s is from a different"
1297 " version of LyX, but a temporary"
1298 " file for converting it could"
1299 " not be created."),
1300 from_utf8(fn.absFileName())));
1301 return LyX2LyXNoTempFile;
1304 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1305 if (lyx2lyx.empty()) {
1306 Alert::error(_("Conversion script not found"),
1307 bformat(_("%1$s is from a different"
1308 " version of LyX, but the"
1309 " conversion script lyx2lyx"
1310 " could not be found."),
1311 from_utf8(fn.absFileName())));
1312 return LyX2LyXNotFound;
1316 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1317 ostringstream command;
1318 command << os::python()
1319 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1320 << " -t " << convert<string>(LYX_FORMAT)
1321 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1322 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1323 string const command_str = command.str();
1325 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1327 cmd_ret const ret = runCommand(command_str);
1328 if (ret.first != 0) {
1329 if (from_format < LYX_FORMAT) {
1330 Alert::error(_("Conversion script failed"),
1331 bformat(_("%1$s is from an older version"
1332 " of LyX and the lyx2lyx script"
1333 " failed to convert it."),
1334 from_utf8(fn.absFileName())));
1335 return LyX2LyXOlderFormat;
1337 Alert::error(_("Conversion script failed"),
1338 bformat(_("%1$s is from a newer version"
1339 " of LyX and the lyx2lyx script"
1340 " failed to convert it."),
1341 from_utf8(fn.absFileName())));
1342 return LyX2LyXNewerFormat;
1349 FileName Buffer::getBackupName() const {
1350 FileName const & fn = fileName();
1351 string const fname = fn.onlyFileNameWithoutExt();
1352 string const fext = fn.extension() + "~";
1353 string const fpath = lyxrc.backupdir_path.empty() ?
1354 fn.onlyPath().absFileName() :
1355 lyxrc.backupdir_path;
1356 string const fform = convert<string>(d->file_format);
1357 string const backname = fname + "-lyxformat-" + fform;
1358 FileName backup(addName(fpath, addExtension(backname, fext)));
1360 // limit recursion, just in case
1362 unsigned long orig_checksum = 0;
1363 while (backup.exists() && v < 100) {
1364 if (orig_checksum == 0)
1365 orig_checksum = fn.checksum();
1366 unsigned long new_checksum = backup.checksum();
1367 if (orig_checksum == new_checksum) {
1368 LYXERR(Debug::FILES, "Not backing up " << fn <<
1369 "since " << backup << "has the same checksum.");
1370 // a bit of a hack, but we have to check this anyway
1371 // below, and setting this is simpler than introducing
1372 // a special boolean for this purpose.
1376 string const newbackname = backname + "-" + convert<string>(v);
1377 backup.set(addName(fpath, addExtension(newbackname, fext)));
1380 return v < 100 ? backup : FileName();
1384 // Should probably be moved to somewhere else: BufferView? GuiView?
1385 bool Buffer::save() const
1387 FileMonitorBlocker block = d->blockFileMonitor();
1388 docstring const file = makeDisplayPath(absFileName(), 20);
1389 d->filename.refresh();
1391 // check the read-only status before moving the file as a backup
1392 if (d->filename.exists()) {
1393 bool const read_only = !d->filename.isWritable();
1395 Alert::warning(_("File is read-only"),
1396 bformat(_("The file %1$s cannot be written because it "
1397 "is marked as read-only."), file));
1402 // ask if the disk file has been externally modified (use checksum method)
1403 if (fileName().exists() && isChecksumModified()) {
1405 bformat(_("Document %1$s has been externally modified. "
1406 "Are you sure you want to overwrite this file?"), file);
1407 int const ret = Alert::prompt(_("Overwrite modified file?"),
1408 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1413 // We don't need autosaves in the immediate future. (Asger)
1414 resetAutosaveTimers();
1416 // if the file does not yet exist, none of the backup activity
1417 // that follows is necessary
1418 if (!fileName().exists()) {
1419 if (!writeFile(fileName()))
1425 // we first write the file to a new name, then move it to its
1426 // proper location once that has been done successfully. that
1427 // way we preserve the original file if something goes wrong.
1428 string const justname = fileName().onlyFileNameWithoutExt();
1429 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1430 justname + "-XXXXXX.lyx");
1431 bool const symlink = fileName().isSymLink();
1433 tempfile->setAutoRemove(false);
1435 FileName savefile(tempfile->name());
1436 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1437 if (!writeFile(savefile))
1440 // we will set this to false if we fail
1441 bool made_backup = true;
1443 FileName backupName;
1444 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1446 if (d->need_format_backup)
1447 backupName = getBackupName();
1449 // If we for some reason failed to find a backup name in case of
1450 // a format change, this will still set one. It's the best we can
1452 if (backupName.empty()) {
1453 backupName.set(fileName().absFileName() + "~");
1454 if (!lyxrc.backupdir_path.empty()) {
1455 string const mangledName =
1456 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1457 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1461 LYXERR(Debug::FILES, "Backing up original file to " <<
1462 backupName.absFileName());
1463 // Except file is symlink do not copy because of #6587.
1464 // Hard links have bad luck.
1465 made_backup = symlink ?
1466 fileName().copyTo(backupName):
1467 fileName().moveTo(backupName);
1470 Alert::error(_("Backup failure"),
1471 bformat(_("Cannot create backup file %1$s.\n"
1472 "Please check whether the directory exists and is writable."),
1473 from_utf8(backupName.absFileName())));
1474 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1475 } else if (d->need_format_backup) {
1476 // the original file has been backed up successfully, so we
1477 // will not need to do that again
1478 d->need_format_backup = false;
1482 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1483 // Only do this if tempfile is not in autoremove mode
1486 // If we have no symlink, we can simply rename the temp file.
1487 // Otherwise, we need to copy it so the symlink stays intact.
1488 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1489 savefile.moveTo(fileName()))
1491 // saveCheckSum() was already called by writeFile(), but the
1492 // time stamp is invalidated by copying/moving
1495 if (d->file_format != LYX_FORMAT)
1496 // the file associated with this buffer is now in the current format
1497 d->file_format = LYX_FORMAT;
1500 // else we saved the file, but failed to move it to the right location.
1502 if (needBackup && made_backup && !symlink) {
1503 // the original file was moved to some new location, so it will look
1504 // to the user as if it was deleted. (see bug #9234.) we could try
1505 // to restore it, but that would basically mean trying to do again
1506 // what we just failed to do. better to leave things as they are.
1507 Alert::error(_("Write failure"),
1508 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1509 "But LyX could not move it to:\n %2$s.\n"
1510 "Your original file has been backed up to:\n %3$s"),
1511 from_utf8(savefile.absFileName()),
1512 from_utf8(fileName().absFileName()),
1513 from_utf8(backupName.absFileName())));
1515 // either we did not try to make a backup, or else we tried and failed,
1516 // or else the original file was a symlink, in which case it was copied,
1517 // not moved. so the original file is intact.
1518 Alert::error(_("Write failure"),
1519 bformat(_("Cannot move saved file to:\n %1$s.\n"
1520 "But the file has successfully been saved as:\n %2$s."),
1521 from_utf8(fileName().absFileName()),
1522 from_utf8(savefile.absFileName())));
1528 bool Buffer::writeFile(FileName const & fname) const
1530 if (d->read_only && fname == d->filename)
1533 bool retval = false;
1535 docstring const str = bformat(_("Saving document %1$s..."),
1536 makeDisplayPath(fname.absFileName()));
1539 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1541 if (params().compressed) {
1542 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1543 retval = ofs && write(ofs);
1545 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1546 retval = ofs && write(ofs);
1550 message(str + _(" could not write file!"));
1555 // removeAutosaveFile();
1558 message(str + _(" done."));
1564 docstring Buffer::emergencyWrite()
1566 // No need to save if the buffer has not changed.
1570 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1572 docstring user_message = bformat(
1573 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1575 // We try to save three places:
1576 // 1) Same place as document. Unless it is an unnamed doc.
1578 string s = absFileName();
1581 if (writeFile(FileName(s))) {
1583 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1584 return user_message;
1586 user_message += " " + _("Save failed! Trying again...\n");
1590 // 2) In HOME directory.
1591 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1593 lyxerr << ' ' << s << endl;
1594 if (writeFile(FileName(s))) {
1596 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1597 return user_message;
1600 user_message += " " + _("Save failed! Trying yet again...\n");
1602 // 3) In "/tmp" directory.
1603 // MakeAbsPath to prepend the current
1604 // drive letter on OS/2
1605 s = addName(package().temp_dir().absFileName(), absFileName());
1607 lyxerr << ' ' << s << endl;
1608 if (writeFile(FileName(s))) {
1610 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1611 return user_message;
1614 user_message += " " + _("Save failed! Document is lost.");
1617 return user_message;
1621 bool Buffer::write(ostream & ofs) const
1624 // Use the standard "C" locale for file output.
1625 ofs.imbue(locale::classic());
1628 // The top of the file should not be written by params().
1630 // write out a comment in the top of the file
1631 // Important: Keep the version formatting in sync with lyx2lyx and
1632 // tex2lyx (bug 7951)
1633 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1634 << " created this file. For more info see http://www.lyx.org/\n"
1635 << "\\lyxformat " << LYX_FORMAT << "\n"
1636 << "\\begin_document\n";
1638 /// For each author, set 'used' to true if there is a change
1639 /// by this author in the document; otherwise set it to 'false'.
1640 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1641 AuthorList::Authors::const_iterator a_end = params().authors().end();
1642 for (; a_it != a_end; ++a_it)
1643 a_it->setUsed(false);
1645 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1646 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1647 for ( ; it != end; ++it)
1648 it->checkAuthors(params().authors());
1650 // now write out the buffer parameters.
1651 ofs << "\\begin_header\n";
1652 params().writeFile(ofs, this);
1653 ofs << "\\end_header\n";
1656 ofs << "\n\\begin_body\n";
1658 ofs << "\n\\end_body\n";
1660 // Write marker that shows file is complete
1661 ofs << "\\end_document" << endl;
1663 // Shouldn't really be needed....
1666 // how to check if close went ok?
1667 // Following is an attempt... (BE 20001011)
1669 // good() returns false if any error occurred, including some
1670 // formatting error.
1671 // bad() returns true if something bad happened in the buffer,
1672 // which should include file system full errors.
1677 lyxerr << "File was not closed properly." << endl;
1684 bool Buffer::makeLaTeXFile(FileName const & fname,
1685 string const & original_path,
1686 OutputParams const & runparams_in,
1687 OutputWhat output) const
1689 OutputParams runparams = runparams_in;
1691 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1692 // Check here, because the "flavor" is not known in BufferParams::encoding()
1693 // (power users can override this safety measure selecting "utf8-plain").
1694 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1695 && (runparams.encoding->name() != "utf8-plain"))
1696 runparams.encoding = encodings.fromLyXName("ascii");
1698 string const encoding = runparams.encoding->iconvName();
1699 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1702 try { ofs.reset(encoding); }
1703 catch (iconv_codecvt_facet_exception const & e) {
1704 lyxerr << "Caught iconv exception: " << e.what() << endl;
1705 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1706 "verify that the support software for your encoding (%1$s) is "
1707 "properly installed"), from_ascii(encoding)));
1710 if (!openFileWrite(ofs, fname))
1713 ErrorList & errorList = d->errorLists["Export"];
1715 bool failed_export = false;
1718 // make sure we are ready to export
1719 // this needs to be done before we validate
1720 // FIXME Do we need to do this all the time? I.e., in children
1721 // of a master we are exporting?
1723 updateMacroInstances(OutputUpdate);
1726 writeLaTeXSource(os, original_path, runparams, output);
1728 catch (EncodingException const & e) {
1729 docstring const failed(1, e.failed_char);
1731 oss << "0x" << hex << e.failed_char << dec;
1732 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1733 " (code point %2$s)"),
1734 failed, from_utf8(oss.str()));
1735 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1736 "representable in the chosen encoding.\n"
1737 "Changing the document encoding to utf8 could help."),
1738 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1739 failed_export = true;
1741 catch (iconv_codecvt_facet_exception const & e) {
1742 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1744 failed_export = true;
1746 catch (exception const & e) {
1747 errorList.push_back(ErrorItem(_("conversion failed"),
1749 lyxerr << e.what() << endl;
1750 failed_export = true;
1753 lyxerr << "Caught some really weird exception..." << endl;
1757 d->texrow = move(os.texrow());
1761 failed_export = true;
1762 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1765 if (runparams_in.silent)
1769 return !failed_export;
1773 void Buffer::writeLaTeXSource(otexstream & os,
1774 string const & original_path,
1775 OutputParams const & runparams_in,
1776 OutputWhat output) const
1778 // The child documents, if any, shall be already loaded at this point.
1780 OutputParams runparams = runparams_in;
1782 // XeTeX with TeX fonts is only safe with ASCII encoding,
1783 // Check here, because the "flavor" is not known in BufferParams::encoding()
1784 // (power users can override this safety measure selecting "utf8-plain").
1785 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1786 && (runparams.encoding->name() != "utf8-plain"))
1787 runparams.encoding = encodings.fromLyXName("ascii");
1788 // FIXME: when only the current paragraph is shown, this is ignored
1789 // (or not reached) and characters encodable in the current
1790 // encoding are not converted to ASCII-representation.
1792 // If we are compiling a file standalone, even if this is the
1793 // child of some other buffer, let's cut the link here, so the
1794 // file is really independent and no concurring settings from
1795 // the master (e.g. branch state) interfere (see #8100).
1796 if (!runparams.is_child)
1797 d->ignore_parent = true;
1799 // Classify the unicode characters appearing in math insets
1800 BufferEncodings::initUnicodeMath(*this);
1802 // validate the buffer.
1803 LYXERR(Debug::LATEX, " Validating buffer...");
1804 LaTeXFeatures features(*this, params(), runparams);
1806 // This is only set once per document (in master)
1807 if (!runparams.is_child)
1808 runparams.use_polyglossia = features.usePolyglossia();
1809 LYXERR(Debug::LATEX, " Buffer validation done.");
1811 bool const output_preamble =
1812 output == FullSource || output == OnlyPreamble;
1813 bool const output_body =
1814 output == FullSource || output == OnlyBody;
1816 // The starting paragraph of the coming rows is the
1817 // first paragraph of the document. (Asger)
1818 if (output_preamble && runparams.nice) {
1819 os << "%% LyX " << lyx_version << " created this file. "
1820 "For more info, see http://www.lyx.org/.\n"
1821 "%% Do not edit unless you really know what "
1824 LYXERR(Debug::INFO, "lyx document header finished");
1826 // There are a few differences between nice LaTeX and usual files:
1827 // usual files have \batchmode and special input@path to allow
1828 // inclusion of figures specified by an explicitly relative path
1829 // (i.e., a path starting with './' or '../') with either \input or
1830 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1831 // input@path is set when the actual parameter original_path is set.
1832 // This is done for usual tex-file, but not for nice-latex-file.
1833 // (Matthias 250696)
1834 // Note that input@path is only needed for something the user does
1835 // in the preamble, included .tex files or ERT, files included by
1836 // LyX work without it.
1837 if (output_preamble) {
1838 if (!runparams.nice) {
1839 // code for usual, NOT nice-latex-file
1840 os << "\\batchmode\n"; // changed from \nonstopmode
1842 if (!original_path.empty()) {
1844 // We don't know the encoding of inputpath
1845 docstring const inputpath = from_utf8(original_path);
1846 docstring uncodable_glyphs;
1847 Encoding const * const enc = runparams.encoding;
1849 for (size_t n = 0; n < inputpath.size(); ++n) {
1850 if (!enc->encodable(inputpath[n])) {
1851 docstring const glyph(1, inputpath[n]);
1852 LYXERR0("Uncodable character '"
1854 << "' in input path!");
1855 uncodable_glyphs += glyph;
1860 // warn user if we found uncodable glyphs.
1861 if (!uncodable_glyphs.empty()) {
1862 frontend::Alert::warning(
1863 _("Uncodable character in file path"),
1865 _("The path of your document\n"
1867 "contains glyphs that are unknown "
1868 "in the current document encoding "
1869 "(namely %2$s). This may result in "
1870 "incomplete output, unless "
1871 "TEXINPUTS contains the document "
1872 "directory and you don't use "
1873 "explicitly relative paths (i.e., "
1874 "paths starting with './' or "
1875 "'../') in the preamble or in ERT."
1876 "\n\nIn case of problems, choose "
1877 "an appropriate document encoding\n"
1878 "(such as utf8) or change the "
1880 inputpath, uncodable_glyphs));
1883 support::latex_path(original_path);
1884 if (contains(docdir, '#')) {
1885 docdir = subst(docdir, "#", "\\#");
1886 os << "\\catcode`\\#=11"
1887 "\\def\\#{#}\\catcode`\\#=6\n";
1889 if (contains(docdir, '%')) {
1890 docdir = subst(docdir, "%", "\\%");
1891 os << "\\catcode`\\%=11"
1892 "\\def\\%{%}\\catcode`\\%=14\n";
1894 os << "\\makeatletter\n"
1895 << "\\def\\input@path{{"
1897 << "\\makeatother\n";
1901 // get parent macros (if this buffer has a parent) which will be
1902 // written at the document begin further down.
1903 MacroSet parentMacros;
1904 listParentMacros(parentMacros, features);
1906 // Write the preamble
1907 runparams.use_babel = params().writeLaTeX(os, features,
1908 d->filename.onlyPath());
1910 // Biblatex bibliographies are loaded here
1911 if (params().useBiblatex()) {
1912 vector<docstring> const bibfiles =
1913 prepareBibFilePaths(runparams, getBibfilesCache(), true);
1914 for (docstring const & file: bibfiles)
1915 os << "\\addbibresource{" << file << "}\n";
1918 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1919 && !features.hasOnlyPolyglossiaLanguages()) {
1922 vector<string> bll = features.getBabelExclusiveLanguages();
1923 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1926 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1931 blangs = bll.size() > 1 ?
1932 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1933 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1937 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1942 plangs = pll.size() > 1 ?
1943 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1944 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1945 if (!blangs.empty())
1949 frontend::Alert::warning(
1950 _("Incompatible Languages!"),
1952 _("You cannot use the following languages "
1953 "together in one LaTeX document because "
1954 "they require conflicting language packages:\n"
1959 // Japanese might be required only in some children of a document,
1960 // but once required, we must keep use_japanese true.
1961 runparams.use_japanese |= features.isRequired("japanese");
1964 // Restore the parenthood if needed
1965 if (!runparams.is_child)
1966 d->ignore_parent = false;
1971 // mark the beginning of the body to separate it from InPreamble insets
1972 os.texrow().start(TexRow::beginDocument());
1973 os << "\\begin{document}\n";
1975 // mark the start of a new paragraph by simulating a newline,
1976 // so that os.afterParbreak() returns true at document start
1979 // output the parent macros
1980 MacroSet::iterator it = parentMacros.begin();
1981 MacroSet::iterator end = parentMacros.end();
1982 for (; it != end; ++it) {
1983 int num_lines = (*it)->write(os.os(), true);
1984 os.texrow().newlines(num_lines);
1987 } // output_preamble
1989 LYXERR(Debug::INFO, "preamble finished, now the body.");
1992 latexParagraphs(*this, text(), os, runparams);
1994 // Restore the parenthood if needed
1995 if (!runparams.is_child)
1996 d->ignore_parent = false;
1998 // add this just in case after all the paragraphs
2001 if (output_preamble) {
2002 os << "\\end{document}\n";
2003 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2005 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2007 runparams_in.encoding = runparams.encoding;
2009 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2010 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2014 void Buffer::makeDocBookFile(FileName const & fname,
2015 OutputParams const & runparams,
2016 OutputWhat output) const
2018 LYXERR(Debug::LATEX, "makeDocBookFile...");
2021 if (!openFileWrite(ofs, fname))
2024 // make sure we are ready to export
2025 // this needs to be done before we validate
2027 updateMacroInstances(OutputUpdate);
2029 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2033 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2037 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2038 OutputParams const & runparams,
2039 OutputWhat output) const
2041 LaTeXFeatures features(*this, params(), runparams);
2046 DocumentClass const & tclass = params().documentClass();
2047 string const & top_element = tclass.latexname();
2049 bool const output_preamble =
2050 output == FullSource || output == OnlyPreamble;
2051 bool const output_body =
2052 output == FullSource || output == OnlyBody;
2054 if (output_preamble) {
2055 if (runparams.flavor == OutputParams::XML)
2056 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2059 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2062 if (! tclass.class_header().empty())
2063 os << from_ascii(tclass.class_header());
2064 else if (runparams.flavor == OutputParams::XML)
2065 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2066 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2068 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2070 docstring preamble = params().preamble;
2071 if (runparams.flavor != OutputParams::XML ) {
2072 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2073 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2074 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2075 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2078 string const name = runparams.nice
2079 ? changeExtension(absFileName(), ".sgml") : fname;
2080 preamble += features.getIncludedFiles(name);
2081 preamble += features.getLyXSGMLEntities();
2083 if (!preamble.empty()) {
2084 os << "\n [ " << preamble << " ]";
2090 string top = top_element;
2092 if (runparams.flavor == OutputParams::XML)
2093 top += params().language->code();
2095 top += params().language->code().substr(0, 2);
2098 if (!params().options.empty()) {
2100 top += params().options;
2103 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2104 << " file was created by LyX " << lyx_version
2105 << "\n See http://www.lyx.org/ for more information -->\n";
2107 params().documentClass().counters().reset();
2109 sgml::openTag(os, top);
2111 docbookParagraphs(text(), *this, os, runparams);
2112 sgml::closeTag(os, top_element);
2117 void Buffer::makeLyXHTMLFile(FileName const & fname,
2118 OutputParams const & runparams) const
2120 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2123 if (!openFileWrite(ofs, fname))
2126 // make sure we are ready to export
2127 // this has to be done before we validate
2128 updateBuffer(UpdateMaster, OutputUpdate);
2129 updateMacroInstances(OutputUpdate);
2131 writeLyXHTMLSource(ofs, runparams, FullSource);
2135 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2139 void Buffer::writeLyXHTMLSource(odocstream & os,
2140 OutputParams const & runparams,
2141 OutputWhat output) const
2143 LaTeXFeatures features(*this, params(), runparams);
2145 d->bibinfo_.makeCitationLabels(*this);
2147 bool const output_preamble =
2148 output == FullSource || output == OnlyPreamble;
2149 bool const output_body =
2150 output == FullSource || output == OnlyBody || output == IncludedFile;
2152 if (output_preamble) {
2153 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2154 << "<!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"
2155 // FIXME Language should be set properly.
2156 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2158 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2159 // FIXME Presumably need to set this right
2160 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2162 docstring const & doctitle = features.htmlTitle();
2164 << (doctitle.empty() ?
2165 from_ascii("LyX Document") :
2166 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2169 docstring styles = features.getTClassHTMLPreamble();
2170 if (!styles.empty())
2171 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2173 styles = features.getPreambleSnippets().str;
2174 if (!styles.empty())
2175 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2177 // we will collect CSS information in a stream, and then output it
2178 // either here, as part of the header, or else in a separate file.
2179 odocstringstream css;
2180 styles = features.getCSSSnippets();
2181 if (!styles.empty())
2182 css << "/* LyX Provided Styles */\n" << styles << '\n';
2184 styles = features.getTClassHTMLStyles();
2185 if (!styles.empty())
2186 css << "/* Layout-provided Styles */\n" << styles << '\n';
2188 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2189 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2190 if (needfg || needbg) {
2191 css << "\nbody {\n";
2194 << from_ascii(X11hexname(params().fontcolor))
2197 css << " background-color: "
2198 << from_ascii(X11hexname(params().backgroundcolor))
2203 docstring const dstyles = css.str();
2204 if (!dstyles.empty()) {
2205 bool written = false;
2206 if (params().html_css_as_file) {
2207 // open a file for CSS info
2209 string const fcssname = addName(temppath(), "docstyle.css");
2210 FileName const fcssfile = FileName(fcssname);
2211 if (openFileWrite(ocss, fcssfile)) {
2215 // write link to header
2216 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2218 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2221 // we are here if the CSS is supposed to be written to the header
2222 // or if we failed to write it to an external file.
2224 os << "<style type='text/css'>\n"
2233 bool const output_body_tag = (output != IncludedFile);
2234 if (output_body_tag)
2235 os << "<body dir=\"auto\">\n";
2237 if (output != IncludedFile)
2238 // if we're an included file, the counters are in the master.
2239 params().documentClass().counters().reset();
2240 xhtmlParagraphs(text(), *this, xs, runparams);
2241 if (output_body_tag)
2245 if (output_preamble)
2250 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2251 // Other flags: -wall -v0 -x
2252 int Buffer::runChktex()
2256 // get LaTeX-Filename
2257 FileName const path(temppath());
2258 string const name = addName(path.absFileName(), latexName());
2259 string const org_path = filePath();
2261 PathChanger p(path); // path to LaTeX file
2262 message(_("Running chktex..."));
2264 // Generate the LaTeX file if neccessary
2265 OutputParams runparams(¶ms().encoding());
2266 runparams.flavor = OutputParams::LATEX;
2267 runparams.nice = false;
2268 runparams.linelen = lyxrc.plaintext_linelen;
2269 makeLaTeXFile(FileName(name), org_path, runparams);
2272 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2273 int const res = chktex.run(terr); // run chktex
2276 Alert::error(_("chktex failure"),
2277 _("Could not run chktex successfully."));
2279 ErrorList & errlist = d->errorLists["ChkTeX"];
2281 bufferErrors(terr, errlist);
2286 if (runparams.silent)
2287 d->errorLists["ChkTeX"].clear();
2295 void Buffer::validate(LaTeXFeatures & features) const
2297 // Validate the buffer params, but not for included
2298 // files, since they also use the parent buffer's
2300 if (!features.runparams().is_child)
2301 params().validate(features);
2303 for (Paragraph const & p : paragraphs())
2304 p.validate(features);
2306 if (lyxerr.debugging(Debug::LATEX)) {
2307 features.showStruct();
2312 void Buffer::getLabelList(vector<docstring> & list) const
2314 // If this is a child document, use the master's list instead.
2316 masterBuffer()->getLabelList(list);
2321 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2322 Toc::const_iterator toc_it = toc->begin();
2323 Toc::const_iterator end = toc->end();
2324 for (; toc_it != end; ++toc_it) {
2325 if (toc_it->depth() == 0)
2326 list.push_back(toc_it->str());
2331 void Buffer::updateBibfilesCache(UpdateScope scope) const
2333 // FIXME This is probably unnecssary, given where we call this.
2334 // If this is a child document, use the parent's cache instead.
2335 if (parent() && scope != UpdateChildOnly) {
2336 masterBuffer()->updateBibfilesCache();
2340 d->bibfiles_cache_.clear();
2341 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2342 if (it->lyxCode() == BIBTEX_CODE) {
2343 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2344 support::FileNamePairList const bibfiles = inset.getBibFiles();
2345 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2348 } else if (it->lyxCode() == INCLUDE_CODE) {
2349 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2350 Buffer const * const incbuf = inset.getChildBuffer();
2353 support::FileNamePairList const & bibfiles =
2354 incbuf->getBibfilesCache(UpdateChildOnly);
2355 if (!bibfiles.empty()) {
2356 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2362 d->bibfile_cache_valid_ = true;
2363 d->bibinfo_cache_valid_ = false;
2364 d->cite_labels_valid_ = false;
2368 void Buffer::invalidateBibinfoCache() const
2370 d->bibinfo_cache_valid_ = false;
2371 d->cite_labels_valid_ = false;
2372 // also invalidate the cache for the parent buffer
2373 Buffer const * const pbuf = d->parent();
2375 pbuf->invalidateBibinfoCache();
2379 void Buffer::invalidateBibfileCache() const
2381 d->bibfile_cache_valid_ = false;
2382 d->bibinfo_cache_valid_ = false;
2383 d->cite_labels_valid_ = false;
2384 // also invalidate the cache for the parent buffer
2385 Buffer const * const pbuf = d->parent();
2387 pbuf->invalidateBibfileCache();
2391 support::FileNamePairList const & Buffer::getBibfilesCache(UpdateScope scope) const
2393 // FIXME This is probably unnecessary, given where we call this.
2394 // If this is a child document, use the master's cache instead.
2395 Buffer const * const pbuf = masterBuffer();
2396 if (pbuf != this && scope != UpdateChildOnly)
2397 return pbuf->getBibfilesCache();
2399 if (!d->bibfile_cache_valid_)
2400 this->updateBibfilesCache(scope);
2402 return d->bibfiles_cache_;
2406 BiblioInfo const & Buffer::masterBibInfo() const
2408 Buffer const * const tmp = masterBuffer();
2410 return tmp->masterBibInfo();
2415 void Buffer::checkIfBibInfoCacheIsValid() const
2417 // use the master's cache
2418 Buffer const * const tmp = masterBuffer();
2420 tmp->checkIfBibInfoCacheIsValid();
2424 // compare the cached timestamps with the actual ones.
2425 FileNamePairList const & bibfiles_cache = getBibfilesCache();
2426 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2427 FileNamePairList::const_iterator en = bibfiles_cache.end();
2428 for (; ei != en; ++ ei) {
2429 FileName const fn = ei->second;
2430 time_t lastw = fn.lastModified();
2431 time_t prevw = d->bibfile_status_[fn];
2432 if (lastw != prevw) {
2433 d->bibinfo_cache_valid_ = false;
2434 d->cite_labels_valid_ = false;
2435 d->bibfile_status_[fn] = lastw;
2441 void Buffer::reloadBibInfoCache() const
2443 // use the master's cache
2444 Buffer const * const tmp = masterBuffer();
2446 tmp->reloadBibInfoCache();
2450 checkIfBibInfoCacheIsValid();
2451 if (d->bibinfo_cache_valid_)
2454 d->bibinfo_.clear();
2456 d->bibinfo_cache_valid_ = true;
2460 void Buffer::collectBibKeys() const
2462 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2463 it->collectBibKeys(it);
2467 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2469 Buffer const * tmp = masterBuffer();
2470 BiblioInfo & masterbi = (tmp == this) ?
2471 d->bibinfo_ : tmp->d->bibinfo_;
2472 masterbi.mergeBiblioInfo(bi);
2476 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2478 Buffer const * tmp = masterBuffer();
2479 BiblioInfo & masterbi = (tmp == this) ?
2480 d->bibinfo_ : tmp->d->bibinfo_;
2485 void Buffer::makeCitationLabels() const
2487 Buffer const * const master = masterBuffer();
2488 return d->bibinfo_.makeCitationLabels(*master);
2492 bool Buffer::citeLabelsValid() const
2494 return masterBuffer()->d->cite_labels_valid_;
2498 void Buffer::removeBiblioTempFiles() const
2500 // We remove files that contain LaTeX commands specific to the
2501 // particular bibliographic style being used, in order to avoid
2502 // LaTeX errors when we switch style.
2503 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2504 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2505 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2506 aux_file.removeFile();
2507 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2508 bbl_file.removeFile();
2509 // Also for the parent buffer
2510 Buffer const * const pbuf = parent();
2512 pbuf->removeBiblioTempFiles();
2516 bool Buffer::isDepClean(string const & name) const
2518 DepClean::const_iterator const it = d->dep_clean.find(name);
2519 if (it == d->dep_clean.end())
2525 void Buffer::markDepClean(string const & name)
2527 d->dep_clean[name] = true;
2531 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2534 // FIXME? if there is an Buffer LFUN that can be dispatched even
2535 // if internal, put a switch '(cmd.action)' here.
2541 switch (cmd.action()) {
2543 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2544 flag.setOnOff(hasReadonlyFlag());
2547 // FIXME: There is need for a command-line import.
2548 //case LFUN_BUFFER_IMPORT:
2550 case LFUN_BUFFER_AUTO_SAVE:
2553 case LFUN_BUFFER_EXPORT_CUSTOM:
2554 // FIXME: Nothing to check here?
2557 case LFUN_BUFFER_EXPORT: {
2558 docstring const arg = cmd.argument();
2559 if (arg == "custom") {
2563 string format = (arg.empty() || arg == "default") ?
2564 params().getDefaultOutputFormat() : to_utf8(arg);
2565 size_t pos = format.find(' ');
2566 if (pos != string::npos)
2567 format = format.substr(0, pos);
2568 enable = params().isExportable(format, false);
2570 flag.message(bformat(
2571 _("Don't know how to export to format: %1$s"), arg));
2575 case LFUN_BUFFER_CHKTEX:
2576 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2579 case LFUN_BUILD_PROGRAM:
2580 enable = params().isExportable("program", false);
2583 case LFUN_BRANCH_ACTIVATE:
2584 case LFUN_BRANCH_DEACTIVATE:
2585 case LFUN_BRANCH_MASTER_ACTIVATE:
2586 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2587 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2588 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2589 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2590 : params().branchlist();
2591 docstring const branchName = cmd.argument();
2592 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2596 case LFUN_BRANCH_ADD:
2597 case LFUN_BRANCHES_RENAME:
2598 // if no Buffer is present, then of course we won't be called!
2601 case LFUN_BUFFER_LANGUAGE:
2602 enable = !isReadonly();
2605 case LFUN_BUFFER_VIEW_CACHE:
2606 (d->preview_file_).refresh();
2607 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2610 case LFUN_CHANGES_TRACK:
2611 flag.setEnabled(true);
2612 flag.setOnOff(params().track_changes);
2615 case LFUN_CHANGES_OUTPUT:
2616 flag.setEnabled(true);
2617 flag.setOnOff(params().output_changes);
2620 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2621 flag.setOnOff(params().compressed);
2625 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2626 flag.setOnOff(params().output_sync);
2633 flag.setEnabled(enable);
2638 void Buffer::dispatch(string const & command, DispatchResult & result)
2640 return dispatch(lyxaction.lookupFunc(command), result);
2644 // NOTE We can end up here even if we have no GUI, because we are called
2645 // by LyX::exec to handled command-line requests. So we may need to check
2646 // whether we have a GUI or not. The boolean use_gui holds this information.
2647 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2650 // FIXME? if there is an Buffer LFUN that can be dispatched even
2651 // if internal, put a switch '(cmd.action())' here.
2652 dr.dispatched(false);
2655 string const argument = to_utf8(func.argument());
2656 // We'll set this back to false if need be.
2657 bool dispatched = true;
2658 undo().beginUndoGroup();
2660 switch (func.action()) {
2661 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2662 if (lyxvc().inUse()) {
2663 string log = lyxvc().toggleReadOnly();
2668 setReadonly(!hasReadonlyFlag());
2671 case LFUN_BUFFER_EXPORT: {
2672 string const format = (argument.empty() || argument == "default") ?
2673 params().getDefaultOutputFormat() : argument;
2674 ExportStatus const status = doExport(format, false);
2675 dr.setError(status != ExportSuccess);
2676 if (status != ExportSuccess)
2677 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2678 from_utf8(format)));
2682 case LFUN_BUILD_PROGRAM: {
2683 ExportStatus const status = doExport("program", true);
2684 dr.setError(status != ExportSuccess);
2685 if (status != ExportSuccess)
2686 dr.setMessage(_("Error generating literate programming code."));
2690 case LFUN_BUFFER_CHKTEX:
2694 case LFUN_BUFFER_EXPORT_CUSTOM: {
2696 string command = split(argument, format_name, ' ');
2697 Format const * format = theFormats().getFormat(format_name);
2699 lyxerr << "Format \"" << format_name
2700 << "\" not recognized!"
2705 // The name of the file created by the conversion process
2708 // Output to filename
2709 if (format->name() == "lyx") {
2710 string const latexname = latexName(false);
2711 filename = changeExtension(latexname,
2712 format->extension());
2713 filename = addName(temppath(), filename);
2715 if (!writeFile(FileName(filename)))
2719 doExport(format_name, true, filename);
2722 // Substitute $$FName for filename
2723 if (!contains(command, "$$FName"))
2724 command = "( " + command + " ) < $$FName";
2725 command = subst(command, "$$FName", filename);
2727 // Execute the command in the background
2729 call.startscript(Systemcall::DontWait, command,
2730 filePath(), layoutPos());
2734 // FIXME: There is need for a command-line import.
2736 case LFUN_BUFFER_IMPORT:
2741 case LFUN_BUFFER_AUTO_SAVE:
2743 resetAutosaveTimers();
2746 case LFUN_BRANCH_ACTIVATE:
2747 case LFUN_BRANCH_DEACTIVATE:
2748 case LFUN_BRANCH_MASTER_ACTIVATE:
2749 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2750 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2751 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2752 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2755 docstring const branch_name = func.argument();
2756 // the case without a branch name is handled elsewhere
2757 if (branch_name.empty()) {
2761 Branch * branch = buf->params().branchlist().find(branch_name);
2763 LYXERR0("Branch " << branch_name << " does not exist.");
2765 docstring const msg =
2766 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2770 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2771 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2772 if (branch->isSelected() != activate) {
2773 buf->undo().recordUndoBufferParams(CursorData());
2774 branch->setSelected(activate);
2776 dr.screenUpdate(Update::Force);
2777 dr.forceBufferUpdate();
2782 case LFUN_BRANCH_ADD: {
2783 docstring branch_name = func.argument();
2784 if (branch_name.empty()) {
2788 BranchList & branch_list = params().branchlist();
2789 vector<docstring> const branches =
2790 getVectorFromString(branch_name, branch_list.separator());
2792 for (vector<docstring>::const_iterator it = branches.begin();
2793 it != branches.end(); ++it) {
2795 Branch * branch = branch_list.find(branch_name);
2797 LYXERR0("Branch " << branch_name << " already exists.");
2801 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2803 undo().recordUndoBufferParams(CursorData());
2804 branch_list.add(branch_name);
2805 branch = branch_list.find(branch_name);
2806 string const x11hexname = X11hexname(branch->color());
2807 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2808 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2810 dr.screenUpdate(Update::Force);
2818 case LFUN_BRANCHES_RENAME: {
2819 if (func.argument().empty())
2822 docstring const oldname = from_utf8(func.getArg(0));
2823 docstring const newname = from_utf8(func.getArg(1));
2824 InsetIterator it = inset_iterator_begin(inset());
2825 InsetIterator const end = inset_iterator_end(inset());
2826 bool success = false;
2827 for (; it != end; ++it) {
2828 if (it->lyxCode() == BRANCH_CODE) {
2829 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2830 if (ins.branch() == oldname) {
2831 undo().recordUndo(CursorData(it));
2832 ins.rename(newname);
2837 if (it->lyxCode() == INCLUDE_CODE) {
2838 // get buffer of external file
2839 InsetInclude const & ins =
2840 static_cast<InsetInclude const &>(*it);
2841 Buffer * child = ins.getChildBuffer();
2844 child->dispatch(func, dr);
2849 dr.screenUpdate(Update::Force);
2850 dr.forceBufferUpdate();
2855 case LFUN_BUFFER_VIEW_CACHE:
2856 if (!theFormats().view(*this, d->preview_file_,
2857 d->preview_format_))
2858 dr.setMessage(_("Error viewing the output file."));
2861 case LFUN_CHANGES_TRACK:
2862 if (params().save_transient_properties)
2863 undo().recordUndoBufferParams(CursorData());
2864 params().track_changes = !params().track_changes;
2865 if (!params().track_changes)
2866 dr.forceChangesUpdate();
2869 case LFUN_CHANGES_OUTPUT:
2870 if (params().save_transient_properties)
2871 undo().recordUndoBufferParams(CursorData());
2872 params().output_changes = !params().output_changes;
2873 if (params().output_changes) {
2874 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2875 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2876 LaTeXFeatures::isAvailable("xcolor");
2878 if (!dvipost && !xcolorulem) {
2879 Alert::warning(_("Changes not shown in LaTeX output"),
2880 _("Changes will not be highlighted in LaTeX output, "
2881 "because neither dvipost nor xcolor/ulem are installed.\n"
2882 "Please install these packages or redefine "
2883 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2884 } else if (!xcolorulem) {
2885 Alert::warning(_("Changes not shown in LaTeX output"),
2886 _("Changes will not be highlighted in LaTeX output "
2887 "when using pdflatex, because xcolor and ulem are not installed.\n"
2888 "Please install both packages or redefine "
2889 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2894 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2895 // turn compression on/off
2896 undo().recordUndoBufferParams(CursorData());
2897 params().compressed = !params().compressed;
2900 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2901 undo().recordUndoBufferParams(CursorData());
2902 params().output_sync = !params().output_sync;
2909 dr.dispatched(dispatched);
2910 undo().endUndoGroup();
2914 void Buffer::changeLanguage(Language const * from, Language const * to)
2916 LASSERT(from, return);
2917 LASSERT(to, return);
2919 for_each(par_iterator_begin(),
2921 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2925 bool Buffer::isMultiLingual() const
2927 ParConstIterator end = par_iterator_end();
2928 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2929 if (it->isMultiLingual(params()))
2936 std::set<Language const *> Buffer::getLanguages() const
2938 std::set<Language const *> languages;
2939 getLanguages(languages);
2944 void Buffer::getLanguages(std::set<Language const *> & languages) const
2946 ParConstIterator end = par_iterator_end();
2947 // add the buffer language, even if it's not actively used
2948 languages.insert(language());
2949 // iterate over the paragraphs
2950 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2951 it->getLanguages(languages);
2953 ListOfBuffers clist = getDescendents();
2954 ListOfBuffers::const_iterator cit = clist.begin();
2955 ListOfBuffers::const_iterator const cen = clist.end();
2956 for (; cit != cen; ++cit)
2957 (*cit)->getLanguages(languages);
2961 DocIterator Buffer::getParFromID(int const id) const
2963 Buffer * buf = const_cast<Buffer *>(this);
2965 // This means non-existent
2966 return doc_iterator_end(buf);
2968 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2969 if (it.paragraph().id() == id)
2972 return doc_iterator_end(buf);
2976 bool Buffer::hasParWithID(int const id) const
2978 return !getParFromID(id).atEnd();
2982 ParIterator Buffer::par_iterator_begin()
2984 return ParIterator(doc_iterator_begin(this));
2988 ParIterator Buffer::par_iterator_end()
2990 return ParIterator(doc_iterator_end(this));
2994 ParConstIterator Buffer::par_iterator_begin() const
2996 return ParConstIterator(doc_iterator_begin(this));
3000 ParConstIterator Buffer::par_iterator_end() const
3002 return ParConstIterator(doc_iterator_end(this));
3006 Language const * Buffer::language() const
3008 return params().language;
3012 docstring const Buffer::B_(string const & l10n) const
3014 return params().B_(l10n);
3018 bool Buffer::isClean() const
3020 return d->lyx_clean;
3024 bool Buffer::isChecksumModified() const
3026 LASSERT(d->filename.exists(), return false);
3027 return d->checksum_ != d->filename.checksum();
3031 void Buffer::saveCheckSum() const
3033 FileName const & file = d->filename;
3035 d->checksum_ = file.exists() ? file.checksum()
3036 : 0; // in the case of save to a new file.
3040 void Buffer::markClean() const
3042 if (!d->lyx_clean) {
3043 d->lyx_clean = true;
3046 // if the .lyx file has been saved, we don't need an
3048 d->bak_clean = true;
3049 d->undo_.markDirty();
3050 clearExternalModification();
3054 void Buffer::setUnnamed(bool flag)
3060 bool Buffer::isUnnamed() const
3067 /// Don't check unnamed, here: isInternal() is used in
3068 /// newBuffer(), where the unnamed flag has not been set by anyone
3069 /// yet. Also, for an internal buffer, there should be no need for
3070 /// retrieving fileName() nor for checking if it is unnamed or not.
3071 bool Buffer::isInternal() const
3073 return d->internal_buffer;
3077 void Buffer::setInternal(bool flag)
3079 d->internal_buffer = flag;
3083 void Buffer::markDirty()
3086 d->lyx_clean = false;
3089 d->bak_clean = false;
3091 DepClean::iterator it = d->dep_clean.begin();
3092 DepClean::const_iterator const end = d->dep_clean.end();
3094 for (; it != end; ++it)
3099 FileName Buffer::fileName() const
3105 string Buffer::absFileName() const
3107 return d->filename.absFileName();
3111 string Buffer::filePath() const
3113 string const abs = d->filename.onlyPath().absFileName();
3116 int last = abs.length() - 1;
3118 return abs[last] == '/' ? abs : abs + '/';
3122 DocFileName Buffer::getReferencedFileName(string const & fn) const
3125 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3126 result.set(fn, filePath());
3128 // filePath() ends with a path separator
3129 FileName const test(filePath() + fn);
3131 result.set(fn, filePath());
3133 result.set(fn, params().origin);
3140 string const Buffer::prepareFileNameForLaTeX(string const & name,
3141 string const & ext, bool nice) const
3143 string const fname = makeAbsPath(name, filePath()).absFileName();
3144 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3150 return to_utf8(makeRelPath(from_utf8(fname),
3151 from_utf8(masterBuffer()->filePath())));
3155 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3156 FileNamePairList const bibfilelist,
3157 bool const add_extension) const
3159 // If we are processing the LaTeX file in a temp directory then
3160 // copy the .bib databases to this temp directory, mangling their
3161 // names in the process. Store this mangled name in the list of
3163 // (We need to do all this because BibTeX *really*, *really*
3164 // can't handle "files with spaces" and Windows users tend to
3165 // use such filenames.)
3166 // Otherwise, store the (maybe absolute) path to the original,
3167 // unmangled database name.
3169 vector<docstring> res;
3171 // determine the export format
3172 string const tex_format = flavor2format(runparams.flavor);
3174 // check for spaces in paths
3175 bool found_space = false;
3177 FileNamePairList::const_iterator it = bibfilelist.begin();
3178 FileNamePairList::const_iterator en = bibfilelist.end();
3179 for (; it != en; ++it) {
3180 string utf8input = to_utf8(it->first);
3182 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3183 FileName const try_in_file =
3184 makeAbsPath(database + ".bib", filePath());
3185 bool const not_from_texmf = try_in_file.isReadableFile();
3187 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3189 // mangledFileName() needs the extension
3190 DocFileName const in_file = DocFileName(try_in_file);
3191 database = removeExtension(in_file.mangledFileName());
3192 FileName const out_file = makeAbsPath(database + ".bib",
3193 masterBuffer()->temppath());
3194 bool const success = in_file.copyTo(out_file);
3196 LYXERR0("Failed to copy '" << in_file
3197 << "' to '" << out_file << "'");
3199 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3200 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3201 if (!isValidLaTeXFileName(database)) {
3202 frontend::Alert::warning(_("Invalid filename"),
3203 _("The following filename will cause troubles "
3204 "when running the exported file through LaTeX: ") +
3205 from_utf8(database));
3207 if (!isValidDVIFileName(database)) {
3208 frontend::Alert::warning(_("Problematic filename for DVI"),
3209 _("The following filename can cause troubles "
3210 "when running the exported file through LaTeX "
3211 "and opening the resulting DVI: ") +
3212 from_utf8(database), true);
3220 docstring const path = from_utf8(latex_path(database));
3222 if (contains(path, ' '))
3225 if (find(res.begin(), res.end(), path) == res.end())
3226 res.push_back(path);
3229 // Check if there are spaces in the path and warn BibTeX users, if so.
3230 // (biber can cope with such paths)
3231 if (!prefixIs(runparams.bibtex_command, "biber")) {
3232 // Post this warning only once.
3233 static bool warned_about_spaces = false;
3234 if (!warned_about_spaces &&
3235 runparams.nice && found_space) {
3236 warned_about_spaces = true;
3237 Alert::warning(_("Export Warning!"),
3238 _("There are spaces in the paths to your BibTeX databases.\n"
3239 "BibTeX will be unable to find them."));
3248 string Buffer::layoutPos() const
3250 return d->layout_position;
3254 void Buffer::setLayoutPos(string const & path)
3257 d->layout_position.clear();
3261 LATTEST(FileName::isAbsolute(path));
3263 d->layout_position =
3264 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3266 if (d->layout_position.empty())
3267 d->layout_position = ".";
3271 bool Buffer::hasReadonlyFlag() const
3273 return d->read_only;
3277 bool Buffer::isReadonly() const
3279 return hasReadonlyFlag() || notifiesExternalModification();
3283 void Buffer::setParent(Buffer const * buffer)
3285 // Avoids recursive include.
3286 d->setParent(buffer == this ? 0 : buffer);
3291 Buffer const * Buffer::parent() const
3297 ListOfBuffers Buffer::allRelatives() const
3299 ListOfBuffers lb = masterBuffer()->getDescendents();
3300 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3305 Buffer const * Buffer::masterBuffer() const
3307 // FIXME Should be make sure we are not in some kind
3308 // of recursive include? A -> B -> A will crash this.
3309 Buffer const * const pbuf = d->parent();
3313 return pbuf->masterBuffer();
3317 bool Buffer::isChild(Buffer * child) const
3319 return d->children_positions.find(child) != d->children_positions.end();
3323 DocIterator Buffer::firstChildPosition(Buffer const * child)
3325 Impl::BufferPositionMap::iterator it;
3326 it = d->children_positions.find(child);
3327 if (it == d->children_positions.end())
3328 return DocIterator(this);
3333 bool Buffer::hasChildren() const
3335 return !d->children_positions.empty();
3339 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3341 // loop over children
3342 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3343 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3344 for (; it != end; ++it) {
3345 Buffer * child = const_cast<Buffer *>(it->first);
3347 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3348 if (bit != clist.end())
3350 clist.push_back(child);
3352 // there might be grandchildren
3353 child->collectChildren(clist, true);
3358 ListOfBuffers Buffer::getChildren() const
3361 collectChildren(v, false);
3362 // Make sure we have not included ourselves.
3363 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3364 if (bit != v.end()) {
3365 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3372 ListOfBuffers Buffer::getDescendents() const
3375 collectChildren(v, true);
3376 // Make sure we have not included ourselves.
3377 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3378 if (bit != v.end()) {
3379 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3386 template<typename M>
3387 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3392 typename M::const_iterator it = m.lower_bound(x);
3393 if (it == m.begin())
3401 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3402 DocIterator const & pos) const
3404 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3406 // if paragraphs have no macro context set, pos will be empty
3410 // we haven't found anything yet
3411 DocIterator bestPos = owner_->par_iterator_begin();
3412 MacroData const * bestData = 0;
3414 // find macro definitions for name
3415 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3416 if (nameIt != macros.end()) {
3417 // find last definition in front of pos or at pos itself
3418 PositionScopeMacroMap::const_iterator it
3419 = greatest_below(nameIt->second, pos);
3420 if (it != nameIt->second.end()) {
3422 // scope ends behind pos?
3423 if (pos < it->second.scope) {
3424 // Looks good, remember this. If there
3425 // is no external macro behind this,
3426 // we found the right one already.
3427 bestPos = it->first;
3428 bestData = &it->second.macro;
3432 // try previous macro if there is one
3433 if (it == nameIt->second.begin())
3440 // find macros in included files
3441 PositionScopeBufferMap::const_iterator it
3442 = greatest_below(position_to_children, pos);
3443 if (it == position_to_children.end())
3444 // no children before
3448 // do we know something better (i.e. later) already?
3449 if (it->first < bestPos )
3452 // scope ends behind pos?
3453 if (pos < it->second.scope
3454 && (cloned_buffer_ ||
3455 theBufferList().isLoaded(it->second.buffer))) {
3456 // look for macro in external file
3458 MacroData const * data
3459 = it->second.buffer->getMacro(name, false);
3462 bestPos = it->first;
3468 // try previous file if there is one
3469 if (it == position_to_children.begin())
3474 // return the best macro we have found
3479 MacroData const * Buffer::getMacro(docstring const & name,
3480 DocIterator const & pos, bool global) const
3485 // query buffer macros
3486 MacroData const * data = d->getBufferMacro(name, pos);
3490 // If there is a master buffer, query that
3491 Buffer const * const pbuf = d->parent();
3493 d->macro_lock = true;
3494 MacroData const * macro = pbuf->getMacro(
3495 name, *this, false);
3496 d->macro_lock = false;
3502 data = MacroTable::globalMacros().get(name);
3511 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3513 // set scope end behind the last paragraph
3514 DocIterator scope = par_iterator_begin();
3515 scope.pit() = scope.lastpit() + 1;
3517 return getMacro(name, scope, global);
3521 MacroData const * Buffer::getMacro(docstring const & name,
3522 Buffer const & child, bool global) const
3524 // look where the child buffer is included first
3525 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3526 if (it == d->children_positions.end())
3529 // check for macros at the inclusion position
3530 return getMacro(name, it->second, global);
3534 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3536 pit_type const lastpit = it.lastpit();
3538 // look for macros in each paragraph
3539 while (it.pit() <= lastpit) {
3540 Paragraph & par = it.paragraph();
3542 // iterate over the insets of the current paragraph
3543 InsetList const & insets = par.insetList();
3544 InsetList::const_iterator iit = insets.begin();
3545 InsetList::const_iterator end = insets.end();
3546 for (; iit != end; ++iit) {
3547 it.pos() = iit->pos;
3549 // is it a nested text inset?
3550 if (iit->inset->asInsetText()) {
3551 // Inset needs its own scope?
3552 InsetText const * itext = iit->inset->asInsetText();
3553 bool newScope = itext->isMacroScope();
3555 // scope which ends just behind the inset
3556 DocIterator insetScope = it;
3559 // collect macros in inset
3560 it.push_back(CursorSlice(*iit->inset));
3561 updateMacros(it, newScope ? insetScope : scope);
3566 if (iit->inset->asInsetTabular()) {
3567 CursorSlice slice(*iit->inset);
3568 size_t const numcells = slice.nargs();
3569 for (; slice.idx() < numcells; slice.forwardIdx()) {
3570 it.push_back(slice);
3571 updateMacros(it, scope);
3577 // is it an external file?
3578 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3579 // get buffer of external file
3580 InsetInclude const & inset =
3581 static_cast<InsetInclude const &>(*iit->inset);
3583 Buffer * child = inset.getChildBuffer();
3588 // register its position, but only when it is
3589 // included first in the buffer
3590 if (children_positions.find(child) ==
3591 children_positions.end())
3592 children_positions[child] = it;
3594 // register child with its scope
3595 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3599 InsetMath * im = iit->inset->asInsetMath();
3600 if (doing_export && im) {
3601 InsetMathHull * hull = im->asHullInset();
3603 hull->recordLocation(it);
3606 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3610 MathMacroTemplate & macroTemplate =
3611 *iit->inset->asInsetMath()->asMacroTemplate();
3612 MacroContext mc(owner_, it);
3613 macroTemplate.updateToContext(mc);
3616 bool valid = macroTemplate.validMacro();
3617 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3618 // then the BufferView's cursor will be invalid in
3619 // some cases which leads to crashes.
3624 // FIXME (Abdel), I don't understand why we pass 'it' here
3625 // instead of 'macroTemplate' defined above... is this correct?
3626 macros[macroTemplate.name()][it] =
3627 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3637 void Buffer::updateMacros() const
3642 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3644 // start with empty table
3646 d->children_positions.clear();
3647 d->position_to_children.clear();
3649 // Iterate over buffer, starting with first paragraph
3650 // The scope must be bigger than any lookup DocIterator
3651 // later. For the global lookup, lastpit+1 is used, hence
3652 // we use lastpit+2 here.
3653 DocIterator it = par_iterator_begin();
3654 DocIterator outerScope = it;
3655 outerScope.pit() = outerScope.lastpit() + 2;
3656 d->updateMacros(it, outerScope);
3660 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3662 InsetIterator it = inset_iterator_begin(inset());
3663 InsetIterator const end = inset_iterator_end(inset());
3664 for (; it != end; ++it) {
3665 if (it->lyxCode() == BRANCH_CODE) {
3666 InsetBranch & br = static_cast<InsetBranch &>(*it);
3667 docstring const name = br.branch();
3668 if (!from_master && !params().branchlist().find(name))
3669 result.push_back(name);
3670 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3671 result.push_back(name);
3674 if (it->lyxCode() == INCLUDE_CODE) {
3675 // get buffer of external file
3676 InsetInclude const & ins =
3677 static_cast<InsetInclude const &>(*it);
3678 Buffer * child = ins.getChildBuffer();
3681 child->getUsedBranches(result, true);
3684 // remove duplicates
3689 void Buffer::updateMacroInstances(UpdateType utype) const
3691 LYXERR(Debug::MACROS, "updateMacroInstances for "
3692 << d->filename.onlyFileName());
3693 DocIterator it = doc_iterator_begin(this);
3695 DocIterator const end = doc_iterator_end(this);
3696 for (; it != end; it.forwardInset()) {
3697 // look for MathData cells in InsetMathNest insets
3698 InsetMath * minset = it.nextInset()->asInsetMath();
3702 // update macro in all cells of the InsetMathNest
3703 DocIterator::idx_type n = minset->nargs();
3704 MacroContext mc = MacroContext(this, it);
3705 for (DocIterator::idx_type i = 0; i < n; ++i) {
3706 MathData & data = minset->cell(i);
3707 data.updateMacros(0, mc, utype, 0);
3713 void Buffer::listMacroNames(MacroNameSet & macros) const
3718 d->macro_lock = true;
3720 // loop over macro names
3721 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3722 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3723 for (; nameIt != nameEnd; ++nameIt)
3724 macros.insert(nameIt->first);
3726 // loop over children
3727 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3728 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3729 for (; it != end; ++it)
3730 it->first->listMacroNames(macros);
3733 Buffer const * const pbuf = d->parent();
3735 pbuf->listMacroNames(macros);
3737 d->macro_lock = false;
3741 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3743 Buffer const * const pbuf = d->parent();
3748 pbuf->listMacroNames(names);
3751 MacroNameSet::iterator it = names.begin();
3752 MacroNameSet::iterator end = names.end();
3753 for (; it != end; ++it) {
3755 MacroData const * data =
3756 pbuf->getMacro(*it, *this, false);
3758 macros.insert(data);
3760 // we cannot access the original MathMacroTemplate anymore
3761 // here to calls validate method. So we do its work here manually.
3762 // FIXME: somehow make the template accessible here.
3763 if (data->optionals() > 0)
3764 features.require("xargs");
3770 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3773 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3775 RefCache::iterator it = d->ref_cache_.find(label);
3776 if (it != d->ref_cache_.end())
3777 return it->second.second;
3779 static InsetLabel const * dummy_il = 0;
3780 static References const dummy_refs = References();
3781 it = d->ref_cache_.insert(
3782 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3783 return it->second.second;
3787 Buffer::References const & Buffer::references(docstring const & label) const
3789 return const_cast<Buffer *>(this)->getReferenceCache(label);
3793 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3795 References & refs = getReferenceCache(label);
3796 refs.push_back(make_pair(inset, it));
3800 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3802 masterBuffer()->d->ref_cache_[label].first = il;
3806 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3808 return masterBuffer()->d->ref_cache_[label].first;
3812 void Buffer::clearReferenceCache() const
3815 d->ref_cache_.clear();
3819 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3821 //FIXME: This does not work for child documents yet.
3822 reloadBibInfoCache();
3824 // Check if the label 'from' appears more than once
3825 BiblioInfo const & keys = masterBibInfo();
3826 BiblioInfo::const_iterator bit = keys.begin();
3827 BiblioInfo::const_iterator bend = keys.end();
3828 vector<docstring> labels;
3830 for (; bit != bend; ++bit)
3832 labels.push_back(bit->first);
3834 if (count(labels.begin(), labels.end(), from) > 1)
3837 string const paramName = "key";
3838 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3839 if (it->lyxCode() != CITE_CODE)
3841 InsetCommand * inset = it->asInsetCommand();
3842 docstring const oldValue = inset->getParam(paramName);
3843 if (oldValue == from)
3844 inset->setParam(paramName, to);
3848 // returns NULL if id-to-row conversion is unsupported
3849 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3850 pit_type par_begin, pit_type par_end,
3851 OutputWhat output, bool master) const
3853 unique_ptr<TexRow> texrow;
3854 OutputParams runparams(¶ms().encoding());
3855 runparams.nice = true;
3856 runparams.flavor = params().getOutputFlavor(format);
3857 runparams.linelen = lyxrc.plaintext_linelen;
3858 // No side effect of file copying and image conversion
3859 runparams.dryrun = true;
3861 if (output == CurrentParagraph) {
3862 runparams.par_begin = par_begin;
3863 runparams.par_end = par_end;
3864 if (par_begin + 1 == par_end) {
3866 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3870 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3871 convert<docstring>(par_begin),
3872 convert<docstring>(par_end - 1))
3875 // output paragraphs
3876 if (runparams.flavor == OutputParams::LYX) {
3877 Paragraph const & par = text().paragraphs()[par_begin];
3879 depth_type dt = par.getDepth();
3880 par.write(ods, params(), dt);
3881 os << from_utf8(ods.str());
3882 } else if (runparams.flavor == OutputParams::HTML) {
3884 setMathFlavor(runparams);
3885 xhtmlParagraphs(text(), *this, xs, runparams);
3886 } else if (runparams.flavor == OutputParams::TEXT) {
3888 // FIXME Handles only one paragraph, unlike the others.
3889 // Probably should have some routine with a signature like them.
3890 writePlaintextParagraph(*this,
3891 text().paragraphs()[par_begin], os, runparams, dummy);
3892 } else if (params().isDocBook()) {
3893 docbookParagraphs(text(), *this, os, runparams);
3895 // If we are previewing a paragraph, even if this is the
3896 // child of some other buffer, let's cut the link here,
3897 // so that no concurring settings from the master
3898 // (e.g. branch state) interfere (see #8101).
3900 d->ignore_parent = true;
3901 // We need to validate the Buffer params' features here
3902 // in order to know if we should output polyglossia
3903 // macros (instead of babel macros)
3904 LaTeXFeatures features(*this, params(), runparams);
3906 runparams.use_polyglossia = features.usePolyglossia();
3907 // latex or literate
3910 ots.texrow().newlines(2);
3912 latexParagraphs(*this, text(), ots, runparams);
3913 texrow = ots.releaseTexRow();
3915 // Restore the parenthood
3917 d->ignore_parent = false;
3921 if (output == FullSource)
3922 os << _("Preview source code");
3923 else if (output == OnlyPreamble)
3924 os << _("Preview preamble");
3925 else if (output == OnlyBody)
3926 os << _("Preview body");
3928 if (runparams.flavor == OutputParams::LYX) {
3930 if (output == FullSource)
3932 else if (output == OnlyPreamble)
3933 params().writeFile(ods, this);
3934 else if (output == OnlyBody)
3936 os << from_utf8(ods.str());
3937 } else if (runparams.flavor == OutputParams::HTML) {
3938 writeLyXHTMLSource(os, runparams, output);
3939 } else if (runparams.flavor == OutputParams::TEXT) {
3940 if (output == OnlyPreamble) {
3941 os << "% "<< _("Plain text does not have a preamble.");
3943 writePlaintextFile(*this, os, runparams);
3944 } else if (params().isDocBook()) {
3945 writeDocBookSource(os, absFileName(), runparams, output);
3947 // latex or literate
3950 ots.texrow().newlines(2);
3952 runparams.is_child = true;
3953 writeLaTeXSource(ots, string(), runparams, output);
3954 texrow = ots.releaseTexRow();
3961 ErrorList & Buffer::errorList(string const & type) const
3963 return d->errorLists[type];
3967 void Buffer::updateTocItem(std::string const & type,
3968 DocIterator const & dit) const
3971 d->gui_->updateTocItem(type, dit);
3975 void Buffer::structureChanged() const
3978 d->gui_->structureChanged();
3982 void Buffer::errors(string const & err, bool from_master) const
3985 d->gui_->errors(err, from_master);
3989 void Buffer::message(docstring const & msg) const
3992 d->gui_->message(msg);
3996 void Buffer::setBusy(bool on) const
3999 d->gui_->setBusy(on);
4003 void Buffer::updateTitles() const
4006 d->wa_->updateTitles();
4010 void Buffer::resetAutosaveTimers() const
4013 d->gui_->resetAutosaveTimers();
4017 bool Buffer::hasGuiDelegate() const
4023 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4032 class AutoSaveBuffer : public ForkedProcess {
4035 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4036 : buffer_(buffer), fname_(fname) {}
4038 virtual shared_ptr<ForkedProcess> clone() const
4040 return make_shared<AutoSaveBuffer>(*this);
4045 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4046 from_utf8(fname_.absFileName())));
4047 return run(DontWait);
4051 virtual int generateChild();
4053 Buffer const & buffer_;
4058 int AutoSaveBuffer::generateChild()
4060 #if defined(__APPLE__)
4061 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4062 * We should use something else like threads.
4064 * Since I do not know how to determine at run time what is the OS X
4065 * version, I just disable forking altogether for now (JMarc)
4067 pid_t const pid = -1;
4069 // tmp_ret will be located (usually) in /tmp
4070 // will that be a problem?
4071 // Note that this calls ForkedCalls::fork(), so it's
4072 // ok cross-platform.
4073 pid_t const pid = fork();
4074 // If you want to debug the autosave
4075 // you should set pid to -1, and comment out the fork.
4076 if (pid != 0 && pid != -1)
4080 // pid = -1 signifies that lyx was unable
4081 // to fork. But we will do the save
4083 bool failed = false;
4084 TempFile tempfile("lyxautoXXXXXX.lyx");
4085 tempfile.setAutoRemove(false);
4086 FileName const tmp_ret = tempfile.name();
4087 if (!tmp_ret.empty()) {
4088 if (!buffer_.writeFile(tmp_ret))
4090 else if (!tmp_ret.moveTo(fname_))
4096 // failed to write/rename tmp_ret so try writing direct
4097 if (!buffer_.writeFile(fname_)) {
4098 // It is dangerous to do this in the child,
4099 // but safe in the parent, so...
4100 if (pid == -1) // emit message signal.
4101 buffer_.message(_("Autosave failed!"));
4105 if (pid == 0) // we are the child so...
4114 FileName Buffer::getEmergencyFileName() const
4116 return FileName(d->filename.absFileName() + ".emergency");
4120 FileName Buffer::getAutosaveFileName() const
4122 // if the document is unnamed try to save in the backup dir, else
4123 // in the default document path, and as a last try in the filePath,
4124 // which will most often be the temporary directory
4127 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4128 : lyxrc.backupdir_path;
4129 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4132 string const fname = "#" + d->filename.onlyFileName() + "#";
4134 return makeAbsPath(fname, fpath);
4138 void Buffer::removeAutosaveFile() const
4140 FileName const f = getAutosaveFileName();
4146 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4148 FileName const newauto = getAutosaveFileName();
4150 if (newauto != oldauto && oldauto.exists())
4151 if (!oldauto.moveTo(newauto))
4152 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4156 bool Buffer::autoSave() const
4158 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4159 if (buf->d->bak_clean || hasReadonlyFlag())
4162 message(_("Autosaving current document..."));
4163 buf->d->bak_clean = true;
4165 FileName const fname = getAutosaveFileName();
4166 LASSERT(d->cloned_buffer_, return false);
4168 // If this buffer is cloned, we assume that
4169 // we are running in a separate thread already.
4170 TempFile tempfile("lyxautoXXXXXX.lyx");
4171 tempfile.setAutoRemove(false);
4172 FileName const tmp_ret = tempfile.name();
4173 if (!tmp_ret.empty()) {
4175 // assume successful write of tmp_ret
4176 if (tmp_ret.moveTo(fname))
4179 // failed to write/rename tmp_ret so try writing direct
4180 return writeFile(fname);
4184 void Buffer::setExportStatus(bool e) const
4186 d->doing_export = e;
4187 ListOfBuffers clist = getDescendents();
4188 ListOfBuffers::const_iterator cit = clist.begin();
4189 ListOfBuffers::const_iterator const cen = clist.end();
4190 for (; cit != cen; ++cit)
4191 (*cit)->d->doing_export = e;
4195 bool Buffer::isExporting() const
4197 return d->doing_export;
4201 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4205 return doExport(target, put_in_tempdir, result_file);
4208 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4209 string & result_file) const
4211 bool const update_unincluded =
4212 params().maintain_unincluded_children
4213 && !params().getIncludedChildren().empty();
4215 // (1) export with all included children (omit \includeonly)
4216 if (update_unincluded) {
4217 ExportStatus const status =
4218 doExport(target, put_in_tempdir, true, result_file);
4219 if (status != ExportSuccess)
4222 // (2) export with included children only
4223 return doExport(target, put_in_tempdir, false, result_file);
4227 void Buffer::setMathFlavor(OutputParams & op) const
4229 switch (params().html_math_output) {
4230 case BufferParams::MathML:
4231 op.math_flavor = OutputParams::MathAsMathML;
4233 case BufferParams::HTML:
4234 op.math_flavor = OutputParams::MathAsHTML;
4236 case BufferParams::Images:
4237 op.math_flavor = OutputParams::MathAsImages;
4239 case BufferParams::LaTeX:
4240 op.math_flavor = OutputParams::MathAsLaTeX;
4246 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4247 bool includeall, string & result_file) const
4249 LYXERR(Debug::FILES, "target=" << target);
4250 OutputParams runparams(¶ms().encoding());
4251 string format = target;
4252 string dest_filename;
4253 size_t pos = target.find(' ');
4254 if (pos != string::npos) {
4255 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4256 format = target.substr(0, pos);
4257 if (format == "default")
4258 format = params().getDefaultOutputFormat();
4259 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4260 FileName(dest_filename).onlyPath().createPath();
4261 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4263 MarkAsExporting exporting(this);
4264 string backend_format;
4265 runparams.flavor = OutputParams::LATEX;
4266 runparams.linelen = lyxrc.plaintext_linelen;
4267 runparams.includeall = includeall;
4268 vector<string> backs = params().backends();
4269 Converters converters = theConverters();
4270 bool need_nice_file = false;
4271 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4272 // Get shortest path to format
4273 converters.buildGraph();
4274 Graph::EdgePath path;
4275 for (vector<string>::const_iterator it = backs.begin();
4276 it != backs.end(); ++it) {
4277 Graph::EdgePath p = converters.getPath(*it, format);
4278 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4279 backend_format = *it;
4284 if (!put_in_tempdir) {
4285 // Only show this alert if this is an export to a non-temporary
4286 // file (not for previewing).
4287 Alert::error(_("Couldn't export file"), bformat(
4288 _("No information for exporting the format %1$s."),
4289 theFormats().prettyName(format)));
4291 return ExportNoPathToFormat;
4293 runparams.flavor = converters.getFlavor(path, this);
4294 Graph::EdgePath::const_iterator it = path.begin();
4295 Graph::EdgePath::const_iterator en = path.end();
4296 for (; it != en; ++it)
4297 if (theConverters().get(*it).nice()) {
4298 need_nice_file = true;
4303 backend_format = format;
4304 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4305 // FIXME: Don't hardcode format names here, but use a flag
4306 if (backend_format == "pdflatex")
4307 runparams.flavor = OutputParams::PDFLATEX;
4308 else if (backend_format == "luatex")
4309 runparams.flavor = OutputParams::LUATEX;
4310 else if (backend_format == "dviluatex")
4311 runparams.flavor = OutputParams::DVILUATEX;
4312 else if (backend_format == "xetex")
4313 runparams.flavor = OutputParams::XETEX;
4316 string filename = latexName(false);
4317 filename = addName(temppath(), filename);
4318 filename = changeExtension(filename,
4319 theFormats().extension(backend_format));
4320 LYXERR(Debug::FILES, "filename=" << filename);
4322 // Plain text backend
4323 if (backend_format == "text") {
4324 runparams.flavor = OutputParams::TEXT;
4325 writePlaintextFile(*this, FileName(filename), runparams);
4328 else if (backend_format == "xhtml") {
4329 runparams.flavor = OutputParams::HTML;
4330 setMathFlavor(runparams);
4331 makeLyXHTMLFile(FileName(filename), runparams);
4332 } else if (backend_format == "lyx")
4333 writeFile(FileName(filename));
4335 else if (params().isDocBook()) {
4336 runparams.nice = !put_in_tempdir;
4337 makeDocBookFile(FileName(filename), runparams);
4340 else if (backend_format == format || need_nice_file) {
4341 runparams.nice = true;
4342 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4343 if (d->cloned_buffer_)
4344 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4347 } else if (!lyxrc.tex_allows_spaces
4348 && contains(filePath(), ' ')) {
4349 Alert::error(_("File name error"),
4350 _("The directory path to the document cannot contain spaces."));
4351 return ExportTexPathHasSpaces;
4353 runparams.nice = false;
4354 bool const success = makeLaTeXFile(
4355 FileName(filename), filePath(), runparams);
4356 if (d->cloned_buffer_)
4357 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4362 string const error_type = (format == "program")
4363 ? "Build" : params().bufferFormat();
4364 ErrorList & error_list = d->errorLists[error_type];
4365 string const ext = theFormats().extension(format);
4366 FileName const tmp_result_file(changeExtension(filename, ext));
4367 bool const success = converters.convert(this, FileName(filename),
4368 tmp_result_file, FileName(absFileName()), backend_format, format,
4371 // Emit the signal to show the error list or copy it back to the
4372 // cloned Buffer so that it can be emitted afterwards.
4373 if (format != backend_format) {
4374 if (runparams.silent)
4376 else if (d->cloned_buffer_)
4377 d->cloned_buffer_->d->errorLists[error_type] =
4378 d->errorLists[error_type];
4381 // also to the children, in case of master-buffer-view
4382 ListOfBuffers clist = getDescendents();
4383 ListOfBuffers::const_iterator cit = clist.begin();
4384 ListOfBuffers::const_iterator const cen = clist.end();
4385 for (; cit != cen; ++cit) {
4386 if (runparams.silent)
4387 (*cit)->d->errorLists[error_type].clear();
4388 else if (d->cloned_buffer_) {
4389 // Enable reverse search by copying back the
4390 // texrow object to the cloned buffer.
4391 // FIXME: this is not thread safe.
4392 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4393 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4394 (*cit)->d->errorLists[error_type];
4396 (*cit)->errors(error_type, true);
4400 if (d->cloned_buffer_) {
4401 // Enable reverse dvi or pdf to work by copying back the texrow
4402 // object to the cloned buffer.
4403 // FIXME: There is a possibility of concurrent access to texrow
4404 // here from the main GUI thread that should be securized.
4405 d->cloned_buffer_->d->texrow = d->texrow;
4406 string const error_type = params().bufferFormat();
4407 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4411 if (put_in_tempdir) {
4412 result_file = tmp_result_file.absFileName();
4413 return success ? ExportSuccess : ExportConverterError;
4416 if (dest_filename.empty())
4417 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4419 result_file = dest_filename;
4420 // We need to copy referenced files (e. g. included graphics
4421 // if format == "dvi") to the result dir.
4422 vector<ExportedFile> const files =
4423 runparams.exportdata->externalFiles(format);
4424 string const dest = runparams.export_folder.empty() ?
4425 onlyPath(result_file) : runparams.export_folder;
4426 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4427 : force_overwrite == ALL_FILES;
4428 CopyStatus status = use_force ? FORCE : SUCCESS;
4430 vector<ExportedFile>::const_iterator it = files.begin();
4431 vector<ExportedFile>::const_iterator const en = files.end();
4432 for (; it != en && status != CANCEL; ++it) {
4433 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4434 string fixedName = it->exportName;
4435 if (!runparams.export_folder.empty()) {
4436 // Relative pathnames starting with ../ will be sanitized
4437 // if exporting to a different folder
4438 while (fixedName.substr(0, 3) == "../")
4439 fixedName = fixedName.substr(3, fixedName.length() - 3);
4441 FileName fixedFileName = makeAbsPath(fixedName, dest);
4442 fixedFileName.onlyPath().createPath();
4443 status = copyFile(fmt, it->sourceName,
4445 it->exportName, status == FORCE,
4446 runparams.export_folder.empty());
4449 if (status == CANCEL) {
4450 message(_("Document export cancelled."));
4451 return ExportCancel;
4454 if (tmp_result_file.exists()) {
4455 // Finally copy the main file
4456 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4457 : force_overwrite != NO_FILES;
4458 if (status == SUCCESS && use_force)
4460 status = copyFile(format, tmp_result_file,
4461 FileName(result_file), result_file,
4463 if (status == CANCEL) {
4464 message(_("Document export cancelled."));
4465 return ExportCancel;
4467 message(bformat(_("Document exported as %1$s "
4469 theFormats().prettyName(format),
4470 makeDisplayPath(result_file)));
4473 // This must be a dummy converter like fax (bug 1888)
4474 message(bformat(_("Document exported as %1$s"),
4475 theFormats().prettyName(format)));
4478 return success ? ExportSuccess : ExportConverterError;
4482 Buffer::ExportStatus Buffer::preview(string const & format) const
4484 bool const update_unincluded =
4485 params().maintain_unincluded_children
4486 && !params().getIncludedChildren().empty();
4487 return preview(format, update_unincluded);
4491 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4493 MarkAsExporting exporting(this);
4495 // (1) export with all included children (omit \includeonly)
4497 ExportStatus const status = doExport(format, true, true, result_file);
4498 if (status != ExportSuccess)
4501 // (2) export with included children only
4502 ExportStatus const status = doExport(format, true, false, result_file);
4503 FileName const previewFile(result_file);
4505 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4506 theimpl->preview_file_ = previewFile;
4507 theimpl->preview_format_ = format;
4508 theimpl->preview_error_ = (status != ExportSuccess);
4510 if (status != ExportSuccess)
4513 if (previewFile.exists())
4514 return theFormats().view(*this, previewFile, format) ?
4515 PreviewSuccess : PreviewError;
4517 // Successful export but no output file?
4518 // Probably a bug in error detection.
4519 LATTEST(status != ExportSuccess);
4524 Buffer::ReadStatus Buffer::extractFromVC()
4526 bool const found = LyXVC::file_not_found_hook(d->filename);
4528 return ReadFileNotFound;
4529 if (!d->filename.isReadableFile())
4535 Buffer::ReadStatus Buffer::loadEmergency()
4537 FileName const emergencyFile = getEmergencyFileName();
4538 if (!emergencyFile.exists()
4539 || emergencyFile.lastModified() <= d->filename.lastModified())
4540 return ReadFileNotFound;
4542 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4543 docstring const text = bformat(_("An emergency save of the document "
4544 "%1$s exists.\n\nRecover emergency save?"), file);
4546 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4547 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4553 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4554 bool const success = (ret_llf == ReadSuccess);
4556 if (hasReadonlyFlag()) {
4557 Alert::warning(_("File is read-only"),
4558 bformat(_("An emergency file is successfully loaded, "
4559 "but the original file %1$s is marked read-only. "
4560 "Please make sure to save the document as a different "
4561 "file."), from_utf8(d->filename.absFileName())));
4564 lyxvc().file_found_hook(d->filename);
4565 str = _("Document was successfully recovered.");
4567 str = _("Document was NOT successfully recovered.");
4568 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4569 makeDisplayPath(emergencyFile.absFileName()));
4571 int const del_emerg =
4572 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4573 _("&Remove"), _("&Keep"));
4574 if (del_emerg == 0) {
4575 emergencyFile.removeFile();
4577 Alert::warning(_("Emergency file deleted"),
4578 _("Do not forget to save your file now!"), true);
4580 return success ? ReadSuccess : ReadEmergencyFailure;
4583 int const del_emerg =
4584 Alert::prompt(_("Delete emergency file?"),
4585 _("Remove emergency file now?"), 1, 1,
4586 _("&Remove"), _("&Keep"));
4588 emergencyFile.removeFile();
4589 return ReadOriginal;
4599 Buffer::ReadStatus Buffer::loadAutosave()
4601 // Now check if autosave file is newer.
4602 FileName const autosaveFile = getAutosaveFileName();
4603 if (!autosaveFile.exists()
4604 || autosaveFile.lastModified() <= d->filename.lastModified())
4605 return ReadFileNotFound;
4607 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4608 docstring const text = bformat(_("The backup of the document %1$s "
4609 "is newer.\n\nLoad the backup instead?"), file);
4610 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4611 _("&Load backup"), _("Load &original"), _("&Cancel"));
4616 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4617 // the file is not saved if we load the autosave file.
4618 if (ret_llf == ReadSuccess) {
4619 if (hasReadonlyFlag()) {
4620 Alert::warning(_("File is read-only"),
4621 bformat(_("A backup file is successfully loaded, "
4622 "but the original file %1$s is marked read-only. "
4623 "Please make sure to save the document as a "
4625 from_utf8(d->filename.absFileName())));
4628 lyxvc().file_found_hook(d->filename);
4631 return ReadAutosaveFailure;
4634 // Here we delete the autosave
4635 autosaveFile.removeFile();
4636 return ReadOriginal;
4644 Buffer::ReadStatus Buffer::loadLyXFile()
4646 if (!d->filename.isReadableFile()) {
4647 ReadStatus const ret_rvc = extractFromVC();
4648 if (ret_rvc != ReadSuccess)
4652 ReadStatus const ret_re = loadEmergency();
4653 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4656 ReadStatus const ret_ra = loadAutosave();
4657 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4660 return loadThisLyXFile(d->filename);
4664 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4666 return readFile(fn);
4670 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4672 for (auto const & err : terr) {
4673 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4674 int errorRow = err.error_in_line;
4675 Buffer const * buf = 0;
4677 if (err.child_name.empty())
4678 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4680 // The error occurred in a child
4681 for (Buffer const * child : getDescendents()) {
4682 string const child_name =
4683 DocFileName(changeExtension(child->absFileName(), "tex")).
4685 if (err.child_name != child_name)
4687 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4688 if (!TexRow::isNone(start)) {
4689 buf = d->cloned_buffer_
4690 ? child->d->cloned_buffer_->d->owner_
4697 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4703 void Buffer::setBuffersForInsets() const
4705 inset().setBuffer(const_cast<Buffer &>(*this));
4709 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4711 LBUFERR(!text().paragraphs().empty());
4713 // Use the master text class also for child documents
4714 Buffer const * const master = masterBuffer();
4715 DocumentClass const & textclass = master->params().documentClass();
4717 // do this only if we are the top-level Buffer
4718 if (master == this) {
4719 textclass.counters().reset(from_ascii("bibitem"));
4720 reloadBibInfoCache();
4723 // keep the buffers to be children in this set. If the call from the
4724 // master comes back we can see which of them were actually seen (i.e.
4725 // via an InsetInclude). The remaining ones in the set need still be updated.
4726 static std::set<Buffer const *> bufToUpdate;
4727 if (scope == UpdateMaster) {
4728 // If this is a child document start with the master
4729 if (master != this) {
4730 bufToUpdate.insert(this);
4731 master->updateBuffer(UpdateMaster, utype);
4732 // If the master buffer has no gui associated with it, then the TocModel is
4733 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4734 // (bug 5699). The same happens if the master buffer is open in a different
4735 // window. This test catches both possibilities.
4736 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4737 // There remains a problem here: If there is another child open in yet a third
4738 // window, that TOC is not updated. So some more general solution is needed at
4740 if (master->d->gui_ != d->gui_)
4743 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4744 if (bufToUpdate.find(this) == bufToUpdate.end())
4748 // start over the counters in the master
4749 textclass.counters().reset();
4752 // update will be done below for this buffer
4753 bufToUpdate.erase(this);
4755 // update all caches
4756 clearReferenceCache();
4758 setChangesPresent(false);
4760 Buffer & cbuf = const_cast<Buffer &>(*this);
4763 ParIterator parit = cbuf.par_iterator_begin();
4764 updateBuffer(parit, utype);
4767 /// Update the tocBackend for any buffer. The outliner uses the master's,
4768 /// and the navigation menu uses the child's.
4769 cbuf.tocBackend().update(true, utype);
4774 d->bibinfo_cache_valid_ = true;
4775 d->cite_labels_valid_ = true;
4776 if (scope == UpdateMaster)
4777 cbuf.structureChanged();
4781 static depth_type getDepth(DocIterator const & it)
4783 depth_type depth = 0;
4784 for (size_t i = 0 ; i < it.depth() ; ++i)
4785 if (!it[i].inset().inMathed())
4786 depth += it[i].paragraph().getDepth() + 1;
4787 // remove 1 since the outer inset does not count
4788 // we should have at least one non-math inset, so
4789 // depth should nevery be 0. but maybe it is worth
4790 // marking this, just in case.
4792 // coverity[INTEGER_OVERFLOW]
4796 static depth_type getItemDepth(ParIterator const & it)
4798 Paragraph const & par = *it;
4799 LabelType const labeltype = par.layout().labeltype;
4801 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4804 // this will hold the lowest depth encountered up to now.
4805 depth_type min_depth = getDepth(it);
4806 ParIterator prev_it = it;
4809 --prev_it.top().pit();
4811 // start of nested inset: go to outer par
4813 if (prev_it.empty()) {
4814 // start of document: nothing to do
4819 // We search for the first paragraph with same label
4820 // that is not more deeply nested.
4821 Paragraph & prev_par = *prev_it;
4822 depth_type const prev_depth = getDepth(prev_it);
4823 if (labeltype == prev_par.layout().labeltype) {
4824 if (prev_depth < min_depth)
4825 return prev_par.itemdepth + 1;
4826 if (prev_depth == min_depth)
4827 return prev_par.itemdepth;
4829 min_depth = min(min_depth, prev_depth);
4830 // small optimization: if we are at depth 0, we won't
4831 // find anything else
4832 if (prev_depth == 0)
4838 static bool needEnumCounterReset(ParIterator const & it)
4840 Paragraph const & par = *it;
4841 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4842 depth_type const cur_depth = par.getDepth();
4843 ParIterator prev_it = it;
4844 while (prev_it.pit()) {
4845 --prev_it.top().pit();
4846 Paragraph const & prev_par = *prev_it;
4847 if (prev_par.getDepth() <= cur_depth)
4848 return prev_par.layout().name() != par.layout().name();
4850 // start of nested inset: reset
4855 // set the label of a paragraph. This includes the counters.
4856 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4858 BufferParams const & bp = owner_->masterBuffer()->params();
4859 DocumentClass const & textclass = bp.documentClass();
4860 Paragraph & par = it.paragraph();
4861 Layout const & layout = par.layout();
4862 Counters & counters = textclass.counters();
4864 if (par.params().startOfAppendix()) {
4865 // We want to reset the counter corresponding to toplevel sectioning
4866 Layout const & lay = textclass.getTOCLayout();
4867 docstring const cnt = lay.counter;
4869 counters.reset(cnt);
4870 counters.appendix(true);
4872 par.params().appendix(counters.appendix());
4874 // Compute the item depth of the paragraph
4875 par.itemdepth = getItemDepth(it);
4877 if (layout.margintype == MARGIN_MANUAL) {
4878 if (par.params().labelWidthString().empty())
4879 par.params().labelWidthString(par.expandLabel(layout, bp));
4880 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4881 // we do not need to do anything here, since the empty case is
4882 // handled during export.
4884 par.params().labelWidthString(docstring());
4887 switch(layout.labeltype) {
4888 case LABEL_ITEMIZE: {
4889 // At some point of time we should do something more
4890 // clever here, like:
4891 // par.params().labelString(
4892 // bp.user_defined_bullet(par.itemdepth).getText());
4893 // for now, use a simple hardcoded label
4894 docstring itemlabel;
4895 switch (par.itemdepth) {
4897 itemlabel = char_type(0x2022);
4900 itemlabel = char_type(0x2013);
4903 itemlabel = char_type(0x2217);
4906 itemlabel = char_type(0x2219); // or 0x00b7
4909 par.params().labelString(itemlabel);
4913 case LABEL_ENUMERATE: {
4914 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4916 switch (par.itemdepth) {
4925 enumcounter += "iv";
4928 // not a valid enumdepth...
4932 // Increase the master counter?
4933 if (layout.stepmastercounter && needEnumCounterReset(it))
4934 counters.stepMaster(enumcounter, utype);
4936 // Maybe we have to reset the enumeration counter.
4937 if (!layout.resumecounter && needEnumCounterReset(it))
4938 counters.reset(enumcounter);
4939 counters.step(enumcounter, utype);
4941 string const & lang = par.getParLanguage(bp)->code();
4942 par.params().labelString(counters.theCounter(enumcounter, lang));
4947 case LABEL_SENSITIVE: {
4948 string const & type = counters.current_float();
4949 docstring full_label;
4951 full_label = owner_->B_("Senseless!!! ");
4953 docstring name = owner_->B_(textclass.floats().getType(type).name());
4954 if (counters.hasCounter(from_utf8(type))) {
4955 string const & lang = par.getParLanguage(bp)->code();
4956 counters.step(from_utf8(type), utype);
4957 full_label = bformat(from_ascii("%1$s %2$s:"),
4959 counters.theCounter(from_utf8(type), lang));
4961 full_label = bformat(from_ascii("%1$s #:"), name);
4963 par.params().labelString(full_label);
4967 case LABEL_NO_LABEL:
4968 par.params().labelString(docstring());
4972 case LABEL_CENTERED:
4973 case LABEL_STATIC: {
4974 docstring const & lcounter = layout.counter;
4975 if (!lcounter.empty()) {
4976 if (layout.toclevel <= bp.secnumdepth
4977 && (layout.latextype != LATEX_ENVIRONMENT
4978 || it.text()->isFirstInSequence(it.pit()))) {
4979 if (counters.hasCounter(lcounter))
4980 counters.step(lcounter, utype);
4981 par.params().labelString(par.expandLabel(layout, bp));
4983 par.params().labelString(docstring());
4985 par.params().labelString(par.expandLabel(layout, bp));
4991 par.params().labelString(par.expandLabel(layout, bp));
4996 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4998 // LASSERT: Is it safe to continue here, or should we just return?
4999 LASSERT(parit.pit() == 0, /**/);
5001 // Set the position of the text in the buffer to be able
5002 // to resolve macros in it.
5003 parit.text()->setMacrocontextPosition(parit);
5005 depth_type maxdepth = 0;
5006 pit_type const lastpit = parit.lastpit();
5007 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5008 // reduce depth if necessary
5009 if (parit->params().depth() > maxdepth) {
5010 /** FIXME: this function is const, but
5011 * nevertheless it modifies the buffer. To be
5012 * cleaner, one should modify the buffer in
5013 * another function, which is actually
5014 * non-const. This would however be costly in
5015 * terms of code duplication.
5017 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5018 parit->params().depth(maxdepth);
5020 maxdepth = parit->getMaxDepthAfter();
5022 if (utype == OutputUpdate) {
5023 // track the active counters
5024 // we have to do this for the master buffer, since the local
5025 // buffer isn't tracking anything.
5026 masterBuffer()->params().documentClass().counters().
5027 setActiveLayout(parit->layout());
5030 // set the counter for this paragraph
5031 d->setLabel(parit, utype);
5033 // update change-tracking flag
5034 parit->addChangesToBuffer(*this);
5037 InsetList::const_iterator iit = parit->insetList().begin();
5038 InsetList::const_iterator end = parit->insetList().end();
5039 for (; iit != end; ++iit) {
5040 parit.pos() = iit->pos;
5041 iit->inset->updateBuffer(parit, utype);
5047 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5048 WordLangTuple & word_lang, docstring_list & suggestions) const
5052 suggestions.clear();
5053 word_lang = WordLangTuple();
5054 bool const to_end = to.empty();
5055 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5056 // OK, we start from here.
5057 for (; from != end; from.forwardPos()) {
5058 // This skips all insets with spell check disabled.
5059 while (!from.allowSpellCheck()) {
5063 // If from is at the end of the document (which is possible
5064 // when "from" was changed above) LyX will crash later otherwise.
5065 if (from.atEnd() || (!to_end && from >= end))
5068 from.paragraph().spellCheck();
5069 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5070 if (SpellChecker::misspelled(res)) {
5074 // Do not increase progress when from == to, otherwise the word
5075 // count will be wrong.
5085 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5087 bool inword = false;
5092 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5093 if (!dit.inTexted()) {
5098 Paragraph const & par = dit.paragraph();
5099 pos_type const pos = dit.pos();
5101 // Copied and adapted from isWordSeparator() in Paragraph
5102 if (pos == dit.lastpos()) {
5105 Inset const * ins = par.getInset(pos);
5106 if (ins && skipNoOutput && !ins->producesOutput()) {
5109 // stop if end of range was skipped
5110 if (!to.atEnd() && dit >= to)
5113 } else if (!par.isDeleted(pos)) {
5114 if (par.isWordSeparator(pos))
5120 if (ins && ins->isLetter())
5122 else if (ins && ins->isSpace())
5125 char_type const c = par.getChar(pos);
5126 if (isPrintableNonspace(c))
5128 else if (isSpace(c))
5138 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5140 d->updateStatistics(from, to, skipNoOutput);
5144 int Buffer::wordCount() const
5146 return d->wordCount();
5150 int Buffer::charCount(bool with_blanks) const
5152 return d->charCount(with_blanks);
5156 Buffer::ReadStatus Buffer::reload()
5159 // c.f. bug http://www.lyx.org/trac/ticket/6587
5160 removeAutosaveFile();
5161 // e.g., read-only status could have changed due to version control
5162 d->filename.refresh();
5163 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5165 // clear parent. this will get reset if need be.
5167 ReadStatus const status = loadLyXFile();
5168 if (status == ReadSuccess) {
5173 message(bformat(_("Document %1$s reloaded."), disp_fn));
5176 message(bformat(_("Could not reload document %1$s."), disp_fn));
5186 bool Buffer::saveAs(FileName const & fn)
5188 FileName const old_name = fileName();
5189 FileName const old_auto = getAutosaveFileName();
5190 bool const old_unnamed = isUnnamed();
5191 bool success = true;
5192 d->old_position = filePath();
5199 // bring the autosave file with us, just in case.
5200 moveAutosaveFile(old_auto);
5201 // validate version control data and
5202 // correct buffer title
5203 lyxvc().file_found_hook(fileName());
5205 // the file has now been saved to the new location.
5206 // we need to check that the locations of child buffers
5208 checkChildBuffers();
5209 checkMasterBuffer();
5212 // reset the old filename and unnamed state
5213 setFileName(old_name);
5214 setUnnamed(old_unnamed);
5218 d->old_position.clear();
5223 void Buffer::checkChildBuffers()
5225 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5226 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5227 for (; it != en; ++it) {
5228 DocIterator dit = it->second;
5229 Buffer * cbuf = const_cast<Buffer *>(it->first);
5230 if (!cbuf || !theBufferList().isLoaded(cbuf))
5232 Inset * inset = dit.nextInset();
5233 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5234 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5235 docstring const & incfile = inset_inc->getParam("filename");
5236 string oldloc = cbuf->absFileName();
5237 string newloc = makeAbsPath(to_utf8(incfile),
5238 onlyPath(absFileName())).absFileName();
5239 if (oldloc == newloc)
5241 // the location of the child file is incorrect.
5243 inset_inc->setChildBuffer(0);
5245 // invalidate cache of children
5246 d->children_positions.clear();
5247 d->position_to_children.clear();
5251 // If a child has been saved under a different name/path, it might have been
5252 // orphaned. Therefore the master needs to be reset (bug 8161).
5253 void Buffer::checkMasterBuffer()
5255 Buffer const * const master = masterBuffer();
5259 // necessary to re-register the child (bug 5873)
5260 // FIXME: clean up updateMacros (here, only
5261 // child registering is needed).
5262 master->updateMacros();
5263 // (re)set master as master buffer, but only
5264 // if we are a real child
5265 if (master->isChild(this))
5272 string Buffer::includedFilePath(string const & name, string const & ext) const
5274 if (d->old_position.empty() ||
5275 equivalent(FileName(d->old_position), FileName(filePath())))
5278 bool isabsolute = FileName::isAbsolute(name);
5279 // both old_position and filePath() end with a path separator
5280 string absname = isabsolute ? name : d->old_position + name;
5282 // if old_position is set to origin, we need to do the equivalent of
5283 // getReferencedFileName() (see readDocument())
5284 if (!isabsolute && d->old_position == params().origin) {
5285 FileName const test(addExtension(filePath() + name, ext));
5287 absname = filePath() + name;
5290 if (!FileName(addExtension(absname, ext)).exists())
5294 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5296 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5297 from_utf8(filePath())));
5301 void Buffer::setChangesPresent(bool b) const
5303 d->tracked_changes_present_ = b;
5307 bool Buffer::areChangesPresent() const
5309 return d->tracked_changes_present_;
5313 void Buffer::updateChangesPresent() const
5315 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5316 setChangesPresent(false);
5317 ParConstIterator it = par_iterator_begin();
5318 ParConstIterator const end = par_iterator_end();
5319 for (; !areChangesPresent() && it != end; ++it)
5320 it->addChangesToBuffer(*this);
5324 void Buffer::Impl::refreshFileMonitor()
5326 if (file_monitor_ && file_monitor_->filename() == filename.absFileName())
5327 return file_monitor_->refresh();
5329 // The previous file monitor is invalid
5330 // This also destroys the previous file monitor and all its connections
5331 file_monitor_ = FileSystemWatcher::monitor(filename);
5332 fileExternallyModified(false);
5333 // file_monitor_ will be destroyed with *this, so it is not going to call a
5334 // destroyed object method.
5335 file_monitor_->connect([this](){ fileExternallyModified(true); });
5339 void Buffer::Impl::fileExternallyModified(bool modified) const
5342 lyx_clean = bak_clean = false;
5343 externally_modified_ = modified;
5345 wa_->updateTitles();
5349 bool Buffer::notifiesExternalModification() const
5351 return d->isExternallyModified();
5355 void Buffer::clearExternalModification() const
5357 d->fileExternallyModified(false);