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 const 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 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1406 if (d->need_format_backup)
1407 backupName = getBackupName();
1409 // If we for some reason failed to find a backup name in case of
1410 // a format change, this will still set one. It's the best we can
1412 if (backupName.empty()) {
1413 backupName.set(fileName().absFileName() + "~");
1414 if (!lyxrc.backupdir_path.empty()) {
1415 string const mangledName =
1416 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1417 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1421 LYXERR(Debug::FILES, "Backing up original file to " <<
1422 backupName.absFileName());
1423 // Except file is symlink do not copy because of #6587.
1424 // Hard links have bad luck.
1425 made_backup = symlink ?
1426 fileName().copyTo(backupName):
1427 fileName().moveTo(backupName);
1430 Alert::error(_("Backup failure"),
1431 bformat(_("Cannot create backup file %1$s.\n"
1432 "Please check whether the directory exists and is writable."),
1433 from_utf8(backupName.absFileName())));
1434 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1435 } else if (d->need_format_backup) {
1436 // the original file has been backed up successfully, so we
1437 // will not need to do that again
1438 d->need_format_backup = false;
1442 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1443 // Only do this if tempfile is not in autoremove mode
1446 // If we have no symlink, we can simply rename the temp file.
1447 // Otherwise, we need to copy it so the symlink stays intact.
1448 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1449 savefile.moveTo(fileName()))
1451 // saveCheckSum() was already called by writeFile(), but the
1452 // time stamp is invalidated by copying/moving
1455 if (d->file_format != LYX_FORMAT)
1456 // the file associated with this buffer is now in the current format
1457 d->file_format = LYX_FORMAT;
1460 // else we saved the file, but failed to move it to the right location.
1462 if (needBackup && made_backup && !symlink) {
1463 // the original file was moved to some new location, so it will look
1464 // to the user as if it was deleted. (see bug #9234.) we could try
1465 // to restore it, but that would basically mean trying to do again
1466 // what we just failed to do. better to leave things as they are.
1467 Alert::error(_("Write failure"),
1468 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1469 "But LyX could not move it to:\n %2$s.\n"
1470 "Your original file has been backed up to:\n %3$s"),
1471 from_utf8(savefile.absFileName()),
1472 from_utf8(fileName().absFileName()),
1473 from_utf8(backupName.absFileName())));
1475 // either we did not try to make a backup, or else we tried and failed,
1476 // or else the original file was a symlink, in which case it was copied,
1477 // not moved. so the original file is intact.
1478 Alert::error(_("Write failure"),
1479 bformat(_("Cannot move saved file to:\n %1$s.\n"
1480 "But the file has successfully been saved as:\n %2$s."),
1481 from_utf8(fileName().absFileName()),
1482 from_utf8(savefile.absFileName())));
1488 bool Buffer::writeFile(FileName const & fname) const
1490 if (d->read_only && fname == d->filename)
1493 bool retval = false;
1495 docstring const str = bformat(_("Saving document %1$s..."),
1496 makeDisplayPath(fname.absFileName()));
1499 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1501 if (params().compressed) {
1502 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1503 retval = ofs && write(ofs);
1505 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1506 retval = ofs && write(ofs);
1510 message(str + _(" could not write file!"));
1515 // removeAutosaveFile();
1518 message(str + _(" done."));
1524 docstring Buffer::emergencyWrite()
1526 // No need to save if the buffer has not changed.
1530 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1532 docstring user_message = bformat(
1533 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1535 // We try to save three places:
1536 // 1) Same place as document. Unless it is an unnamed doc.
1538 string s = absFileName();
1541 if (writeFile(FileName(s))) {
1543 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1544 return user_message;
1546 user_message += " " + _("Save failed! Trying again...\n");
1550 // 2) In HOME directory.
1551 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1553 lyxerr << ' ' << s << endl;
1554 if (writeFile(FileName(s))) {
1556 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1557 return user_message;
1560 user_message += " " + _("Save failed! Trying yet again...\n");
1562 // 3) In "/tmp" directory.
1563 // MakeAbsPath to prepend the current
1564 // drive letter on OS/2
1565 s = addName(package().temp_dir().absFileName(), absFileName());
1567 lyxerr << ' ' << s << endl;
1568 if (writeFile(FileName(s))) {
1570 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1571 return user_message;
1574 user_message += " " + _("Save failed! Bummer. Document is lost.");
1577 return user_message;
1581 bool Buffer::write(ostream & ofs) const
1584 // Use the standard "C" locale for file output.
1585 ofs.imbue(locale::classic());
1588 // The top of the file should not be written by params().
1590 // write out a comment in the top of the file
1591 // Important: Keep the version formatting in sync with lyx2lyx and
1592 // tex2lyx (bug 7951)
1593 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1594 << " created this file. For more info see http://www.lyx.org/\n"
1595 << "\\lyxformat " << LYX_FORMAT << "\n"
1596 << "\\begin_document\n";
1598 /// For each author, set 'used' to true if there is a change
1599 /// by this author in the document; otherwise set it to 'false'.
1600 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1601 AuthorList::Authors::const_iterator a_end = params().authors().end();
1602 for (; a_it != a_end; ++a_it)
1603 a_it->setUsed(false);
1605 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1606 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1607 for ( ; it != end; ++it)
1608 it->checkAuthors(params().authors());
1610 // now write out the buffer parameters.
1611 ofs << "\\begin_header\n";
1612 params().writeFile(ofs, this);
1613 ofs << "\\end_header\n";
1616 ofs << "\n\\begin_body\n";
1618 ofs << "\n\\end_body\n";
1620 // Write marker that shows file is complete
1621 ofs << "\\end_document" << endl;
1623 // Shouldn't really be needed....
1626 // how to check if close went ok?
1627 // Following is an attempt... (BE 20001011)
1629 // good() returns false if any error occurred, including some
1630 // formatting error.
1631 // bad() returns true if something bad happened in the buffer,
1632 // which should include file system full errors.
1637 lyxerr << "File was not closed properly." << endl;
1644 bool Buffer::makeLaTeXFile(FileName const & fname,
1645 string const & original_path,
1646 OutputParams const & runparams_in,
1647 OutputWhat output) const
1649 OutputParams runparams = runparams_in;
1651 // XeTeX with TeX fonts is only safe with ASCII encoding,
1652 // but the "flavor" is not known in BufferParams::encoding().
1653 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1654 runparams.encoding = encodings.fromLyXName("ascii");
1656 string const encoding = runparams.encoding->iconvName();
1657 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1660 try { ofs.reset(encoding); }
1661 catch (iconv_codecvt_facet_exception const & e) {
1662 lyxerr << "Caught iconv exception: " << e.what() << endl;
1663 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1664 "verify that the support software for your encoding (%1$s) is "
1665 "properly installed"), from_ascii(encoding)));
1668 if (!openFileWrite(ofs, fname))
1671 ErrorList & errorList = d->errorLists["Export"];
1673 bool failed_export = false;
1674 otexstream os(ofs, d->texrow);
1676 // make sure we are ready to export
1677 // this needs to be done before we validate
1678 // FIXME Do we need to do this all the time? I.e., in children
1679 // of a master we are exporting?
1681 updateMacroInstances(OutputUpdate);
1684 os.texrow().reset();
1685 writeLaTeXSource(os, original_path, runparams, output);
1687 catch (EncodingException const & e) {
1688 docstring const failed(1, e.failed_char);
1690 oss << "0x" << hex << e.failed_char << dec;
1691 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1692 " (code point %2$s)"),
1693 failed, from_utf8(oss.str()));
1694 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1695 "representable in the chosen encoding.\n"
1696 "Changing the document encoding to utf8 could help."),
1697 e.par_id, e.pos, e.pos + 1));
1698 failed_export = true;
1700 catch (iconv_codecvt_facet_exception const & e) {
1701 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1702 _(e.what()), -1, 0, 0));
1703 failed_export = true;
1705 catch (exception const & e) {
1706 errorList.push_back(ErrorItem(_("conversion failed"),
1707 _(e.what()), -1, 0, 0));
1708 failed_export = true;
1711 lyxerr << "Caught some really weird exception..." << endl;
1717 failed_export = true;
1718 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1721 if (runparams_in.silent)
1725 return !failed_export;
1729 void Buffer::writeLaTeXSource(otexstream & os,
1730 string const & original_path,
1731 OutputParams const & runparams_in,
1732 OutputWhat output) const
1734 // The child documents, if any, shall be already loaded at this point.
1736 OutputParams runparams = runparams_in;
1738 // XeTeX with TeX fonts is only safe with ASCII encoding,
1739 // but the "flavor" is not known in BufferParams::encoding().
1740 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1741 runparams.encoding = encodings.fromLyXName("ascii");
1742 // FIXME: when only the current paragraph is shown, this is ignored
1743 // (or not reached) and characters encodable in the current
1744 // encoding are not converted to ASCII-representation.
1746 // If we are compiling a file standalone, even if this is the
1747 // child of some other buffer, let's cut the link here, so the
1748 // file is really independent and no concurring settings from
1749 // the master (e.g. branch state) interfere (see #8100).
1750 if (!runparams.is_child)
1751 d->ignore_parent = true;
1753 // Classify the unicode characters appearing in math insets
1754 BufferEncodings::initUnicodeMath(*this);
1756 // validate the buffer.
1757 LYXERR(Debug::LATEX, " Validating buffer...");
1758 LaTeXFeatures features(*this, params(), runparams);
1760 // This is only set once per document (in master)
1761 if (!runparams.is_child)
1762 runparams.use_polyglossia = features.usePolyglossia();
1763 LYXERR(Debug::LATEX, " Buffer validation done.");
1765 bool const output_preamble =
1766 output == FullSource || output == OnlyPreamble;
1767 bool const output_body =
1768 output == FullSource || output == OnlyBody;
1770 // The starting paragraph of the coming rows is the
1771 // first paragraph of the document. (Asger)
1772 if (output_preamble && runparams.nice) {
1773 os << "%% LyX " << lyx_version << " created this file. "
1774 "For more info, see http://www.lyx.org/.\n"
1775 "%% Do not edit unless you really know what "
1778 LYXERR(Debug::INFO, "lyx document header finished");
1780 // There are a few differences between nice LaTeX and usual files:
1781 // usual files have \batchmode and special input@path to allow
1782 // inclusion of figures specified by an explicitly relative path
1783 // (i.e., a path starting with './' or '../') with either \input or
1784 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1785 // input@path is set when the actual parameter original_path is set.
1786 // This is done for usual tex-file, but not for nice-latex-file.
1787 // (Matthias 250696)
1788 // Note that input@path is only needed for something the user does
1789 // in the preamble, included .tex files or ERT, files included by
1790 // LyX work without it.
1791 if (output_preamble) {
1792 if (!runparams.nice) {
1793 // code for usual, NOT nice-latex-file
1794 os << "\\batchmode\n"; // changed from \nonstopmode
1796 if (!original_path.empty()) {
1798 // We don't know the encoding of inputpath
1799 docstring const inputpath = from_utf8(original_path);
1800 docstring uncodable_glyphs;
1801 Encoding const * const enc = runparams.encoding;
1803 for (size_t n = 0; n < inputpath.size(); ++n) {
1804 if (!enc->encodable(inputpath[n])) {
1805 docstring const glyph(1, inputpath[n]);
1806 LYXERR0("Uncodable character '"
1808 << "' in input path!");
1809 uncodable_glyphs += glyph;
1814 // warn user if we found uncodable glyphs.
1815 if (!uncodable_glyphs.empty()) {
1816 frontend::Alert::warning(
1817 _("Uncodable character in file path"),
1819 _("The path of your document\n"
1821 "contains glyphs that are unknown "
1822 "in the current document encoding "
1823 "(namely %2$s). This may result in "
1824 "incomplete output, unless "
1825 "TEXINPUTS contains the document "
1826 "directory and you don't use "
1827 "explicitly relative paths (i.e., "
1828 "paths starting with './' or "
1829 "'../') in the preamble or in ERT."
1830 "\n\nIn case of problems, choose "
1831 "an appropriate document encoding\n"
1832 "(such as utf8) or change the "
1834 inputpath, uncodable_glyphs));
1837 support::latex_path(original_path);
1838 if (contains(docdir, '#')) {
1839 docdir = subst(docdir, "#", "\\#");
1840 os << "\\catcode`\\#=11"
1841 "\\def\\#{#}\\catcode`\\#=6\n";
1843 if (contains(docdir, '%')) {
1844 docdir = subst(docdir, "%", "\\%");
1845 os << "\\catcode`\\%=11"
1846 "\\def\\%{%}\\catcode`\\%=14\n";
1848 os << "\\makeatletter\n"
1849 << "\\def\\input@path{{"
1851 << "\\makeatother\n";
1855 // get parent macros (if this buffer has a parent) which will be
1856 // written at the document begin further down.
1857 MacroSet parentMacros;
1858 listParentMacros(parentMacros, features);
1860 // Write the preamble
1861 runparams.use_babel = params().writeLaTeX(os, features,
1862 d->filename.onlyPath());
1864 // Japanese might be required only in some children of a document,
1865 // but once required, we must keep use_japanese true.
1866 runparams.use_japanese |= features.isRequired("japanese");
1869 // Restore the parenthood if needed
1870 if (!runparams.is_child)
1871 d->ignore_parent = false;
1876 os << "\\begin{document}\n";
1878 // output the parent macros
1879 MacroSet::iterator it = parentMacros.begin();
1880 MacroSet::iterator end = parentMacros.end();
1881 for (; it != end; ++it) {
1882 int num_lines = (*it)->write(os.os(), true);
1883 os.texrow().newlines(num_lines);
1886 } // output_preamble
1888 os.texrow().start(paragraphs().begin()->id(), 0);
1890 LYXERR(Debug::INFO, "preamble finished, now the body.");
1893 latexParagraphs(*this, text(), os, runparams);
1895 // Restore the parenthood if needed
1896 if (!runparams.is_child)
1897 d->ignore_parent = false;
1899 // add this just in case after all the paragraphs
1902 if (output_preamble) {
1903 os << "\\end{document}\n";
1904 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1906 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1908 runparams_in.encoding = runparams.encoding;
1910 os.texrow().finalize();
1912 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1913 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1917 void Buffer::makeDocBookFile(FileName const & fname,
1918 OutputParams const & runparams,
1919 OutputWhat output) const
1921 LYXERR(Debug::LATEX, "makeDocBookFile...");
1924 if (!openFileWrite(ofs, fname))
1927 // make sure we are ready to export
1928 // this needs to be done before we validate
1930 updateMacroInstances(OutputUpdate);
1932 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1936 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1940 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1941 OutputParams const & runparams,
1942 OutputWhat output) const
1944 LaTeXFeatures features(*this, params(), runparams);
1947 d->texrow.reset(false);
1949 DocumentClass const & tclass = params().documentClass();
1950 string const & top_element = tclass.latexname();
1952 bool const output_preamble =
1953 output == FullSource || output == OnlyPreamble;
1954 bool const output_body =
1955 output == FullSource || output == OnlyBody;
1957 if (output_preamble) {
1958 if (runparams.flavor == OutputParams::XML)
1959 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1962 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1965 if (! tclass.class_header().empty())
1966 os << from_ascii(tclass.class_header());
1967 else if (runparams.flavor == OutputParams::XML)
1968 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1969 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1971 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1973 docstring preamble = from_utf8(params().preamble);
1974 if (runparams.flavor != OutputParams::XML ) {
1975 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1976 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1977 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1978 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1981 string const name = runparams.nice
1982 ? changeExtension(absFileName(), ".sgml") : fname;
1983 preamble += features.getIncludedFiles(name);
1984 preamble += features.getLyXSGMLEntities();
1986 if (!preamble.empty()) {
1987 os << "\n [ " << preamble << " ]";
1993 string top = top_element;
1995 if (runparams.flavor == OutputParams::XML)
1996 top += params().language->code();
1998 top += params().language->code().substr(0, 2);
2001 if (!params().options.empty()) {
2003 top += params().options;
2006 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2007 << " file was created by LyX " << lyx_version
2008 << "\n See http://www.lyx.org/ for more information -->\n";
2010 params().documentClass().counters().reset();
2012 sgml::openTag(os, top);
2014 docbookParagraphs(text(), *this, os, runparams);
2015 sgml::closeTag(os, top_element);
2020 void Buffer::makeLyXHTMLFile(FileName const & fname,
2021 OutputParams const & runparams) const
2023 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2026 if (!openFileWrite(ofs, fname))
2029 // make sure we are ready to export
2030 // this has to be done before we validate
2031 updateBuffer(UpdateMaster, OutputUpdate);
2032 updateMacroInstances(OutputUpdate);
2034 writeLyXHTMLSource(ofs, runparams, FullSource);
2038 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2042 void Buffer::writeLyXHTMLSource(odocstream & os,
2043 OutputParams const & runparams,
2044 OutputWhat output) const
2046 LaTeXFeatures features(*this, params(), runparams);
2048 d->bibinfo_.makeCitationLabels(*this);
2050 bool const output_preamble =
2051 output == FullSource || output == OnlyPreamble;
2052 bool const output_body =
2053 output == FullSource || output == OnlyBody || output == IncludedFile;
2055 if (output_preamble) {
2056 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2057 << "<!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"
2058 // FIXME Language should be set properly.
2059 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2061 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2062 // FIXME Presumably need to set this right
2063 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2065 docstring const & doctitle = features.htmlTitle();
2067 << (doctitle.empty() ?
2068 from_ascii("LyX Document") :
2069 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2072 docstring styles = features.getTClassHTMLPreamble();
2073 if (!styles.empty())
2074 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2076 styles = from_utf8(features.getPreambleSnippets());
2077 if (!styles.empty())
2078 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2080 // we will collect CSS information in a stream, and then output it
2081 // either here, as part of the header, or else in a separate file.
2082 odocstringstream css;
2083 styles = from_utf8(features.getCSSSnippets());
2084 if (!styles.empty())
2085 css << "/* LyX Provided Styles */\n" << styles << '\n';
2087 styles = features.getTClassHTMLStyles();
2088 if (!styles.empty())
2089 css << "/* Layout-provided Styles */\n" << styles << '\n';
2091 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2092 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2093 if (needfg || needbg) {
2094 css << "\nbody {\n";
2097 << from_ascii(X11hexname(params().fontcolor))
2100 css << " background-color: "
2101 << from_ascii(X11hexname(params().backgroundcolor))
2106 docstring const dstyles = css.str();
2107 if (!dstyles.empty()) {
2108 bool written = false;
2109 if (params().html_css_as_file) {
2110 // open a file for CSS info
2112 string const fcssname = addName(temppath(), "docstyle.css");
2113 FileName const fcssfile = FileName(fcssname);
2114 if (openFileWrite(ocss, fcssfile)) {
2118 // write link to header
2119 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2121 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2124 // we are here if the CSS is supposed to be written to the header
2125 // or if we failed to write it to an external file.
2127 os << "<style type='text/css'>\n"
2136 bool const output_body_tag = (output != IncludedFile);
2137 if (output_body_tag)
2140 if (output != IncludedFile)
2141 // if we're an included file, the counters are in the master.
2142 params().documentClass().counters().reset();
2143 xhtmlParagraphs(text(), *this, xs, runparams);
2144 if (output_body_tag)
2148 if (output_preamble)
2153 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2154 // Other flags: -wall -v0 -x
2155 int Buffer::runChktex()
2159 // get LaTeX-Filename
2160 FileName const path(temppath());
2161 string const name = addName(path.absFileName(), latexName());
2162 string const org_path = filePath();
2164 PathChanger p(path); // path to LaTeX file
2165 message(_("Running chktex..."));
2167 // Generate the LaTeX file if neccessary
2168 OutputParams runparams(¶ms().encoding());
2169 runparams.flavor = OutputParams::LATEX;
2170 runparams.nice = false;
2171 runparams.linelen = lyxrc.plaintext_linelen;
2172 makeLaTeXFile(FileName(name), org_path, runparams);
2175 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2176 int const res = chktex.run(terr); // run chktex
2179 Alert::error(_("chktex failure"),
2180 _("Could not run chktex successfully."));
2182 ErrorList & errlist = d->errorLists["ChkTeX"];
2184 bufferErrors(terr, errlist);
2189 if (runparams.silent)
2190 d->errorLists["ChkTeX"].clear();
2198 void Buffer::validate(LaTeXFeatures & features) const
2200 // Validate the buffer params, but not for included
2201 // files, since they also use the parent buffer's
2203 if (!features.runparams().is_child)
2204 params().validate(features);
2206 for_each(paragraphs().begin(), paragraphs().end(),
2207 bind(&Paragraph::validate, _1, ref(features)));
2209 if (lyxerr.debugging(Debug::LATEX)) {
2210 features.showStruct();
2215 void Buffer::getLabelList(vector<docstring> & list) const
2217 // If this is a child document, use the master's list instead.
2219 masterBuffer()->getLabelList(list);
2224 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2225 TocIterator toc_it = toc->begin();
2226 TocIterator end = toc->end();
2227 for (; toc_it != end; ++toc_it) {
2228 if (toc_it->depth() == 0)
2229 list.push_back(toc_it->str());
2234 void Buffer::updateBibfilesCache(UpdateScope scope) const
2236 // FIXME This is probably unnecssary, given where we call this.
2237 // If this is a child document, use the parent's cache instead.
2238 if (parent() && scope != UpdateChildOnly) {
2239 masterBuffer()->updateBibfilesCache();
2243 d->bibfiles_cache_.clear();
2244 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2245 if (it->lyxCode() == BIBTEX_CODE) {
2246 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2247 support::FileNameList const bibfiles = inset.getBibFiles();
2248 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2251 } else if (it->lyxCode() == INCLUDE_CODE) {
2252 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2253 Buffer const * const incbuf = inset.getChildBuffer();
2256 support::FileNameList const & bibfiles =
2257 incbuf->getBibfilesCache(UpdateChildOnly);
2258 if (!bibfiles.empty()) {
2259 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2265 d->bibfile_cache_valid_ = true;
2266 d->bibinfo_cache_valid_ = false;
2267 d->cite_labels_valid_ = false;
2271 void Buffer::invalidateBibinfoCache() const
2273 d->bibinfo_cache_valid_ = false;
2274 d->cite_labels_valid_ = false;
2275 // also invalidate the cache for the parent buffer
2276 Buffer const * const pbuf = d->parent();
2278 pbuf->invalidateBibinfoCache();
2282 void Buffer::invalidateBibfileCache() const
2284 d->bibfile_cache_valid_ = false;
2285 d->bibinfo_cache_valid_ = false;
2286 d->cite_labels_valid_ = false;
2287 // also invalidate the cache for the parent buffer
2288 Buffer const * const pbuf = d->parent();
2290 pbuf->invalidateBibfileCache();
2294 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2296 // FIXME This is probably unnecessary, given where we call this.
2297 // If this is a child document, use the master's cache instead.
2298 Buffer const * const pbuf = masterBuffer();
2299 if (pbuf != this && scope != UpdateChildOnly)
2300 return pbuf->getBibfilesCache();
2302 if (!d->bibfile_cache_valid_)
2303 this->updateBibfilesCache(scope);
2305 return d->bibfiles_cache_;
2309 BiblioInfo const & Buffer::masterBibInfo() const
2311 Buffer const * const tmp = masterBuffer();
2313 return tmp->masterBibInfo();
2318 void Buffer::checkIfBibInfoCacheIsValid() const
2320 // use the master's cache
2321 Buffer const * const tmp = masterBuffer();
2323 tmp->checkIfBibInfoCacheIsValid();
2327 // compare the cached timestamps with the actual ones.
2328 FileNameList const & bibfiles_cache = getBibfilesCache();
2329 FileNameList::const_iterator ei = bibfiles_cache.begin();
2330 FileNameList::const_iterator en = bibfiles_cache.end();
2331 for (; ei != en; ++ ei) {
2332 time_t lastw = ei->lastModified();
2333 time_t prevw = d->bibfile_status_[*ei];
2334 if (lastw != prevw) {
2335 d->bibinfo_cache_valid_ = false;
2336 d->cite_labels_valid_ = false;
2337 d->bibfile_status_[*ei] = lastw;
2343 void Buffer::reloadBibInfoCache() const
2345 // use the master's cache
2346 Buffer const * const tmp = masterBuffer();
2348 tmp->reloadBibInfoCache();
2352 checkIfBibInfoCacheIsValid();
2353 if (d->bibinfo_cache_valid_)
2356 d->bibinfo_.clear();
2358 d->bibinfo_cache_valid_ = true;
2362 void Buffer::collectBibKeys() const
2364 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2365 it->collectBibKeys(it);
2369 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2371 Buffer const * tmp = masterBuffer();
2372 BiblioInfo & masterbi = (tmp == this) ?
2373 d->bibinfo_ : tmp->d->bibinfo_;
2374 masterbi.mergeBiblioInfo(bi);
2378 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2380 Buffer const * tmp = masterBuffer();
2381 BiblioInfo & masterbi = (tmp == this) ?
2382 d->bibinfo_ : tmp->d->bibinfo_;
2387 void Buffer::makeCitationLabels() const
2389 Buffer const * const master = masterBuffer();
2390 return d->bibinfo_.makeCitationLabels(*master);
2394 bool Buffer::citeLabelsValid() const
2396 return masterBuffer()->d->cite_labels_valid_;
2400 void Buffer::removeBiblioTempFiles() const
2402 // We remove files that contain LaTeX commands specific to the
2403 // particular bibliographic style being used, in order to avoid
2404 // LaTeX errors when we switch style.
2405 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2406 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2407 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2408 aux_file.removeFile();
2409 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2410 bbl_file.removeFile();
2411 // Also for the parent buffer
2412 Buffer const * const pbuf = parent();
2414 pbuf->removeBiblioTempFiles();
2418 bool Buffer::isDepClean(string const & name) const
2420 DepClean::const_iterator const it = d->dep_clean.find(name);
2421 if (it == d->dep_clean.end())
2427 void Buffer::markDepClean(string const & name)
2429 d->dep_clean[name] = true;
2433 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2436 // FIXME? if there is an Buffer LFUN that can be dispatched even
2437 // if internal, put a switch '(cmd.action)' here.
2443 switch (cmd.action()) {
2445 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2446 flag.setOnOff(isReadonly());
2449 // FIXME: There is need for a command-line import.
2450 //case LFUN_BUFFER_IMPORT:
2452 case LFUN_BUFFER_AUTO_SAVE:
2455 case LFUN_BUFFER_EXPORT_CUSTOM:
2456 // FIXME: Nothing to check here?
2459 case LFUN_BUFFER_EXPORT: {
2460 docstring const arg = cmd.argument();
2461 if (arg == "custom") {
2465 string format = to_utf8(arg);
2466 size_t pos = format.find(' ');
2467 if (pos != string::npos)
2468 format = format.substr(0, pos);
2469 enable = params().isExportable(format);
2471 flag.message(bformat(
2472 _("Don't know how to export to format: %1$s"), arg));
2476 case LFUN_BUFFER_CHKTEX:
2477 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2480 case LFUN_BUILD_PROGRAM:
2481 enable = params().isExportable("program");
2484 case LFUN_BRANCH_ACTIVATE:
2485 case LFUN_BRANCH_DEACTIVATE:
2486 case LFUN_BRANCH_MASTER_ACTIVATE:
2487 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2488 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2489 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2490 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2491 : params().branchlist();
2492 docstring const branchName = cmd.argument();
2493 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2497 case LFUN_BRANCH_ADD:
2498 case LFUN_BRANCHES_RENAME:
2499 // if no Buffer is present, then of course we won't be called!
2502 case LFUN_BUFFER_LANGUAGE:
2503 enable = !isReadonly();
2506 case LFUN_BUFFER_VIEW_CACHE:
2507 (d->preview_file_).refresh();
2508 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2511 case LFUN_CHANGES_TRACK:
2512 flag.setEnabled(true);
2513 flag.setOnOff(params().track_changes);
2516 case LFUN_CHANGES_OUTPUT:
2517 flag.setEnabled(true);
2518 flag.setOnOff(params().output_changes);
2521 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2522 flag.setOnOff(params().compressed);
2526 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2527 flag.setOnOff(params().output_sync);
2534 flag.setEnabled(enable);
2539 void Buffer::dispatch(string const & command, DispatchResult & result)
2541 return dispatch(lyxaction.lookupFunc(command), result);
2545 // NOTE We can end up here even if we have no GUI, because we are called
2546 // by LyX::exec to handled command-line requests. So we may need to check
2547 // whether we have a GUI or not. The boolean use_gui holds this information.
2548 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2551 // FIXME? if there is an Buffer LFUN that can be dispatched even
2552 // if internal, put a switch '(cmd.action())' here.
2553 dr.dispatched(false);
2556 string const argument = to_utf8(func.argument());
2557 // We'll set this back to false if need be.
2558 bool dispatched = true;
2559 undo().beginUndoGroup();
2561 switch (func.action()) {
2562 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2563 if (lyxvc().inUse()) {
2564 string log = lyxvc().toggleReadOnly();
2569 setReadonly(!isReadonly());
2572 case LFUN_BUFFER_EXPORT: {
2573 ExportStatus const status = doExport(argument, false);
2574 dr.setError(status != ExportSuccess);
2575 if (status != ExportSuccess)
2576 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2581 case LFUN_BUILD_PROGRAM: {
2582 ExportStatus const status = doExport("program", true);
2583 dr.setError(status != ExportSuccess);
2584 if (status != ExportSuccess)
2585 dr.setMessage(_("Error generating literate programming code."));
2589 case LFUN_BUFFER_CHKTEX:
2593 case LFUN_BUFFER_EXPORT_CUSTOM: {
2595 string command = split(argument, format_name, ' ');
2596 Format const * format = formats.getFormat(format_name);
2598 lyxerr << "Format \"" << format_name
2599 << "\" not recognized!"
2604 // The name of the file created by the conversion process
2607 // Output to filename
2608 if (format->name() == "lyx") {
2609 string const latexname = latexName(false);
2610 filename = changeExtension(latexname,
2611 format->extension());
2612 filename = addName(temppath(), filename);
2614 if (!writeFile(FileName(filename)))
2618 doExport(format_name, true, filename);
2621 // Substitute $$FName for filename
2622 if (!contains(command, "$$FName"))
2623 command = "( " + command + " ) < $$FName";
2624 command = subst(command, "$$FName", filename);
2626 // Execute the command in the background
2628 call.startscript(Systemcall::DontWait, command,
2629 filePath(), layoutPos());
2633 // FIXME: There is need for a command-line import.
2635 case LFUN_BUFFER_IMPORT:
2640 case LFUN_BUFFER_AUTO_SAVE:
2642 resetAutosaveTimers();
2645 case LFUN_BRANCH_ACTIVATE:
2646 case LFUN_BRANCH_DEACTIVATE:
2647 case LFUN_BRANCH_MASTER_ACTIVATE:
2648 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2649 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2650 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2651 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2654 docstring const branch_name = func.argument();
2655 // the case without a branch name is handled elsewhere
2656 if (branch_name.empty()) {
2660 Branch * branch = buf->params().branchlist().find(branch_name);
2662 LYXERR0("Branch " << branch_name << " does not exist.");
2664 docstring const msg =
2665 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2669 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2670 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2671 if (branch->isSelected() != activate) {
2672 buf->undo().recordUndoBufferParams(CursorData());
2673 branch->setSelected(activate);
2675 dr.screenUpdate(Update::Force);
2676 dr.forceBufferUpdate();
2681 case LFUN_BRANCH_ADD: {
2682 docstring branch_name = func.argument();
2683 if (branch_name.empty()) {
2687 BranchList & branch_list = params().branchlist();
2688 vector<docstring> const branches =
2689 getVectorFromString(branch_name, branch_list.separator());
2691 for (vector<docstring>::const_iterator it = branches.begin();
2692 it != branches.end(); ++it) {
2694 Branch * branch = branch_list.find(branch_name);
2696 LYXERR0("Branch " << branch_name << " already exists.");
2700 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2702 undo().recordUndoBufferParams(CursorData());
2703 branch_list.add(branch_name);
2704 branch = branch_list.find(branch_name);
2705 string const x11hexname = X11hexname(branch->color());
2706 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2707 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2709 dr.screenUpdate(Update::Force);
2717 case LFUN_BRANCHES_RENAME: {
2718 if (func.argument().empty())
2721 docstring const oldname = from_utf8(func.getArg(0));
2722 docstring const newname = from_utf8(func.getArg(1));
2723 InsetIterator it = inset_iterator_begin(inset());
2724 InsetIterator const end = inset_iterator_end(inset());
2725 bool success = false;
2726 for (; it != end; ++it) {
2727 if (it->lyxCode() == BRANCH_CODE) {
2728 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2729 if (ins.branch() == oldname) {
2730 undo().recordUndo(CursorData(it));
2731 ins.rename(newname);
2736 if (it->lyxCode() == INCLUDE_CODE) {
2737 // get buffer of external file
2738 InsetInclude const & ins =
2739 static_cast<InsetInclude const &>(*it);
2740 Buffer * child = ins.getChildBuffer();
2743 child->dispatch(func, dr);
2748 dr.screenUpdate(Update::Force);
2749 dr.forceBufferUpdate();
2754 case LFUN_BUFFER_VIEW_CACHE:
2755 if (!formats.view(*this, d->preview_file_,
2756 d->preview_format_))
2757 dr.setMessage(_("Error viewing the output file."));
2760 case LFUN_CHANGES_TRACK:
2761 undo().recordUndoBufferParams(CursorData());
2762 params().track_changes = !params().track_changes;
2765 case LFUN_CHANGES_OUTPUT:
2766 undo().recordUndoBufferParams(CursorData());
2767 params().output_changes = !params().output_changes;
2768 if (params().output_changes) {
2769 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2770 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2771 LaTeXFeatures::isAvailable("xcolor");
2773 if (!dvipost && !xcolorulem) {
2774 Alert::warning(_("Changes not shown in LaTeX output"),
2775 _("Changes will not be highlighted in LaTeX output, "
2776 "because neither dvipost nor xcolor/ulem are installed.\n"
2777 "Please install these packages or redefine "
2778 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2779 } else if (!xcolorulem) {
2780 Alert::warning(_("Changes not shown in LaTeX output"),
2781 _("Changes will not be highlighted in LaTeX output "
2782 "when using pdflatex, because xcolor and ulem are not installed.\n"
2783 "Please install both packages or redefine "
2784 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2789 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2790 // turn compression on/off
2791 undo().recordUndoBufferParams(CursorData());
2792 params().compressed = !params().compressed;
2795 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2796 undo().recordUndoBufferParams(CursorData());
2797 params().output_sync = !params().output_sync;
2804 dr.dispatched(dispatched);
2805 undo().endUndoGroup();
2809 void Buffer::changeLanguage(Language const * from, Language const * to)
2811 LASSERT(from, return);
2812 LASSERT(to, return);
2814 for_each(par_iterator_begin(),
2816 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2820 bool Buffer::isMultiLingual() const
2822 ParConstIterator end = par_iterator_end();
2823 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2824 if (it->isMultiLingual(params()))
2831 std::set<Language const *> Buffer::getLanguages() const
2833 std::set<Language const *> languages;
2834 getLanguages(languages);
2839 void Buffer::getLanguages(std::set<Language const *> & languages) const
2841 ParConstIterator end = par_iterator_end();
2842 // add the buffer language, even if it's not actively used
2843 languages.insert(language());
2844 // iterate over the paragraphs
2845 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2846 it->getLanguages(languages);
2848 ListOfBuffers clist = getDescendents();
2849 ListOfBuffers::const_iterator cit = clist.begin();
2850 ListOfBuffers::const_iterator const cen = clist.end();
2851 for (; cit != cen; ++cit)
2852 (*cit)->getLanguages(languages);
2856 DocIterator Buffer::getParFromID(int const id) const
2858 Buffer * buf = const_cast<Buffer *>(this);
2860 // John says this is called with id == -1 from undo
2861 lyxerr << "getParFromID(), id: " << id << endl;
2862 return doc_iterator_end(buf);
2865 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2866 if (it.paragraph().id() == id)
2869 return doc_iterator_end(buf);
2873 bool Buffer::hasParWithID(int const id) const
2875 return !getParFromID(id).atEnd();
2879 ParIterator Buffer::par_iterator_begin()
2881 return ParIterator(doc_iterator_begin(this));
2885 ParIterator Buffer::par_iterator_end()
2887 return ParIterator(doc_iterator_end(this));
2891 ParConstIterator Buffer::par_iterator_begin() const
2893 return ParConstIterator(doc_iterator_begin(this));
2897 ParConstIterator Buffer::par_iterator_end() const
2899 return ParConstIterator(doc_iterator_end(this));
2903 Language const * Buffer::language() const
2905 return params().language;
2909 docstring const Buffer::B_(string const & l10n) const
2911 return params().B_(l10n);
2915 bool Buffer::isClean() const
2917 return d->lyx_clean;
2921 bool Buffer::isExternallyModified(CheckMethod method) const
2923 LASSERT(d->filename.exists(), return false);
2924 // if method == timestamp, check timestamp before checksum
2925 return (method == checksum_method
2926 || d->timestamp_ != d->filename.lastModified())
2927 && d->checksum_ != d->filename.checksum();
2931 void Buffer::saveCheckSum() const
2933 FileName const & file = d->filename;
2936 if (file.exists()) {
2937 d->timestamp_ = file.lastModified();
2938 d->checksum_ = file.checksum();
2940 // in the case of save to a new file.
2947 void Buffer::markClean() const
2949 if (!d->lyx_clean) {
2950 d->lyx_clean = true;
2953 // if the .lyx file has been saved, we don't need an
2955 d->bak_clean = true;
2956 d->undo_.markDirty();
2960 void Buffer::setUnnamed(bool flag)
2966 bool Buffer::isUnnamed() const
2973 /// Don't check unnamed, here: isInternal() is used in
2974 /// newBuffer(), where the unnamed flag has not been set by anyone
2975 /// yet. Also, for an internal buffer, there should be no need for
2976 /// retrieving fileName() nor for checking if it is unnamed or not.
2977 bool Buffer::isInternal() const
2979 return d->internal_buffer;
2983 void Buffer::setInternal(bool flag)
2985 d->internal_buffer = flag;
2989 void Buffer::markDirty()
2992 d->lyx_clean = false;
2995 d->bak_clean = false;
2997 DepClean::iterator it = d->dep_clean.begin();
2998 DepClean::const_iterator const end = d->dep_clean.end();
3000 for (; it != end; ++it)
3005 FileName Buffer::fileName() const
3011 string Buffer::absFileName() const
3013 return d->filename.absFileName();
3017 string Buffer::filePath() const
3019 string const abs = d->filename.onlyPath().absFileName();
3022 int last = abs.length() - 1;
3024 return abs[last] == '/' ? abs : abs + '/';
3028 string Buffer::originFilePath() const
3030 if (FileName::isAbsolute(params().origin))
3031 return params().origin;
3037 string Buffer::layoutPos() const
3039 return d->layout_position;
3043 void Buffer::setLayoutPos(string const & path)
3046 d->layout_position.clear();
3050 LATTEST(FileName::isAbsolute(path));
3052 d->layout_position =
3053 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3055 if (d->layout_position.empty())
3056 d->layout_position = ".";
3060 bool Buffer::isReadonly() const
3062 return d->read_only;
3066 void Buffer::setParent(Buffer const * buffer)
3068 // Avoids recursive include.
3069 d->setParent(buffer == this ? 0 : buffer);
3074 Buffer const * Buffer::parent() const
3080 ListOfBuffers Buffer::allRelatives() const
3082 ListOfBuffers lb = masterBuffer()->getDescendents();
3083 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3088 Buffer const * Buffer::masterBuffer() const
3090 // FIXME Should be make sure we are not in some kind
3091 // of recursive include? A -> B -> A will crash this.
3092 Buffer const * const pbuf = d->parent();
3096 return pbuf->masterBuffer();
3100 bool Buffer::isChild(Buffer * child) const
3102 return d->children_positions.find(child) != d->children_positions.end();
3106 DocIterator Buffer::firstChildPosition(Buffer const * child)
3108 Impl::BufferPositionMap::iterator it;
3109 it = d->children_positions.find(child);
3110 if (it == d->children_positions.end())
3111 return DocIterator(this);
3116 bool Buffer::hasChildren() const
3118 return !d->children_positions.empty();
3122 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3124 // loop over children
3125 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3126 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3127 for (; it != end; ++it) {
3128 Buffer * child = const_cast<Buffer *>(it->first);
3130 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3131 if (bit != clist.end())
3133 clist.push_back(child);
3135 // there might be grandchildren
3136 child->collectChildren(clist, true);
3141 ListOfBuffers Buffer::getChildren() const
3144 collectChildren(v, false);
3145 // Make sure we have not included ourselves.
3146 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3147 if (bit != v.end()) {
3148 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3155 ListOfBuffers Buffer::getDescendents() const
3158 collectChildren(v, true);
3159 // Make sure we have not included ourselves.
3160 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3161 if (bit != v.end()) {
3162 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3169 template<typename M>
3170 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3175 typename M::const_iterator it = m.lower_bound(x);
3176 if (it == m.begin())
3184 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3185 DocIterator const & pos) const
3187 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3189 // if paragraphs have no macro context set, pos will be empty
3193 // we haven't found anything yet
3194 DocIterator bestPos = owner_->par_iterator_begin();
3195 MacroData const * bestData = 0;
3197 // find macro definitions for name
3198 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3199 if (nameIt != macros.end()) {
3200 // find last definition in front of pos or at pos itself
3201 PositionScopeMacroMap::const_iterator it
3202 = greatest_below(nameIt->second, pos);
3203 if (it != nameIt->second.end()) {
3205 // scope ends behind pos?
3206 if (pos < it->second.scope) {
3207 // Looks good, remember this. If there
3208 // is no external macro behind this,
3209 // we found the right one already.
3210 bestPos = it->first;
3211 bestData = &it->second.macro;
3215 // try previous macro if there is one
3216 if (it == nameIt->second.begin())
3223 // find macros in included files
3224 PositionScopeBufferMap::const_iterator it
3225 = greatest_below(position_to_children, pos);
3226 if (it == position_to_children.end())
3227 // no children before
3231 // do we know something better (i.e. later) already?
3232 if (it->first < bestPos )
3235 // scope ends behind pos?
3236 if (pos < it->second.scope
3237 && (cloned_buffer_ ||
3238 theBufferList().isLoaded(it->second.buffer))) {
3239 // look for macro in external file
3241 MacroData const * data
3242 = it->second.buffer->getMacro(name, false);
3245 bestPos = it->first;
3251 // try previous file if there is one
3252 if (it == position_to_children.begin())
3257 // return the best macro we have found
3262 MacroData const * Buffer::getMacro(docstring const & name,
3263 DocIterator const & pos, bool global) const
3268 // query buffer macros
3269 MacroData const * data = d->getBufferMacro(name, pos);
3273 // If there is a master buffer, query that
3274 Buffer const * const pbuf = d->parent();
3276 d->macro_lock = true;
3277 MacroData const * macro = pbuf->getMacro(
3278 name, *this, false);
3279 d->macro_lock = false;
3285 data = MacroTable::globalMacros().get(name);
3294 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3296 // set scope end behind the last paragraph
3297 DocIterator scope = par_iterator_begin();
3298 scope.pit() = scope.lastpit() + 1;
3300 return getMacro(name, scope, global);
3304 MacroData const * Buffer::getMacro(docstring const & name,
3305 Buffer const & child, bool global) const
3307 // look where the child buffer is included first
3308 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3309 if (it == d->children_positions.end())
3312 // check for macros at the inclusion position
3313 return getMacro(name, it->second, global);
3317 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3319 pit_type const lastpit = it.lastpit();
3321 // look for macros in each paragraph
3322 while (it.pit() <= lastpit) {
3323 Paragraph & par = it.paragraph();
3325 // iterate over the insets of the current paragraph
3326 InsetList const & insets = par.insetList();
3327 InsetList::const_iterator iit = insets.begin();
3328 InsetList::const_iterator end = insets.end();
3329 for (; iit != end; ++iit) {
3330 it.pos() = iit->pos;
3332 // is it a nested text inset?
3333 if (iit->inset->asInsetText()) {
3334 // Inset needs its own scope?
3335 InsetText const * itext = iit->inset->asInsetText();
3336 bool newScope = itext->isMacroScope();
3338 // scope which ends just behind the inset
3339 DocIterator insetScope = it;
3342 // collect macros in inset
3343 it.push_back(CursorSlice(*iit->inset));
3344 updateMacros(it, newScope ? insetScope : scope);
3349 if (iit->inset->asInsetTabular()) {
3350 CursorSlice slice(*iit->inset);
3351 size_t const numcells = slice.nargs();
3352 for (; slice.idx() < numcells; slice.forwardIdx()) {
3353 it.push_back(slice);
3354 updateMacros(it, scope);
3360 // is it an external file?
3361 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3362 // get buffer of external file
3363 InsetInclude const & inset =
3364 static_cast<InsetInclude const &>(*iit->inset);
3366 Buffer * child = inset.getChildBuffer();
3371 // register its position, but only when it is
3372 // included first in the buffer
3373 if (children_positions.find(child) ==
3374 children_positions.end())
3375 children_positions[child] = it;
3377 // register child with its scope
3378 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3382 InsetMath * im = iit->inset->asInsetMath();
3383 if (doing_export && im) {
3384 InsetMathHull * hull = im->asHullInset();
3386 hull->recordLocation(it);
3389 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3393 MathMacroTemplate & macroTemplate =
3394 *iit->inset->asInsetMath()->asMacroTemplate();
3395 MacroContext mc(owner_, it);
3396 macroTemplate.updateToContext(mc);
3399 bool valid = macroTemplate.validMacro();
3400 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3401 // then the BufferView's cursor will be invalid in
3402 // some cases which leads to crashes.
3407 // FIXME (Abdel), I don't understand why we pass 'it' here
3408 // instead of 'macroTemplate' defined above... is this correct?
3409 macros[macroTemplate.name()][it] =
3410 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3420 void Buffer::updateMacros() const
3425 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3427 // start with empty table
3429 d->children_positions.clear();
3430 d->position_to_children.clear();
3432 // Iterate over buffer, starting with first paragraph
3433 // The scope must be bigger than any lookup DocIterator
3434 // later. For the global lookup, lastpit+1 is used, hence
3435 // we use lastpit+2 here.
3436 DocIterator it = par_iterator_begin();
3437 DocIterator outerScope = it;
3438 outerScope.pit() = outerScope.lastpit() + 2;
3439 d->updateMacros(it, outerScope);
3443 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3445 InsetIterator it = inset_iterator_begin(inset());
3446 InsetIterator const end = inset_iterator_end(inset());
3447 for (; it != end; ++it) {
3448 if (it->lyxCode() == BRANCH_CODE) {
3449 InsetBranch & br = static_cast<InsetBranch &>(*it);
3450 docstring const name = br.branch();
3451 if (!from_master && !params().branchlist().find(name))
3452 result.push_back(name);
3453 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3454 result.push_back(name);
3457 if (it->lyxCode() == INCLUDE_CODE) {
3458 // get buffer of external file
3459 InsetInclude const & ins =
3460 static_cast<InsetInclude const &>(*it);
3461 Buffer * child = ins.getChildBuffer();
3464 child->getUsedBranches(result, true);
3467 // remove duplicates
3472 void Buffer::updateMacroInstances(UpdateType utype) const
3474 LYXERR(Debug::MACROS, "updateMacroInstances for "
3475 << d->filename.onlyFileName());
3476 DocIterator it = doc_iterator_begin(this);
3478 DocIterator const end = doc_iterator_end(this);
3479 for (; it != end; it.forwardInset()) {
3480 // look for MathData cells in InsetMathNest insets
3481 InsetMath * minset = it.nextInset()->asInsetMath();
3485 // update macro in all cells of the InsetMathNest
3486 DocIterator::idx_type n = minset->nargs();
3487 MacroContext mc = MacroContext(this, it);
3488 for (DocIterator::idx_type i = 0; i < n; ++i) {
3489 MathData & data = minset->cell(i);
3490 data.updateMacros(0, mc, utype);
3496 void Buffer::listMacroNames(MacroNameSet & macros) const
3501 d->macro_lock = true;
3503 // loop over macro names
3504 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3505 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3506 for (; nameIt != nameEnd; ++nameIt)
3507 macros.insert(nameIt->first);
3509 // loop over children
3510 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3511 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3512 for (; it != end; ++it)
3513 it->first->listMacroNames(macros);
3516 Buffer const * const pbuf = d->parent();
3518 pbuf->listMacroNames(macros);
3520 d->macro_lock = false;
3524 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3526 Buffer const * const pbuf = d->parent();
3531 pbuf->listMacroNames(names);
3534 MacroNameSet::iterator it = names.begin();
3535 MacroNameSet::iterator end = names.end();
3536 for (; it != end; ++it) {
3538 MacroData const * data =
3539 pbuf->getMacro(*it, *this, false);
3541 macros.insert(data);
3543 // we cannot access the original MathMacroTemplate anymore
3544 // here to calls validate method. So we do its work here manually.
3545 // FIXME: somehow make the template accessible here.
3546 if (data->optionals() > 0)
3547 features.require("xargs");
3553 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3556 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3558 RefCache::iterator it = d->ref_cache_.find(label);
3559 if (it != d->ref_cache_.end())
3560 return it->second.second;
3562 static InsetLabel const * dummy_il = 0;
3563 static References const dummy_refs = References();
3564 it = d->ref_cache_.insert(
3565 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3566 return it->second.second;
3570 Buffer::References const & Buffer::references(docstring const & label) const
3572 return const_cast<Buffer *>(this)->getReferenceCache(label);
3576 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3578 References & refs = getReferenceCache(label);
3579 refs.push_back(make_pair(inset, it));
3583 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3585 masterBuffer()->d->ref_cache_[label].first = il;
3589 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3591 return masterBuffer()->d->ref_cache_[label].first;
3595 void Buffer::clearReferenceCache() const
3598 d->ref_cache_.clear();
3602 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3604 //FIXME: This does not work for child documents yet.
3605 reloadBibInfoCache();
3607 // Check if the label 'from' appears more than once
3608 BiblioInfo const & keys = masterBibInfo();
3609 BiblioInfo::const_iterator bit = keys.begin();
3610 BiblioInfo::const_iterator bend = keys.end();
3611 vector<docstring> labels;
3613 for (; bit != bend; ++bit)
3615 labels.push_back(bit->first);
3617 if (count(labels.begin(), labels.end(), from) > 1)
3620 string const paramName = "key";
3621 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3622 if (it->lyxCode() != CITE_CODE)
3624 InsetCommand * inset = it->asInsetCommand();
3625 docstring const oldValue = inset->getParam(paramName);
3626 if (oldValue == from)
3627 inset->setParam(paramName, to);
3631 // returns NULL if id-to-row conversion is unsupported
3632 auto_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3633 pit_type par_begin, pit_type par_end,
3634 OutputWhat output, bool master) const
3636 auto_ptr<TexRow> texrow(NULL);
3637 OutputParams runparams(¶ms().encoding());
3638 runparams.nice = true;
3639 runparams.flavor = params().getOutputFlavor(format);
3640 runparams.linelen = lyxrc.plaintext_linelen;
3641 // No side effect of file copying and image conversion
3642 runparams.dryrun = true;
3644 if (output == CurrentParagraph) {
3645 runparams.par_begin = par_begin;
3646 runparams.par_end = par_end;
3647 if (par_begin + 1 == par_end) {
3649 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3653 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3654 convert<docstring>(par_begin),
3655 convert<docstring>(par_end - 1))
3658 // output paragraphs
3659 if (runparams.flavor == OutputParams::LYX) {
3660 Paragraph const & par = text().paragraphs()[par_begin];
3662 depth_type dt = par.getDepth();
3663 par.write(ods, params(), dt);
3664 os << from_utf8(ods.str());
3665 } else if (runparams.flavor == OutputParams::HTML) {
3667 setMathFlavor(runparams);
3668 xhtmlParagraphs(text(), *this, xs, runparams);
3669 } else if (runparams.flavor == OutputParams::TEXT) {
3671 // FIXME Handles only one paragraph, unlike the others.
3672 // Probably should have some routine with a signature like them.
3673 writePlaintextParagraph(*this,
3674 text().paragraphs()[par_begin], os, runparams, dummy);
3675 } else if (params().isDocBook()) {
3676 docbookParagraphs(text(), *this, os, runparams);
3678 // If we are previewing a paragraph, even if this is the
3679 // child of some other buffer, let's cut the link here,
3680 // so that no concurring settings from the master
3681 // (e.g. branch state) interfere (see #8101).
3683 d->ignore_parent = true;
3684 // We need to validate the Buffer params' features here
3685 // in order to know if we should output polyglossia
3686 // macros (instead of babel macros)
3687 LaTeXFeatures features(*this, params(), runparams);
3688 params().validate(features);
3689 runparams.use_polyglossia = features.usePolyglossia();
3690 texrow.reset(new TexRow());
3693 // latex or literate
3694 otexstream ots(os, *texrow);
3697 latexParagraphs(*this, text(), ots, runparams);
3700 // Restore the parenthood
3702 d->ignore_parent = false;
3706 if (output == FullSource)
3707 os << _("Preview source code");
3708 else if (output == OnlyPreamble)
3709 os << _("Preview preamble");
3710 else if (output == OnlyBody)
3711 os << _("Preview body");
3713 if (runparams.flavor == OutputParams::LYX) {
3715 if (output == FullSource)
3717 else if (output == OnlyPreamble)
3718 params().writeFile(ods, this);
3719 else if (output == OnlyBody)
3721 os << from_utf8(ods.str());
3722 } else if (runparams.flavor == OutputParams::HTML) {
3723 writeLyXHTMLSource(os, runparams, output);
3724 } else if (runparams.flavor == OutputParams::TEXT) {
3725 if (output == OnlyPreamble) {
3726 os << "% "<< _("Plain text does not have a preamble.");
3728 writePlaintextFile(*this, os, runparams);
3729 } else if (params().isDocBook()) {
3730 writeDocBookSource(os, absFileName(), runparams, output);
3732 // latex or literate
3733 texrow.reset(new TexRow());
3736 otexstream ots(os, *texrow);
3738 runparams.is_child = true;
3739 writeLaTeXSource(ots, string(), runparams, output);
3747 ErrorList & Buffer::errorList(string const & type) const
3749 return d->errorLists[type];
3753 void Buffer::updateTocItem(std::string const & type,
3754 DocIterator const & dit) const
3757 d->gui_->updateTocItem(type, dit);
3761 void Buffer::structureChanged() const
3764 d->gui_->structureChanged();
3768 void Buffer::errors(string const & err, bool from_master) const
3771 d->gui_->errors(err, from_master);
3775 void Buffer::message(docstring const & msg) const
3778 d->gui_->message(msg);
3782 void Buffer::setBusy(bool on) const
3785 d->gui_->setBusy(on);
3789 void Buffer::updateTitles() const
3792 d->wa_->updateTitles();
3796 void Buffer::resetAutosaveTimers() const
3799 d->gui_->resetAutosaveTimers();
3803 bool Buffer::hasGuiDelegate() const
3809 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3818 class AutoSaveBuffer : public ForkedProcess {
3821 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3822 : buffer_(buffer), fname_(fname) {}
3824 virtual shared_ptr<ForkedProcess> clone() const
3826 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3831 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3832 from_utf8(fname_.absFileName())));
3833 return run(DontWait);
3837 virtual int generateChild();
3839 Buffer const & buffer_;
3844 int AutoSaveBuffer::generateChild()
3846 #if defined(__APPLE__)
3847 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3848 * We should use something else like threads.
3850 * Since I do not know how to determine at run time what is the OS X
3851 * version, I just disable forking altogether for now (JMarc)
3853 pid_t const pid = -1;
3855 // tmp_ret will be located (usually) in /tmp
3856 // will that be a problem?
3857 // Note that this calls ForkedCalls::fork(), so it's
3858 // ok cross-platform.
3859 pid_t const pid = fork();
3860 // If you want to debug the autosave
3861 // you should set pid to -1, and comment out the fork.
3862 if (pid != 0 && pid != -1)
3866 // pid = -1 signifies that lyx was unable
3867 // to fork. But we will do the save
3869 bool failed = false;
3870 TempFile tempfile("lyxautoXXXXXX.lyx");
3871 tempfile.setAutoRemove(false);
3872 FileName const tmp_ret = tempfile.name();
3873 if (!tmp_ret.empty()) {
3874 if (!buffer_.writeFile(tmp_ret))
3876 else if (!tmp_ret.moveTo(fname_))
3882 // failed to write/rename tmp_ret so try writing direct
3883 if (!buffer_.writeFile(fname_)) {
3884 // It is dangerous to do this in the child,
3885 // but safe in the parent, so...
3886 if (pid == -1) // emit message signal.
3887 buffer_.message(_("Autosave failed!"));
3891 if (pid == 0) // we are the child so...
3900 FileName Buffer::getEmergencyFileName() const
3902 return FileName(d->filename.absFileName() + ".emergency");
3906 FileName Buffer::getAutosaveFileName() const
3908 // if the document is unnamed try to save in the backup dir, else
3909 // in the default document path, and as a last try in the filePath,
3910 // which will most often be the temporary directory
3913 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3914 : lyxrc.backupdir_path;
3915 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3918 string const fname = "#" + d->filename.onlyFileName() + "#";
3920 return makeAbsPath(fname, fpath);
3924 void Buffer::removeAutosaveFile() const
3926 FileName const f = getAutosaveFileName();
3932 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3934 FileName const newauto = getAutosaveFileName();
3936 if (newauto != oldauto && oldauto.exists())
3937 if (!oldauto.moveTo(newauto))
3938 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3942 bool Buffer::autoSave() const
3944 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3945 if (buf->d->bak_clean || isReadonly())
3948 message(_("Autosaving current document..."));
3949 buf->d->bak_clean = true;
3951 FileName const fname = getAutosaveFileName();
3952 LASSERT(d->cloned_buffer_, return false);
3954 // If this buffer is cloned, we assume that
3955 // we are running in a separate thread already.
3956 TempFile tempfile("lyxautoXXXXXX.lyx");
3957 tempfile.setAutoRemove(false);
3958 FileName const tmp_ret = tempfile.name();
3959 if (!tmp_ret.empty()) {
3961 // assume successful write of tmp_ret
3962 if (tmp_ret.moveTo(fname))
3965 // failed to write/rename tmp_ret so try writing direct
3966 return writeFile(fname);
3970 void Buffer::setExportStatus(bool e) const
3972 d->doing_export = e;
3973 ListOfBuffers clist = getDescendents();
3974 ListOfBuffers::const_iterator cit = clist.begin();
3975 ListOfBuffers::const_iterator const cen = clist.end();
3976 for (; cit != cen; ++cit)
3977 (*cit)->d->doing_export = e;
3981 bool Buffer::isExporting() const
3983 return d->doing_export;
3987 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3991 return doExport(target, put_in_tempdir, result_file);
3994 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3995 string & result_file) const
3997 bool const update_unincluded =
3998 params().maintain_unincluded_children
3999 && !params().getIncludedChildren().empty();
4001 // (1) export with all included children (omit \includeonly)
4002 if (update_unincluded) {
4003 ExportStatus const status =
4004 doExport(target, put_in_tempdir, true, result_file);
4005 if (status != ExportSuccess)
4008 // (2) export with included children only
4009 return doExport(target, put_in_tempdir, false, result_file);
4013 void Buffer::setMathFlavor(OutputParams & op) const
4015 switch (params().html_math_output) {
4016 case BufferParams::MathML:
4017 op.math_flavor = OutputParams::MathAsMathML;
4019 case BufferParams::HTML:
4020 op.math_flavor = OutputParams::MathAsHTML;
4022 case BufferParams::Images:
4023 op.math_flavor = OutputParams::MathAsImages;
4025 case BufferParams::LaTeX:
4026 op.math_flavor = OutputParams::MathAsLaTeX;
4032 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4033 bool includeall, string & result_file) const
4035 LYXERR(Debug::FILES, "target=" << target);
4036 OutputParams runparams(¶ms().encoding());
4037 string format = target;
4038 string dest_filename;
4039 size_t pos = target.find(' ');
4040 if (pos != string::npos) {
4041 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4042 format = target.substr(0, pos);
4043 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4044 FileName(dest_filename).onlyPath().createPath();
4045 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4047 MarkAsExporting exporting(this);
4048 string backend_format;
4049 runparams.flavor = OutputParams::LATEX;
4050 runparams.linelen = lyxrc.plaintext_linelen;
4051 runparams.includeall = includeall;
4052 vector<string> backs = params().backends();
4053 Converters converters = theConverters();
4054 bool need_nice_file = false;
4055 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4056 // Get shortest path to format
4057 converters.buildGraph();
4058 Graph::EdgePath path;
4059 for (vector<string>::const_iterator it = backs.begin();
4060 it != backs.end(); ++it) {
4061 Graph::EdgePath p = converters.getPath(*it, format);
4062 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4063 backend_format = *it;
4068 if (!put_in_tempdir) {
4069 // Only show this alert if this is an export to a non-temporary
4070 // file (not for previewing).
4071 Alert::error(_("Couldn't export file"), bformat(
4072 _("No information for exporting the format %1$s."),
4073 formats.prettyName(format)));
4075 return ExportNoPathToFormat;
4077 runparams.flavor = converters.getFlavor(path, this);
4078 Graph::EdgePath::const_iterator it = path.begin();
4079 Graph::EdgePath::const_iterator en = path.end();
4080 for (; it != en; ++it)
4081 if (theConverters().get(*it).nice()) {
4082 need_nice_file = true;
4087 backend_format = format;
4088 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4089 // FIXME: Don't hardcode format names here, but use a flag
4090 if (backend_format == "pdflatex")
4091 runparams.flavor = OutputParams::PDFLATEX;
4092 else if (backend_format == "luatex")
4093 runparams.flavor = OutputParams::LUATEX;
4094 else if (backend_format == "dviluatex")
4095 runparams.flavor = OutputParams::DVILUATEX;
4096 else if (backend_format == "xetex")
4097 runparams.flavor = OutputParams::XETEX;
4100 string filename = latexName(false);
4101 filename = addName(temppath(), filename);
4102 filename = changeExtension(filename,
4103 formats.extension(backend_format));
4104 LYXERR(Debug::FILES, "filename=" << filename);
4106 // Plain text backend
4107 if (backend_format == "text") {
4108 runparams.flavor = OutputParams::TEXT;
4109 writePlaintextFile(*this, FileName(filename), runparams);
4112 else if (backend_format == "xhtml") {
4113 runparams.flavor = OutputParams::HTML;
4114 setMathFlavor(runparams);
4115 makeLyXHTMLFile(FileName(filename), runparams);
4116 } else if (backend_format == "lyx")
4117 writeFile(FileName(filename));
4119 else if (params().isDocBook()) {
4120 runparams.nice = !put_in_tempdir;
4121 makeDocBookFile(FileName(filename), runparams);
4124 else if (backend_format == format || need_nice_file) {
4125 runparams.nice = true;
4126 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4127 if (d->cloned_buffer_)
4128 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4131 } else if (!lyxrc.tex_allows_spaces
4132 && contains(filePath(), ' ')) {
4133 Alert::error(_("File name error"),
4134 _("The directory path to the document cannot contain spaces."));
4135 return ExportTexPathHasSpaces;
4137 runparams.nice = false;
4138 bool const success = makeLaTeXFile(
4139 FileName(filename), filePath(), runparams);
4140 if (d->cloned_buffer_)
4141 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4146 string const error_type = (format == "program")
4147 ? "Build" : params().bufferFormat();
4148 ErrorList & error_list = d->errorLists[error_type];
4149 string const ext = formats.extension(format);
4150 FileName const tmp_result_file(changeExtension(filename, ext));
4151 bool const success = converters.convert(this, FileName(filename),
4152 tmp_result_file, FileName(absFileName()), backend_format, format,
4155 // Emit the signal to show the error list or copy it back to the
4156 // cloned Buffer so that it can be emitted afterwards.
4157 if (format != backend_format) {
4158 if (runparams.silent)
4160 else if (d->cloned_buffer_)
4161 d->cloned_buffer_->d->errorLists[error_type] =
4162 d->errorLists[error_type];
4165 // also to the children, in case of master-buffer-view
4166 ListOfBuffers clist = getDescendents();
4167 ListOfBuffers::const_iterator cit = clist.begin();
4168 ListOfBuffers::const_iterator const cen = clist.end();
4169 for (; cit != cen; ++cit) {
4170 if (runparams.silent)
4171 (*cit)->d->errorLists[error_type].clear();
4172 else if (d->cloned_buffer_) {
4173 // Enable reverse search by copying back the
4174 // texrow object to the cloned buffer.
4175 // FIXME: this is not thread safe.
4176 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4177 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4178 (*cit)->d->errorLists[error_type];
4180 (*cit)->errors(error_type, true);
4184 if (d->cloned_buffer_) {
4185 // Enable reverse dvi or pdf to work by copying back the texrow
4186 // object to the cloned buffer.
4187 // FIXME: There is a possibility of concurrent access to texrow
4188 // here from the main GUI thread that should be securized.
4189 d->cloned_buffer_->d->texrow = d->texrow;
4190 string const error_type = params().bufferFormat();
4191 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4195 if (put_in_tempdir) {
4196 result_file = tmp_result_file.absFileName();
4197 return success ? ExportSuccess : ExportConverterError;
4200 if (dest_filename.empty())
4201 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4203 result_file = dest_filename;
4204 // We need to copy referenced files (e. g. included graphics
4205 // if format == "dvi") to the result dir.
4206 vector<ExportedFile> const files =
4207 runparams.exportdata->externalFiles(format);
4208 string const dest = runparams.export_folder.empty() ?
4209 onlyPath(result_file) : runparams.export_folder;
4210 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4211 : force_overwrite == ALL_FILES;
4212 CopyStatus status = use_force ? FORCE : SUCCESS;
4214 vector<ExportedFile>::const_iterator it = files.begin();
4215 vector<ExportedFile>::const_iterator const en = files.end();
4216 for (; it != en && status != CANCEL; ++it) {
4217 string const fmt = formats.getFormatFromFile(it->sourceName);
4218 string fixedName = it->exportName;
4219 if (!runparams.export_folder.empty()) {
4220 // Relative pathnames starting with ../ will be sanitized
4221 // if exporting to a different folder
4222 while (fixedName.substr(0, 3) == "../")
4223 fixedName = fixedName.substr(3, fixedName.length() - 3);
4225 FileName fixedFileName = makeAbsPath(fixedName, dest);
4226 fixedFileName.onlyPath().createPath();
4227 status = copyFile(fmt, it->sourceName,
4229 it->exportName, status == FORCE,
4230 runparams.export_folder.empty());
4233 if (status == CANCEL) {
4234 message(_("Document export cancelled."));
4235 return ExportCancel;
4238 if (tmp_result_file.exists()) {
4239 // Finally copy the main file
4240 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4241 : force_overwrite != NO_FILES;
4242 if (status == SUCCESS && use_force)
4244 status = copyFile(format, tmp_result_file,
4245 FileName(result_file), result_file,
4247 if (status == CANCEL) {
4248 message(_("Document export cancelled."));
4249 return ExportCancel;
4251 message(bformat(_("Document exported as %1$s "
4253 formats.prettyName(format),
4254 makeDisplayPath(result_file)));
4257 // This must be a dummy converter like fax (bug 1888)
4258 message(bformat(_("Document exported as %1$s"),
4259 formats.prettyName(format)));
4262 return success ? ExportSuccess : ExportConverterError;
4266 Buffer::ExportStatus Buffer::preview(string const & format) const
4268 bool const update_unincluded =
4269 params().maintain_unincluded_children
4270 && !params().getIncludedChildren().empty();
4271 return preview(format, update_unincluded);
4275 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4277 MarkAsExporting exporting(this);
4279 // (1) export with all included children (omit \includeonly)
4281 ExportStatus const status = doExport(format, true, true, result_file);
4282 if (status != ExportSuccess)
4285 // (2) export with included children only
4286 ExportStatus const status = doExport(format, true, false, result_file);
4287 FileName const previewFile(result_file);
4289 LATTEST (isClone());
4290 d->cloned_buffer_->d->preview_file_ = previewFile;
4291 d->cloned_buffer_->d->preview_format_ = format;
4292 d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4294 if (status != ExportSuccess)
4296 if (previewFile.exists()) {
4297 if (!formats.view(*this, previewFile, format))
4298 return PreviewError;
4300 return PreviewSuccess;
4303 // Successful export but no output file?
4304 // Probably a bug in error detection.
4305 LATTEST (status != ExportSuccess);
4312 Buffer::ReadStatus Buffer::extractFromVC()
4314 bool const found = LyXVC::file_not_found_hook(d->filename);
4316 return ReadFileNotFound;
4317 if (!d->filename.isReadableFile())
4323 Buffer::ReadStatus Buffer::loadEmergency()
4325 FileName const emergencyFile = getEmergencyFileName();
4326 if (!emergencyFile.exists()
4327 || emergencyFile.lastModified() <= d->filename.lastModified())
4328 return ReadFileNotFound;
4330 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4331 docstring const text = bformat(_("An emergency save of the document "
4332 "%1$s exists.\n\nRecover emergency save?"), file);
4334 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4335 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4341 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4342 bool const success = (ret_llf == ReadSuccess);
4345 Alert::warning(_("File is read-only"),
4346 bformat(_("An emergency file is successfully loaded, "
4347 "but the original file %1$s is marked read-only. "
4348 "Please make sure to save the document as a different "
4349 "file."), from_utf8(d->filename.absFileName())));
4352 lyxvc().file_found_hook(d->filename);
4353 str = _("Document was successfully recovered.");
4355 str = _("Document was NOT successfully recovered.");
4356 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4357 makeDisplayPath(emergencyFile.absFileName()));
4359 int const del_emerg =
4360 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4361 _("&Remove"), _("&Keep"));
4362 if (del_emerg == 0) {
4363 emergencyFile.removeFile();
4365 Alert::warning(_("Emergency file deleted"),
4366 _("Do not forget to save your file now!"), true);
4368 return success ? ReadSuccess : ReadEmergencyFailure;
4371 int const del_emerg =
4372 Alert::prompt(_("Delete emergency file?"),
4373 _("Remove emergency file now?"), 1, 1,
4374 _("&Remove"), _("&Keep"));
4376 emergencyFile.removeFile();
4377 return ReadOriginal;
4387 Buffer::ReadStatus Buffer::loadAutosave()
4389 // Now check if autosave file is newer.
4390 FileName const autosaveFile = getAutosaveFileName();
4391 if (!autosaveFile.exists()
4392 || autosaveFile.lastModified() <= d->filename.lastModified())
4393 return ReadFileNotFound;
4395 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4396 docstring const text = bformat(_("The backup of the document %1$s "
4397 "is newer.\n\nLoad the backup instead?"), file);
4398 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4399 _("&Load backup"), _("Load &original"), _("&Cancel"));
4404 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4405 // the file is not saved if we load the autosave file.
4406 if (ret_llf == ReadSuccess) {
4408 Alert::warning(_("File is read-only"),
4409 bformat(_("A backup file is successfully loaded, "
4410 "but the original file %1$s is marked read-only. "
4411 "Please make sure to save the document as a "
4413 from_utf8(d->filename.absFileName())));
4416 lyxvc().file_found_hook(d->filename);
4419 return ReadAutosaveFailure;
4422 // Here we delete the autosave
4423 autosaveFile.removeFile();
4424 return ReadOriginal;
4432 Buffer::ReadStatus Buffer::loadLyXFile()
4434 if (!d->filename.isReadableFile()) {
4435 ReadStatus const ret_rvc = extractFromVC();
4436 if (ret_rvc != ReadSuccess)
4440 ReadStatus const ret_re = loadEmergency();
4441 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4444 ReadStatus const ret_ra = loadAutosave();
4445 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4448 return loadThisLyXFile(d->filename);
4452 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4454 return readFile(fn);
4458 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4460 TeXErrors::Errors::const_iterator it = terr.begin();
4461 TeXErrors::Errors::const_iterator end = terr.end();
4462 ListOfBuffers clist = getDescendents();
4463 ListOfBuffers::const_iterator cen = clist.end();
4465 for (; it != end; ++it) {
4468 int errorRow = it->error_in_line;
4469 Buffer const * buf = 0;
4471 if (it->child_name.empty())
4472 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4474 // The error occurred in a child
4475 ListOfBuffers::const_iterator cit = clist.begin();
4476 for (; cit != cen; ++cit) {
4477 string const child_name =
4478 DocFileName(changeExtension(
4479 (*cit)->absFileName(), "tex")).
4481 if (it->child_name != child_name)
4483 (*cit)->d->texrow.getIdFromRow(errorRow,
4484 id_start, pos_start);
4485 if (id_start != -1) {
4486 buf = d->cloned_buffer_
4487 ? (*cit)->d->cloned_buffer_->d->owner_
4488 : (*cit)->d->owner_;
4499 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4500 } while (found && id_start == id_end && pos_start == pos_end);
4502 if (id_start != id_end) {
4503 // Next registered position is outside the inset where
4504 // the error occurred, so signal end-of-paragraph
4508 errorList.push_back(ErrorItem(it->error_desc,
4509 it->error_text, id_start, pos_start, pos_end, buf));
4514 void Buffer::setBuffersForInsets() const
4516 inset().setBuffer(const_cast<Buffer &>(*this));
4520 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4522 LBUFERR(!text().paragraphs().empty());
4524 // Use the master text class also for child documents
4525 Buffer const * const master = masterBuffer();
4526 DocumentClass const & textclass = master->params().documentClass();
4528 // do this only if we are the top-level Buffer
4529 if (master == this) {
4530 textclass.counters().reset(from_ascii("bibitem"));
4531 reloadBibInfoCache();
4534 // keep the buffers to be children in this set. If the call from the
4535 // master comes back we can see which of them were actually seen (i.e.
4536 // via an InsetInclude). The remaining ones in the set need still be updated.
4537 static std::set<Buffer const *> bufToUpdate;
4538 if (scope == UpdateMaster) {
4539 // If this is a child document start with the master
4540 if (master != this) {
4541 bufToUpdate.insert(this);
4542 master->updateBuffer(UpdateMaster, utype);
4543 // If the master buffer has no gui associated with it, then the TocModel is
4544 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4545 // (bug 5699). The same happens if the master buffer is open in a different
4546 // window. This test catches both possibilities.
4547 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4548 // There remains a problem here: If there is another child open in yet a third
4549 // window, that TOC is not updated. So some more general solution is needed at
4551 if (master->d->gui_ != d->gui_)
4554 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4555 if (bufToUpdate.find(this) == bufToUpdate.end())
4559 // start over the counters in the master
4560 textclass.counters().reset();
4563 // update will be done below for this buffer
4564 bufToUpdate.erase(this);
4566 // update all caches
4567 clearReferenceCache();
4570 Buffer & cbuf = const_cast<Buffer &>(*this);
4573 ParIterator parit = cbuf.par_iterator_begin();
4574 updateBuffer(parit, utype);
4577 // TocBackend update will be done later.
4580 d->bibinfo_cache_valid_ = true;
4581 d->cite_labels_valid_ = true;
4583 cbuf.tocBackend().update(true, utype);
4584 if (scope == UpdateMaster)
4585 cbuf.structureChanged();
4589 static depth_type getDepth(DocIterator const & it)
4591 depth_type depth = 0;
4592 for (size_t i = 0 ; i < it.depth() ; ++i)
4593 if (!it[i].inset().inMathed())
4594 depth += it[i].paragraph().getDepth() + 1;
4595 // remove 1 since the outer inset does not count
4599 static depth_type getItemDepth(ParIterator const & it)
4601 Paragraph const & par = *it;
4602 LabelType const labeltype = par.layout().labeltype;
4604 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4607 // this will hold the lowest depth encountered up to now.
4608 depth_type min_depth = getDepth(it);
4609 ParIterator prev_it = it;
4612 --prev_it.top().pit();
4614 // start of nested inset: go to outer par
4616 if (prev_it.empty()) {
4617 // start of document: nothing to do
4622 // We search for the first paragraph with same label
4623 // that is not more deeply nested.
4624 Paragraph & prev_par = *prev_it;
4625 depth_type const prev_depth = getDepth(prev_it);
4626 if (labeltype == prev_par.layout().labeltype) {
4627 if (prev_depth < min_depth)
4628 return prev_par.itemdepth + 1;
4629 if (prev_depth == min_depth)
4630 return prev_par.itemdepth;
4632 min_depth = min(min_depth, prev_depth);
4633 // small optimization: if we are at depth 0, we won't
4634 // find anything else
4635 if (prev_depth == 0)
4641 static bool needEnumCounterReset(ParIterator const & it)
4643 Paragraph const & par = *it;
4644 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4645 depth_type const cur_depth = par.getDepth();
4646 ParIterator prev_it = it;
4647 while (prev_it.pit()) {
4648 --prev_it.top().pit();
4649 Paragraph const & prev_par = *prev_it;
4650 if (prev_par.getDepth() <= cur_depth)
4651 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4653 // start of nested inset: reset
4658 // set the label of a paragraph. This includes the counters.
4659 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4661 BufferParams const & bp = owner_->masterBuffer()->params();
4662 DocumentClass const & textclass = bp.documentClass();
4663 Paragraph & par = it.paragraph();
4664 Layout const & layout = par.layout();
4665 Counters & counters = textclass.counters();
4667 if (par.params().startOfAppendix()) {
4668 // We want to reset the counter corresponding to toplevel sectioning
4669 Layout const & lay = textclass.getTOCLayout();
4670 docstring const cnt = lay.counter;
4672 counters.reset(cnt);
4673 counters.appendix(true);
4675 par.params().appendix(counters.appendix());
4677 // Compute the item depth of the paragraph
4678 par.itemdepth = getItemDepth(it);
4680 if (layout.margintype == MARGIN_MANUAL) {
4681 if (par.params().labelWidthString().empty())
4682 par.params().labelWidthString(par.expandLabel(layout, bp));
4683 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4684 // we do not need to do anything here, since the empty case is
4685 // handled during export.
4687 par.params().labelWidthString(docstring());
4690 switch(layout.labeltype) {
4691 case LABEL_ITEMIZE: {
4692 // At some point of time we should do something more
4693 // clever here, like:
4694 // par.params().labelString(
4695 // bp.user_defined_bullet(par.itemdepth).getText());
4696 // for now, use a simple hardcoded label
4697 docstring itemlabel;
4698 switch (par.itemdepth) {
4700 itemlabel = char_type(0x2022);
4703 itemlabel = char_type(0x2013);
4706 itemlabel = char_type(0x2217);
4709 itemlabel = char_type(0x2219); // or 0x00b7
4712 par.params().labelString(itemlabel);
4716 case LABEL_ENUMERATE: {
4717 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4719 switch (par.itemdepth) {
4728 enumcounter += "iv";
4731 // not a valid enumdepth...
4735 // Maybe we have to reset the enumeration counter.
4736 if (needEnumCounterReset(it))
4737 counters.reset(enumcounter);
4738 counters.step(enumcounter, utype);
4740 string const & lang = par.getParLanguage(bp)->code();
4741 par.params().labelString(counters.theCounter(enumcounter, lang));
4746 case LABEL_SENSITIVE: {
4747 string const & type = counters.current_float();
4748 docstring full_label;
4750 full_label = owner_->B_("Senseless!!! ");
4752 docstring name = owner_->B_(textclass.floats().getType(type).name());
4753 if (counters.hasCounter(from_utf8(type))) {
4754 string const & lang = par.getParLanguage(bp)->code();
4755 counters.step(from_utf8(type), utype);
4756 full_label = bformat(from_ascii("%1$s %2$s:"),
4758 counters.theCounter(from_utf8(type), lang));
4760 full_label = bformat(from_ascii("%1$s #:"), name);
4762 par.params().labelString(full_label);
4766 case LABEL_NO_LABEL:
4767 par.params().labelString(docstring());
4771 case LABEL_CENTERED:
4772 case LABEL_STATIC: {
4773 docstring const & lcounter = layout.counter;
4774 if (!lcounter.empty()) {
4775 if (layout.toclevel <= bp.secnumdepth
4776 && (layout.latextype != LATEX_ENVIRONMENT
4777 || it.text()->isFirstInSequence(it.pit()))) {
4778 if (counters.hasCounter(lcounter))
4779 counters.step(lcounter, utype);
4780 par.params().labelString(par.expandLabel(layout, bp));
4782 par.params().labelString(docstring());
4784 par.params().labelString(par.expandLabel(layout, bp));
4790 par.params().labelString(par.expandLabel(layout, bp));
4795 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4797 // LASSERT: Is it safe to continue here, or should we just return?
4798 LASSERT(parit.pit() == 0, /**/);
4800 // Set the position of the text in the buffer to be able
4801 // to resolve macros in it.
4802 parit.text()->setMacrocontextPosition(parit);
4804 depth_type maxdepth = 0;
4805 pit_type const lastpit = parit.lastpit();
4806 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4807 // reduce depth if necessary
4808 if (parit->params().depth() > maxdepth) {
4809 /** FIXME: this function is const, but
4810 * nevertheless it modifies the buffer. To be
4811 * cleaner, one should modify the buffer in
4812 * another function, which is actually
4813 * non-const. This would however be costly in
4814 * terms of code duplication.
4816 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4817 parit->params().depth(maxdepth);
4819 maxdepth = parit->getMaxDepthAfter();
4821 if (utype == OutputUpdate) {
4822 // track the active counters
4823 // we have to do this for the master buffer, since the local
4824 // buffer isn't tracking anything.
4825 masterBuffer()->params().documentClass().counters().
4826 setActiveLayout(parit->layout());
4829 // set the counter for this paragraph
4830 d->setLabel(parit, utype);
4833 InsetList::const_iterator iit = parit->insetList().begin();
4834 InsetList::const_iterator end = parit->insetList().end();
4835 for (; iit != end; ++iit) {
4836 parit.pos() = iit->pos;
4837 iit->inset->updateBuffer(parit, utype);
4843 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4844 WordLangTuple & word_lang, docstring_list & suggestions) const
4848 suggestions.clear();
4849 word_lang = WordLangTuple();
4850 bool const to_end = to.empty();
4851 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4852 // OK, we start from here.
4853 for (; from != end; from.forwardPos()) {
4854 // This skips all insets with spell check disabled.
4855 while (!from.allowSpellCheck()) {
4859 // If from is at the end of the document (which is possible
4860 // when "from" was changed above) LyX will crash later otherwise.
4861 if (from.atEnd() || (!to_end && from >= end))
4864 from.paragraph().spellCheck();
4865 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4866 if (SpellChecker::misspelled(res)) {
4870 // Do not increase progress when from == to, otherwise the word
4871 // count will be wrong.
4881 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4883 bool inword = false;
4888 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4889 if (!dit.inTexted()) {
4894 Paragraph const & par = dit.paragraph();
4895 pos_type const pos = dit.pos();
4897 // Copied and adapted from isWordSeparator() in Paragraph
4898 if (pos == dit.lastpos()) {
4901 Inset const * ins = par.getInset(pos);
4902 if (ins && skipNoOutput && !ins->producesOutput()) {
4905 // stop if end of range was skipped
4906 if (!to.atEnd() && dit >= to)
4909 } else if (!par.isDeleted(pos)) {
4910 if (par.isWordSeparator(pos))
4916 if (ins && ins->isLetter())
4918 else if (ins && ins->isSpace())
4921 char_type const c = par.getChar(pos);
4922 if (isPrintableNonspace(c))
4924 else if (isSpace(c))
4934 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4936 d->updateStatistics(from, to, skipNoOutput);
4940 int Buffer::wordCount() const
4942 return d->wordCount();
4946 int Buffer::charCount(bool with_blanks) const
4948 return d->charCount(with_blanks);
4952 Buffer::ReadStatus Buffer::reload()
4955 // c.f. bug http://www.lyx.org/trac/ticket/6587
4956 removeAutosaveFile();
4957 // e.g., read-only status could have changed due to version control
4958 d->filename.refresh();
4959 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4961 // clear parent. this will get reset if need be.
4963 ReadStatus const status = loadLyXFile();
4964 if (status == ReadSuccess) {
4969 message(bformat(_("Document %1$s reloaded."), disp_fn));
4972 message(bformat(_("Could not reload document %1$s."), disp_fn));
4982 bool Buffer::saveAs(FileName const & fn)
4984 FileName const old_name = fileName();
4985 FileName const old_auto = getAutosaveFileName();
4986 bool const old_unnamed = isUnnamed();
4987 bool success = true;
4988 d->old_position = filePath();
4995 // bring the autosave file with us, just in case.
4996 moveAutosaveFile(old_auto);
4997 // validate version control data and
4998 // correct buffer title
4999 lyxvc().file_found_hook(fileName());
5001 // the file has now been saved to the new location.
5002 // we need to check that the locations of child buffers
5004 checkChildBuffers();
5005 checkMasterBuffer();
5008 // reset the old filename and unnamed state
5009 setFileName(old_name);
5010 setUnnamed(old_unnamed);
5014 d->old_position.clear();
5019 void Buffer::checkChildBuffers()
5021 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5022 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5023 for (; it != en; ++it) {
5024 DocIterator dit = it->second;
5025 Buffer * cbuf = const_cast<Buffer *>(it->first);
5026 if (!cbuf || !theBufferList().isLoaded(cbuf))
5028 Inset * inset = dit.nextInset();
5029 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5030 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5031 docstring const & incfile = inset_inc->getParam("filename");
5032 string oldloc = cbuf->absFileName();
5033 string newloc = makeAbsPath(to_utf8(incfile),
5034 onlyPath(absFileName())).absFileName();
5035 if (oldloc == newloc)
5037 // the location of the child file is incorrect.
5039 inset_inc->setChildBuffer(0);
5041 // invalidate cache of children
5042 d->children_positions.clear();
5043 d->position_to_children.clear();
5047 // If a child has been saved under a different name/path, it might have been
5048 // orphaned. Therefore the master needs to be reset (bug 8161).
5049 void Buffer::checkMasterBuffer()
5051 Buffer const * const master = masterBuffer();
5055 // necessary to re-register the child (bug 5873)
5056 // FIXME: clean up updateMacros (here, only
5057 // child registering is needed).
5058 master->updateMacros();
5059 // (re)set master as master buffer, but only
5060 // if we are a real child
5061 if (master->isChild(this))
5068 string Buffer::includedFilePath(string const & name, string const & ext) const
5070 bool isabsolute = FileName::isAbsolute(name);
5071 // old_position already contains a trailing path separator
5072 string const absname = isabsolute ? name : d->old_position + name;
5074 if (d->old_position.empty()
5075 || equivalent(FileName(d->old_position), FileName(filePath()))
5076 || !FileName(addExtension(absname, ext)).exists())
5080 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5082 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5083 from_utf8(filePath())));