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"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/mutex.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
121 using namespace lyx::support;
122 using namespace lyx::graphics;
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
139 // A storehouse for the cloned buffers.
140 list<CloneList *> cloned_buffers;
146 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
150 delete preview_loader_;
158 /// search for macro in local (buffer) table or in children
159 MacroData const * getBufferMacro(docstring const & name,
160 DocIterator const & pos) const;
162 /// Update macro table starting with position of it \param it in some
164 void updateMacros(DocIterator & it, DocIterator & scope);
166 void setLabel(ParIterator & it, UpdateType utype) const;
168 /** If we have branches that use the file suffix
169 feature, return the file name with suffix appended.
171 support::FileName exportFileName() const;
178 mutable TexRow texrow;
180 /// need to regenerate .tex?
184 mutable bool lyx_clean;
186 /// is autosave needed?
187 mutable bool bak_clean;
189 /// is this an unnamed file (New...)?
192 /// is this an internal bufffer?
193 bool internal_buffer;
198 /// name of the file the buffer is associated with.
201 /** Set to true only when the file is fully loaded.
202 * Used to prevent the premature generation of previews
203 * and by the citation inset.
205 bool file_fully_loaded;
207 /// original format of loaded file
210 /// if the file was originally loaded from an older format, do
211 /// we need to back it up still?
212 bool need_format_backup;
214 /// Ignore the parent (e.g. when exporting a child standalone)?
218 mutable TocBackend toc_backend;
223 ScopeMacro(DocIterator const & s, MacroData const & m)
224 : scope(s), macro(m) {}
228 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
229 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
230 /// map from the macro name to the position map,
231 /// which maps the macro definition position to the scope and the MacroData.
232 NamePositionScopeMacroMap macros;
233 /// This seem to change the way Buffer::getMacro() works
234 mutable bool macro_lock;
236 /// positions of child buffers in the buffer
237 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
240 ScopeBuffer(DocIterator const & s,Buffer const * b)
241 : scope(s), buffer(b) {}
243 Buffer const * buffer;
245 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
246 /// position of children buffers in this buffer
247 BufferPositionMap children_positions;
248 /// map from children inclusion positions to their scope and their buffer
249 PositionScopeBufferMap position_to_children;
251 /// Contains the old buffer filePath() while saving-as, or the
252 /// directory where the document was last saved while loading.
255 /** Keeps track of the path of local layout files.
256 * If possible, it is always relative to the buffer path.
257 * Empty for layouts in system or user directory.
259 string layout_position;
261 /// Container for all sort of Buffer dependant errors.
262 map<string, ErrorList> errorLists;
264 /// timestamp and checksum used to test if the file has been externally
265 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
267 unsigned long checksum_;
270 frontend::WorkAreaManager * wa_;
272 frontend::GuiBufferDelegate * gui_;
277 /// A cache for the bibfiles (including bibfiles of loaded child
278 /// documents), needed for appropriate update of natbib labels.
279 mutable support::FileNameList bibfiles_cache_;
281 // FIXME The caching mechanism could be improved. At present, we have a
282 // cache for each Buffer, that caches all the bibliography info for that
283 // Buffer. A more efficient solution would be to have a global cache per
284 // file, and then to construct the Buffer's bibinfo from that.
285 /// A cache for bibliography info
286 mutable BiblioInfo bibinfo_;
287 /// whether the bibinfo cache is valid
288 mutable bool bibinfo_cache_valid_;
289 /// whether the bibfile cache is valid
290 mutable bool bibfile_cache_valid_;
291 /// Cache of timestamps of .bib files
292 map<FileName, time_t> bibfile_status_;
293 /// Indicates whether the bibinfo has changed since the last time
294 /// we ran updateBuffer(), i.e., whether citation labels may need
296 mutable bool cite_labels_valid_;
298 /// These two hold the file name and format, written to by
299 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
300 FileName preview_file_;
301 string preview_format_;
302 /// If there was an error when previewing, on the next preview we do
303 /// a fresh compile (e.g. in case the user installed a package that
307 mutable RefCache ref_cache_;
309 /// our Text that should be wrapped in an InsetText
313 PreviewLoader * preview_loader_;
315 /// This is here to force the test to be done whenever parent_buffer
317 Buffer const * parent() const
319 // ignore_parent temporarily "orphans" a buffer
320 // (e.g. if a child is compiled standalone)
323 // if parent_buffer is not loaded, then it has been unloaded,
324 // which means that parent_buffer is an invalid pointer. So we
325 // set it to null in that case.
326 // however, the BufferList doesn't know about cloned buffers, so
327 // they will always be regarded as unloaded. in that case, we hope
329 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
331 return parent_buffer;
335 void setParent(Buffer const * pb)
337 if (parent_buffer == pb)
340 if (!cloned_buffer_ && parent_buffer && pb)
341 LYXERR0("Warning: a buffer should not have two parents!");
343 if (!cloned_buffer_ && parent_buffer) {
344 parent_buffer->invalidateBibfileCache();
345 parent_buffer->invalidateBibinfoCache();
349 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
350 /// This one is useful for preview detached in a thread.
351 Buffer const * cloned_buffer_;
353 CloneList * clone_list_;
354 /// are we in the process of exporting this buffer?
355 mutable bool doing_export;
357 /// compute statistics
358 /// \p from initial position
359 /// \p to points to the end position
360 void updateStatistics(DocIterator & from, DocIterator & to,
361 bool skipNoOutput = true);
362 /// statistics accessor functions
363 int wordCount() const
367 int charCount(bool with_blanks) const
370 + (with_blanks ? blank_count_ : 0);
374 /// So we can force access via the accessors.
375 mutable Buffer const * parent_buffer;
384 /// Creates the per buffer temporary directory
385 static FileName createBufferTmpDir()
387 // FIXME This would be the ideal application for a TempDir class (like
388 // TempFile but for directories)
393 Mutex::Locker locker(&mutex);
394 counter = convert<string>(count++);
396 // We are in our own directory. Why bother to mangle name?
397 // In fact I wrote this code to circumvent a problematic behaviour
398 // (bug?) of EMX mkstemp().
399 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
402 if (!tmpfl.createDirectory(0777)) {
403 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
404 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
405 from_utf8(tmpfl.absFileName())));
411 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
412 Buffer const * cloned_buffer)
413 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
414 internal_buffer(false), read_only(readonly_), filename(file),
415 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
416 ignore_parent(false), toc_backend(owner), macro_lock(false), timestamp_(0),
417 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
418 bibfile_cache_valid_(false), cite_labels_valid_(false), inset(0),
419 preview_loader_(0), cloned_buffer_(cloned_buffer), clone_list_(0),
420 doing_export(false), parent_buffer(0),
421 word_count_(0), char_count_(0), blank_count_(0)
423 if (!cloned_buffer_) {
424 temppath = createBufferTmpDir();
425 lyxvc.setBuffer(owner_);
427 wa_ = new frontend::WorkAreaManager;
430 temppath = cloned_buffer_->d->temppath;
431 file_fully_loaded = true;
432 params = cloned_buffer_->d->params;
433 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
434 bibinfo_ = cloned_buffer_->d->bibinfo_;
435 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
436 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
437 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
438 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
439 unnamed = cloned_buffer_->d->unnamed;
440 internal_buffer = cloned_buffer_->d->internal_buffer;
441 layout_position = cloned_buffer_->d->layout_position;
442 preview_file_ = cloned_buffer_->d->preview_file_;
443 preview_format_ = cloned_buffer_->d->preview_format_;
444 preview_error_ = cloned_buffer_->d->preview_error_;
448 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
449 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
451 LYXERR(Debug::INFO, "Buffer::Buffer()");
453 d->inset = new InsetText(*cloned_buffer->d->inset);
454 d->inset->setBuffer(*this);
455 // FIXME: optimize this loop somewhat, maybe by creating a new
456 // general recursive Inset::setId().
457 DocIterator it = doc_iterator_begin(this);
458 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
459 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
460 it.paragraph().setId(cloned_it.paragraph().id());
462 d->inset = new InsetText(this);
463 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
469 LYXERR(Debug::INFO, "Buffer::~Buffer()");
470 // here the buffer should take care that it is
471 // saved properly, before it goes into the void.
473 // GuiView already destroyed
477 // No need to do additional cleanups for internal buffer.
483 // this is in case of recursive includes: we won't try to delete
484 // ourselves as a child.
485 d->clone_list_->erase(this);
486 // loop over children
487 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
488 Impl::BufferPositionMap::iterator end = d->children_positions.end();
489 for (; it != end; ++it) {
490 Buffer * child = const_cast<Buffer *>(it->first);
491 if (d->clone_list_->erase(child))
494 // if we're the master buffer, then we should get rid of the list
497 // If this is not empty, we have leaked something. Worse, one of the
498 // children still has a reference to this list. But we will try to
499 // continue, rather than shut down.
500 LATTEST(d->clone_list_->empty());
501 list<CloneList *>::iterator it =
502 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
503 if (it == cloned_buffers.end()) {
504 // We will leak in this case, but it is safe to continue.
507 cloned_buffers.erase(it);
508 delete d->clone_list_;
510 // FIXME Do we really need to do this right before we delete d?
511 // clear references to children in macro tables
512 d->children_positions.clear();
513 d->position_to_children.clear();
515 // loop over children
516 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
517 Impl::BufferPositionMap::iterator end = d->children_positions.end();
518 for (; it != end; ++it) {
519 Buffer * child = const_cast<Buffer *>(it->first);
520 if (theBufferList().isLoaded(child))
521 theBufferList().releaseChild(this, child);
525 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
526 msg += emergencyWrite();
527 Alert::warning(_("Attempting to close changed document!"), msg);
530 // FIXME Do we really need to do this right before we delete d?
531 // clear references to children in macro tables
532 d->children_positions.clear();
533 d->position_to_children.clear();
535 if (!d->temppath.destroyDirectory()) {
536 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
537 from_utf8(d->temppath.absFileName())));
546 Buffer * Buffer::cloneFromMaster() const
549 cloned_buffers.push_back(new CloneList);
550 CloneList * clones = cloned_buffers.back();
552 masterBuffer()->cloneWithChildren(bufmap, clones);
554 // make sure we got cloned
555 BufferMap::const_iterator bit = bufmap.find(this);
556 LASSERT(bit != bufmap.end(), return 0);
557 Buffer * cloned_buffer = bit->second;
559 return cloned_buffer;
563 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
565 // have we already been cloned?
566 if (bufmap.find(this) != bufmap.end())
569 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
571 // The clone needs its own DocumentClass, since running updateBuffer() will
572 // modify it, and we would otherwise be sharing it with the original Buffer.
573 buffer_clone->params().makeDocumentClass(true);
575 cap::switchBetweenClasses(
576 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
577 static_cast<InsetText &>(buffer_clone->inset()), el);
579 bufmap[this] = buffer_clone;
580 clones->insert(buffer_clone);
581 buffer_clone->d->clone_list_ = clones;
582 buffer_clone->d->macro_lock = true;
583 buffer_clone->d->children_positions.clear();
585 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
586 // math macro caches need to be rethought and simplified.
587 // I am not sure wether we should handle Buffer cloning here or in BufferList.
588 // Right now BufferList knows nothing about buffer clones.
589 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
590 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
591 for (; it != end; ++it) {
592 DocIterator dit = it->first.clone(buffer_clone);
593 dit.setBuffer(buffer_clone);
594 Buffer * child = const_cast<Buffer *>(it->second.buffer);
596 child->cloneWithChildren(bufmap, clones);
597 BufferMap::iterator const bit = bufmap.find(child);
598 LASSERT(bit != bufmap.end(), continue);
599 Buffer * child_clone = bit->second;
601 Inset * inset = dit.nextInset();
602 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
603 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
604 inset_inc->setChildBuffer(child_clone);
605 child_clone->d->setParent(buffer_clone);
606 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
607 buffer_clone->setChild(dit, child_clone);
609 buffer_clone->d->macro_lock = false;
614 Buffer * Buffer::cloneBufferOnly() const {
615 cloned_buffers.push_back(new CloneList);
616 CloneList * clones = cloned_buffers.back();
617 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
619 // The clone needs its own DocumentClass, since running updateBuffer() will
620 // modify it, and we would otherwise be sharing it with the original Buffer.
621 buffer_clone->params().makeDocumentClass(true);
623 cap::switchBetweenClasses(
624 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
625 static_cast<InsetText &>(buffer_clone->inset()), el);
627 clones->insert(buffer_clone);
628 buffer_clone->d->clone_list_ = clones;
630 // we won't be cloning the children
631 buffer_clone->d->children_positions.clear();
636 bool Buffer::isClone() const
638 return d->cloned_buffer_;
642 void Buffer::changed(bool update_metrics) const
645 d->wa_->redrawAll(update_metrics);
649 frontend::WorkAreaManager & Buffer::workAreaManager() const
656 Text & Buffer::text() const
658 return d->inset->text();
662 Inset & Buffer::inset() const
668 BufferParams & Buffer::params()
674 BufferParams const & Buffer::params() const
680 BufferParams const & Buffer::masterParams() const
682 if (masterBuffer() == this)
685 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
686 // Copy child authors to the params. We need those pointers.
687 AuthorList const & child_authors = params().authors();
688 AuthorList::Authors::const_iterator it = child_authors.begin();
689 for (; it != child_authors.end(); ++it)
690 mparams.authors().record(*it);
695 double Buffer::fontScalingFactor() const
697 return isExporting() ? 75.0 * params().html_math_img_scale
698 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
702 ParagraphList & Buffer::paragraphs()
704 return text().paragraphs();
708 ParagraphList const & Buffer::paragraphs() const
710 return text().paragraphs();
714 LyXVC & Buffer::lyxvc()
720 LyXVC const & Buffer::lyxvc() const
726 string const Buffer::temppath() const
728 return d->temppath.absFileName();
732 TexRow & Buffer::texrow()
738 TexRow const & Buffer::texrow() const
744 TocBackend & Buffer::tocBackend() const
746 return d->toc_backend;
750 Undo & Buffer::undo()
756 void Buffer::setChild(DocIterator const & dit, Buffer * child)
758 d->children_positions[child] = dit;
762 string Buffer::latexName(bool const no_path) const
764 FileName latex_name =
765 makeLatexName(d->exportFileName());
766 return no_path ? latex_name.onlyFileName()
767 : latex_name.absFileName();
771 FileName Buffer::Impl::exportFileName() const
773 docstring const branch_suffix =
774 params.branchlist().getFileNameSuffix();
775 if (branch_suffix.empty())
778 string const name = filename.onlyFileNameWithoutExt()
779 + to_utf8(branch_suffix);
780 FileName res(filename.onlyPath().absFileName() + "/" + name);
781 res.changeExtension(filename.extension());
787 string Buffer::logName(LogType * type) const
789 string const filename = latexName(false);
791 if (filename.empty()) {
797 string const path = temppath();
799 FileName const fname(addName(temppath(),
800 onlyFileName(changeExtension(filename,
803 // FIXME: how do we know this is the name of the build log?
804 FileName const bname(
805 addName(path, onlyFileName(
806 changeExtension(filename,
807 formats.extension(params().bufferFormat()) + ".out"))));
809 // Also consider the master buffer log file
810 FileName masterfname = fname;
811 LogType mtype = latexlog;
812 if (masterBuffer() != this) {
813 string const mlogfile = masterBuffer()->logName(&mtype);
814 masterfname = FileName(mlogfile);
817 // If no Latex log or Build log is newer, show Build log
818 if (bname.exists() &&
819 ((!fname.exists() && !masterfname.exists())
820 || (fname.lastModified() < bname.lastModified()
821 && masterfname.lastModified() < bname.lastModified()))) {
822 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
825 return bname.absFileName();
826 // If we have a newer master file log or only a master log, show this
827 } else if (fname != masterfname
828 && (!fname.exists() && (masterfname.exists()
829 || fname.lastModified() < masterfname.lastModified()))) {
830 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
833 return masterfname.absFileName();
835 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
838 return fname.absFileName();
842 void Buffer::setReadonly(bool const flag)
844 if (d->read_only != flag) {
851 void Buffer::setFileName(FileName const & fname)
853 bool const changed = fname != d->filename;
856 lyxvc().file_found_hook(fname);
857 setReadonly(d->filename.isReadOnly());
863 int Buffer::readHeader(Lexer & lex)
865 int unknown_tokens = 0;
867 int begin_header_line = -1;
869 // Initialize parameters that may be/go lacking in header:
870 params().branchlist().clear();
871 params().preamble.erase();
872 params().options.erase();
873 params().master.erase();
874 params().float_placement.erase();
875 params().paperwidth.erase();
876 params().paperheight.erase();
877 params().leftmargin.erase();
878 params().rightmargin.erase();
879 params().topmargin.erase();
880 params().bottommargin.erase();
881 params().headheight.erase();
882 params().headsep.erase();
883 params().footskip.erase();
884 params().columnsep.erase();
885 params().fonts_cjk.erase();
886 params().listings_params.clear();
887 params().clearLayoutModules();
888 params().clearRemovedModules();
889 params().clearIncludedChildren();
890 params().pdfoptions().clear();
891 params().indiceslist().clear();
892 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
893 params().isbackgroundcolor = false;
894 params().fontcolor = RGBColor(0, 0, 0);
895 params().isfontcolor = false;
896 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
897 params().boxbgcolor = RGBColor(0xFF, 0, 0);
898 params().html_latex_start.clear();
899 params().html_latex_end.clear();
900 params().html_math_img_scale = 1.0;
901 params().output_sync_macro.erase();
902 params().setLocalLayout(string(), false);
903 params().setLocalLayout(string(), true);
905 for (int i = 0; i < 4; ++i) {
906 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
907 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
910 ErrorList & errorList = d->errorLists["Parse"];
919 if (token == "\\end_header")
923 if (token == "\\begin_header") {
924 begin_header_line = line;
928 LYXERR(Debug::PARSER, "Handling document header token: `"
931 string const result =
932 params().readToken(lex, token, d->filename.onlyPath());
933 if (!result.empty()) {
934 if (token == "\\textclass") {
935 d->layout_position = result;
938 docstring const s = bformat(_("Unknown token: "
942 errorList.push_back(ErrorItem(_("Document header error"),
947 if (begin_header_line) {
948 docstring const s = _("\\begin_header is missing");
949 errorList.push_back(ErrorItem(_("Document header error"),
953 params().makeDocumentClass();
955 return unknown_tokens;
960 // changed to be public and have one parameter
961 // Returns true if "\end_document" is not read (Asger)
962 bool Buffer::readDocument(Lexer & lex)
964 ErrorList & errorList = d->errorLists["Parse"];
967 // remove dummy empty par
968 paragraphs().clear();
970 if (!lex.checkFor("\\begin_document")) {
971 docstring const s = _("\\begin_document is missing");
972 errorList.push_back(ErrorItem(_("Document header error"),
978 if (params().output_changes) {
979 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
980 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
981 LaTeXFeatures::isAvailable("xcolor");
983 if (!dvipost && !xcolorulem) {
984 Alert::warning(_("Changes not shown in LaTeX output"),
985 _("Changes will not be highlighted in LaTeX output, "
986 "because neither dvipost nor xcolor/ulem are installed.\n"
987 "Please install these packages or redefine "
988 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
989 } else if (!xcolorulem) {
990 Alert::warning(_("Changes not shown in LaTeX output"),
991 _("Changes will not be highlighted in LaTeX output "
992 "when using pdflatex, because xcolor and ulem are not installed.\n"
993 "Please install both packages or redefine "
994 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
998 if (!parent() && !params().master.empty()) {
999 FileName const master_file = makeAbsPath(params().master,
1000 onlyPath(absFileName()));
1001 if (isLyXFileName(master_file.absFileName())) {
1003 checkAndLoadLyXFile(master_file, true);
1005 // necessary e.g. after a reload
1006 // to re-register the child (bug 5873)
1007 // FIXME: clean up updateMacros (here, only
1008 // child registering is needed).
1009 master->updateMacros();
1010 // set master as master buffer, but only
1011 // if we are a real child
1012 if (master->isChild(this))
1014 // if the master is not fully loaded
1015 // it is probably just loading this
1016 // child. No warning needed then.
1017 else if (master->isFullyLoaded())
1018 LYXERR0("The master '"
1020 << "' assigned to this document ("
1022 << ") does not include "
1023 "this document. Ignoring the master assignment.");
1028 // assure we have a default index
1029 params().indiceslist().addDefault(B_("Index"));
1032 d->old_position = originFilePath();
1033 bool const res = text().read(lex, errorList, d->inset);
1034 d->old_position.clear();
1036 // inform parent buffer about local macros
1038 Buffer const * pbuf = parent();
1039 UserMacroSet::const_iterator cit = usermacros.begin();
1040 UserMacroSet::const_iterator end = usermacros.end();
1041 for (; cit != end; ++cit)
1042 pbuf->usermacros.insert(*cit);
1046 updateMacroInstances(InternalUpdate);
1051 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1053 Format const * fmt = formats.getFormat(format);
1056 // It is important to use the correct extension here, since some
1057 // converters create a wrong output file otherwise (e.g. html2latex)
1058 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1059 FileName const name(tempfile.name());
1060 ofdocstream os(name.toFilesystemEncoding().c_str());
1061 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1062 bool const success = !(os << contents).fail();
1065 bool converted = false;
1067 params().compressed = false;
1069 // remove dummy empty par
1070 paragraphs().clear();
1072 converted = importFile(format, name, errorList);
1081 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1083 if (!theConverters().isReachable(format, "lyx"))
1086 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1087 FileName const lyx(tempfile.name());
1088 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1089 return readFile(lyx) == ReadSuccess;
1095 bool Buffer::readString(string const & s)
1097 params().compressed = false;
1100 istringstream is(s);
1102 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1103 FileName const fn = tempfile.name();
1106 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1108 if (success && file_format != LYX_FORMAT) {
1109 // We need to call lyx2lyx, so write the input to a file
1110 ofstream os(fn.toFilesystemEncoding().c_str());
1113 // lyxvc in readFile
1114 if (readFile(fn) != ReadSuccess)
1118 if (readDocument(lex))
1124 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1128 if (!lex.setFile(fname)) {
1129 Alert::error(_("File Not Found"),
1130 bformat(_("Unable to open file `%1$s'."),
1131 from_utf8(fn.absFileName())));
1132 return ReadFileNotFound;
1136 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1137 if (ret_plf != ReadSuccess)
1140 if (file_format != LYX_FORMAT) {
1142 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1143 if (ret_clf != ReadSuccess)
1145 ret_clf = readFile(tmpFile);
1146 if (ret_clf == ReadSuccess) {
1147 d->file_format = file_format;
1148 d->need_format_backup = true;
1153 // FIXME: InsetInfo needs to know whether the file is under VCS
1154 // during the parse process, so this has to be done before.
1155 lyxvc().file_found_hook(d->filename);
1157 if (readDocument(lex)) {
1158 Alert::error(_("Document format failure"),
1159 bformat(_("%1$s ended unexpectedly, which means"
1160 " that it is probably corrupted."),
1161 from_utf8(fn.absFileName())));
1162 return ReadDocumentFailure;
1165 d->file_fully_loaded = true;
1166 d->read_only = !d->filename.isWritable();
1167 params().compressed = formats.isZippedFile(d->filename);
1173 bool Buffer::isFullyLoaded() const
1175 return d->file_fully_loaded;
1179 void Buffer::setFullyLoaded(bool value)
1181 d->file_fully_loaded = value;
1185 bool Buffer::lastPreviewError() const
1187 return d->preview_error_;
1191 PreviewLoader * Buffer::loader() const
1193 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1195 if (!d->preview_loader_)
1196 d->preview_loader_ = new PreviewLoader(*this);
1197 return d->preview_loader_;
1201 void Buffer::removePreviews() const
1203 delete d->preview_loader_;
1204 d->preview_loader_ = 0;
1208 void Buffer::updatePreviews() const
1210 PreviewLoader * ploader = loader();
1214 InsetIterator it = inset_iterator_begin(*d->inset);
1215 InsetIterator const end = inset_iterator_end(*d->inset);
1216 for (; it != end; ++it)
1217 it->addPreview(it, *ploader);
1219 ploader->startLoading();
1223 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1224 FileName const & fn, int & file_format) const
1226 if(!lex.checkFor("\\lyxformat")) {
1227 Alert::error(_("Document format failure"),
1228 bformat(_("%1$s is not a readable LyX document."),
1229 from_utf8(fn.absFileName())));
1230 return ReadNoLyXFormat;
1236 // LyX formats 217 and earlier were written as 2.17. This corresponds
1237 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1238 // these cases. See also: www.lyx.org/trac/changeset/1313.
1239 size_t dot = tmp_format.find_first_of(".,");
1240 if (dot != string::npos)
1241 tmp_format.erase(dot, 1);
1243 file_format = convert<int>(tmp_format);
1248 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1249 FileName & tmpfile, int from_format)
1251 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1252 tempfile.setAutoRemove(false);
1253 tmpfile = tempfile.name();
1254 if(tmpfile.empty()) {
1255 Alert::error(_("Conversion failed"),
1256 bformat(_("%1$s is from a different"
1257 " version of LyX, but a temporary"
1258 " file for converting it could"
1259 " not be created."),
1260 from_utf8(fn.absFileName())));
1261 return LyX2LyXNoTempFile;
1264 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1265 if (lyx2lyx.empty()) {
1266 Alert::error(_("Conversion script not found"),
1267 bformat(_("%1$s is from a different"
1268 " version of LyX, but the"
1269 " conversion script lyx2lyx"
1270 " could not be found."),
1271 from_utf8(fn.absFileName())));
1272 return LyX2LyXNotFound;
1276 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1277 ostringstream command;
1278 command << os::python()
1279 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1280 << " -t " << convert<string>(LYX_FORMAT)
1281 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1282 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1283 string const command_str = command.str();
1285 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1287 cmd_ret const ret = runCommand(command_str);
1288 if (ret.first != 0) {
1289 if (from_format < LYX_FORMAT) {
1290 Alert::error(_("Conversion script failed"),
1291 bformat(_("%1$s is from an older version"
1292 " of LyX and the lyx2lyx script"
1293 " failed to convert it."),
1294 from_utf8(fn.absFileName())));
1295 return LyX2LyXOlderFormat;
1297 Alert::error(_("Conversion script failed"),
1298 bformat(_("%1$s is from a newer version"
1299 " of LyX and the lyx2lyx script"
1300 " failed to convert it."),
1301 from_utf8(fn.absFileName())));
1302 return LyX2LyXNewerFormat;
1309 FileName Buffer::getBackupName() const {
1310 FileName const & fn = fileName();
1311 string const fname = fn.onlyFileNameWithoutExt();
1312 string const fext = fn.extension();
1313 string const fpath = lyxrc.backupdir_path.empty() ?
1314 fn.onlyPath().absFileName() :
1315 lyxrc.backupdir_path;
1316 string const fform = convert<string>(d->file_format);
1317 string const backname = fname + "-" + fform;
1318 FileName backup(addName(fpath, addExtension(backname, fext)));
1320 // limit recursion, just in case
1322 unsigned long orig_checksum = 0;
1323 while (backup.exists() && v < 100) {
1324 if (orig_checksum == 0)
1325 orig_checksum = fn.checksum();
1326 unsigned long new_checksum = backup.checksum();
1327 if (orig_checksum == new_checksum) {
1328 LYXERR(Debug::FILES, "Not backing up " << fn <<
1329 "since " << backup << "has the same checksum.");
1330 // a bit of a hack, but we have to check this anyway
1331 // below, and setting this is simpler than introducing
1332 // a special boolean for this purpose.
1336 string newbackname = backname + "-" + convert<string>(v);
1337 backup.set(addName(fpath, addExtension(newbackname, fext)));
1340 return v < 100 ? backup : FileName();
1344 // Should probably be moved to somewhere else: BufferView? GuiView?
1345 bool Buffer::save() const
1347 docstring const file = makeDisplayPath(absFileName(), 20);
1348 d->filename.refresh();
1350 // check the read-only status before moving the file as a backup
1351 if (d->filename.exists()) {
1352 bool const read_only = !d->filename.isWritable();
1354 Alert::warning(_("File is read-only"),
1355 bformat(_("The file %1$s cannot be written because it "
1356 "is marked as read-only."), file));
1361 // ask if the disk file has been externally modified (use checksum method)
1362 if (fileName().exists() && isExternallyModified(checksum_method)) {
1364 bformat(_("Document %1$s has been externally modified. "
1365 "Are you sure you want to overwrite this file?"), file);
1366 int const ret = Alert::prompt(_("Overwrite modified file?"),
1367 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1372 // We don't need autosaves in the immediate future. (Asger)
1373 resetAutosaveTimers();
1375 // if the file does not yet exist, none of the backup activity
1376 // that follows is necessary
1377 if (!fileName().exists()) {
1378 if (!writeFile(fileName()))
1384 // we first write the file to a new name, then move it to its
1385 // proper location once that has been done successfully. that
1386 // way we preserve the original file if something goes wrong.
1387 string const justname = fileName().onlyFileNameWithoutExt();
1388 boost::scoped_ptr<TempFile>
1389 tempfile(new TempFile(fileName().onlyPath(),
1390 justname + "-XXXXXX.lyx"));
1391 bool const symlink = fileName().isSymLink();
1393 tempfile->setAutoRemove(false);
1395 FileName savefile(tempfile->name());
1396 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1397 if (!writeFile(savefile))
1400 // we will set this to false if we fail
1401 bool made_backup = true;
1403 FileName backupName;
1404 if (lyxrc.make_backup || d->need_format_backup) {
1405 if (d->need_format_backup)
1406 backupName = getBackupName();
1408 // If we for some reason failed to find a backup name in case of
1409 // a format change, this will still set one. It's the best we can
1411 if (backupName.empty()) {
1412 backupName.set(fileName().absFileName() + "~");
1413 if (!lyxrc.backupdir_path.empty()) {
1414 string const mangledName =
1415 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1416 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1420 LYXERR(Debug::FILES, "Backing up original file to " <<
1421 backupName.absFileName());
1422 // Except file is symlink do not copy because of #6587.
1423 // Hard links have bad luck.
1424 made_backup = symlink ?
1425 fileName().copyTo(backupName):
1426 fileName().moveTo(backupName);
1429 Alert::error(_("Backup failure"),
1430 bformat(_("Cannot create backup file %1$s.\n"
1431 "Please check whether the directory exists and is writable."),
1432 from_utf8(backupName.absFileName())));
1433 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1434 } else if (d->need_format_backup) {
1435 // the original file has been backed up successfully, so we
1436 // will not need to do that again
1437 d->need_format_backup = false;
1441 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1442 // Only do this if tempfile is not in autoremove mode
1445 // If we have no symlink, we can simply rename the temp file.
1446 // Otherwise, we need to copy it so the symlink stays intact.
1447 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1448 savefile.moveTo(fileName()))
1450 // saveCheckSum() was already called by writeFile(), but the
1451 // time stamp is invalidated by copying/moving
1454 if (d->file_format != LYX_FORMAT)
1455 // the file associated with this buffer is now in the current format
1456 d->file_format = LYX_FORMAT;
1459 // else we saved the file, but failed to move it to the right location.
1461 if (lyxrc.make_backup && made_backup && !symlink) {
1462 // the original file was moved to filename.lyx~, so it will look
1463 // to the user as if it was deleted. (see bug #9234.) we could try
1464 // to restore it, but that would basically mean trying to do again
1465 // what we just failed to do. better to leave things as they are.
1466 Alert::error(_("Write failure"),
1467 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1468 "But LyX could not move it to:\n %2$s.\n"
1469 "Your original file has been backed up to:\n %3$s"),
1470 from_utf8(savefile.absFileName()),
1471 from_utf8(fileName().absFileName()),
1472 from_utf8(backupName.absFileName())));
1474 // either we did not try to make a backup, or else we tried and failed,
1475 // or else the original file was a symlink, in which case it was copied,
1476 // not moved. so the original file is intact.
1477 Alert::error(_("Write failure"),
1478 bformat(_("Cannot move saved file to:\n %1$s.\n"
1479 "But the file has successfully been saved as:\n %2$s."),
1480 from_utf8(fileName().absFileName()),
1481 from_utf8(savefile.absFileName())));
1487 bool Buffer::writeFile(FileName const & fname) const
1489 if (d->read_only && fname == d->filename)
1492 bool retval = false;
1494 docstring const str = bformat(_("Saving document %1$s..."),
1495 makeDisplayPath(fname.absFileName()));
1498 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1500 if (params().compressed) {
1501 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1502 retval = ofs && write(ofs);
1504 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1505 retval = ofs && write(ofs);
1509 message(str + _(" could not write file!"));
1514 // removeAutosaveFile();
1517 message(str + _(" done."));
1523 docstring Buffer::emergencyWrite()
1525 // No need to save if the buffer has not changed.
1529 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1531 docstring user_message = bformat(
1532 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1534 // We try to save three places:
1535 // 1) Same place as document. Unless it is an unnamed doc.
1537 string s = absFileName();
1540 if (writeFile(FileName(s))) {
1542 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1543 return user_message;
1545 user_message += " " + _("Save failed! Trying again...\n");
1549 // 2) In HOME directory.
1550 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1552 lyxerr << ' ' << s << endl;
1553 if (writeFile(FileName(s))) {
1555 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1556 return user_message;
1559 user_message += " " + _("Save failed! Trying yet again...\n");
1561 // 3) In "/tmp" directory.
1562 // MakeAbsPath to prepend the current
1563 // drive letter on OS/2
1564 s = addName(package().temp_dir().absFileName(), absFileName());
1566 lyxerr << ' ' << s << endl;
1567 if (writeFile(FileName(s))) {
1569 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1570 return user_message;
1573 user_message += " " + _("Save failed! Bummer. Document is lost.");
1576 return user_message;
1580 bool Buffer::write(ostream & ofs) const
1583 // Use the standard "C" locale for file output.
1584 ofs.imbue(locale::classic());
1587 // The top of the file should not be written by params().
1589 // write out a comment in the top of the file
1590 // Important: Keep the version formatting in sync with lyx2lyx and
1591 // tex2lyx (bug 7951)
1592 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1593 << " created this file. For more info see http://www.lyx.org/\n"
1594 << "\\lyxformat " << LYX_FORMAT << "\n"
1595 << "\\begin_document\n";
1597 /// For each author, set 'used' to true if there is a change
1598 /// by this author in the document; otherwise set it to 'false'.
1599 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1600 AuthorList::Authors::const_iterator a_end = params().authors().end();
1601 for (; a_it != a_end; ++a_it)
1602 a_it->setUsed(false);
1604 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1605 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1606 for ( ; it != end; ++it)
1607 it->checkAuthors(params().authors());
1609 // now write out the buffer parameters.
1610 ofs << "\\begin_header\n";
1611 params().writeFile(ofs, this);
1612 ofs << "\\end_header\n";
1615 ofs << "\n\\begin_body\n";
1617 ofs << "\n\\end_body\n";
1619 // Write marker that shows file is complete
1620 ofs << "\\end_document" << endl;
1622 // Shouldn't really be needed....
1625 // how to check if close went ok?
1626 // Following is an attempt... (BE 20001011)
1628 // good() returns false if any error occurred, including some
1629 // formatting error.
1630 // bad() returns true if something bad happened in the buffer,
1631 // which should include file system full errors.
1636 lyxerr << "File was not closed properly." << endl;
1643 bool Buffer::makeLaTeXFile(FileName const & fname,
1644 string const & original_path,
1645 OutputParams const & runparams_in,
1646 OutputWhat output) const
1648 OutputParams runparams = runparams_in;
1650 // XeTeX with TeX fonts is only safe with ASCII encoding,
1651 // but the "flavor" is not known in BufferParams::encoding().
1652 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1653 runparams.encoding = encodings.fromLyXName("ascii");
1655 string const encoding = runparams.encoding->iconvName();
1656 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1659 try { ofs.reset(encoding); }
1660 catch (iconv_codecvt_facet_exception const & e) {
1661 lyxerr << "Caught iconv exception: " << e.what() << endl;
1662 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1663 "verify that the support software for your encoding (%1$s) is "
1664 "properly installed"), from_ascii(encoding)));
1667 if (!openFileWrite(ofs, fname))
1670 ErrorList & errorList = d->errorLists["Export"];
1672 bool failed_export = false;
1673 otexstream os(ofs, d->texrow);
1675 // make sure we are ready to export
1676 // this needs to be done before we validate
1677 // FIXME Do we need to do this all the time? I.e., in children
1678 // of a master we are exporting?
1680 updateMacroInstances(OutputUpdate);
1683 os.texrow().reset();
1684 writeLaTeXSource(os, original_path, runparams, output);
1686 catch (EncodingException const & e) {
1687 docstring const failed(1, e.failed_char);
1689 oss << "0x" << hex << e.failed_char << dec;
1690 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1691 " (code point %2$s)"),
1692 failed, from_utf8(oss.str()));
1693 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1694 "representable in the chosen encoding.\n"
1695 "Changing the document encoding to utf8 could help."),
1696 e.par_id, e.pos, e.pos + 1));
1697 failed_export = true;
1699 catch (iconv_codecvt_facet_exception const & e) {
1700 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1701 _(e.what()), -1, 0, 0));
1702 failed_export = true;
1704 catch (exception const & e) {
1705 errorList.push_back(ErrorItem(_("conversion failed"),
1706 _(e.what()), -1, 0, 0));
1707 failed_export = true;
1710 lyxerr << "Caught some really weird exception..." << endl;
1716 failed_export = true;
1717 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1720 if (runparams_in.silent)
1724 return !failed_export;
1728 void Buffer::writeLaTeXSource(otexstream & os,
1729 string const & original_path,
1730 OutputParams const & runparams_in,
1731 OutputWhat output) const
1733 // The child documents, if any, shall be already loaded at this point.
1735 OutputParams runparams = runparams_in;
1737 // XeTeX with TeX fonts is only safe with ASCII encoding,
1738 // but the "flavor" is not known in BufferParams::encoding().
1739 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1740 runparams.encoding = encodings.fromLyXName("ascii");
1741 // FIXME: when only the current paragraph is shown, this is ignored
1742 // (or not reached) and characters encodable in the current
1743 // encoding are not converted to ASCII-representation.
1745 // If we are compiling a file standalone, even if this is the
1746 // child of some other buffer, let's cut the link here, so the
1747 // file is really independent and no concurring settings from
1748 // the master (e.g. branch state) interfere (see #8100).
1749 if (!runparams.is_child)
1750 d->ignore_parent = true;
1752 // Classify the unicode characters appearing in math insets
1753 BufferEncodings::initUnicodeMath(*this);
1755 // validate the buffer.
1756 LYXERR(Debug::LATEX, " Validating buffer...");
1757 LaTeXFeatures features(*this, params(), runparams);
1759 // This is only set once per document (in master)
1760 if (!runparams.is_child)
1761 runparams.use_polyglossia = features.usePolyglossia();
1762 LYXERR(Debug::LATEX, " Buffer validation done.");
1764 bool const output_preamble =
1765 output == FullSource || output == OnlyPreamble;
1766 bool const output_body =
1767 output == FullSource || output == OnlyBody;
1769 // The starting paragraph of the coming rows is the
1770 // first paragraph of the document. (Asger)
1771 if (output_preamble && runparams.nice) {
1772 os << "%% LyX " << lyx_version << " created this file. "
1773 "For more info, see http://www.lyx.org/.\n"
1774 "%% Do not edit unless you really know what "
1777 LYXERR(Debug::INFO, "lyx document header finished");
1779 // There are a few differences between nice LaTeX and usual files:
1780 // usual files have \batchmode and special input@path to allow
1781 // inclusion of figures specified by an explicitly relative path
1782 // (i.e., a path starting with './' or '../') with either \input or
1783 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1784 // input@path is set when the actual parameter original_path is set.
1785 // This is done for usual tex-file, but not for nice-latex-file.
1786 // (Matthias 250696)
1787 // Note that input@path is only needed for something the user does
1788 // in the preamble, included .tex files or ERT, files included by
1789 // LyX work without it.
1790 if (output_preamble) {
1791 if (!runparams.nice) {
1792 // code for usual, NOT nice-latex-file
1793 os << "\\batchmode\n"; // changed from \nonstopmode
1795 if (!original_path.empty()) {
1797 // We don't know the encoding of inputpath
1798 docstring const inputpath = from_utf8(original_path);
1799 docstring uncodable_glyphs;
1800 Encoding const * const enc = runparams.encoding;
1802 for (size_t n = 0; n < inputpath.size(); ++n) {
1803 if (!enc->encodable(inputpath[n])) {
1804 docstring const glyph(1, inputpath[n]);
1805 LYXERR0("Uncodable character '"
1807 << "' in input path!");
1808 uncodable_glyphs += glyph;
1813 // warn user if we found uncodable glyphs.
1814 if (!uncodable_glyphs.empty()) {
1815 frontend::Alert::warning(
1816 _("Uncodable character in file path"),
1818 _("The path of your document\n"
1820 "contains glyphs that are unknown "
1821 "in the current document encoding "
1822 "(namely %2$s). This may result in "
1823 "incomplete output, unless "
1824 "TEXINPUTS contains the document "
1825 "directory and you don't use "
1826 "explicitly relative paths (i.e., "
1827 "paths starting with './' or "
1828 "'../') in the preamble or in ERT."
1829 "\n\nIn case of problems, choose "
1830 "an appropriate document encoding\n"
1831 "(such as utf8) or change the "
1833 inputpath, uncodable_glyphs));
1836 support::latex_path(original_path);
1837 if (contains(docdir, '#')) {
1838 docdir = subst(docdir, "#", "\\#");
1839 os << "\\catcode`\\#=11"
1840 "\\def\\#{#}\\catcode`\\#=6\n";
1842 if (contains(docdir, '%')) {
1843 docdir = subst(docdir, "%", "\\%");
1844 os << "\\catcode`\\%=11"
1845 "\\def\\%{%}\\catcode`\\%=14\n";
1847 os << "\\makeatletter\n"
1848 << "\\def\\input@path{{"
1850 << "\\makeatother\n";
1854 // get parent macros (if this buffer has a parent) which will be
1855 // written at the document begin further down.
1856 MacroSet parentMacros;
1857 listParentMacros(parentMacros, features);
1859 // Write the preamble
1860 runparams.use_babel = params().writeLaTeX(os, features,
1861 d->filename.onlyPath());
1863 // Japanese might be required only in some children of a document,
1864 // but once required, we must keep use_japanese true.
1865 runparams.use_japanese |= features.isRequired("japanese");
1868 // Restore the parenthood if needed
1869 if (!runparams.is_child)
1870 d->ignore_parent = false;
1875 os << "\\begin{document}\n";
1877 // output the parent macros
1878 MacroSet::iterator it = parentMacros.begin();
1879 MacroSet::iterator end = parentMacros.end();
1880 for (; it != end; ++it) {
1881 int num_lines = (*it)->write(os.os(), true);
1882 os.texrow().newlines(num_lines);
1885 } // output_preamble
1887 os.texrow().start(paragraphs().begin()->id(), 0);
1889 LYXERR(Debug::INFO, "preamble finished, now the body.");
1892 latexParagraphs(*this, text(), os, runparams);
1894 // Restore the parenthood if needed
1895 if (!runparams.is_child)
1896 d->ignore_parent = false;
1898 // add this just in case after all the paragraphs
1901 if (output_preamble) {
1902 os << "\\end{document}\n";
1903 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1905 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1907 runparams_in.encoding = runparams.encoding;
1909 os.texrow().finalize();
1911 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1912 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1916 void Buffer::makeDocBookFile(FileName const & fname,
1917 OutputParams const & runparams,
1918 OutputWhat output) const
1920 LYXERR(Debug::LATEX, "makeDocBookFile...");
1923 if (!openFileWrite(ofs, fname))
1926 // make sure we are ready to export
1927 // this needs to be done before we validate
1929 updateMacroInstances(OutputUpdate);
1931 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1935 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1939 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1940 OutputParams const & runparams,
1941 OutputWhat output) const
1943 LaTeXFeatures features(*this, params(), runparams);
1946 d->texrow.reset(false);
1948 DocumentClass const & tclass = params().documentClass();
1949 string const & top_element = tclass.latexname();
1951 bool const output_preamble =
1952 output == FullSource || output == OnlyPreamble;
1953 bool const output_body =
1954 output == FullSource || output == OnlyBody;
1956 if (output_preamble) {
1957 if (runparams.flavor == OutputParams::XML)
1958 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1961 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1964 if (! tclass.class_header().empty())
1965 os << from_ascii(tclass.class_header());
1966 else if (runparams.flavor == OutputParams::XML)
1967 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1968 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1970 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1972 docstring preamble = from_utf8(params().preamble);
1973 if (runparams.flavor != OutputParams::XML ) {
1974 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1975 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1976 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1977 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1980 string const name = runparams.nice
1981 ? changeExtension(absFileName(), ".sgml") : fname;
1982 preamble += features.getIncludedFiles(name);
1983 preamble += features.getLyXSGMLEntities();
1985 if (!preamble.empty()) {
1986 os << "\n [ " << preamble << " ]";
1992 string top = top_element;
1994 if (runparams.flavor == OutputParams::XML)
1995 top += params().language->code();
1997 top += params().language->code().substr(0, 2);
2000 if (!params().options.empty()) {
2002 top += params().options;
2005 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2006 << " file was created by LyX " << lyx_version
2007 << "\n See http://www.lyx.org/ for more information -->\n";
2009 params().documentClass().counters().reset();
2011 sgml::openTag(os, top);
2013 docbookParagraphs(text(), *this, os, runparams);
2014 sgml::closeTag(os, top_element);
2019 void Buffer::makeLyXHTMLFile(FileName const & fname,
2020 OutputParams const & runparams) const
2022 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2025 if (!openFileWrite(ofs, fname))
2028 // make sure we are ready to export
2029 // this has to be done before we validate
2030 updateBuffer(UpdateMaster, OutputUpdate);
2031 updateMacroInstances(OutputUpdate);
2033 writeLyXHTMLSource(ofs, runparams, FullSource);
2037 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2041 void Buffer::writeLyXHTMLSource(odocstream & os,
2042 OutputParams const & runparams,
2043 OutputWhat output) const
2045 LaTeXFeatures features(*this, params(), runparams);
2047 d->bibinfo_.makeCitationLabels(*this);
2049 bool const output_preamble =
2050 output == FullSource || output == OnlyPreamble;
2051 bool const output_body =
2052 output == FullSource || output == OnlyBody || output == IncludedFile;
2054 if (output_preamble) {
2055 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2056 << "<!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"
2057 // FIXME Language should be set properly.
2058 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2060 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2061 // FIXME Presumably need to set this right
2062 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2064 docstring const & doctitle = features.htmlTitle();
2066 << (doctitle.empty() ?
2067 from_ascii("LyX Document") :
2068 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2071 docstring styles = features.getTClassHTMLPreamble();
2072 if (!styles.empty())
2073 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2075 styles = from_utf8(features.getPreambleSnippets());
2076 if (!styles.empty())
2077 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2079 // we will collect CSS information in a stream, and then output it
2080 // either here, as part of the header, or else in a separate file.
2081 odocstringstream css;
2082 styles = from_utf8(features.getCSSSnippets());
2083 if (!styles.empty())
2084 css << "/* LyX Provided Styles */\n" << styles << '\n';
2086 styles = features.getTClassHTMLStyles();
2087 if (!styles.empty())
2088 css << "/* Layout-provided Styles */\n" << styles << '\n';
2090 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2091 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2092 if (needfg || needbg) {
2093 css << "\nbody {\n";
2096 << from_ascii(X11hexname(params().fontcolor))
2099 css << " background-color: "
2100 << from_ascii(X11hexname(params().backgroundcolor))
2105 docstring const dstyles = css.str();
2106 if (!dstyles.empty()) {
2107 bool written = false;
2108 if (params().html_css_as_file) {
2109 // open a file for CSS info
2111 string const fcssname = addName(temppath(), "docstyle.css");
2112 FileName const fcssfile = FileName(fcssname);
2113 if (openFileWrite(ocss, fcssfile)) {
2117 // write link to header
2118 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2120 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2123 // we are here if the CSS is supposed to be written to the header
2124 // or if we failed to write it to an external file.
2126 os << "<style type='text/css'>\n"
2135 bool const output_body_tag = (output != IncludedFile);
2136 if (output_body_tag)
2139 if (output != IncludedFile)
2140 // if we're an included file, the counters are in the master.
2141 params().documentClass().counters().reset();
2142 xhtmlParagraphs(text(), *this, xs, runparams);
2143 if (output_body_tag)
2147 if (output_preamble)
2152 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2153 // Other flags: -wall -v0 -x
2154 int Buffer::runChktex()
2158 // get LaTeX-Filename
2159 FileName const path(temppath());
2160 string const name = addName(path.absFileName(), latexName());
2161 string const org_path = filePath();
2163 PathChanger p(path); // path to LaTeX file
2164 message(_("Running chktex..."));
2166 // Generate the LaTeX file if neccessary
2167 OutputParams runparams(¶ms().encoding());
2168 runparams.flavor = OutputParams::LATEX;
2169 runparams.nice = false;
2170 runparams.linelen = lyxrc.plaintext_linelen;
2171 makeLaTeXFile(FileName(name), org_path, runparams);
2174 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2175 int const res = chktex.run(terr); // run chktex
2178 Alert::error(_("chktex failure"),
2179 _("Could not run chktex successfully."));
2181 ErrorList & errlist = d->errorLists["ChkTeX"];
2183 bufferErrors(terr, errlist);
2188 if (runparams.silent)
2189 d->errorLists["ChkTeX"].clear();
2197 void Buffer::validate(LaTeXFeatures & features) const
2199 // Validate the buffer params, but not for included
2200 // files, since they also use the parent buffer's
2202 if (!features.runparams().is_child)
2203 params().validate(features);
2205 for_each(paragraphs().begin(), paragraphs().end(),
2206 bind(&Paragraph::validate, _1, ref(features)));
2208 if (lyxerr.debugging(Debug::LATEX)) {
2209 features.showStruct();
2214 void Buffer::getLabelList(vector<docstring> & list) const
2216 // If this is a child document, use the master's list instead.
2218 masterBuffer()->getLabelList(list);
2223 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2224 TocIterator toc_it = toc->begin();
2225 TocIterator end = toc->end();
2226 for (; toc_it != end; ++toc_it) {
2227 if (toc_it->depth() == 0)
2228 list.push_back(toc_it->str());
2233 void Buffer::updateBibfilesCache(UpdateScope scope) const
2235 // FIXME This is probably unnecssary, given where we call this.
2236 // If this is a child document, use the parent's cache instead.
2237 if (parent() && scope != UpdateChildOnly) {
2238 masterBuffer()->updateBibfilesCache();
2242 d->bibfiles_cache_.clear();
2243 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2244 if (it->lyxCode() == BIBTEX_CODE) {
2245 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2246 support::FileNameList const bibfiles = inset.getBibFiles();
2247 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2250 } else if (it->lyxCode() == INCLUDE_CODE) {
2251 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2252 Buffer const * const incbuf = inset.getChildBuffer();
2255 support::FileNameList const & bibfiles =
2256 incbuf->getBibfilesCache(UpdateChildOnly);
2257 if (!bibfiles.empty()) {
2258 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2264 d->bibfile_cache_valid_ = true;
2265 d->bibinfo_cache_valid_ = false;
2266 d->cite_labels_valid_ = false;
2270 void Buffer::invalidateBibinfoCache() const
2272 d->bibinfo_cache_valid_ = false;
2273 d->cite_labels_valid_ = false;
2274 // also invalidate the cache for the parent buffer
2275 Buffer const * const pbuf = d->parent();
2277 pbuf->invalidateBibinfoCache();
2281 void Buffer::invalidateBibfileCache() const
2283 d->bibfile_cache_valid_ = false;
2284 d->bibinfo_cache_valid_ = false;
2285 d->cite_labels_valid_ = false;
2286 // also invalidate the cache for the parent buffer
2287 Buffer const * const pbuf = d->parent();
2289 pbuf->invalidateBibfileCache();
2293 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2295 // FIXME This is probably unnecessary, given where we call this.
2296 // If this is a child document, use the master's cache instead.
2297 Buffer const * const pbuf = masterBuffer();
2298 if (pbuf != this && scope != UpdateChildOnly)
2299 return pbuf->getBibfilesCache();
2301 if (!d->bibfile_cache_valid_)
2302 this->updateBibfilesCache(scope);
2304 return d->bibfiles_cache_;
2308 BiblioInfo const & Buffer::masterBibInfo() const
2310 Buffer const * const tmp = masterBuffer();
2312 return tmp->masterBibInfo();
2317 void Buffer::checkIfBibInfoCacheIsValid() const
2319 // use the master's cache
2320 Buffer const * const tmp = masterBuffer();
2322 tmp->checkIfBibInfoCacheIsValid();
2326 // compare the cached timestamps with the actual ones.
2327 FileNameList const & bibfiles_cache = getBibfilesCache();
2328 FileNameList::const_iterator ei = bibfiles_cache.begin();
2329 FileNameList::const_iterator en = bibfiles_cache.end();
2330 for (; ei != en; ++ ei) {
2331 time_t lastw = ei->lastModified();
2332 time_t prevw = d->bibfile_status_[*ei];
2333 if (lastw != prevw) {
2334 d->bibinfo_cache_valid_ = false;
2335 d->cite_labels_valid_ = false;
2336 d->bibfile_status_[*ei] = lastw;
2342 void Buffer::reloadBibInfoCache() const
2344 // use the master's cache
2345 Buffer const * const tmp = masterBuffer();
2347 tmp->reloadBibInfoCache();
2351 checkIfBibInfoCacheIsValid();
2352 if (d->bibinfo_cache_valid_)
2355 d->bibinfo_.clear();
2357 d->bibinfo_cache_valid_ = true;
2361 void Buffer::collectBibKeys() const
2363 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2364 it->collectBibKeys(it);
2368 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2370 Buffer const * tmp = masterBuffer();
2371 BiblioInfo & masterbi = (tmp == this) ?
2372 d->bibinfo_ : tmp->d->bibinfo_;
2373 masterbi.mergeBiblioInfo(bi);
2377 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2379 Buffer const * tmp = masterBuffer();
2380 BiblioInfo & masterbi = (tmp == this) ?
2381 d->bibinfo_ : tmp->d->bibinfo_;
2386 void Buffer::makeCitationLabels() const
2388 Buffer const * const master = masterBuffer();
2389 return d->bibinfo_.makeCitationLabels(*master);
2393 bool Buffer::citeLabelsValid() const
2395 return masterBuffer()->d->cite_labels_valid_;
2399 void Buffer::removeBiblioTempFiles() const
2401 // We remove files that contain LaTeX commands specific to the
2402 // particular bibliographic style being used, in order to avoid
2403 // LaTeX errors when we switch style.
2404 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2405 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2406 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2407 aux_file.removeFile();
2408 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2409 bbl_file.removeFile();
2410 // Also for the parent buffer
2411 Buffer const * const pbuf = parent();
2413 pbuf->removeBiblioTempFiles();
2417 bool Buffer::isDepClean(string const & name) const
2419 DepClean::const_iterator const it = d->dep_clean.find(name);
2420 if (it == d->dep_clean.end())
2426 void Buffer::markDepClean(string const & name)
2428 d->dep_clean[name] = true;
2432 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2435 // FIXME? if there is an Buffer LFUN that can be dispatched even
2436 // if internal, put a switch '(cmd.action)' here.
2442 switch (cmd.action()) {
2444 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2445 flag.setOnOff(isReadonly());
2448 // FIXME: There is need for a command-line import.
2449 //case LFUN_BUFFER_IMPORT:
2451 case LFUN_BUFFER_AUTO_SAVE:
2454 case LFUN_BUFFER_EXPORT_CUSTOM:
2455 // FIXME: Nothing to check here?
2458 case LFUN_BUFFER_EXPORT: {
2459 docstring const arg = cmd.argument();
2460 if (arg == "custom") {
2464 string format = to_utf8(arg);
2465 size_t pos = format.find(' ');
2466 if (pos != string::npos)
2467 format = format.substr(0, pos);
2468 enable = params().isExportable(format);
2470 flag.message(bformat(
2471 _("Don't know how to export to format: %1$s"), arg));
2475 case LFUN_BUFFER_CHKTEX:
2476 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2479 case LFUN_BUILD_PROGRAM:
2480 enable = params().isExportable("program");
2483 case LFUN_BRANCH_ACTIVATE:
2484 case LFUN_BRANCH_DEACTIVATE:
2485 case LFUN_BRANCH_MASTER_ACTIVATE:
2486 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2487 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2488 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2489 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2490 : params().branchlist();
2491 docstring const branchName = cmd.argument();
2492 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2496 case LFUN_BRANCH_ADD:
2497 case LFUN_BRANCHES_RENAME:
2498 // if no Buffer is present, then of course we won't be called!
2501 case LFUN_BUFFER_LANGUAGE:
2502 enable = !isReadonly();
2505 case LFUN_BUFFER_VIEW_CACHE:
2506 (d->preview_file_).refresh();
2507 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2510 case LFUN_CHANGES_TRACK:
2511 flag.setEnabled(true);
2512 flag.setOnOff(params().track_changes);
2515 case LFUN_CHANGES_OUTPUT:
2516 flag.setEnabled(true);
2517 flag.setOnOff(params().output_changes);
2520 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2521 flag.setOnOff(params().compressed);
2525 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2526 flag.setOnOff(params().output_sync);
2533 flag.setEnabled(enable);
2538 void Buffer::dispatch(string const & command, DispatchResult & result)
2540 return dispatch(lyxaction.lookupFunc(command), result);
2544 // NOTE We can end up here even if we have no GUI, because we are called
2545 // by LyX::exec to handled command-line requests. So we may need to check
2546 // whether we have a GUI or not. The boolean use_gui holds this information.
2547 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2550 // FIXME? if there is an Buffer LFUN that can be dispatched even
2551 // if internal, put a switch '(cmd.action())' here.
2552 dr.dispatched(false);
2555 string const argument = to_utf8(func.argument());
2556 // We'll set this back to false if need be.
2557 bool dispatched = true;
2558 undo().beginUndoGroup();
2560 switch (func.action()) {
2561 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2562 if (lyxvc().inUse()) {
2563 string log = lyxvc().toggleReadOnly();
2568 setReadonly(!isReadonly());
2571 case LFUN_BUFFER_EXPORT: {
2572 ExportStatus const status = doExport(argument, false);
2573 dr.setError(status != ExportSuccess);
2574 if (status != ExportSuccess)
2575 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2580 case LFUN_BUILD_PROGRAM: {
2581 ExportStatus const status = doExport("program", true);
2582 dr.setError(status != ExportSuccess);
2583 if (status != ExportSuccess)
2584 dr.setMessage(_("Error generating literate programming code."));
2588 case LFUN_BUFFER_CHKTEX:
2592 case LFUN_BUFFER_EXPORT_CUSTOM: {
2594 string command = split(argument, format_name, ' ');
2595 Format const * format = formats.getFormat(format_name);
2597 lyxerr << "Format \"" << format_name
2598 << "\" not recognized!"
2603 // The name of the file created by the conversion process
2606 // Output to filename
2607 if (format->name() == "lyx") {
2608 string const latexname = latexName(false);
2609 filename = changeExtension(latexname,
2610 format->extension());
2611 filename = addName(temppath(), filename);
2613 if (!writeFile(FileName(filename)))
2617 doExport(format_name, true, filename);
2620 // Substitute $$FName for filename
2621 if (!contains(command, "$$FName"))
2622 command = "( " + command + " ) < $$FName";
2623 command = subst(command, "$$FName", filename);
2625 // Execute the command in the background
2627 call.startscript(Systemcall::DontWait, command,
2628 filePath(), layoutPos());
2632 // FIXME: There is need for a command-line import.
2634 case LFUN_BUFFER_IMPORT:
2639 case LFUN_BUFFER_AUTO_SAVE:
2641 resetAutosaveTimers();
2644 case LFUN_BRANCH_ACTIVATE:
2645 case LFUN_BRANCH_DEACTIVATE:
2646 case LFUN_BRANCH_MASTER_ACTIVATE:
2647 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2648 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2649 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2650 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2653 docstring const branch_name = func.argument();
2654 // the case without a branch name is handled elsewhere
2655 if (branch_name.empty()) {
2659 Branch * branch = buf->params().branchlist().find(branch_name);
2661 LYXERR0("Branch " << branch_name << " does not exist.");
2663 docstring const msg =
2664 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2668 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2669 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2670 if (branch->isSelected() != activate) {
2671 buf->undo().recordUndoBufferParams(CursorData());
2672 branch->setSelected(activate);
2674 dr.screenUpdate(Update::Force);
2675 dr.forceBufferUpdate();
2680 case LFUN_BRANCH_ADD: {
2681 docstring branch_name = func.argument();
2682 if (branch_name.empty()) {
2686 BranchList & branch_list = params().branchlist();
2687 vector<docstring> const branches =
2688 getVectorFromString(branch_name, branch_list.separator());
2690 for (vector<docstring>::const_iterator it = branches.begin();
2691 it != branches.end(); ++it) {
2693 Branch * branch = branch_list.find(branch_name);
2695 LYXERR0("Branch " << branch_name << " already exists.");
2699 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2701 undo().recordUndoBufferParams(CursorData());
2702 branch_list.add(branch_name);
2703 branch = branch_list.find(branch_name);
2704 string const x11hexname = X11hexname(branch->color());
2705 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2706 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2708 dr.screenUpdate(Update::Force);
2716 case LFUN_BRANCHES_RENAME: {
2717 if (func.argument().empty())
2720 docstring const oldname = from_utf8(func.getArg(0));
2721 docstring const newname = from_utf8(func.getArg(1));
2722 InsetIterator it = inset_iterator_begin(inset());
2723 InsetIterator const end = inset_iterator_end(inset());
2724 bool success = false;
2725 for (; it != end; ++it) {
2726 if (it->lyxCode() == BRANCH_CODE) {
2727 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2728 if (ins.branch() == oldname) {
2729 undo().recordUndo(CursorData(it));
2730 ins.rename(newname);
2735 if (it->lyxCode() == INCLUDE_CODE) {
2736 // get buffer of external file
2737 InsetInclude const & ins =
2738 static_cast<InsetInclude const &>(*it);
2739 Buffer * child = ins.getChildBuffer();
2742 child->dispatch(func, dr);
2747 dr.screenUpdate(Update::Force);
2748 dr.forceBufferUpdate();
2753 case LFUN_BUFFER_VIEW_CACHE:
2754 if (!formats.view(*this, d->preview_file_,
2755 d->preview_format_))
2756 dr.setMessage(_("Error viewing the output file."));
2759 case LFUN_CHANGES_TRACK:
2760 undo().recordUndoBufferParams(CursorData());
2761 params().track_changes = !params().track_changes;
2764 case LFUN_CHANGES_OUTPUT:
2765 undo().recordUndoBufferParams(CursorData());
2766 params().output_changes = !params().output_changes;
2767 if (params().output_changes) {
2768 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2769 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2770 LaTeXFeatures::isAvailable("xcolor");
2772 if (!dvipost && !xcolorulem) {
2773 Alert::warning(_("Changes not shown in LaTeX output"),
2774 _("Changes will not be highlighted in LaTeX output, "
2775 "because neither dvipost nor xcolor/ulem are installed.\n"
2776 "Please install these packages or redefine "
2777 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2778 } else if (!xcolorulem) {
2779 Alert::warning(_("Changes not shown in LaTeX output"),
2780 _("Changes will not be highlighted in LaTeX output "
2781 "when using pdflatex, because xcolor and ulem are not installed.\n"
2782 "Please install both packages or redefine "
2783 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2788 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2789 // turn compression on/off
2790 undo().recordUndoBufferParams(CursorData());
2791 params().compressed = !params().compressed;
2794 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2795 undo().recordUndoBufferParams(CursorData());
2796 params().output_sync = !params().output_sync;
2803 dr.dispatched(dispatched);
2804 undo().endUndoGroup();
2808 void Buffer::changeLanguage(Language const * from, Language const * to)
2810 LASSERT(from, return);
2811 LASSERT(to, return);
2813 for_each(par_iterator_begin(),
2815 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2819 bool Buffer::isMultiLingual() const
2821 ParConstIterator end = par_iterator_end();
2822 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2823 if (it->isMultiLingual(params()))
2830 std::set<Language const *> Buffer::getLanguages() const
2832 std::set<Language const *> languages;
2833 getLanguages(languages);
2838 void Buffer::getLanguages(std::set<Language const *> & languages) const
2840 ParConstIterator end = par_iterator_end();
2841 // add the buffer language, even if it's not actively used
2842 languages.insert(language());
2843 // iterate over the paragraphs
2844 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2845 it->getLanguages(languages);
2847 ListOfBuffers clist = getDescendents();
2848 ListOfBuffers::const_iterator cit = clist.begin();
2849 ListOfBuffers::const_iterator const cen = clist.end();
2850 for (; cit != cen; ++cit)
2851 (*cit)->getLanguages(languages);
2855 DocIterator Buffer::getParFromID(int const id) const
2857 Buffer * buf = const_cast<Buffer *>(this);
2859 // John says this is called with id == -1 from undo
2860 lyxerr << "getParFromID(), id: " << id << endl;
2861 return doc_iterator_end(buf);
2864 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2865 if (it.paragraph().id() == id)
2868 return doc_iterator_end(buf);
2872 bool Buffer::hasParWithID(int const id) const
2874 return !getParFromID(id).atEnd();
2878 ParIterator Buffer::par_iterator_begin()
2880 return ParIterator(doc_iterator_begin(this));
2884 ParIterator Buffer::par_iterator_end()
2886 return ParIterator(doc_iterator_end(this));
2890 ParConstIterator Buffer::par_iterator_begin() const
2892 return ParConstIterator(doc_iterator_begin(this));
2896 ParConstIterator Buffer::par_iterator_end() const
2898 return ParConstIterator(doc_iterator_end(this));
2902 Language const * Buffer::language() const
2904 return params().language;
2908 docstring const Buffer::B_(string const & l10n) const
2910 return params().B_(l10n);
2914 bool Buffer::isClean() const
2916 return d->lyx_clean;
2920 bool Buffer::isExternallyModified(CheckMethod method) const
2922 LASSERT(d->filename.exists(), return false);
2923 // if method == timestamp, check timestamp before checksum
2924 return (method == checksum_method
2925 || d->timestamp_ != d->filename.lastModified())
2926 && d->checksum_ != d->filename.checksum();
2930 void Buffer::saveCheckSum() const
2932 FileName const & file = d->filename;
2935 if (file.exists()) {
2936 d->timestamp_ = file.lastModified();
2937 d->checksum_ = file.checksum();
2939 // in the case of save to a new file.
2946 void Buffer::markClean() const
2948 if (!d->lyx_clean) {
2949 d->lyx_clean = true;
2952 // if the .lyx file has been saved, we don't need an
2954 d->bak_clean = true;
2955 d->undo_.markDirty();
2959 void Buffer::setUnnamed(bool flag)
2965 bool Buffer::isUnnamed() const
2972 /// Don't check unnamed, here: isInternal() is used in
2973 /// newBuffer(), where the unnamed flag has not been set by anyone
2974 /// yet. Also, for an internal buffer, there should be no need for
2975 /// retrieving fileName() nor for checking if it is unnamed or not.
2976 bool Buffer::isInternal() const
2978 return d->internal_buffer;
2982 void Buffer::setInternal(bool flag)
2984 d->internal_buffer = flag;
2988 void Buffer::markDirty()
2991 d->lyx_clean = false;
2994 d->bak_clean = false;
2996 DepClean::iterator it = d->dep_clean.begin();
2997 DepClean::const_iterator const end = d->dep_clean.end();
2999 for (; it != end; ++it)
3004 FileName Buffer::fileName() const
3010 string Buffer::absFileName() const
3012 return d->filename.absFileName();
3016 string Buffer::filePath() const
3018 string const abs = d->filename.onlyPath().absFileName();
3021 int last = abs.length() - 1;
3023 return abs[last] == '/' ? abs : abs + '/';
3027 string Buffer::originFilePath() const
3029 if (FileName::isAbsolute(params().origin))
3030 return params().origin;
3036 string Buffer::layoutPos() const
3038 return d->layout_position;
3042 void Buffer::setLayoutPos(string const & path)
3045 d->layout_position.clear();
3049 LATTEST(FileName::isAbsolute(path));
3051 d->layout_position =
3052 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3054 if (d->layout_position.empty())
3055 d->layout_position = ".";
3059 bool Buffer::isReadonly() const
3061 return d->read_only;
3065 void Buffer::setParent(Buffer const * buffer)
3067 // Avoids recursive include.
3068 d->setParent(buffer == this ? 0 : buffer);
3073 Buffer const * Buffer::parent() const
3079 ListOfBuffers Buffer::allRelatives() const
3081 ListOfBuffers lb = masterBuffer()->getDescendents();
3082 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3087 Buffer const * Buffer::masterBuffer() const
3089 // FIXME Should be make sure we are not in some kind
3090 // of recursive include? A -> B -> A will crash this.
3091 Buffer const * const pbuf = d->parent();
3095 return pbuf->masterBuffer();
3099 bool Buffer::isChild(Buffer * child) const
3101 return d->children_positions.find(child) != d->children_positions.end();
3105 DocIterator Buffer::firstChildPosition(Buffer const * child)
3107 Impl::BufferPositionMap::iterator it;
3108 it = d->children_positions.find(child);
3109 if (it == d->children_positions.end())
3110 return DocIterator(this);
3115 bool Buffer::hasChildren() const
3117 return !d->children_positions.empty();
3121 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3123 // loop over children
3124 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3125 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3126 for (; it != end; ++it) {
3127 Buffer * child = const_cast<Buffer *>(it->first);
3129 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3130 if (bit != clist.end())
3132 clist.push_back(child);
3134 // there might be grandchildren
3135 child->collectChildren(clist, true);
3140 ListOfBuffers Buffer::getChildren() const
3143 collectChildren(v, false);
3144 // Make sure we have not included ourselves.
3145 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3146 if (bit != v.end()) {
3147 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3154 ListOfBuffers Buffer::getDescendents() const
3157 collectChildren(v, true);
3158 // Make sure we have not included ourselves.
3159 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3160 if (bit != v.end()) {
3161 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3168 template<typename M>
3169 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3174 typename M::const_iterator it = m.lower_bound(x);
3175 if (it == m.begin())
3183 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3184 DocIterator const & pos) const
3186 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3188 // if paragraphs have no macro context set, pos will be empty
3192 // we haven't found anything yet
3193 DocIterator bestPos = owner_->par_iterator_begin();
3194 MacroData const * bestData = 0;
3196 // find macro definitions for name
3197 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3198 if (nameIt != macros.end()) {
3199 // find last definition in front of pos or at pos itself
3200 PositionScopeMacroMap::const_iterator it
3201 = greatest_below(nameIt->second, pos);
3202 if (it != nameIt->second.end()) {
3204 // scope ends behind pos?
3205 if (pos < it->second.scope) {
3206 // Looks good, remember this. If there
3207 // is no external macro behind this,
3208 // we found the right one already.
3209 bestPos = it->first;
3210 bestData = &it->second.macro;
3214 // try previous macro if there is one
3215 if (it == nameIt->second.begin())
3222 // find macros in included files
3223 PositionScopeBufferMap::const_iterator it
3224 = greatest_below(position_to_children, pos);
3225 if (it == position_to_children.end())
3226 // no children before
3230 // do we know something better (i.e. later) already?
3231 if (it->first < bestPos )
3234 // scope ends behind pos?
3235 if (pos < it->second.scope
3236 && (cloned_buffer_ ||
3237 theBufferList().isLoaded(it->second.buffer))) {
3238 // look for macro in external file
3240 MacroData const * data
3241 = it->second.buffer->getMacro(name, false);
3244 bestPos = it->first;
3250 // try previous file if there is one
3251 if (it == position_to_children.begin())
3256 // return the best macro we have found
3261 MacroData const * Buffer::getMacro(docstring const & name,
3262 DocIterator const & pos, bool global) const
3267 // query buffer macros
3268 MacroData const * data = d->getBufferMacro(name, pos);
3272 // If there is a master buffer, query that
3273 Buffer const * const pbuf = d->parent();
3275 d->macro_lock = true;
3276 MacroData const * macro = pbuf->getMacro(
3277 name, *this, false);
3278 d->macro_lock = false;
3284 data = MacroTable::globalMacros().get(name);
3293 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3295 // set scope end behind the last paragraph
3296 DocIterator scope = par_iterator_begin();
3297 scope.pit() = scope.lastpit() + 1;
3299 return getMacro(name, scope, global);
3303 MacroData const * Buffer::getMacro(docstring const & name,
3304 Buffer const & child, bool global) const
3306 // look where the child buffer is included first
3307 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3308 if (it == d->children_positions.end())
3311 // check for macros at the inclusion position
3312 return getMacro(name, it->second, global);
3316 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3318 pit_type const lastpit = it.lastpit();
3320 // look for macros in each paragraph
3321 while (it.pit() <= lastpit) {
3322 Paragraph & par = it.paragraph();
3324 // iterate over the insets of the current paragraph
3325 InsetList const & insets = par.insetList();
3326 InsetList::const_iterator iit = insets.begin();
3327 InsetList::const_iterator end = insets.end();
3328 for (; iit != end; ++iit) {
3329 it.pos() = iit->pos;
3331 // is it a nested text inset?
3332 if (iit->inset->asInsetText()) {
3333 // Inset needs its own scope?
3334 InsetText const * itext = iit->inset->asInsetText();
3335 bool newScope = itext->isMacroScope();
3337 // scope which ends just behind the inset
3338 DocIterator insetScope = it;
3341 // collect macros in inset
3342 it.push_back(CursorSlice(*iit->inset));
3343 updateMacros(it, newScope ? insetScope : scope);
3348 if (iit->inset->asInsetTabular()) {
3349 CursorSlice slice(*iit->inset);
3350 size_t const numcells = slice.nargs();
3351 for (; slice.idx() < numcells; slice.forwardIdx()) {
3352 it.push_back(slice);
3353 updateMacros(it, scope);
3359 // is it an external file?
3360 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3361 // get buffer of external file
3362 InsetInclude const & inset =
3363 static_cast<InsetInclude const &>(*iit->inset);
3365 Buffer * child = inset.getChildBuffer();
3370 // register its position, but only when it is
3371 // included first in the buffer
3372 if (children_positions.find(child) ==
3373 children_positions.end())
3374 children_positions[child] = it;
3376 // register child with its scope
3377 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3381 InsetMath * im = iit->inset->asInsetMath();
3382 if (doing_export && im) {
3383 InsetMathHull * hull = im->asHullInset();
3385 hull->recordLocation(it);
3388 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3392 MathMacroTemplate & macroTemplate =
3393 *iit->inset->asInsetMath()->asMacroTemplate();
3394 MacroContext mc(owner_, it);
3395 macroTemplate.updateToContext(mc);
3398 bool valid = macroTemplate.validMacro();
3399 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3400 // then the BufferView's cursor will be invalid in
3401 // some cases which leads to crashes.
3406 // FIXME (Abdel), I don't understand why we pass 'it' here
3407 // instead of 'macroTemplate' defined above... is this correct?
3408 macros[macroTemplate.name()][it] =
3409 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3419 void Buffer::updateMacros() const
3424 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3426 // start with empty table
3428 d->children_positions.clear();
3429 d->position_to_children.clear();
3431 // Iterate over buffer, starting with first paragraph
3432 // The scope must be bigger than any lookup DocIterator
3433 // later. For the global lookup, lastpit+1 is used, hence
3434 // we use lastpit+2 here.
3435 DocIterator it = par_iterator_begin();
3436 DocIterator outerScope = it;
3437 outerScope.pit() = outerScope.lastpit() + 2;
3438 d->updateMacros(it, outerScope);
3442 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3444 InsetIterator it = inset_iterator_begin(inset());
3445 InsetIterator const end = inset_iterator_end(inset());
3446 for (; it != end; ++it) {
3447 if (it->lyxCode() == BRANCH_CODE) {
3448 InsetBranch & br = static_cast<InsetBranch &>(*it);
3449 docstring const name = br.branch();
3450 if (!from_master && !params().branchlist().find(name))
3451 result.push_back(name);
3452 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3453 result.push_back(name);
3456 if (it->lyxCode() == INCLUDE_CODE) {
3457 // get buffer of external file
3458 InsetInclude const & ins =
3459 static_cast<InsetInclude const &>(*it);
3460 Buffer * child = ins.getChildBuffer();
3463 child->getUsedBranches(result, true);
3466 // remove duplicates
3471 void Buffer::updateMacroInstances(UpdateType utype) const
3473 LYXERR(Debug::MACROS, "updateMacroInstances for "
3474 << d->filename.onlyFileName());
3475 DocIterator it = doc_iterator_begin(this);
3477 DocIterator const end = doc_iterator_end(this);
3478 for (; it != end; it.forwardInset()) {
3479 // look for MathData cells in InsetMathNest insets
3480 InsetMath * minset = it.nextInset()->asInsetMath();
3484 // update macro in all cells of the InsetMathNest
3485 DocIterator::idx_type n = minset->nargs();
3486 MacroContext mc = MacroContext(this, it);
3487 for (DocIterator::idx_type i = 0; i < n; ++i) {
3488 MathData & data = minset->cell(i);
3489 data.updateMacros(0, mc, utype);
3495 void Buffer::listMacroNames(MacroNameSet & macros) const
3500 d->macro_lock = true;
3502 // loop over macro names
3503 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3504 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3505 for (; nameIt != nameEnd; ++nameIt)
3506 macros.insert(nameIt->first);
3508 // loop over children
3509 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3510 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3511 for (; it != end; ++it)
3512 it->first->listMacroNames(macros);
3515 Buffer const * const pbuf = d->parent();
3517 pbuf->listMacroNames(macros);
3519 d->macro_lock = false;
3523 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3525 Buffer const * const pbuf = d->parent();
3530 pbuf->listMacroNames(names);
3533 MacroNameSet::iterator it = names.begin();
3534 MacroNameSet::iterator end = names.end();
3535 for (; it != end; ++it) {
3537 MacroData const * data =
3538 pbuf->getMacro(*it, *this, false);
3540 macros.insert(data);
3542 // we cannot access the original MathMacroTemplate anymore
3543 // here to calls validate method. So we do its work here manually.
3544 // FIXME: somehow make the template accessible here.
3545 if (data->optionals() > 0)
3546 features.require("xargs");
3552 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3555 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3557 RefCache::iterator it = d->ref_cache_.find(label);
3558 if (it != d->ref_cache_.end())
3559 return it->second.second;
3561 static InsetLabel const * dummy_il = 0;
3562 static References const dummy_refs = References();
3563 it = d->ref_cache_.insert(
3564 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3565 return it->second.second;
3569 Buffer::References const & Buffer::references(docstring const & label) const
3571 return const_cast<Buffer *>(this)->getReferenceCache(label);
3575 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3577 References & refs = getReferenceCache(label);
3578 refs.push_back(make_pair(inset, it));
3582 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3584 masterBuffer()->d->ref_cache_[label].first = il;
3588 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3590 return masterBuffer()->d->ref_cache_[label].first;
3594 void Buffer::clearReferenceCache() const
3597 d->ref_cache_.clear();
3601 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3603 //FIXME: This does not work for child documents yet.
3604 reloadBibInfoCache();
3606 // Check if the label 'from' appears more than once
3607 BiblioInfo const & keys = masterBibInfo();
3608 BiblioInfo::const_iterator bit = keys.begin();
3609 BiblioInfo::const_iterator bend = keys.end();
3610 vector<docstring> labels;
3612 for (; bit != bend; ++bit)
3614 labels.push_back(bit->first);
3616 if (count(labels.begin(), labels.end(), from) > 1)
3619 string const paramName = "key";
3620 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3621 if (it->lyxCode() != CITE_CODE)
3623 InsetCommand * inset = it->asInsetCommand();
3624 docstring const oldValue = inset->getParam(paramName);
3625 if (oldValue == from)
3626 inset->setParam(paramName, to);
3630 // returns NULL if id-to-row conversion is unsupported
3631 auto_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3632 pit_type par_begin, pit_type par_end,
3633 OutputWhat output, bool master) const
3635 auto_ptr<TexRow> texrow(NULL);
3636 OutputParams runparams(¶ms().encoding());
3637 runparams.nice = true;
3638 runparams.flavor = params().getOutputFlavor(format);
3639 runparams.linelen = lyxrc.plaintext_linelen;
3640 // No side effect of file copying and image conversion
3641 runparams.dryrun = true;
3643 if (output == CurrentParagraph) {
3644 runparams.par_begin = par_begin;
3645 runparams.par_end = par_end;
3646 if (par_begin + 1 == par_end) {
3648 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3652 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3653 convert<docstring>(par_begin),
3654 convert<docstring>(par_end - 1))
3657 // output paragraphs
3658 if (runparams.flavor == OutputParams::LYX) {
3659 Paragraph const & par = text().paragraphs()[par_begin];
3661 depth_type dt = par.getDepth();
3662 par.write(ods, params(), dt);
3663 os << from_utf8(ods.str());
3664 } else if (runparams.flavor == OutputParams::HTML) {
3666 setMathFlavor(runparams);
3667 xhtmlParagraphs(text(), *this, xs, runparams);
3668 } else if (runparams.flavor == OutputParams::TEXT) {
3670 // FIXME Handles only one paragraph, unlike the others.
3671 // Probably should have some routine with a signature like them.
3672 writePlaintextParagraph(*this,
3673 text().paragraphs()[par_begin], os, runparams, dummy);
3674 } else if (params().isDocBook()) {
3675 docbookParagraphs(text(), *this, os, runparams);
3677 // If we are previewing a paragraph, even if this is the
3678 // child of some other buffer, let's cut the link here,
3679 // so that no concurring settings from the master
3680 // (e.g. branch state) interfere (see #8101).
3682 d->ignore_parent = true;
3683 // We need to validate the Buffer params' features here
3684 // in order to know if we should output polyglossia
3685 // macros (instead of babel macros)
3686 LaTeXFeatures features(*this, params(), runparams);
3687 params().validate(features);
3688 runparams.use_polyglossia = features.usePolyglossia();
3689 texrow.reset(new TexRow());
3692 // latex or literate
3693 otexstream ots(os, *texrow);
3696 latexParagraphs(*this, text(), ots, runparams);
3699 // Restore the parenthood
3701 d->ignore_parent = false;
3705 if (output == FullSource)
3706 os << _("Preview source code");
3707 else if (output == OnlyPreamble)
3708 os << _("Preview preamble");
3709 else if (output == OnlyBody)
3710 os << _("Preview body");
3712 if (runparams.flavor == OutputParams::LYX) {
3714 if (output == FullSource)
3716 else if (output == OnlyPreamble)
3717 params().writeFile(ods, this);
3718 else if (output == OnlyBody)
3720 os << from_utf8(ods.str());
3721 } else if (runparams.flavor == OutputParams::HTML) {
3722 writeLyXHTMLSource(os, runparams, output);
3723 } else if (runparams.flavor == OutputParams::TEXT) {
3724 if (output == OnlyPreamble) {
3725 os << "% "<< _("Plain text does not have a preamble.");
3727 writePlaintextFile(*this, os, runparams);
3728 } else if (params().isDocBook()) {
3729 writeDocBookSource(os, absFileName(), runparams, output);
3731 // latex or literate
3732 texrow.reset(new TexRow());
3735 otexstream ots(os, *texrow);
3737 runparams.is_child = true;
3738 writeLaTeXSource(ots, string(), runparams, output);
3746 ErrorList & Buffer::errorList(string const & type) const
3748 return d->errorLists[type];
3752 void Buffer::updateTocItem(std::string const & type,
3753 DocIterator const & dit) const
3756 d->gui_->updateTocItem(type, dit);
3760 void Buffer::structureChanged() const
3763 d->gui_->structureChanged();
3767 void Buffer::errors(string const & err, bool from_master) const
3770 d->gui_->errors(err, from_master);
3774 void Buffer::message(docstring const & msg) const
3777 d->gui_->message(msg);
3781 void Buffer::setBusy(bool on) const
3784 d->gui_->setBusy(on);
3788 void Buffer::updateTitles() const
3791 d->wa_->updateTitles();
3795 void Buffer::resetAutosaveTimers() const
3798 d->gui_->resetAutosaveTimers();
3802 bool Buffer::hasGuiDelegate() const
3808 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3817 class AutoSaveBuffer : public ForkedProcess {
3820 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3821 : buffer_(buffer), fname_(fname) {}
3823 virtual shared_ptr<ForkedProcess> clone() const
3825 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3830 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3831 from_utf8(fname_.absFileName())));
3832 return run(DontWait);
3836 virtual int generateChild();
3838 Buffer const & buffer_;
3843 int AutoSaveBuffer::generateChild()
3845 #if defined(__APPLE__)
3846 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3847 * We should use something else like threads.
3849 * Since I do not know how to determine at run time what is the OS X
3850 * version, I just disable forking altogether for now (JMarc)
3852 pid_t const pid = -1;
3854 // tmp_ret will be located (usually) in /tmp
3855 // will that be a problem?
3856 // Note that this calls ForkedCalls::fork(), so it's
3857 // ok cross-platform.
3858 pid_t const pid = fork();
3859 // If you want to debug the autosave
3860 // you should set pid to -1, and comment out the fork.
3861 if (pid != 0 && pid != -1)
3865 // pid = -1 signifies that lyx was unable
3866 // to fork. But we will do the save
3868 bool failed = false;
3869 TempFile tempfile("lyxautoXXXXXX.lyx");
3870 tempfile.setAutoRemove(false);
3871 FileName const tmp_ret = tempfile.name();
3872 if (!tmp_ret.empty()) {
3873 if (!buffer_.writeFile(tmp_ret))
3875 else if (!tmp_ret.moveTo(fname_))
3881 // failed to write/rename tmp_ret so try writing direct
3882 if (!buffer_.writeFile(fname_)) {
3883 // It is dangerous to do this in the child,
3884 // but safe in the parent, so...
3885 if (pid == -1) // emit message signal.
3886 buffer_.message(_("Autosave failed!"));
3890 if (pid == 0) // we are the child so...
3899 FileName Buffer::getEmergencyFileName() const
3901 return FileName(d->filename.absFileName() + ".emergency");
3905 FileName Buffer::getAutosaveFileName() const
3907 // if the document is unnamed try to save in the backup dir, else
3908 // in the default document path, and as a last try in the filePath,
3909 // which will most often be the temporary directory
3912 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3913 : lyxrc.backupdir_path;
3914 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3917 string const fname = "#" + d->filename.onlyFileName() + "#";
3919 return makeAbsPath(fname, fpath);
3923 void Buffer::removeAutosaveFile() const
3925 FileName const f = getAutosaveFileName();
3931 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3933 FileName const newauto = getAutosaveFileName();
3935 if (newauto != oldauto && oldauto.exists())
3936 if (!oldauto.moveTo(newauto))
3937 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3941 bool Buffer::autoSave() const
3943 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3944 if (buf->d->bak_clean || isReadonly())
3947 message(_("Autosaving current document..."));
3948 buf->d->bak_clean = true;
3950 FileName const fname = getAutosaveFileName();
3951 LASSERT(d->cloned_buffer_, return false);
3953 // If this buffer is cloned, we assume that
3954 // we are running in a separate thread already.
3955 TempFile tempfile("lyxautoXXXXXX.lyx");
3956 tempfile.setAutoRemove(false);
3957 FileName const tmp_ret = tempfile.name();
3958 if (!tmp_ret.empty()) {
3960 // assume successful write of tmp_ret
3961 if (tmp_ret.moveTo(fname))
3964 // failed to write/rename tmp_ret so try writing direct
3965 return writeFile(fname);
3969 void Buffer::setExportStatus(bool e) const
3971 d->doing_export = e;
3972 ListOfBuffers clist = getDescendents();
3973 ListOfBuffers::const_iterator cit = clist.begin();
3974 ListOfBuffers::const_iterator const cen = clist.end();
3975 for (; cit != cen; ++cit)
3976 (*cit)->d->doing_export = e;
3980 bool Buffer::isExporting() const
3982 return d->doing_export;
3986 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3990 return doExport(target, put_in_tempdir, result_file);
3993 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3994 string & result_file) const
3996 bool const update_unincluded =
3997 params().maintain_unincluded_children
3998 && !params().getIncludedChildren().empty();
4000 // (1) export with all included children (omit \includeonly)
4001 if (update_unincluded) {
4002 ExportStatus const status =
4003 doExport(target, put_in_tempdir, true, result_file);
4004 if (status != ExportSuccess)
4007 // (2) export with included children only
4008 return doExport(target, put_in_tempdir, false, result_file);
4012 void Buffer::setMathFlavor(OutputParams & op) const
4014 switch (params().html_math_output) {
4015 case BufferParams::MathML:
4016 op.math_flavor = OutputParams::MathAsMathML;
4018 case BufferParams::HTML:
4019 op.math_flavor = OutputParams::MathAsHTML;
4021 case BufferParams::Images:
4022 op.math_flavor = OutputParams::MathAsImages;
4024 case BufferParams::LaTeX:
4025 op.math_flavor = OutputParams::MathAsLaTeX;
4031 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4032 bool includeall, string & result_file) const
4034 LYXERR(Debug::FILES, "target=" << target);
4035 OutputParams runparams(¶ms().encoding());
4036 string format = target;
4037 string dest_filename;
4038 size_t pos = target.find(' ');
4039 if (pos != string::npos) {
4040 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4041 format = target.substr(0, pos);
4042 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4043 FileName(dest_filename).onlyPath().createPath();
4044 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4046 MarkAsExporting exporting(this);
4047 string backend_format;
4048 runparams.flavor = OutputParams::LATEX;
4049 runparams.linelen = lyxrc.plaintext_linelen;
4050 runparams.includeall = includeall;
4051 vector<string> backs = params().backends();
4052 Converters converters = theConverters();
4053 bool need_nice_file = false;
4054 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4055 // Get shortest path to format
4056 converters.buildGraph();
4057 Graph::EdgePath path;
4058 for (vector<string>::const_iterator it = backs.begin();
4059 it != backs.end(); ++it) {
4060 Graph::EdgePath p = converters.getPath(*it, format);
4061 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4062 backend_format = *it;
4067 if (!put_in_tempdir) {
4068 // Only show this alert if this is an export to a non-temporary
4069 // file (not for previewing).
4070 Alert::error(_("Couldn't export file"), bformat(
4071 _("No information for exporting the format %1$s."),
4072 formats.prettyName(format)));
4074 return ExportNoPathToFormat;
4076 runparams.flavor = converters.getFlavor(path, this);
4077 Graph::EdgePath::const_iterator it = path.begin();
4078 Graph::EdgePath::const_iterator en = path.end();
4079 for (; it != en; ++it)
4080 if (theConverters().get(*it).nice()) {
4081 need_nice_file = true;
4086 backend_format = format;
4087 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4088 // FIXME: Don't hardcode format names here, but use a flag
4089 if (backend_format == "pdflatex")
4090 runparams.flavor = OutputParams::PDFLATEX;
4091 else if (backend_format == "luatex")
4092 runparams.flavor = OutputParams::LUATEX;
4093 else if (backend_format == "dviluatex")
4094 runparams.flavor = OutputParams::DVILUATEX;
4095 else if (backend_format == "xetex")
4096 runparams.flavor = OutputParams::XETEX;
4099 string filename = latexName(false);
4100 filename = addName(temppath(), filename);
4101 filename = changeExtension(filename,
4102 formats.extension(backend_format));
4103 LYXERR(Debug::FILES, "filename=" << filename);
4105 // Plain text backend
4106 if (backend_format == "text") {
4107 runparams.flavor = OutputParams::TEXT;
4108 writePlaintextFile(*this, FileName(filename), runparams);
4111 else if (backend_format == "xhtml") {
4112 runparams.flavor = OutputParams::HTML;
4113 setMathFlavor(runparams);
4114 makeLyXHTMLFile(FileName(filename), runparams);
4115 } else if (backend_format == "lyx")
4116 writeFile(FileName(filename));
4118 else if (params().isDocBook()) {
4119 runparams.nice = !put_in_tempdir;
4120 makeDocBookFile(FileName(filename), runparams);
4123 else if (backend_format == format || need_nice_file) {
4124 runparams.nice = true;
4125 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4126 if (d->cloned_buffer_)
4127 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4130 } else if (!lyxrc.tex_allows_spaces
4131 && contains(filePath(), ' ')) {
4132 Alert::error(_("File name error"),
4133 _("The directory path to the document cannot contain spaces."));
4134 return ExportTexPathHasSpaces;
4136 runparams.nice = false;
4137 bool const success = makeLaTeXFile(
4138 FileName(filename), filePath(), runparams);
4139 if (d->cloned_buffer_)
4140 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4145 string const error_type = (format == "program")
4146 ? "Build" : params().bufferFormat();
4147 ErrorList & error_list = d->errorLists[error_type];
4148 string const ext = formats.extension(format);
4149 FileName const tmp_result_file(changeExtension(filename, ext));
4150 bool const success = converters.convert(this, FileName(filename),
4151 tmp_result_file, FileName(absFileName()), backend_format, format,
4154 // Emit the signal to show the error list or copy it back to the
4155 // cloned Buffer so that it can be emitted afterwards.
4156 if (format != backend_format) {
4157 if (runparams.silent)
4159 else if (d->cloned_buffer_)
4160 d->cloned_buffer_->d->errorLists[error_type] =
4161 d->errorLists[error_type];
4164 // also to the children, in case of master-buffer-view
4165 ListOfBuffers clist = getDescendents();
4166 ListOfBuffers::const_iterator cit = clist.begin();
4167 ListOfBuffers::const_iterator const cen = clist.end();
4168 for (; cit != cen; ++cit) {
4169 if (runparams.silent)
4170 (*cit)->d->errorLists[error_type].clear();
4171 else if (d->cloned_buffer_) {
4172 // Enable reverse search by copying back the
4173 // texrow object to the cloned buffer.
4174 // FIXME: this is not thread safe.
4175 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4176 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4177 (*cit)->d->errorLists[error_type];
4179 (*cit)->errors(error_type, true);
4183 if (d->cloned_buffer_) {
4184 // Enable reverse dvi or pdf to work by copying back the texrow
4185 // object to the cloned buffer.
4186 // FIXME: There is a possibility of concurrent access to texrow
4187 // here from the main GUI thread that should be securized.
4188 d->cloned_buffer_->d->texrow = d->texrow;
4189 string const error_type = params().bufferFormat();
4190 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4194 if (put_in_tempdir) {
4195 result_file = tmp_result_file.absFileName();
4196 return success ? ExportSuccess : ExportConverterError;
4199 if (dest_filename.empty())
4200 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4202 result_file = dest_filename;
4203 // We need to copy referenced files (e. g. included graphics
4204 // if format == "dvi") to the result dir.
4205 vector<ExportedFile> const files =
4206 runparams.exportdata->externalFiles(format);
4207 string const dest = runparams.export_folder.empty() ?
4208 onlyPath(result_file) : runparams.export_folder;
4209 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4210 : force_overwrite == ALL_FILES;
4211 CopyStatus status = use_force ? FORCE : SUCCESS;
4213 vector<ExportedFile>::const_iterator it = files.begin();
4214 vector<ExportedFile>::const_iterator const en = files.end();
4215 for (; it != en && status != CANCEL; ++it) {
4216 string const fmt = formats.getFormatFromFile(it->sourceName);
4217 string fixedName = it->exportName;
4218 if (!runparams.export_folder.empty()) {
4219 // Relative pathnames starting with ../ will be sanitized
4220 // if exporting to a different folder
4221 while (fixedName.substr(0, 3) == "../")
4222 fixedName = fixedName.substr(3, fixedName.length() - 3);
4224 FileName fixedFileName = makeAbsPath(fixedName, dest);
4225 fixedFileName.onlyPath().createPath();
4226 status = copyFile(fmt, it->sourceName,
4228 it->exportName, status == FORCE,
4229 runparams.export_folder.empty());
4232 if (status == CANCEL) {
4233 message(_("Document export cancelled."));
4234 return ExportCancel;
4237 if (tmp_result_file.exists()) {
4238 // Finally copy the main file
4239 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4240 : force_overwrite != NO_FILES;
4241 if (status == SUCCESS && use_force)
4243 status = copyFile(format, tmp_result_file,
4244 FileName(result_file), result_file,
4246 if (status == CANCEL) {
4247 message(_("Document export cancelled."));
4248 return ExportCancel;
4250 message(bformat(_("Document exported as %1$s "
4252 formats.prettyName(format),
4253 makeDisplayPath(result_file)));
4256 // This must be a dummy converter like fax (bug 1888)
4257 message(bformat(_("Document exported as %1$s"),
4258 formats.prettyName(format)));
4261 return success ? ExportSuccess : ExportConverterError;
4265 Buffer::ExportStatus Buffer::preview(string const & format) const
4267 bool const update_unincluded =
4268 params().maintain_unincluded_children
4269 && !params().getIncludedChildren().empty();
4270 return preview(format, update_unincluded);
4274 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4276 MarkAsExporting exporting(this);
4278 // (1) export with all included children (omit \includeonly)
4280 ExportStatus const status = doExport(format, true, true, result_file);
4281 if (status != ExportSuccess)
4284 // (2) export with included children only
4285 ExportStatus const status = doExport(format, true, false, result_file);
4286 FileName const previewFile(result_file);
4288 LATTEST (isClone());
4289 d->cloned_buffer_->d->preview_file_ = previewFile;
4290 d->cloned_buffer_->d->preview_format_ = format;
4291 d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4293 if (status != ExportSuccess)
4295 if (previewFile.exists()) {
4296 if (!formats.view(*this, previewFile, format))
4297 return PreviewError;
4299 return PreviewSuccess;
4302 // Successful export but no output file?
4303 // Probably a bug in error detection.
4304 LATTEST (status != ExportSuccess);
4311 Buffer::ReadStatus Buffer::extractFromVC()
4313 bool const found = LyXVC::file_not_found_hook(d->filename);
4315 return ReadFileNotFound;
4316 if (!d->filename.isReadableFile())
4322 Buffer::ReadStatus Buffer::loadEmergency()
4324 FileName const emergencyFile = getEmergencyFileName();
4325 if (!emergencyFile.exists()
4326 || emergencyFile.lastModified() <= d->filename.lastModified())
4327 return ReadFileNotFound;
4329 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4330 docstring const text = bformat(_("An emergency save of the document "
4331 "%1$s exists.\n\nRecover emergency save?"), file);
4333 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4334 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4340 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4341 bool const success = (ret_llf == ReadSuccess);
4344 Alert::warning(_("File is read-only"),
4345 bformat(_("An emergency file is successfully loaded, "
4346 "but the original file %1$s is marked read-only. "
4347 "Please make sure to save the document as a different "
4348 "file."), from_utf8(d->filename.absFileName())));
4351 lyxvc().file_found_hook(d->filename);
4352 str = _("Document was successfully recovered.");
4354 str = _("Document was NOT successfully recovered.");
4355 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4356 makeDisplayPath(emergencyFile.absFileName()));
4358 int const del_emerg =
4359 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4360 _("&Remove"), _("&Keep"));
4361 if (del_emerg == 0) {
4362 emergencyFile.removeFile();
4364 Alert::warning(_("Emergency file deleted"),
4365 _("Do not forget to save your file now!"), true);
4367 return success ? ReadSuccess : ReadEmergencyFailure;
4370 int const del_emerg =
4371 Alert::prompt(_("Delete emergency file?"),
4372 _("Remove emergency file now?"), 1, 1,
4373 _("&Remove"), _("&Keep"));
4375 emergencyFile.removeFile();
4376 return ReadOriginal;
4386 Buffer::ReadStatus Buffer::loadAutosave()
4388 // Now check if autosave file is newer.
4389 FileName const autosaveFile = getAutosaveFileName();
4390 if (!autosaveFile.exists()
4391 || autosaveFile.lastModified() <= d->filename.lastModified())
4392 return ReadFileNotFound;
4394 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4395 docstring const text = bformat(_("The backup of the document %1$s "
4396 "is newer.\n\nLoad the backup instead?"), file);
4397 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4398 _("&Load backup"), _("Load &original"), _("&Cancel"));
4403 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4404 // the file is not saved if we load the autosave file.
4405 if (ret_llf == ReadSuccess) {
4407 Alert::warning(_("File is read-only"),
4408 bformat(_("A backup file is successfully loaded, "
4409 "but the original file %1$s is marked read-only. "
4410 "Please make sure to save the document as a "
4412 from_utf8(d->filename.absFileName())));
4415 lyxvc().file_found_hook(d->filename);
4418 return ReadAutosaveFailure;
4421 // Here we delete the autosave
4422 autosaveFile.removeFile();
4423 return ReadOriginal;
4431 Buffer::ReadStatus Buffer::loadLyXFile()
4433 if (!d->filename.isReadableFile()) {
4434 ReadStatus const ret_rvc = extractFromVC();
4435 if (ret_rvc != ReadSuccess)
4439 ReadStatus const ret_re = loadEmergency();
4440 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4443 ReadStatus const ret_ra = loadAutosave();
4444 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4447 return loadThisLyXFile(d->filename);
4451 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4453 return readFile(fn);
4457 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4459 TeXErrors::Errors::const_iterator it = terr.begin();
4460 TeXErrors::Errors::const_iterator end = terr.end();
4461 ListOfBuffers clist = getDescendents();
4462 ListOfBuffers::const_iterator cen = clist.end();
4464 for (; it != end; ++it) {
4467 int errorRow = it->error_in_line;
4468 Buffer const * buf = 0;
4470 if (it->child_name.empty())
4471 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4473 // The error occurred in a child
4474 ListOfBuffers::const_iterator cit = clist.begin();
4475 for (; cit != cen; ++cit) {
4476 string const child_name =
4477 DocFileName(changeExtension(
4478 (*cit)->absFileName(), "tex")).
4480 if (it->child_name != child_name)
4482 (*cit)->d->texrow.getIdFromRow(errorRow,
4483 id_start, pos_start);
4484 if (id_start != -1) {
4485 buf = d->cloned_buffer_
4486 ? (*cit)->d->cloned_buffer_->d->owner_
4487 : (*cit)->d->owner_;
4498 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4499 } while (found && id_start == id_end && pos_start == pos_end);
4501 if (id_start != id_end) {
4502 // Next registered position is outside the inset where
4503 // the error occurred, so signal end-of-paragraph
4507 errorList.push_back(ErrorItem(it->error_desc,
4508 it->error_text, id_start, pos_start, pos_end, buf));
4513 void Buffer::setBuffersForInsets() const
4515 inset().setBuffer(const_cast<Buffer &>(*this));
4519 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4521 LBUFERR(!text().paragraphs().empty());
4523 // Use the master text class also for child documents
4524 Buffer const * const master = masterBuffer();
4525 DocumentClass const & textclass = master->params().documentClass();
4527 // do this only if we are the top-level Buffer
4528 if (master == this) {
4529 textclass.counters().reset(from_ascii("bibitem"));
4530 reloadBibInfoCache();
4533 // keep the buffers to be children in this set. If the call from the
4534 // master comes back we can see which of them were actually seen (i.e.
4535 // via an InsetInclude). The remaining ones in the set need still be updated.
4536 static std::set<Buffer const *> bufToUpdate;
4537 if (scope == UpdateMaster) {
4538 // If this is a child document start with the master
4539 if (master != this) {
4540 bufToUpdate.insert(this);
4541 master->updateBuffer(UpdateMaster, utype);
4542 // If the master buffer has no gui associated with it, then the TocModel is
4543 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4544 // (bug 5699). The same happens if the master buffer is open in a different
4545 // window. This test catches both possibilities.
4546 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4547 // There remains a problem here: If there is another child open in yet a third
4548 // window, that TOC is not updated. So some more general solution is needed at
4550 if (master->d->gui_ != d->gui_)
4553 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4554 if (bufToUpdate.find(this) == bufToUpdate.end())
4558 // start over the counters in the master
4559 textclass.counters().reset();
4562 // update will be done below for this buffer
4563 bufToUpdate.erase(this);
4565 // update all caches
4566 clearReferenceCache();
4569 Buffer & cbuf = const_cast<Buffer &>(*this);
4572 ParIterator parit = cbuf.par_iterator_begin();
4573 updateBuffer(parit, utype);
4576 // TocBackend update will be done later.
4579 d->bibinfo_cache_valid_ = true;
4580 d->cite_labels_valid_ = true;
4582 cbuf.tocBackend().update(true, utype);
4583 if (scope == UpdateMaster)
4584 cbuf.structureChanged();
4588 static depth_type getDepth(DocIterator const & it)
4590 depth_type depth = 0;
4591 for (size_t i = 0 ; i < it.depth() ; ++i)
4592 if (!it[i].inset().inMathed())
4593 depth += it[i].paragraph().getDepth() + 1;
4594 // remove 1 since the outer inset does not count
4598 static depth_type getItemDepth(ParIterator const & it)
4600 Paragraph const & par = *it;
4601 LabelType const labeltype = par.layout().labeltype;
4603 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4606 // this will hold the lowest depth encountered up to now.
4607 depth_type min_depth = getDepth(it);
4608 ParIterator prev_it = it;
4611 --prev_it.top().pit();
4613 // start of nested inset: go to outer par
4615 if (prev_it.empty()) {
4616 // start of document: nothing to do
4621 // We search for the first paragraph with same label
4622 // that is not more deeply nested.
4623 Paragraph & prev_par = *prev_it;
4624 depth_type const prev_depth = getDepth(prev_it);
4625 if (labeltype == prev_par.layout().labeltype) {
4626 if (prev_depth < min_depth)
4627 return prev_par.itemdepth + 1;
4628 if (prev_depth == min_depth)
4629 return prev_par.itemdepth;
4631 min_depth = min(min_depth, prev_depth);
4632 // small optimization: if we are at depth 0, we won't
4633 // find anything else
4634 if (prev_depth == 0)
4640 static bool needEnumCounterReset(ParIterator const & it)
4642 Paragraph const & par = *it;
4643 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4644 depth_type const cur_depth = par.getDepth();
4645 ParIterator prev_it = it;
4646 while (prev_it.pit()) {
4647 --prev_it.top().pit();
4648 Paragraph const & prev_par = *prev_it;
4649 if (prev_par.getDepth() <= cur_depth)
4650 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4652 // start of nested inset: reset
4657 // set the label of a paragraph. This includes the counters.
4658 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4660 BufferParams const & bp = owner_->masterBuffer()->params();
4661 DocumentClass const & textclass = bp.documentClass();
4662 Paragraph & par = it.paragraph();
4663 Layout const & layout = par.layout();
4664 Counters & counters = textclass.counters();
4666 if (par.params().startOfAppendix()) {
4667 // We want to reset the counter corresponding to toplevel sectioning
4668 Layout const & lay = textclass.getTOCLayout();
4669 docstring const cnt = lay.counter;
4671 counters.reset(cnt);
4672 counters.appendix(true);
4674 par.params().appendix(counters.appendix());
4676 // Compute the item depth of the paragraph
4677 par.itemdepth = getItemDepth(it);
4679 if (layout.margintype == MARGIN_MANUAL) {
4680 if (par.params().labelWidthString().empty())
4681 par.params().labelWidthString(par.expandLabel(layout, bp));
4682 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4683 // we do not need to do anything here, since the empty case is
4684 // handled during export.
4686 par.params().labelWidthString(docstring());
4689 switch(layout.labeltype) {
4690 case LABEL_ITEMIZE: {
4691 // At some point of time we should do something more
4692 // clever here, like:
4693 // par.params().labelString(
4694 // bp.user_defined_bullet(par.itemdepth).getText());
4695 // for now, use a simple hardcoded label
4696 docstring itemlabel;
4697 switch (par.itemdepth) {
4699 itemlabel = char_type(0x2022);
4702 itemlabel = char_type(0x2013);
4705 itemlabel = char_type(0x2217);
4708 itemlabel = char_type(0x2219); // or 0x00b7
4711 par.params().labelString(itemlabel);
4715 case LABEL_ENUMERATE: {
4716 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4718 switch (par.itemdepth) {
4727 enumcounter += "iv";
4730 // not a valid enumdepth...
4734 // Maybe we have to reset the enumeration counter.
4735 if (needEnumCounterReset(it))
4736 counters.reset(enumcounter);
4737 counters.step(enumcounter, utype);
4739 string const & lang = par.getParLanguage(bp)->code();
4740 par.params().labelString(counters.theCounter(enumcounter, lang));
4745 case LABEL_SENSITIVE: {
4746 string const & type = counters.current_float();
4747 docstring full_label;
4749 full_label = owner_->B_("Senseless!!! ");
4751 docstring name = owner_->B_(textclass.floats().getType(type).name());
4752 if (counters.hasCounter(from_utf8(type))) {
4753 string const & lang = par.getParLanguage(bp)->code();
4754 counters.step(from_utf8(type), utype);
4755 full_label = bformat(from_ascii("%1$s %2$s:"),
4757 counters.theCounter(from_utf8(type), lang));
4759 full_label = bformat(from_ascii("%1$s #:"), name);
4761 par.params().labelString(full_label);
4765 case LABEL_NO_LABEL:
4766 par.params().labelString(docstring());
4770 case LABEL_CENTERED:
4771 case LABEL_STATIC: {
4772 docstring const & lcounter = layout.counter;
4773 if (!lcounter.empty()) {
4774 if (layout.toclevel <= bp.secnumdepth
4775 && (layout.latextype != LATEX_ENVIRONMENT
4776 || it.text()->isFirstInSequence(it.pit()))) {
4777 if (counters.hasCounter(lcounter))
4778 counters.step(lcounter, utype);
4779 par.params().labelString(par.expandLabel(layout, bp));
4781 par.params().labelString(docstring());
4783 par.params().labelString(par.expandLabel(layout, bp));
4789 par.params().labelString(par.expandLabel(layout, bp));
4794 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4796 // LASSERT: Is it safe to continue here, or should we just return?
4797 LASSERT(parit.pit() == 0, /**/);
4799 // Set the position of the text in the buffer to be able
4800 // to resolve macros in it.
4801 parit.text()->setMacrocontextPosition(parit);
4803 depth_type maxdepth = 0;
4804 pit_type const lastpit = parit.lastpit();
4805 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4806 // reduce depth if necessary
4807 if (parit->params().depth() > maxdepth) {
4808 /** FIXME: this function is const, but
4809 * nevertheless it modifies the buffer. To be
4810 * cleaner, one should modify the buffer in
4811 * another function, which is actually
4812 * non-const. This would however be costly in
4813 * terms of code duplication.
4815 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4816 parit->params().depth(maxdepth);
4818 maxdepth = parit->getMaxDepthAfter();
4820 if (utype == OutputUpdate) {
4821 // track the active counters
4822 // we have to do this for the master buffer, since the local
4823 // buffer isn't tracking anything.
4824 masterBuffer()->params().documentClass().counters().
4825 setActiveLayout(parit->layout());
4828 // set the counter for this paragraph
4829 d->setLabel(parit, utype);
4832 InsetList::const_iterator iit = parit->insetList().begin();
4833 InsetList::const_iterator end = parit->insetList().end();
4834 for (; iit != end; ++iit) {
4835 parit.pos() = iit->pos;
4836 iit->inset->updateBuffer(parit, utype);
4842 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4843 WordLangTuple & word_lang, docstring_list & suggestions) const
4847 suggestions.clear();
4848 word_lang = WordLangTuple();
4849 bool const to_end = to.empty();
4850 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4851 // OK, we start from here.
4852 for (; from != end; from.forwardPos()) {
4853 // This skips all insets with spell check disabled.
4854 while (!from.allowSpellCheck()) {
4858 // If from is at the end of the document (which is possible
4859 // when "from" was changed above) LyX will crash later otherwise.
4860 if (from.atEnd() || (!to_end && from >= end))
4863 from.paragraph().spellCheck();
4864 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4865 if (SpellChecker::misspelled(res)) {
4869 // Do not increase progress when from == to, otherwise the word
4870 // count will be wrong.
4880 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4882 bool inword = false;
4887 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4888 if (!dit.inTexted()) {
4893 Paragraph const & par = dit.paragraph();
4894 pos_type const pos = dit.pos();
4896 // Copied and adapted from isWordSeparator() in Paragraph
4897 if (pos == dit.lastpos()) {
4900 Inset const * ins = par.getInset(pos);
4901 if (ins && skipNoOutput && !ins->producesOutput()) {
4904 // stop if end of range was skipped
4905 if (!to.atEnd() && dit >= to)
4908 } else if (!par.isDeleted(pos)) {
4909 if (par.isWordSeparator(pos))
4915 if (ins && ins->isLetter())
4917 else if (ins && ins->isSpace())
4920 char_type const c = par.getChar(pos);
4921 if (isPrintableNonspace(c))
4923 else if (isSpace(c))
4933 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4935 d->updateStatistics(from, to, skipNoOutput);
4939 int Buffer::wordCount() const
4941 return d->wordCount();
4945 int Buffer::charCount(bool with_blanks) const
4947 return d->charCount(with_blanks);
4951 Buffer::ReadStatus Buffer::reload()
4954 // c.f. bug http://www.lyx.org/trac/ticket/6587
4955 removeAutosaveFile();
4956 // e.g., read-only status could have changed due to version control
4957 d->filename.refresh();
4958 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4960 // clear parent. this will get reset if need be.
4962 ReadStatus const status = loadLyXFile();
4963 if (status == ReadSuccess) {
4968 message(bformat(_("Document %1$s reloaded."), disp_fn));
4971 message(bformat(_("Could not reload document %1$s."), disp_fn));
4981 bool Buffer::saveAs(FileName const & fn)
4983 FileName const old_name = fileName();
4984 FileName const old_auto = getAutosaveFileName();
4985 bool const old_unnamed = isUnnamed();
4986 bool success = true;
4987 d->old_position = filePath();
4994 // bring the autosave file with us, just in case.
4995 moveAutosaveFile(old_auto);
4996 // validate version control data and
4997 // correct buffer title
4998 lyxvc().file_found_hook(fileName());
5000 // the file has now been saved to the new location.
5001 // we need to check that the locations of child buffers
5003 checkChildBuffers();
5004 checkMasterBuffer();
5007 // reset the old filename and unnamed state
5008 setFileName(old_name);
5009 setUnnamed(old_unnamed);
5013 d->old_position.clear();
5018 void Buffer::checkChildBuffers()
5020 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5021 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5022 for (; it != en; ++it) {
5023 DocIterator dit = it->second;
5024 Buffer * cbuf = const_cast<Buffer *>(it->first);
5025 if (!cbuf || !theBufferList().isLoaded(cbuf))
5027 Inset * inset = dit.nextInset();
5028 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5029 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5030 docstring const & incfile = inset_inc->getParam("filename");
5031 string oldloc = cbuf->absFileName();
5032 string newloc = makeAbsPath(to_utf8(incfile),
5033 onlyPath(absFileName())).absFileName();
5034 if (oldloc == newloc)
5036 // the location of the child file is incorrect.
5038 inset_inc->setChildBuffer(0);
5040 // invalidate cache of children
5041 d->children_positions.clear();
5042 d->position_to_children.clear();
5046 // If a child has been saved under a different name/path, it might have been
5047 // orphaned. Therefore the master needs to be reset (bug 8161).
5048 void Buffer::checkMasterBuffer()
5050 Buffer const * const master = masterBuffer();
5054 // necessary to re-register the child (bug 5873)
5055 // FIXME: clean up updateMacros (here, only
5056 // child registering is needed).
5057 master->updateMacros();
5058 // (re)set master as master buffer, but only
5059 // if we are a real child
5060 if (master->isChild(this))
5067 string Buffer::includedFilePath(string const & name, string const & ext) const
5069 bool isabsolute = FileName::isAbsolute(name);
5070 // old_position already contains a trailing path separator
5071 string const absname = isabsolute ? name : d->old_position + name;
5073 if (d->old_position.empty()
5074 || equivalent(FileName(d->old_position), FileName(filePath()))
5075 || !FileName(addExtension(absname, ext)).exists())
5079 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5081 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5082 from_utf8(filePath())));