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;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
154 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
158 delete preview_loader_;
166 /// search for macro in local (buffer) table or in children
167 MacroData const * getBufferMacro(docstring const & name,
168 DocIterator const & pos) const;
170 /// Update macro table starting with position of it \param it in some
172 void updateMacros(DocIterator & it, DocIterator & scope);
174 void setLabel(ParIterator & it, UpdateType utype) const;
176 /** If we have branches that use the file suffix
177 feature, return the file name with suffix appended.
179 support::FileName exportFileName() const;
186 mutable TexRow texrow;
188 /// need to regenerate .tex?
192 mutable bool lyx_clean;
194 /// is autosave needed?
195 mutable bool bak_clean;
197 /// is this an unnamed file (New...)?
200 /// is this an internal bufffer?
201 bool internal_buffer;
206 /// name of the file the buffer is associated with.
209 /** Set to true only when the file is fully loaded.
210 * Used to prevent the premature generation of previews
211 * and by the citation inset.
213 bool file_fully_loaded;
215 /// Ignore the parent (e.g. when exporting a child standalone)?
219 mutable TocBackend toc_backend;
224 ScopeMacro(DocIterator const & s, MacroData const & m)
225 : scope(s), macro(m) {}
229 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
230 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
231 /// map from the macro name to the position map,
232 /// which maps the macro definition position to the scope and the MacroData.
233 NamePositionScopeMacroMap macros;
234 /// This seem to change the way Buffer::getMacro() works
235 mutable bool macro_lock;
237 /// positions of child buffers in the buffer
238 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
241 ScopeBuffer(DocIterator const & s,Buffer const * b)
242 : scope(s), buffer(b) {}
244 Buffer const * buffer;
246 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
247 /// position of children buffers in this buffer
248 BufferPositionMap children_positions;
249 /// map from children inclusion positions to their scope and their buffer
250 PositionScopeBufferMap position_to_children;
252 /// Container for all sort of Buffer dependant errors.
253 map<string, ErrorList> errorLists;
255 /// timestamp and checksum used to test if the file has been externally
256 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
258 unsigned long checksum_;
261 frontend::WorkAreaManager * wa_;
263 frontend::GuiBufferDelegate * gui_;
268 /// A cache for the bibfiles (including bibfiles of loaded child
269 /// documents), needed for appropriate update of natbib labels.
270 mutable support::FileNameList bibfiles_cache_;
272 // FIXME The caching mechanism could be improved. At present, we have a
273 // cache for each Buffer, that caches all the bibliography info for that
274 // Buffer. A more efficient solution would be to have a global cache per
275 // file, and then to construct the Buffer's bibinfo from that.
276 /// A cache for bibliography info
277 mutable BiblioInfo bibinfo_;
278 /// whether the bibinfo cache is valid
279 mutable bool bibinfo_cache_valid_;
280 /// whether the bibfile cache is valid
281 mutable bool bibfile_cache_valid_;
282 /// Cache of timestamps of .bib files
283 map<FileName, time_t> bibfile_status_;
284 /// Indicates whether the bibinfo has changed since the last time
285 /// we ran updateBuffer(), i.e., whether citation labels may need
287 mutable bool cite_labels_valid_;
289 mutable RefCache ref_cache_;
291 /// our Text that should be wrapped in an InsetText
295 PreviewLoader * preview_loader_;
297 /// This is here to force the test to be done whenever parent_buffer
299 Buffer const * parent() const
301 // ignore_parent temporarily "orphans" a buffer
302 // (e.g. if a child is compiled standalone)
305 // if parent_buffer is not loaded, then it has been unloaded,
306 // which means that parent_buffer is an invalid pointer. So we
307 // set it to null in that case.
308 // however, the BufferList doesn't know about cloned buffers, so
309 // they will always be regarded as unloaded. in that case, we hope
311 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
313 return parent_buffer;
317 void setParent(Buffer const * pb)
319 if (parent_buffer == pb)
322 if (!cloned_buffer_ && parent_buffer && pb)
323 LYXERR0("Warning: a buffer should not have two parents!");
325 if (!cloned_buffer_ && parent_buffer) {
326 parent_buffer->invalidateBibfileCache();
327 parent_buffer->invalidateBibinfoCache();
331 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
332 /// This one is useful for preview detached in a thread.
333 Buffer const * cloned_buffer_;
335 CloneList * clone_list_;
336 /// are we in the process of exporting this buffer?
337 mutable bool doing_export;
339 /// compute statistics
340 /// \p from initial position
341 /// \p to points to the end position
342 void updateStatistics(DocIterator & from, DocIterator & to,
343 bool skipNoOutput = true);
344 /// statistics accessor functions
345 int wordCount() const
349 int charCount(bool with_blanks) const
352 + (with_blanks ? blank_count_ : 0);
356 /// So we can force access via the accessors.
357 mutable Buffer const * parent_buffer;
366 /// Creates the per buffer temporary directory
367 static FileName createBufferTmpDir()
369 // FIXME This would be the ideal application for a TempDir class (like
370 // TempFile but for directories)
375 Mutex::Locker locker(&mutex);
376 counter = convert<string>(count++);
378 // We are in our own directory. Why bother to mangle name?
379 // In fact I wrote this code to circumvent a problematic behaviour
380 // (bug?) of EMX mkstemp().
381 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
384 if (!tmpfl.createDirectory(0777)) {
385 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
386 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
387 from_utf8(tmpfl.absFileName())));
393 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
394 Buffer const * cloned_buffer)
395 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
396 internal_buffer(false), read_only(readonly_), filename(file),
397 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
398 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
399 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
400 cite_labels_valid_(false), inset(0), preview_loader_(0),
401 cloned_buffer_(cloned_buffer), clone_list_(0),
402 doing_export(false), parent_buffer(0),
403 word_count_(0), char_count_(0), blank_count_(0)
405 if (!cloned_buffer_) {
406 temppath = createBufferTmpDir();
407 lyxvc.setBuffer(owner_);
409 wa_ = new frontend::WorkAreaManager;
412 temppath = cloned_buffer_->d->temppath;
413 file_fully_loaded = true;
414 params = cloned_buffer_->d->params;
415 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
416 bibinfo_ = cloned_buffer_->d->bibinfo_;
417 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
418 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
419 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
420 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
421 unnamed = cloned_buffer_->d->unnamed;
422 internal_buffer = cloned_buffer_->d->internal_buffer;
426 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
427 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
429 LYXERR(Debug::INFO, "Buffer::Buffer()");
431 d->inset = new InsetText(*cloned_buffer->d->inset);
432 d->inset->setBuffer(*this);
433 // FIXME: optimize this loop somewhat, maybe by creating a new
434 // general recursive Inset::setId().
435 DocIterator it = doc_iterator_begin(this);
436 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
437 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
438 it.paragraph().setId(cloned_it.paragraph().id());
440 d->inset = new InsetText(this);
441 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
447 LYXERR(Debug::INFO, "Buffer::~Buffer()");
448 // here the buffer should take care that it is
449 // saved properly, before it goes into the void.
451 // GuiView already destroyed
455 // No need to do additional cleanups for internal buffer.
461 // this is in case of recursive includes: we won't try to delete
462 // ourselves as a child.
463 d->clone_list_->erase(this);
464 // loop over children
465 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
466 Impl::BufferPositionMap::iterator end = d->children_positions.end();
467 for (; it != end; ++it) {
468 Buffer * child = const_cast<Buffer *>(it->first);
469 if (d->clone_list_->erase(child))
472 // if we're the master buffer, then we should get rid of the list
475 // If this is not empty, we have leaked something. Worse, one of the
476 // children still has a reference to this list. But we will try to
477 // continue, rather than shut down.
478 LATTEST(d->clone_list_->empty());
479 list<CloneList *>::iterator it =
480 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
481 if (it == cloned_buffers.end()) {
482 // We will leak in this case, but it is safe to continue.
485 cloned_buffers.erase(it);
486 delete d->clone_list_;
488 // FIXME Do we really need to do this right before we delete d?
489 // clear references to children in macro tables
490 d->children_positions.clear();
491 d->position_to_children.clear();
493 // loop over children
494 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
495 Impl::BufferPositionMap::iterator end = d->children_positions.end();
496 for (; it != end; ++it) {
497 Buffer * child = const_cast<Buffer *>(it->first);
498 if (theBufferList().isLoaded(child))
499 theBufferList().releaseChild(this, child);
503 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
504 msg += emergencyWrite();
505 Alert::warning(_("Attempting to close changed document!"), msg);
508 // FIXME Do we really need to do this right before we delete d?
509 // clear references to children in macro tables
510 d->children_positions.clear();
511 d->position_to_children.clear();
513 if (!d->temppath.destroyDirectory()) {
514 Alert::warning(_("Could not remove temporary directory"),
515 bformat(_("Could not remove the temporary directory %1$s"),
516 from_utf8(d->temppath.absFileName())));
525 Buffer * Buffer::cloneFromMaster() const
528 cloned_buffers.push_back(new CloneList);
529 CloneList * clones = cloned_buffers.back();
531 masterBuffer()->cloneWithChildren(bufmap, clones);
533 // make sure we got cloned
534 BufferMap::const_iterator bit = bufmap.find(this);
535 LASSERT(bit != bufmap.end(), return 0);
536 Buffer * cloned_buffer = bit->second;
538 return cloned_buffer;
542 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
544 // have we already been cloned?
545 if (bufmap.find(this) != bufmap.end())
548 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
550 // The clone needs its own DocumentClass, since running updateBuffer() will
551 // modify it, and we would otherwise be sharing it with the original Buffer.
552 buffer_clone->params().makeDocumentClass(true);
554 cap::switchBetweenClasses(
555 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
556 static_cast<InsetText &>(buffer_clone->inset()), el);
558 bufmap[this] = buffer_clone;
559 clones->insert(buffer_clone);
560 buffer_clone->d->clone_list_ = clones;
561 buffer_clone->d->macro_lock = true;
562 buffer_clone->d->children_positions.clear();
564 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
565 // math macro caches need to be rethought and simplified.
566 // I am not sure wether we should handle Buffer cloning here or in BufferList.
567 // Right now BufferList knows nothing about buffer clones.
568 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
569 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
570 for (; it != end; ++it) {
571 DocIterator dit = it->first.clone(buffer_clone);
572 dit.setBuffer(buffer_clone);
573 Buffer * child = const_cast<Buffer *>(it->second.buffer);
575 child->cloneWithChildren(bufmap, clones);
576 BufferMap::iterator const bit = bufmap.find(child);
577 LASSERT(bit != bufmap.end(), continue);
578 Buffer * child_clone = bit->second;
580 Inset * inset = dit.nextInset();
581 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
582 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
583 inset_inc->setChildBuffer(child_clone);
584 child_clone->d->setParent(buffer_clone);
585 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
586 buffer_clone->setChild(dit, child_clone);
588 buffer_clone->d->macro_lock = false;
593 Buffer * Buffer::cloneBufferOnly() const {
594 cloned_buffers.push_back(new CloneList);
595 CloneList * clones = cloned_buffers.back();
596 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
598 // The clone needs its own DocumentClass, since running updateBuffer() will
599 // modify it, and we would otherwise be sharing it with the original Buffer.
600 buffer_clone->params().makeDocumentClass(true);
602 cap::switchBetweenClasses(
603 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
604 static_cast<InsetText &>(buffer_clone->inset()), el);
606 clones->insert(buffer_clone);
607 buffer_clone->d->clone_list_ = clones;
609 // we won't be cloning the children
610 buffer_clone->d->children_positions.clear();
615 bool Buffer::isClone() const
617 return d->cloned_buffer_;
621 void Buffer::changed(bool update_metrics) const
624 d->wa_->redrawAll(update_metrics);
628 frontend::WorkAreaManager & Buffer::workAreaManager() const
635 Text & Buffer::text() const
637 return d->inset->text();
641 Inset & Buffer::inset() const
647 BufferParams & Buffer::params()
653 BufferParams const & Buffer::params() const
659 BufferParams const & Buffer::masterParams() const
661 if (masterBuffer() == this)
664 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
665 // Copy child authors to the params. We need those pointers.
666 AuthorList const & child_authors = params().authors();
667 AuthorList::Authors::const_iterator it = child_authors.begin();
668 for (; it != child_authors.end(); ++it)
669 mparams.authors().record(*it);
674 double Buffer::fontScalingFactor() const
676 return isExporting() ? 75.0 * params().html_math_img_scale
677 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
681 ParagraphList & Buffer::paragraphs()
683 return text().paragraphs();
687 ParagraphList const & Buffer::paragraphs() const
689 return text().paragraphs();
693 LyXVC & Buffer::lyxvc()
699 LyXVC const & Buffer::lyxvc() const
705 string const Buffer::temppath() const
707 return d->temppath.absFileName();
711 TexRow & Buffer::texrow()
717 TexRow const & Buffer::texrow() const
723 TocBackend & Buffer::tocBackend() const
725 return d->toc_backend;
729 Undo & Buffer::undo()
735 void Buffer::setChild(DocIterator const & dit, Buffer * child)
737 d->children_positions[child] = dit;
741 string Buffer::latexName(bool const no_path) const
743 FileName latex_name =
744 makeLatexName(d->exportFileName());
745 return no_path ? latex_name.onlyFileName()
746 : latex_name.absFileName();
750 FileName Buffer::Impl::exportFileName() const
752 docstring const branch_suffix =
753 params.branchlist().getFileNameSuffix();
754 if (branch_suffix.empty())
757 string const name = filename.onlyFileNameWithoutExt()
758 + to_utf8(branch_suffix);
759 FileName res(filename.onlyPath().absFileName() + "/" + name);
760 res.changeExtension(filename.extension());
766 string Buffer::logName(LogType * type) const
768 string const filename = latexName(false);
770 if (filename.empty()) {
776 string const path = temppath();
778 FileName const fname(addName(temppath(),
779 onlyFileName(changeExtension(filename,
782 // FIXME: how do we know this is the name of the build log?
783 FileName const bname(
784 addName(path, onlyFileName(
785 changeExtension(filename,
786 formats.extension(params().bufferFormat()) + ".out"))));
788 // Also consider the master buffer log file
789 FileName masterfname = fname;
790 LogType mtype = latexlog;
791 if (masterBuffer() != this) {
792 string const mlogfile = masterBuffer()->logName(&mtype);
793 masterfname = FileName(mlogfile);
796 // If no Latex log or Build log is newer, show Build log
797 if (bname.exists() &&
798 ((!fname.exists() && !masterfname.exists())
799 || (fname.lastModified() < bname.lastModified()
800 && masterfname.lastModified() < bname.lastModified()))) {
801 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
804 return bname.absFileName();
805 // If we have a newer master file log or only a master log, show this
806 } else if (fname != masterfname
807 && (!fname.exists() && (masterfname.exists()
808 || fname.lastModified() < masterfname.lastModified()))) {
809 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
812 return masterfname.absFileName();
814 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
817 return fname.absFileName();
821 void Buffer::setReadonly(bool const flag)
823 if (d->read_only != flag) {
830 void Buffer::setFileName(FileName const & fname)
832 bool const changed = fname != d->filename;
835 lyxvc().file_found_hook(fname);
836 setReadonly(d->filename.isReadOnly());
842 int Buffer::readHeader(Lexer & lex)
844 int unknown_tokens = 0;
846 int begin_header_line = -1;
848 // Initialize parameters that may be/go lacking in header:
849 params().branchlist().clear();
850 params().preamble.erase();
851 params().options.erase();
852 params().master.erase();
853 params().float_placement.erase();
854 params().paperwidth.erase();
855 params().paperheight.erase();
856 params().leftmargin.erase();
857 params().rightmargin.erase();
858 params().topmargin.erase();
859 params().bottommargin.erase();
860 params().headheight.erase();
861 params().headsep.erase();
862 params().footskip.erase();
863 params().columnsep.erase();
864 params().fonts_cjk.erase();
865 params().listings_params.clear();
866 params().clearLayoutModules();
867 params().clearRemovedModules();
868 params().clearIncludedChildren();
869 params().pdfoptions().clear();
870 params().indiceslist().clear();
871 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
872 params().isbackgroundcolor = false;
873 params().fontcolor = RGBColor(0, 0, 0);
874 params().isfontcolor = false;
875 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
876 params().boxbgcolor = RGBColor(0xFF, 0, 0);
877 params().html_latex_start.clear();
878 params().html_latex_end.clear();
879 params().html_math_img_scale = 1.0;
880 params().output_sync_macro.erase();
881 params().setLocalLayout(string(), false);
882 params().setLocalLayout(string(), true);
884 for (int i = 0; i < 4; ++i) {
885 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
886 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
889 ErrorList & errorList = d->errorLists["Parse"];
898 if (token == "\\end_header")
902 if (token == "\\begin_header") {
903 begin_header_line = line;
907 LYXERR(Debug::PARSER, "Handling document header token: `"
910 string unknown = params().readToken(lex, token, d->filename.onlyPath());
911 if (!unknown.empty()) {
912 if (unknown[0] != '\\' && token == "\\textclass") {
913 Alert::warning(_("Unknown document class"),
914 bformat(_("Using the default document class, because the "
915 "class %1$s is unknown."), from_utf8(unknown)));
918 docstring const s = bformat(_("Unknown token: "
922 errorList.push_back(ErrorItem(_("Document header error"),
927 if (begin_header_line) {
928 docstring const s = _("\\begin_header is missing");
929 errorList.push_back(ErrorItem(_("Document header error"),
933 params().makeDocumentClass();
935 return unknown_tokens;
940 // changed to be public and have one parameter
941 // Returns true if "\end_document" is not read (Asger)
942 bool Buffer::readDocument(Lexer & lex)
944 ErrorList & errorList = d->errorLists["Parse"];
947 // remove dummy empty par
948 paragraphs().clear();
950 if (!lex.checkFor("\\begin_document")) {
951 docstring const s = _("\\begin_document is missing");
952 errorList.push_back(ErrorItem(_("Document header error"),
958 if (params().output_changes) {
959 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
960 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
961 LaTeXFeatures::isAvailable("xcolor");
963 if (!dvipost && !xcolorulem) {
964 Alert::warning(_("Changes not shown in LaTeX output"),
965 _("Changes will not be highlighted in LaTeX output, "
966 "because neither dvipost nor xcolor/ulem are installed.\n"
967 "Please install these packages or redefine "
968 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
969 } else if (!xcolorulem) {
970 Alert::warning(_("Changes not shown in LaTeX output"),
971 _("Changes will not be highlighted in LaTeX output "
972 "when using pdflatex, because xcolor and ulem are not installed.\n"
973 "Please install both packages or redefine "
974 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
978 if (!parent() && !params().master.empty()) {
979 FileName const master_file = makeAbsPath(params().master,
980 onlyPath(absFileName()));
981 if (isLyXFileName(master_file.absFileName())) {
983 checkAndLoadLyXFile(master_file, true);
985 // necessary e.g. after a reload
986 // to re-register the child (bug 5873)
987 // FIXME: clean up updateMacros (here, only
988 // child registering is needed).
989 master->updateMacros();
990 // set master as master buffer, but only
991 // if we are a real child
992 if (master->isChild(this))
994 // if the master is not fully loaded
995 // it is probably just loading this
996 // child. No warning needed then.
997 else if (master->isFullyLoaded())
998 LYXERR0("The master '"
1000 << "' assigned to this document ("
1002 << ") does not include "
1003 "this document. Ignoring the master assignment.");
1008 // assure we have a default index
1009 params().indiceslist().addDefault(B_("Index"));
1012 bool const res = text().read(lex, errorList, d->inset);
1014 // inform parent buffer about local macros
1016 Buffer const * pbuf = parent();
1017 UserMacroSet::const_iterator cit = usermacros.begin();
1018 UserMacroSet::const_iterator end = usermacros.end();
1019 for (; cit != end; ++cit)
1020 pbuf->usermacros.insert(*cit);
1024 updateMacroInstances(InternalUpdate);
1029 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1031 Format const * fmt = formats.getFormat(format);
1034 // It is important to use the correct extension here, since some
1035 // converters create a wrong output file otherwise (e.g. html2latex)
1036 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1037 FileName const name(tempfile.name());
1038 ofdocstream os(name.toFilesystemEncoding().c_str());
1039 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1040 bool const success = !(os << contents).fail();
1043 bool converted = false;
1045 params().compressed = false;
1047 // remove dummy empty par
1048 paragraphs().clear();
1050 converted = importFile(format, name, errorList);
1059 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1061 if (!theConverters().isReachable(format, "lyx"))
1064 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1065 FileName const lyx(tempfile.name());
1066 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1067 return readFile(lyx) == ReadSuccess;
1073 bool Buffer::readString(string const & s)
1075 params().compressed = false;
1078 istringstream is(s);
1080 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1081 FileName const fn = tempfile.name();
1084 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1086 if (success && file_format != LYX_FORMAT) {
1087 // We need to call lyx2lyx, so write the input to a file
1088 ofstream os(fn.toFilesystemEncoding().c_str());
1091 // lyxvc in readFile
1092 if (readFile(fn) != ReadSuccess)
1096 if (readDocument(lex))
1102 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1106 if (!lex.setFile(fname)) {
1107 Alert::error(_("File Not Found"),
1108 bformat(_("Unable to open file `%1$s'."),
1109 from_utf8(fn.absFileName())));
1110 return ReadFileNotFound;
1114 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1115 if (ret_plf != ReadSuccess)
1118 if (file_format != LYX_FORMAT) {
1120 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1121 if (ret_clf != ReadSuccess)
1123 return readFile(tmpFile);
1126 // FIXME: InsetInfo needs to know whether the file is under VCS
1127 // during the parse process, so this has to be done before.
1128 lyxvc().file_found_hook(d->filename);
1130 if (readDocument(lex)) {
1131 Alert::error(_("Document format failure"),
1132 bformat(_("%1$s ended unexpectedly, which means"
1133 " that it is probably corrupted."),
1134 from_utf8(fn.absFileName())));
1135 return ReadDocumentFailure;
1138 d->file_fully_loaded = true;
1139 d->read_only = !d->filename.isWritable();
1140 params().compressed = formats.isZippedFile(d->filename);
1146 bool Buffer::isFullyLoaded() const
1148 return d->file_fully_loaded;
1152 void Buffer::setFullyLoaded(bool value)
1154 d->file_fully_loaded = value;
1158 PreviewLoader * Buffer::loader() const
1160 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1162 if (!d->preview_loader_)
1163 d->preview_loader_ = new PreviewLoader(*this);
1164 return d->preview_loader_;
1168 void Buffer::removePreviews() const
1170 delete d->preview_loader_;
1171 d->preview_loader_ = 0;
1175 void Buffer::updatePreviews() const
1177 PreviewLoader * ploader = loader();
1181 InsetIterator it = inset_iterator_begin(*d->inset);
1182 InsetIterator const end = inset_iterator_end(*d->inset);
1183 for (; it != end; ++it)
1184 it->addPreview(it, *ploader);
1186 ploader->startLoading();
1190 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1191 FileName const & fn, int & file_format) const
1193 if(!lex.checkFor("\\lyxformat")) {
1194 Alert::error(_("Document format failure"),
1195 bformat(_("%1$s is not a readable LyX document."),
1196 from_utf8(fn.absFileName())));
1197 return ReadNoLyXFormat;
1203 // LyX formats 217 and earlier were written as 2.17. This corresponds
1204 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1205 // these cases. See also: www.lyx.org/trac/changeset/1313.
1206 size_t dot = tmp_format.find_first_of(".,");
1207 if (dot != string::npos)
1208 tmp_format.erase(dot, 1);
1210 file_format = convert<int>(tmp_format);
1215 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1216 FileName & tmpfile, int from_format)
1218 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1219 tempfile.setAutoRemove(false);
1220 tmpfile = tempfile.name();
1221 if(tmpfile.empty()) {
1222 Alert::error(_("Conversion failed"),
1223 bformat(_("%1$s is from a different"
1224 " version of LyX, but a temporary"
1225 " file for converting it could"
1226 " not be created."),
1227 from_utf8(fn.absFileName())));
1228 return LyX2LyXNoTempFile;
1231 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1232 if (lyx2lyx.empty()) {
1233 Alert::error(_("Conversion script not found"),
1234 bformat(_("%1$s is from a different"
1235 " version of LyX, but the"
1236 " conversion script lyx2lyx"
1237 " could not be found."),
1238 from_utf8(fn.absFileName())));
1239 return LyX2LyXNotFound;
1243 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1244 ostringstream command;
1245 command << os::python()
1246 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1247 << " -t " << convert<string>(LYX_FORMAT)
1248 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1249 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1250 string const command_str = command.str();
1252 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1254 cmd_ret const ret = runCommand(command_str);
1255 if (ret.first != 0) {
1256 if (from_format < LYX_FORMAT) {
1257 Alert::error(_("Conversion script failed"),
1258 bformat(_("%1$s is from an older version"
1259 " of LyX and the lyx2lyx script"
1260 " failed to convert it."),
1261 from_utf8(fn.absFileName())));
1262 return LyX2LyXOlderFormat;
1264 Alert::error(_("Conversion script failed"),
1265 bformat(_("%1$s is from a newer version"
1266 " of LyX and the lyx2lyx script"
1267 " failed to convert it."),
1268 from_utf8(fn.absFileName())));
1269 return LyX2LyXNewerFormat;
1276 // Should probably be moved to somewhere else: BufferView? GuiView?
1277 bool Buffer::save() const
1279 docstring const file = makeDisplayPath(absFileName(), 20);
1280 d->filename.refresh();
1282 // check the read-only status before moving the file as a backup
1283 if (d->filename.exists()) {
1284 bool const read_only = !d->filename.isWritable();
1286 Alert::warning(_("File is read-only"),
1287 bformat(_("The file %1$s cannot be written because it "
1288 "is marked as read-only."), file));
1293 // ask if the disk file has been externally modified (use checksum method)
1294 if (fileName().exists() && isExternallyModified(checksum_method)) {
1296 bformat(_("Document %1$s has been externally modified. "
1297 "Are you sure you want to overwrite this file?"), file);
1298 int const ret = Alert::prompt(_("Overwrite modified file?"),
1299 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1304 // We don't need autosaves in the immediate future. (Asger)
1305 resetAutosaveTimers();
1307 // if the file does not yet exist, none of the backup activity
1308 // that follows is necessary
1309 if (!fileName().exists())
1310 return writeFile(fileName());
1312 // we first write the file to a new name, then move it to its
1313 // proper location once that has been done successfully. that
1314 // way we preserve the original file if something goes wrong.
1315 string const justname = fileName().onlyFileNameWithoutExt();
1316 boost::scoped_ptr<TempFile>
1317 tempfile(new TempFile(fileName().onlyPath(),
1318 justname + "-XXXXXX.lyx"));
1319 bool const symlink = fileName().isSymLink();
1321 tempfile->setAutoRemove(false);
1323 FileName savefile(tempfile->name());
1324 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1325 if (!writeFile(savefile))
1328 // we will set this to false if we fail
1329 bool made_backup = true;
1331 FileName backupName(absFileName() + '~');
1332 if (lyxrc.make_backup) {
1333 if (!lyxrc.backupdir_path.empty()) {
1334 string const mangledName =
1335 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1336 backupName = FileName(addName(lyxrc.backupdir_path,
1340 LYXERR(Debug::FILES, "Backing up original file to " <<
1341 backupName.absFileName());
1342 // Except file is symlink do not copy because of #6587.
1343 // Hard links have bad luck.
1344 made_backup = symlink ?
1345 fileName().copyTo(backupName):
1346 fileName().moveTo(backupName);
1349 Alert::error(_("Backup failure"),
1350 bformat(_("Cannot create backup file %1$s.\n"
1351 "Please check whether the directory exists and is writable."),
1352 from_utf8(backupName.absFileName())));
1353 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1357 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1358 // Only do this if tempfile is not in autoremove mode
1361 // If we have no symlink, we can simply rename the temp file.
1362 // Otherwise, we need to copy it so the symlink stays intact.
1363 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1364 savefile.moveTo(fileName()))
1366 // saveCheckSum() was already called by writeFile(), but the
1367 // time stamp is invalidated by copying/moving
1372 // else we saved the file, but failed to move it to the right location.
1374 if (lyxrc.make_backup && made_backup && !symlink) {
1375 // the original file was moved to filename.lyx~, so it will look
1376 // to the user as if it was deleted. (see bug #9234.) we could try
1377 // to restore it, but that would basically mean trying to do again
1378 // what we just failed to do. better to leave things as they are.
1379 Alert::error(_("Write failure"),
1380 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1381 "But LyX could not move it to:\n %2$s.\n"
1382 "Your original file has been backed up to:\n %3$s"),
1383 from_utf8(savefile.absFileName()),
1384 from_utf8(fileName().absFileName()),
1385 from_utf8(backupName.absFileName())));
1387 // either we did not try to make a backup, or else we tried and failed,
1388 // or else the original file was a symlink, in which case it was copied,
1389 // not moved. so the original file is intact.
1390 Alert::error(_("Write failure"),
1391 bformat(_("Cannot move saved file to:\n %1$s.\n"
1392 "But the file has successfully been saved as:\n %2$s."),
1393 from_utf8(fileName().absFileName()),
1394 from_utf8(savefile.absFileName())));
1400 bool Buffer::writeFile(FileName const & fname) const
1402 if (d->read_only && fname == d->filename)
1405 bool retval = false;
1407 docstring const str = bformat(_("Saving document %1$s..."),
1408 makeDisplayPath(fname.absFileName()));
1411 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1413 if (params().compressed) {
1414 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1415 retval = ofs && write(ofs);
1417 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1418 retval = ofs && write(ofs);
1422 message(str + _(" could not write file!"));
1427 // removeAutosaveFile();
1430 message(str + _(" done."));
1436 docstring Buffer::emergencyWrite()
1438 // No need to save if the buffer has not changed.
1442 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1444 docstring user_message = bformat(
1445 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1447 // We try to save three places:
1448 // 1) Same place as document. Unless it is an unnamed doc.
1450 string s = absFileName();
1453 if (writeFile(FileName(s))) {
1455 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1456 return user_message;
1458 user_message += " " + _("Save failed! Trying again...\n");
1462 // 2) In HOME directory.
1463 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1465 lyxerr << ' ' << s << endl;
1466 if (writeFile(FileName(s))) {
1468 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1469 return user_message;
1472 user_message += " " + _("Save failed! Trying yet again...\n");
1474 // 3) In "/tmp" directory.
1475 // MakeAbsPath to prepend the current
1476 // drive letter on OS/2
1477 s = addName(package().temp_dir().absFileName(), absFileName());
1479 lyxerr << ' ' << s << endl;
1480 if (writeFile(FileName(s))) {
1482 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1483 return user_message;
1486 user_message += " " + _("Save failed! Bummer. Document is lost.");
1489 return user_message;
1493 bool Buffer::write(ostream & ofs) const
1496 // Use the standard "C" locale for file output.
1497 ofs.imbue(locale::classic());
1500 // The top of the file should not be written by params().
1502 // write out a comment in the top of the file
1503 // Important: Keep the version formatting in sync with lyx2lyx and
1504 // tex2lyx (bug 7951)
1505 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1506 << " created this file. For more info see http://www.lyx.org/\n"
1507 << "\\lyxformat " << LYX_FORMAT << "\n"
1508 << "\\begin_document\n";
1510 /// For each author, set 'used' to true if there is a change
1511 /// by this author in the document; otherwise set it to 'false'.
1512 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1513 AuthorList::Authors::const_iterator a_end = params().authors().end();
1514 for (; a_it != a_end; ++a_it)
1515 a_it->setUsed(false);
1517 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1518 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1519 for ( ; it != end; ++it)
1520 it->checkAuthors(params().authors());
1522 // now write out the buffer parameters.
1523 ofs << "\\begin_header\n";
1524 params().writeFile(ofs);
1525 ofs << "\\end_header\n";
1528 ofs << "\n\\begin_body\n";
1530 ofs << "\n\\end_body\n";
1532 // Write marker that shows file is complete
1533 ofs << "\\end_document" << endl;
1535 // Shouldn't really be needed....
1538 // how to check if close went ok?
1539 // Following is an attempt... (BE 20001011)
1541 // good() returns false if any error occurred, including some
1542 // formatting error.
1543 // bad() returns true if something bad happened in the buffer,
1544 // which should include file system full errors.
1549 lyxerr << "File was not closed properly." << endl;
1556 bool Buffer::makeLaTeXFile(FileName const & fname,
1557 string const & original_path,
1558 OutputParams const & runparams_in,
1559 OutputWhat output) const
1561 OutputParams runparams = runparams_in;
1563 // This is necessary for LuaTeX/XeTeX with tex fonts.
1564 // See FIXME in BufferParams::encoding()
1565 if (runparams.isFullUnicode())
1566 runparams.encoding = encodings.fromLyXName("utf8-plain");
1568 string const encoding = runparams.encoding->iconvName();
1569 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1572 try { ofs.reset(encoding); }
1573 catch (iconv_codecvt_facet_exception const & e) {
1574 lyxerr << "Caught iconv exception: " << e.what() << endl;
1575 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1576 "verify that the support software for your encoding (%1$s) is "
1577 "properly installed"), from_ascii(encoding)));
1580 if (!openFileWrite(ofs, fname))
1583 ErrorList & errorList = d->errorLists["Export"];
1585 bool failed_export = false;
1586 otexstream os(ofs, d->texrow);
1588 // make sure we are ready to export
1589 // this needs to be done before we validate
1590 // FIXME Do we need to do this all the time? I.e., in children
1591 // of a master we are exporting?
1593 updateMacroInstances(OutputUpdate);
1596 os.texrow().reset();
1597 writeLaTeXSource(os, original_path, runparams, output);
1599 catch (EncodingException const & e) {
1600 docstring const failed(1, e.failed_char);
1602 oss << "0x" << hex << e.failed_char << dec;
1603 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1604 " (code point %2$s)"),
1605 failed, from_utf8(oss.str()));
1606 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1607 "representable in the chosen encoding.\n"
1608 "Changing the document encoding to utf8 could help."),
1609 e.par_id, e.pos, e.pos + 1));
1610 failed_export = true;
1612 catch (iconv_codecvt_facet_exception const & e) {
1613 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1614 _(e.what()), -1, 0, 0));
1615 failed_export = true;
1617 catch (exception const & e) {
1618 errorList.push_back(ErrorItem(_("conversion failed"),
1619 _(e.what()), -1, 0, 0));
1620 failed_export = true;
1623 lyxerr << "Caught some really weird exception..." << endl;
1629 failed_export = true;
1630 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1633 if (runparams_in.silent)
1637 return !failed_export;
1641 void Buffer::writeLaTeXSource(otexstream & os,
1642 string const & original_path,
1643 OutputParams const & runparams_in,
1644 OutputWhat output) const
1646 // The child documents, if any, shall be already loaded at this point.
1648 OutputParams runparams = runparams_in;
1650 // This is necessary for LuaTeX/XeTeX with tex fonts.
1651 // See FIXME in BufferParams::encoding()
1652 if (runparams.isFullUnicode())
1653 runparams.encoding = encodings.fromLyXName("utf8-plain");
1655 // If we are compiling a file standalone, even if this is the
1656 // child of some other buffer, let's cut the link here, so the
1657 // file is really independent and no concurring settings from
1658 // the master (e.g. branch state) interfere (see #8100).
1659 if (!runparams.is_child)
1660 d->ignore_parent = true;
1662 // Classify the unicode characters appearing in math insets
1663 BufferEncodings::initUnicodeMath(*this);
1665 // validate the buffer.
1666 LYXERR(Debug::LATEX, " Validating buffer...");
1667 LaTeXFeatures features(*this, params(), runparams);
1669 // This is only set once per document (in master)
1670 if (!runparams.is_child)
1671 runparams.use_polyglossia = features.usePolyglossia();
1672 LYXERR(Debug::LATEX, " Buffer validation done.");
1674 bool const output_preamble =
1675 output == FullSource || output == OnlyPreamble;
1676 bool const output_body =
1677 output == FullSource || output == OnlyBody;
1679 // The starting paragraph of the coming rows is the
1680 // first paragraph of the document. (Asger)
1681 if (output_preamble && runparams.nice) {
1682 os << "%% LyX " << lyx_version << " created this file. "
1683 "For more info, see http://www.lyx.org/.\n"
1684 "%% Do not edit unless you really know what "
1687 LYXERR(Debug::INFO, "lyx document header finished");
1689 // There are a few differences between nice LaTeX and usual files:
1690 // usual files have \batchmode and special input@path to allow
1691 // inclusion of figures specified by an explicitly relative path
1692 // (i.e., a path starting with './' or '../') with either \input or
1693 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1694 // input@path is set when the actual parameter original_path is set.
1695 // This is done for usual tex-file, but not for nice-latex-file.
1696 // (Matthias 250696)
1697 // Note that input@path is only needed for something the user does
1698 // in the preamble, included .tex files or ERT, files included by
1699 // LyX work without it.
1700 if (output_preamble) {
1701 if (!runparams.nice) {
1702 // code for usual, NOT nice-latex-file
1703 os << "\\batchmode\n"; // changed from \nonstopmode
1705 if (!original_path.empty()) {
1707 // We don't know the encoding of inputpath
1708 docstring const inputpath = from_utf8(original_path);
1709 docstring uncodable_glyphs;
1710 Encoding const * const enc = runparams.encoding;
1712 for (size_t n = 0; n < inputpath.size(); ++n) {
1713 if (!enc->encodable(inputpath[n])) {
1714 docstring const glyph(1, inputpath[n]);
1715 LYXERR0("Uncodable character '"
1717 << "' in input path!");
1718 uncodable_glyphs += glyph;
1723 // warn user if we found uncodable glyphs.
1724 if (!uncodable_glyphs.empty()) {
1725 frontend::Alert::warning(
1726 _("Uncodable character in file path"),
1728 _("The path of your document\n"
1730 "contains glyphs that are unknown "
1731 "in the current document encoding "
1732 "(namely %2$s). This may result in "
1733 "incomplete output, unless "
1734 "TEXINPUTS contains the document "
1735 "directory and you don't use "
1736 "explicitly relative paths (i.e., "
1737 "paths starting with './' or "
1738 "'../') in the preamble or in ERT."
1739 "\n\nIn case of problems, choose "
1740 "an appropriate document encoding\n"
1741 "(such as utf8) or change the "
1743 inputpath, uncodable_glyphs));
1746 support::latex_path(original_path);
1747 if (contains(docdir, '#')) {
1748 docdir = subst(docdir, "#", "\\#");
1749 os << "\\catcode`\\#=11"
1750 "\\def\\#{#}\\catcode`\\#=6\n";
1752 if (contains(docdir, '%')) {
1753 docdir = subst(docdir, "%", "\\%");
1754 os << "\\catcode`\\%=11"
1755 "\\def\\%{%}\\catcode`\\%=14\n";
1757 os << "\\makeatletter\n"
1758 << "\\def\\input@path{{"
1759 << docdir << "/}}\n"
1760 << "\\makeatother\n";
1764 // get parent macros (if this buffer has a parent) which will be
1765 // written at the document begin further down.
1766 MacroSet parentMacros;
1767 listParentMacros(parentMacros, features);
1769 // Write the preamble
1770 runparams.use_babel = params().writeLaTeX(os, features,
1771 d->filename.onlyPath());
1773 // Japanese might be required only in some children of a document,
1774 // but once required, we must keep use_japanese true.
1775 runparams.use_japanese |= features.isRequired("japanese");
1778 // Restore the parenthood if needed
1779 if (!runparams.is_child)
1780 d->ignore_parent = false;
1785 os << "\\begin{document}\n";
1787 // output the parent macros
1788 MacroSet::iterator it = parentMacros.begin();
1789 MacroSet::iterator end = parentMacros.end();
1790 for (; it != end; ++it) {
1791 int num_lines = (*it)->write(os.os(), true);
1792 os.texrow().newlines(num_lines);
1795 } // output_preamble
1797 os.texrow().start(paragraphs().begin()->id(), 0);
1799 LYXERR(Debug::INFO, "preamble finished, now the body.");
1802 latexParagraphs(*this, text(), os, runparams);
1804 // Restore the parenthood if needed
1805 if (!runparams.is_child)
1806 d->ignore_parent = false;
1808 // add this just in case after all the paragraphs
1811 if (output_preamble) {
1812 os << "\\end{document}\n";
1813 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1815 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1817 runparams_in.encoding = runparams.encoding;
1819 // Just to be sure. (Asger)
1820 os.texrow().newline();
1822 //for (int i = 0; i<d->texrow.rows(); i++) {
1824 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1825 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1828 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1829 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1833 void Buffer::makeDocBookFile(FileName const & fname,
1834 OutputParams const & runparams,
1835 OutputWhat output) const
1837 LYXERR(Debug::LATEX, "makeDocBookFile...");
1840 if (!openFileWrite(ofs, fname))
1843 // make sure we are ready to export
1844 // this needs to be done before we validate
1846 updateMacroInstances(OutputUpdate);
1848 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1852 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1856 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1857 OutputParams const & runparams,
1858 OutputWhat output) const
1860 LaTeXFeatures features(*this, params(), runparams);
1865 DocumentClass const & tclass = params().documentClass();
1866 string const & top_element = tclass.latexname();
1868 bool const output_preamble =
1869 output == FullSource || output == OnlyPreamble;
1870 bool const output_body =
1871 output == FullSource || output == OnlyBody;
1873 if (output_preamble) {
1874 if (runparams.flavor == OutputParams::XML)
1875 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1878 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1881 if (! tclass.class_header().empty())
1882 os << from_ascii(tclass.class_header());
1883 else if (runparams.flavor == OutputParams::XML)
1884 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1885 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1887 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1889 docstring preamble = from_utf8(params().preamble);
1890 if (runparams.flavor != OutputParams::XML ) {
1891 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1892 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1893 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1894 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1897 string const name = runparams.nice
1898 ? changeExtension(absFileName(), ".sgml") : fname;
1899 preamble += features.getIncludedFiles(name);
1900 preamble += features.getLyXSGMLEntities();
1902 if (!preamble.empty()) {
1903 os << "\n [ " << preamble << " ]";
1909 string top = top_element;
1911 if (runparams.flavor == OutputParams::XML)
1912 top += params().language->code();
1914 top += params().language->code().substr(0, 2);
1917 if (!params().options.empty()) {
1919 top += params().options;
1922 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1923 << " file was created by LyX " << lyx_version
1924 << "\n See http://www.lyx.org/ for more information -->\n";
1926 params().documentClass().counters().reset();
1928 sgml::openTag(os, top);
1930 docbookParagraphs(text(), *this, os, runparams);
1931 sgml::closeTag(os, top_element);
1936 void Buffer::makeLyXHTMLFile(FileName const & fname,
1937 OutputParams const & runparams) const
1939 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1942 if (!openFileWrite(ofs, fname))
1945 // make sure we are ready to export
1946 // this has to be done before we validate
1947 updateBuffer(UpdateMaster, OutputUpdate);
1948 updateMacroInstances(OutputUpdate);
1950 writeLyXHTMLSource(ofs, runparams, FullSource);
1954 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1958 void Buffer::writeLyXHTMLSource(odocstream & os,
1959 OutputParams const & runparams,
1960 OutputWhat output) const
1962 LaTeXFeatures features(*this, params(), runparams);
1964 d->bibinfo_.makeCitationLabels(*this);
1966 bool const output_preamble =
1967 output == FullSource || output == OnlyPreamble;
1968 bool const output_body =
1969 output == FullSource || output == OnlyBody || output == IncludedFile;
1971 if (output_preamble) {
1972 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1973 << "<!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"
1974 // FIXME Language should be set properly.
1975 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1977 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1978 // FIXME Presumably need to set this right
1979 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1981 docstring const & doctitle = features.htmlTitle();
1983 << (doctitle.empty() ?
1984 from_ascii("LyX Document") :
1985 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1988 docstring styles = features.getTClassHTMLPreamble();
1989 if (!styles.empty())
1990 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1992 styles = from_utf8(features.getPreambleSnippets());
1993 if (!styles.empty())
1994 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1996 // we will collect CSS information in a stream, and then output it
1997 // either here, as part of the header, or else in a separate file.
1998 odocstringstream css;
1999 styles = from_utf8(features.getCSSSnippets());
2000 if (!styles.empty())
2001 css << "/* LyX Provided Styles */\n" << styles << '\n';
2003 styles = features.getTClassHTMLStyles();
2004 if (!styles.empty())
2005 css << "/* Layout-provided Styles */\n" << styles << '\n';
2007 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2008 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2009 if (needfg || needbg) {
2010 css << "\nbody {\n";
2013 << from_ascii(X11hexname(params().fontcolor))
2016 css << " background-color: "
2017 << from_ascii(X11hexname(params().backgroundcolor))
2022 docstring const dstyles = css.str();
2023 if (!dstyles.empty()) {
2024 bool written = false;
2025 if (params().html_css_as_file) {
2026 // open a file for CSS info
2028 string const fcssname = addName(temppath(), "docstyle.css");
2029 FileName const fcssfile = FileName(fcssname);
2030 if (openFileWrite(ocss, fcssfile)) {
2034 // write link to header
2035 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2037 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2040 // we are here if the CSS is supposed to be written to the header
2041 // or if we failed to write it to an external file.
2043 os << "<style type='text/css'>\n"
2052 bool const output_body_tag = (output != IncludedFile);
2053 if (output_body_tag)
2056 if (output != IncludedFile)
2057 // if we're an included file, the counters are in the master.
2058 params().documentClass().counters().reset();
2059 xhtmlParagraphs(text(), *this, xs, runparams);
2060 if (output_body_tag)
2064 if (output_preamble)
2069 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2070 // Other flags: -wall -v0 -x
2071 int Buffer::runChktex()
2075 // get LaTeX-Filename
2076 FileName const path(temppath());
2077 string const name = addName(path.absFileName(), latexName());
2078 string const org_path = filePath();
2080 PathChanger p(path); // path to LaTeX file
2081 message(_("Running chktex..."));
2083 // Generate the LaTeX file if neccessary
2084 OutputParams runparams(¶ms().encoding());
2085 runparams.flavor = OutputParams::LATEX;
2086 runparams.nice = false;
2087 runparams.linelen = lyxrc.plaintext_linelen;
2088 makeLaTeXFile(FileName(name), org_path, runparams);
2091 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2092 int const res = chktex.run(terr); // run chktex
2095 Alert::error(_("chktex failure"),
2096 _("Could not run chktex successfully."));
2098 ErrorList & errlist = d->errorLists["ChkTeX"];
2100 bufferErrors(terr, errlist);
2105 if (runparams.silent)
2106 d->errorLists["ChkTeX"].clear();
2114 void Buffer::validate(LaTeXFeatures & features) const
2116 // Validate the buffer params, but not for included
2117 // files, since they also use the parent buffer's
2119 if (!features.runparams().is_child)
2120 params().validate(features);
2122 for_each(paragraphs().begin(), paragraphs().end(),
2123 bind(&Paragraph::validate, _1, ref(features)));
2125 if (lyxerr.debugging(Debug::LATEX)) {
2126 features.showStruct();
2131 void Buffer::getLabelList(vector<docstring> & list) const
2133 // If this is a child document, use the master's list instead.
2135 masterBuffer()->getLabelList(list);
2140 Toc & toc = d->toc_backend.toc("label");
2141 TocIterator toc_it = toc.begin();
2142 TocIterator end = toc.end();
2143 for (; toc_it != end; ++toc_it) {
2144 if (toc_it->depth() == 0)
2145 list.push_back(toc_it->str());
2150 void Buffer::updateBibfilesCache(UpdateScope scope) const
2152 // FIXME This is probably unnecssary, given where we call this.
2153 // If this is a child document, use the parent's cache instead.
2154 if (parent() && scope != UpdateChildOnly) {
2155 masterBuffer()->updateBibfilesCache();
2159 d->bibfiles_cache_.clear();
2160 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2161 if (it->lyxCode() == BIBTEX_CODE) {
2162 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2163 support::FileNameList const bibfiles = inset.getBibFiles();
2164 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2167 } else if (it->lyxCode() == INCLUDE_CODE) {
2168 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2169 Buffer const * const incbuf = inset.getChildBuffer();
2172 support::FileNameList const & bibfiles =
2173 incbuf->getBibfilesCache(UpdateChildOnly);
2174 if (!bibfiles.empty()) {
2175 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2181 d->bibfile_cache_valid_ = true;
2182 d->bibinfo_cache_valid_ = false;
2183 d->cite_labels_valid_ = false;
2187 void Buffer::invalidateBibinfoCache() const
2189 d->bibinfo_cache_valid_ = false;
2190 d->cite_labels_valid_ = false;
2191 // also invalidate the cache for the parent buffer
2192 Buffer const * const pbuf = d->parent();
2194 pbuf->invalidateBibinfoCache();
2198 void Buffer::invalidateBibfileCache() const
2200 d->bibfile_cache_valid_ = false;
2201 d->bibinfo_cache_valid_ = false;
2202 d->cite_labels_valid_ = false;
2203 // also invalidate the cache for the parent buffer
2204 Buffer const * const pbuf = d->parent();
2206 pbuf->invalidateBibfileCache();
2210 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2212 // FIXME This is probably unnecessary, given where we call this.
2213 // If this is a child document, use the master's cache instead.
2214 Buffer const * const pbuf = masterBuffer();
2215 if (pbuf != this && scope != UpdateChildOnly)
2216 return pbuf->getBibfilesCache();
2218 if (!d->bibfile_cache_valid_)
2219 this->updateBibfilesCache(scope);
2221 return d->bibfiles_cache_;
2225 BiblioInfo const & Buffer::masterBibInfo() const
2227 Buffer const * const tmp = masterBuffer();
2229 return tmp->masterBibInfo();
2234 void Buffer::checkIfBibInfoCacheIsValid() const
2236 // use the master's cache
2237 Buffer const * const tmp = masterBuffer();
2239 tmp->checkIfBibInfoCacheIsValid();
2243 // compare the cached timestamps with the actual ones.
2244 FileNameList const & bibfiles_cache = getBibfilesCache();
2245 FileNameList::const_iterator ei = bibfiles_cache.begin();
2246 FileNameList::const_iterator en = bibfiles_cache.end();
2247 for (; ei != en; ++ ei) {
2248 time_t lastw = ei->lastModified();
2249 time_t prevw = d->bibfile_status_[*ei];
2250 if (lastw != prevw) {
2251 d->bibinfo_cache_valid_ = false;
2252 d->cite_labels_valid_ = false;
2253 d->bibfile_status_[*ei] = lastw;
2259 void Buffer::reloadBibInfoCache() const
2261 // use the master's cache
2262 Buffer const * const tmp = masterBuffer();
2264 tmp->reloadBibInfoCache();
2268 checkIfBibInfoCacheIsValid();
2269 if (d->bibinfo_cache_valid_)
2272 d->bibinfo_.clear();
2274 d->bibinfo_cache_valid_ = true;
2278 void Buffer::collectBibKeys() const
2280 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2281 it->collectBibKeys(it);
2285 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2287 Buffer const * tmp = masterBuffer();
2288 BiblioInfo & masterbi = (tmp == this) ?
2289 d->bibinfo_ : tmp->d->bibinfo_;
2290 masterbi.mergeBiblioInfo(bi);
2294 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2296 Buffer const * tmp = masterBuffer();
2297 BiblioInfo & masterbi = (tmp == this) ?
2298 d->bibinfo_ : tmp->d->bibinfo_;
2303 void Buffer::makeCitationLabels() const
2305 Buffer const * const master = masterBuffer();
2306 return d->bibinfo_.makeCitationLabels(*master);
2310 bool Buffer::citeLabelsValid() const
2312 return masterBuffer()->d->cite_labels_valid_;
2316 void Buffer::removeBiblioTempFiles() const
2318 // We remove files that contain LaTeX commands specific to the
2319 // particular bibliographic style being used, in order to avoid
2320 // LaTeX errors when we switch style.
2321 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2322 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2323 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2324 aux_file.removeFile();
2325 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2326 bbl_file.removeFile();
2327 // Also for the parent buffer
2328 Buffer const * const pbuf = parent();
2330 pbuf->removeBiblioTempFiles();
2334 bool Buffer::isDepClean(string const & name) const
2336 DepClean::const_iterator const it = d->dep_clean.find(name);
2337 if (it == d->dep_clean.end())
2343 void Buffer::markDepClean(string const & name)
2345 d->dep_clean[name] = true;
2349 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2352 // FIXME? if there is an Buffer LFUN that can be dispatched even
2353 // if internal, put a switch '(cmd.action)' here.
2359 switch (cmd.action()) {
2361 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2362 flag.setOnOff(isReadonly());
2365 // FIXME: There is need for a command-line import.
2366 //case LFUN_BUFFER_IMPORT:
2368 case LFUN_BUFFER_AUTO_SAVE:
2371 case LFUN_BUFFER_EXPORT_CUSTOM:
2372 // FIXME: Nothing to check here?
2375 case LFUN_BUFFER_EXPORT: {
2376 docstring const arg = cmd.argument();
2377 if (arg == "custom") {
2381 string format = to_utf8(arg);
2382 size_t pos = format.find(' ');
2383 if (pos != string::npos)
2384 format = format.substr(0, pos);
2385 enable = params().isExportable(format);
2387 flag.message(bformat(
2388 _("Don't know how to export to format: %1$s"), arg));
2392 case LFUN_BUFFER_CHKTEX:
2393 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2396 case LFUN_BUILD_PROGRAM:
2397 enable = params().isExportable("program");
2400 case LFUN_BRANCH_ACTIVATE:
2401 case LFUN_BRANCH_DEACTIVATE:
2402 case LFUN_BRANCH_MASTER_ACTIVATE:
2403 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2404 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2405 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2406 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2407 : params().branchlist();
2408 docstring const branchName = cmd.argument();
2409 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2413 case LFUN_BRANCH_ADD:
2414 case LFUN_BRANCHES_RENAME:
2415 case LFUN_BUFFER_PRINT:
2416 // if no Buffer is present, then of course we won't be called!
2419 case LFUN_BUFFER_LANGUAGE:
2420 enable = !isReadonly();
2426 flag.setEnabled(enable);
2431 void Buffer::dispatch(string const & command, DispatchResult & result)
2433 return dispatch(lyxaction.lookupFunc(command), result);
2437 // NOTE We can end up here even if we have no GUI, because we are called
2438 // by LyX::exec to handled command-line requests. So we may need to check
2439 // whether we have a GUI or not. The boolean use_gui holds this information.
2440 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2443 // FIXME? if there is an Buffer LFUN that can be dispatched even
2444 // if internal, put a switch '(cmd.action())' here.
2445 dr.dispatched(false);
2448 string const argument = to_utf8(func.argument());
2449 // We'll set this back to false if need be.
2450 bool dispatched = true;
2451 undo().beginUndoGroup();
2453 switch (func.action()) {
2454 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2455 if (lyxvc().inUse()) {
2456 string log = lyxvc().toggleReadOnly();
2461 setReadonly(!isReadonly());
2464 case LFUN_BUFFER_EXPORT: {
2465 ExportStatus const status = doExport(argument, false);
2466 dr.setError(status != ExportSuccess);
2467 if (status != ExportSuccess)
2468 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2473 case LFUN_BUILD_PROGRAM: {
2474 ExportStatus const status = doExport("program", true);
2475 dr.setError(status != ExportSuccess);
2476 if (status != ExportSuccess)
2477 dr.setMessage(_("Error generating literate programming code."));
2481 case LFUN_BUFFER_CHKTEX:
2485 case LFUN_BUFFER_EXPORT_CUSTOM: {
2487 string command = split(argument, format_name, ' ');
2488 Format const * format = formats.getFormat(format_name);
2490 lyxerr << "Format \"" << format_name
2491 << "\" not recognized!"
2496 // The name of the file created by the conversion process
2499 // Output to filename
2500 if (format->name() == "lyx") {
2501 string const latexname = latexName(false);
2502 filename = changeExtension(latexname,
2503 format->extension());
2504 filename = addName(temppath(), filename);
2506 if (!writeFile(FileName(filename)))
2510 doExport(format_name, true, filename);
2513 // Substitute $$FName for filename
2514 if (!contains(command, "$$FName"))
2515 command = "( " + command + " ) < $$FName";
2516 command = subst(command, "$$FName", filename);
2518 // Execute the command in the background
2520 call.startscript(Systemcall::DontWait, command, filePath());
2524 // FIXME: There is need for a command-line import.
2526 case LFUN_BUFFER_IMPORT:
2531 case LFUN_BUFFER_AUTO_SAVE:
2533 resetAutosaveTimers();
2536 case LFUN_BRANCH_ACTIVATE:
2537 case LFUN_BRANCH_DEACTIVATE:
2538 case LFUN_BRANCH_MASTER_ACTIVATE:
2539 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2540 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2541 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2542 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2545 docstring const branch_name = func.argument();
2546 // the case without a branch name is handled elsewhere
2547 if (branch_name.empty()) {
2551 Branch * branch = buf->params().branchlist().find(branch_name);
2553 LYXERR0("Branch " << branch_name << " does not exist.");
2555 docstring const msg =
2556 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2560 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2561 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2562 if (branch->isSelected() != activate) {
2563 buf->undo().recordUndoBufferParams(CursorData());
2564 branch->setSelected(activate);
2566 dr.screenUpdate(Update::Force);
2567 dr.forceBufferUpdate();
2572 case LFUN_BRANCH_ADD: {
2573 docstring branch_name = func.argument();
2574 if (branch_name.empty()) {
2578 BranchList & branch_list = params().branchlist();
2579 vector<docstring> const branches =
2580 getVectorFromString(branch_name, branch_list.separator());
2582 for (vector<docstring>::const_iterator it = branches.begin();
2583 it != branches.end(); ++it) {
2585 Branch * branch = branch_list.find(branch_name);
2587 LYXERR0("Branch " << branch_name << " already exists.");
2591 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2593 undo().recordUndoBufferParams(CursorData());
2594 branch_list.add(branch_name);
2595 branch = branch_list.find(branch_name);
2596 string const x11hexname = X11hexname(branch->color());
2597 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2598 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2600 dr.screenUpdate(Update::Force);
2608 case LFUN_BRANCHES_RENAME: {
2609 if (func.argument().empty())
2612 docstring const oldname = from_utf8(func.getArg(0));
2613 docstring const newname = from_utf8(func.getArg(1));
2614 InsetIterator it = inset_iterator_begin(inset());
2615 InsetIterator const end = inset_iterator_end(inset());
2616 bool success = false;
2617 for (; it != end; ++it) {
2618 if (it->lyxCode() == BRANCH_CODE) {
2619 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2620 if (ins.branch() == oldname) {
2621 undo().recordUndo(CursorData(it));
2622 ins.rename(newname);
2627 if (it->lyxCode() == INCLUDE_CODE) {
2628 // get buffer of external file
2629 InsetInclude const & ins =
2630 static_cast<InsetInclude const &>(*it);
2631 Buffer * child = ins.getChildBuffer();
2634 child->dispatch(func, dr);
2639 dr.screenUpdate(Update::Force);
2640 dr.forceBufferUpdate();
2645 case LFUN_BUFFER_PRINT: {
2646 // we'll assume there's a problem until we succeed
2648 string target = func.getArg(0);
2649 string target_name = func.getArg(1);
2650 string command = func.getArg(2);
2653 || target_name.empty()
2654 || command.empty()) {
2655 LYXERR0("Unable to parse " << func.argument());
2656 docstring const msg =
2657 bformat(_("Unable to parse \"%1$s\""), func.argument());
2661 if (target != "printer" && target != "file") {
2662 LYXERR0("Unrecognized target \"" << target << '"');
2663 docstring const msg =
2664 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2669 if (doExport("dvi", true) != ExportSuccess) {
2670 showPrintError(absFileName());
2671 dr.setMessage(_("Error exporting to DVI."));
2675 // Push directory path.
2676 string const path = temppath();
2677 // Prevent the compiler from optimizing away p
2681 // there are three cases here:
2682 // 1. we print to a file
2683 // 2. we print directly to a printer
2684 // 3. we print using a spool command (print to file first)
2687 string const dviname = changeExtension(latexName(true), "dvi");
2689 if (target == "printer") {
2690 if (!lyxrc.print_spool_command.empty()) {
2691 // case 3: print using a spool
2692 string const psname = changeExtension(dviname,".ps");
2693 command += ' ' + lyxrc.print_to_file
2696 + quoteName(dviname);
2698 string command2 = lyxrc.print_spool_command + ' ';
2699 if (target_name != "default") {
2700 command2 += lyxrc.print_spool_printerprefix
2704 command2 += quoteName(psname);
2706 // If successful, then spool command
2707 res = one.startscript(Systemcall::Wait, command,
2711 // If there's no GUI, we have to wait on this command. Otherwise,
2712 // LyX deletes the temporary directory, and with it the spooled
2713 // file, before it can be printed!!
2714 Systemcall::Starttype stype = use_gui ?
2715 Systemcall::DontWait : Systemcall::Wait;
2716 res = one.startscript(stype, command2,
2720 // case 2: print directly to a printer
2721 if (target_name != "default")
2722 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2724 Systemcall::Starttype stype = use_gui ?
2725 Systemcall::DontWait : Systemcall::Wait;
2726 res = one.startscript(stype, command +
2727 quoteName(dviname), filePath());
2731 // case 1: print to a file
2732 FileName const filename(makeAbsPath(target_name, filePath()));
2733 FileName const dvifile(makeAbsPath(dviname, path));
2734 if (filename.exists()) {
2735 docstring text = bformat(
2736 _("The file %1$s already exists.\n\n"
2737 "Do you want to overwrite that file?"),
2738 makeDisplayPath(filename.absFileName()));
2739 if (Alert::prompt(_("Overwrite file?"),
2740 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2743 command += ' ' + lyxrc.print_to_file
2744 + quoteName(filename.toFilesystemEncoding())
2746 + quoteName(dvifile.toFilesystemEncoding());
2748 Systemcall::Starttype stype = use_gui ?
2749 Systemcall::DontWait : Systemcall::Wait;
2750 res = one.startscript(stype, command, filePath());
2756 dr.setMessage(_("Error running external commands."));
2757 showPrintError(absFileName());
2766 dr.dispatched(dispatched);
2767 undo().endUndoGroup();
2771 void Buffer::changeLanguage(Language const * from, Language const * to)
2773 LASSERT(from, return);
2774 LASSERT(to, return);
2776 for_each(par_iterator_begin(),
2778 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2782 bool Buffer::isMultiLingual() const
2784 ParConstIterator end = par_iterator_end();
2785 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2786 if (it->isMultiLingual(params()))
2793 std::set<Language const *> Buffer::getLanguages() const
2795 std::set<Language const *> languages;
2796 getLanguages(languages);
2801 void Buffer::getLanguages(std::set<Language const *> & languages) const
2803 ParConstIterator end = par_iterator_end();
2804 // add the buffer language, even if it's not actively used
2805 languages.insert(language());
2806 // iterate over the paragraphs
2807 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2808 it->getLanguages(languages);
2810 ListOfBuffers clist = getDescendents();
2811 ListOfBuffers::const_iterator cit = clist.begin();
2812 ListOfBuffers::const_iterator const cen = clist.end();
2813 for (; cit != cen; ++cit)
2814 (*cit)->getLanguages(languages);
2818 DocIterator Buffer::getParFromID(int const id) const
2820 Buffer * buf = const_cast<Buffer *>(this);
2822 // John says this is called with id == -1 from undo
2823 lyxerr << "getParFromID(), id: " << id << endl;
2824 return doc_iterator_end(buf);
2827 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2828 if (it.paragraph().id() == id)
2831 return doc_iterator_end(buf);
2835 bool Buffer::hasParWithID(int const id) const
2837 return !getParFromID(id).atEnd();
2841 ParIterator Buffer::par_iterator_begin()
2843 return ParIterator(doc_iterator_begin(this));
2847 ParIterator Buffer::par_iterator_end()
2849 return ParIterator(doc_iterator_end(this));
2853 ParConstIterator Buffer::par_iterator_begin() const
2855 return ParConstIterator(doc_iterator_begin(this));
2859 ParConstIterator Buffer::par_iterator_end() const
2861 return ParConstIterator(doc_iterator_end(this));
2865 Language const * Buffer::language() const
2867 return params().language;
2871 docstring const Buffer::B_(string const & l10n) const
2873 return params().B_(l10n);
2877 bool Buffer::isClean() const
2879 return d->lyx_clean;
2883 bool Buffer::isExternallyModified(CheckMethod method) const
2885 LASSERT(d->filename.exists(), return false);
2886 // if method == timestamp, check timestamp before checksum
2887 return (method == checksum_method
2888 || d->timestamp_ != d->filename.lastModified())
2889 && d->checksum_ != d->filename.checksum();
2893 void Buffer::saveCheckSum() const
2895 FileName const & file = d->filename;
2898 if (file.exists()) {
2899 d->timestamp_ = file.lastModified();
2900 d->checksum_ = file.checksum();
2902 // in the case of save to a new file.
2909 void Buffer::markClean() const
2911 if (!d->lyx_clean) {
2912 d->lyx_clean = true;
2915 // if the .lyx file has been saved, we don't need an
2917 d->bak_clean = true;
2918 d->undo_.markDirty();
2922 void Buffer::setUnnamed(bool flag)
2928 bool Buffer::isUnnamed() const
2935 /// Don't check unnamed, here: isInternal() is used in
2936 /// newBuffer(), where the unnamed flag has not been set by anyone
2937 /// yet. Also, for an internal buffer, there should be no need for
2938 /// retrieving fileName() nor for checking if it is unnamed or not.
2939 bool Buffer::isInternal() const
2941 return d->internal_buffer;
2945 void Buffer::setInternal(bool flag)
2947 d->internal_buffer = flag;
2951 void Buffer::markDirty()
2954 d->lyx_clean = false;
2957 d->bak_clean = false;
2959 DepClean::iterator it = d->dep_clean.begin();
2960 DepClean::const_iterator const end = d->dep_clean.end();
2962 for (; it != end; ++it)
2967 FileName Buffer::fileName() const
2973 string Buffer::absFileName() const
2975 return d->filename.absFileName();
2979 string Buffer::filePath() const
2981 string const abs = d->filename.onlyPath().absFileName();
2984 int last = abs.length() - 1;
2986 return abs[last] == '/' ? abs : abs + '/';
2990 bool Buffer::isReadonly() const
2992 return d->read_only;
2996 void Buffer::setParent(Buffer const * buffer)
2998 // Avoids recursive include.
2999 d->setParent(buffer == this ? 0 : buffer);
3004 Buffer const * Buffer::parent() const
3010 ListOfBuffers Buffer::allRelatives() const
3012 ListOfBuffers lb = masterBuffer()->getDescendents();
3013 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3018 Buffer const * Buffer::masterBuffer() const
3020 // FIXME Should be make sure we are not in some kind
3021 // of recursive include? A -> B -> A will crash this.
3022 Buffer const * const pbuf = d->parent();
3026 return pbuf->masterBuffer();
3030 bool Buffer::isChild(Buffer * child) const
3032 return d->children_positions.find(child) != d->children_positions.end();
3036 DocIterator Buffer::firstChildPosition(Buffer const * child)
3038 Impl::BufferPositionMap::iterator it;
3039 it = d->children_positions.find(child);
3040 if (it == d->children_positions.end())
3041 return DocIterator(this);
3046 bool Buffer::hasChildren() const
3048 return !d->children_positions.empty();
3052 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3054 // loop over children
3055 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3056 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3057 for (; it != end; ++it) {
3058 Buffer * child = const_cast<Buffer *>(it->first);
3060 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3061 if (bit != clist.end())
3063 clist.push_back(child);
3065 // there might be grandchildren
3066 child->collectChildren(clist, true);
3071 ListOfBuffers Buffer::getChildren() const
3074 collectChildren(v, false);
3075 // Make sure we have not included ourselves.
3076 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3077 if (bit != v.end()) {
3078 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3085 ListOfBuffers Buffer::getDescendents() const
3088 collectChildren(v, true);
3089 // Make sure we have not included ourselves.
3090 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3091 if (bit != v.end()) {
3092 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3099 template<typename M>
3100 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3105 typename M::const_iterator it = m.lower_bound(x);
3106 if (it == m.begin())
3114 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3115 DocIterator const & pos) const
3117 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3119 // if paragraphs have no macro context set, pos will be empty
3123 // we haven't found anything yet
3124 DocIterator bestPos = owner_->par_iterator_begin();
3125 MacroData const * bestData = 0;
3127 // find macro definitions for name
3128 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3129 if (nameIt != macros.end()) {
3130 // find last definition in front of pos or at pos itself
3131 PositionScopeMacroMap::const_iterator it
3132 = greatest_below(nameIt->second, pos);
3133 if (it != nameIt->second.end()) {
3135 // scope ends behind pos?
3136 if (pos < it->second.scope) {
3137 // Looks good, remember this. If there
3138 // is no external macro behind this,
3139 // we found the right one already.
3140 bestPos = it->first;
3141 bestData = &it->second.macro;
3145 // try previous macro if there is one
3146 if (it == nameIt->second.begin())
3153 // find macros in included files
3154 PositionScopeBufferMap::const_iterator it
3155 = greatest_below(position_to_children, pos);
3156 if (it == position_to_children.end())
3157 // no children before
3161 // do we know something better (i.e. later) already?
3162 if (it->first < bestPos )
3165 // scope ends behind pos?
3166 if (pos < it->second.scope
3167 && (cloned_buffer_ ||
3168 theBufferList().isLoaded(it->second.buffer))) {
3169 // look for macro in external file
3171 MacroData const * data
3172 = it->second.buffer->getMacro(name, false);
3175 bestPos = it->first;
3181 // try previous file if there is one
3182 if (it == position_to_children.begin())
3187 // return the best macro we have found
3192 MacroData const * Buffer::getMacro(docstring const & name,
3193 DocIterator const & pos, bool global) const
3198 // query buffer macros
3199 MacroData const * data = d->getBufferMacro(name, pos);
3203 // If there is a master buffer, query that
3204 Buffer const * const pbuf = d->parent();
3206 d->macro_lock = true;
3207 MacroData const * macro = pbuf->getMacro(
3208 name, *this, false);
3209 d->macro_lock = false;
3215 data = MacroTable::globalMacros().get(name);
3224 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3226 // set scope end behind the last paragraph
3227 DocIterator scope = par_iterator_begin();
3228 scope.pit() = scope.lastpit() + 1;
3230 return getMacro(name, scope, global);
3234 MacroData const * Buffer::getMacro(docstring const & name,
3235 Buffer const & child, bool global) const
3237 // look where the child buffer is included first
3238 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3239 if (it == d->children_positions.end())
3242 // check for macros at the inclusion position
3243 return getMacro(name, it->second, global);
3247 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3249 pit_type const lastpit = it.lastpit();
3251 // look for macros in each paragraph
3252 while (it.pit() <= lastpit) {
3253 Paragraph & par = it.paragraph();
3255 // iterate over the insets of the current paragraph
3256 InsetList const & insets = par.insetList();
3257 InsetList::const_iterator iit = insets.begin();
3258 InsetList::const_iterator end = insets.end();
3259 for (; iit != end; ++iit) {
3260 it.pos() = iit->pos;
3262 // is it a nested text inset?
3263 if (iit->inset->asInsetText()) {
3264 // Inset needs its own scope?
3265 InsetText const * itext = iit->inset->asInsetText();
3266 bool newScope = itext->isMacroScope();
3268 // scope which ends just behind the inset
3269 DocIterator insetScope = it;
3272 // collect macros in inset
3273 it.push_back(CursorSlice(*iit->inset));
3274 updateMacros(it, newScope ? insetScope : scope);
3279 if (iit->inset->asInsetTabular()) {
3280 CursorSlice slice(*iit->inset);
3281 size_t const numcells = slice.nargs();
3282 for (; slice.idx() < numcells; slice.forwardIdx()) {
3283 it.push_back(slice);
3284 updateMacros(it, scope);
3290 // is it an external file?
3291 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3292 // get buffer of external file
3293 InsetInclude const & inset =
3294 static_cast<InsetInclude const &>(*iit->inset);
3296 Buffer * child = inset.getChildBuffer();
3301 // register its position, but only when it is
3302 // included first in the buffer
3303 if (children_positions.find(child) ==
3304 children_positions.end())
3305 children_positions[child] = it;
3307 // register child with its scope
3308 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3312 InsetMath * im = iit->inset->asInsetMath();
3313 if (doing_export && im) {
3314 InsetMathHull * hull = im->asHullInset();
3316 hull->recordLocation(it);
3319 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3323 MathMacroTemplate & macroTemplate =
3324 *iit->inset->asInsetMath()->asMacroTemplate();
3325 MacroContext mc(owner_, it);
3326 macroTemplate.updateToContext(mc);
3329 bool valid = macroTemplate.validMacro();
3330 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3331 // then the BufferView's cursor will be invalid in
3332 // some cases which leads to crashes.
3337 // FIXME (Abdel), I don't understand why we pass 'it' here
3338 // instead of 'macroTemplate' defined above... is this correct?
3339 macros[macroTemplate.name()][it] =
3340 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3350 void Buffer::updateMacros() const
3355 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3357 // start with empty table
3359 d->children_positions.clear();
3360 d->position_to_children.clear();
3362 // Iterate over buffer, starting with first paragraph
3363 // The scope must be bigger than any lookup DocIterator
3364 // later. For the global lookup, lastpit+1 is used, hence
3365 // we use lastpit+2 here.
3366 DocIterator it = par_iterator_begin();
3367 DocIterator outerScope = it;
3368 outerScope.pit() = outerScope.lastpit() + 2;
3369 d->updateMacros(it, outerScope);
3373 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3375 InsetIterator it = inset_iterator_begin(inset());
3376 InsetIterator const end = inset_iterator_end(inset());
3377 for (; it != end; ++it) {
3378 if (it->lyxCode() == BRANCH_CODE) {
3379 InsetBranch & br = static_cast<InsetBranch &>(*it);
3380 docstring const name = br.branch();
3381 if (!from_master && !params().branchlist().find(name))
3382 result.push_back(name);
3383 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3384 result.push_back(name);
3387 if (it->lyxCode() == INCLUDE_CODE) {
3388 // get buffer of external file
3389 InsetInclude const & ins =
3390 static_cast<InsetInclude const &>(*it);
3391 Buffer * child = ins.getChildBuffer();
3394 child->getUsedBranches(result, true);
3397 // remove duplicates
3402 void Buffer::updateMacroInstances(UpdateType utype) const
3404 LYXERR(Debug::MACROS, "updateMacroInstances for "
3405 << d->filename.onlyFileName());
3406 DocIterator it = doc_iterator_begin(this);
3408 DocIterator const end = doc_iterator_end(this);
3409 for (; it != end; it.forwardInset()) {
3410 // look for MathData cells in InsetMathNest insets
3411 InsetMath * minset = it.nextInset()->asInsetMath();
3415 // update macro in all cells of the InsetMathNest
3416 DocIterator::idx_type n = minset->nargs();
3417 MacroContext mc = MacroContext(this, it);
3418 for (DocIterator::idx_type i = 0; i < n; ++i) {
3419 MathData & data = minset->cell(i);
3420 data.updateMacros(0, mc, utype);
3426 void Buffer::listMacroNames(MacroNameSet & macros) const
3431 d->macro_lock = true;
3433 // loop over macro names
3434 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3435 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3436 for (; nameIt != nameEnd; ++nameIt)
3437 macros.insert(nameIt->first);
3439 // loop over children
3440 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3441 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3442 for (; it != end; ++it)
3443 it->first->listMacroNames(macros);
3446 Buffer const * const pbuf = d->parent();
3448 pbuf->listMacroNames(macros);
3450 d->macro_lock = false;
3454 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3456 Buffer const * const pbuf = d->parent();
3461 pbuf->listMacroNames(names);
3464 MacroNameSet::iterator it = names.begin();
3465 MacroNameSet::iterator end = names.end();
3466 for (; it != end; ++it) {
3468 MacroData const * data =
3469 pbuf->getMacro(*it, *this, false);
3471 macros.insert(data);
3473 // we cannot access the original MathMacroTemplate anymore
3474 // here to calls validate method. So we do its work here manually.
3475 // FIXME: somehow make the template accessible here.
3476 if (data->optionals() > 0)
3477 features.require("xargs");
3483 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3486 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3488 RefCache::iterator it = d->ref_cache_.find(label);
3489 if (it != d->ref_cache_.end())
3490 return it->second.second;
3492 static InsetLabel const * dummy_il = 0;
3493 static References const dummy_refs;
3494 it = d->ref_cache_.insert(
3495 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3496 return it->second.second;
3500 Buffer::References const & Buffer::references(docstring const & label) const
3502 return const_cast<Buffer *>(this)->getReferenceCache(label);
3506 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3508 References & refs = getReferenceCache(label);
3509 refs.push_back(make_pair(inset, it));
3513 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3515 masterBuffer()->d->ref_cache_[label].first = il;
3519 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3521 return masterBuffer()->d->ref_cache_[label].first;
3525 void Buffer::clearReferenceCache() const
3528 d->ref_cache_.clear();
3532 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3534 //FIXME: This does not work for child documents yet.
3535 reloadBibInfoCache();
3537 // Check if the label 'from' appears more than once
3538 BiblioInfo const & keys = masterBibInfo();
3539 BiblioInfo::const_iterator bit = keys.begin();
3540 BiblioInfo::const_iterator bend = keys.end();
3541 vector<docstring> labels;
3543 for (; bit != bend; ++bit)
3545 labels.push_back(bit->first);
3547 if (count(labels.begin(), labels.end(), from) > 1)
3550 string const paramName = "key";
3551 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3552 if (it->lyxCode() != CITE_CODE)
3554 InsetCommand * inset = it->asInsetCommand();
3555 docstring const oldValue = inset->getParam(paramName);
3556 if (oldValue == from)
3557 inset->setParam(paramName, to);
3562 void Buffer::getSourceCode(odocstream & os, string const & format,
3563 pit_type par_begin, pit_type par_end,
3564 OutputWhat output, bool master) const
3566 OutputParams runparams(¶ms().encoding());
3567 runparams.nice = true;
3568 runparams.flavor = params().getOutputFlavor(format);
3569 runparams.linelen = lyxrc.plaintext_linelen;
3570 // No side effect of file copying and image conversion
3571 runparams.dryrun = true;
3573 if (output == CurrentParagraph) {
3574 runparams.par_begin = par_begin;
3575 runparams.par_end = par_end;
3576 if (par_begin + 1 == par_end) {
3578 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3582 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3583 convert<docstring>(par_begin),
3584 convert<docstring>(par_end - 1))
3587 // output paragraphs
3588 if (runparams.flavor == OutputParams::LYX) {
3589 Paragraph const & par = text().paragraphs()[par_begin];
3591 depth_type dt = par.getDepth();
3592 par.write(ods, params(), dt);
3593 os << from_utf8(ods.str());
3594 } else if (runparams.flavor == OutputParams::HTML) {
3596 setMathFlavor(runparams);
3597 xhtmlParagraphs(text(), *this, xs, runparams);
3598 } else if (runparams.flavor == OutputParams::TEXT) {
3600 // FIXME Handles only one paragraph, unlike the others.
3601 // Probably should have some routine with a signature like them.
3602 writePlaintextParagraph(*this,
3603 text().paragraphs()[par_begin], os, runparams, dummy);
3604 } else if (params().isDocBook()) {
3605 docbookParagraphs(text(), *this, os, runparams);
3607 // If we are previewing a paragraph, even if this is the
3608 // child of some other buffer, let's cut the link here,
3609 // so that no concurring settings from the master
3610 // (e.g. branch state) interfere (see #8101).
3612 d->ignore_parent = true;
3613 // We need to validate the Buffer params' features here
3614 // in order to know if we should output polyglossia
3615 // macros (instead of babel macros)
3616 LaTeXFeatures features(*this, params(), runparams);
3617 params().validate(features);
3618 runparams.use_polyglossia = features.usePolyglossia();
3623 // latex or literate
3624 otexstream ots(os, texrow);
3627 latexParagraphs(*this, text(), ots, runparams);
3629 // Restore the parenthood
3631 d->ignore_parent = false;
3635 if (output == FullSource)
3636 os << _("Preview source code");
3637 else if (output == OnlyPreamble)
3638 os << _("Preview preamble");
3639 else if (output == OnlyBody)
3640 os << _("Preview body");
3642 if (runparams.flavor == OutputParams::LYX) {
3644 if (output == FullSource)
3646 else if (output == OnlyPreamble)
3647 params().writeFile(ods);
3648 else if (output == OnlyBody)
3650 os << from_utf8(ods.str());
3651 } else if (runparams.flavor == OutputParams::HTML) {
3652 writeLyXHTMLSource(os, runparams, output);
3653 } else if (runparams.flavor == OutputParams::TEXT) {
3654 if (output == OnlyPreamble) {
3655 os << "% "<< _("Plain text does not have a preamble.");
3657 writePlaintextFile(*this, os, runparams);
3658 } else if (params().isDocBook()) {
3659 writeDocBookSource(os, absFileName(), runparams, output);
3661 // latex or literate
3663 d->texrow.newline();
3664 d->texrow.newline();
3665 otexstream ots(os, d->texrow);
3667 runparams.is_child = true;
3668 writeLaTeXSource(ots, string(), runparams, output);
3674 ErrorList & Buffer::errorList(string const & type) const
3676 return d->errorLists[type];
3680 void Buffer::updateTocItem(std::string const & type,
3681 DocIterator const & dit) const
3684 d->gui_->updateTocItem(type, dit);
3688 void Buffer::structureChanged() const
3691 d->gui_->structureChanged();
3695 void Buffer::errors(string const & err, bool from_master) const
3698 d->gui_->errors(err, from_master);
3702 void Buffer::message(docstring const & msg) const
3705 d->gui_->message(msg);
3709 void Buffer::setBusy(bool on) const
3712 d->gui_->setBusy(on);
3716 void Buffer::updateTitles() const
3719 d->wa_->updateTitles();
3723 void Buffer::resetAutosaveTimers() const
3726 d->gui_->resetAutosaveTimers();
3730 bool Buffer::hasGuiDelegate() const
3736 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3745 class AutoSaveBuffer : public ForkedProcess {
3748 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3749 : buffer_(buffer), fname_(fname) {}
3751 virtual shared_ptr<ForkedProcess> clone() const
3753 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3758 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3759 from_utf8(fname_.absFileName())));
3760 return run(DontWait);
3764 virtual int generateChild();
3766 Buffer const & buffer_;
3771 int AutoSaveBuffer::generateChild()
3773 #if defined(__APPLE__)
3774 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3775 * We should use something else like threads.
3777 * Since I do not know how to determine at run time what is the OS X
3778 * version, I just disable forking altogether for now (JMarc)
3780 pid_t const pid = -1;
3782 // tmp_ret will be located (usually) in /tmp
3783 // will that be a problem?
3784 // Note that this calls ForkedCalls::fork(), so it's
3785 // ok cross-platform.
3786 pid_t const pid = fork();
3787 // If you want to debug the autosave
3788 // you should set pid to -1, and comment out the fork.
3789 if (pid != 0 && pid != -1)
3793 // pid = -1 signifies that lyx was unable
3794 // to fork. But we will do the save
3796 bool failed = false;
3797 TempFile tempfile("lyxautoXXXXXX.lyx");
3798 tempfile.setAutoRemove(false);
3799 FileName const tmp_ret = tempfile.name();
3800 if (!tmp_ret.empty()) {
3801 if (!buffer_.writeFile(tmp_ret))
3803 else if (!tmp_ret.moveTo(fname_))
3809 // failed to write/rename tmp_ret so try writing direct
3810 if (!buffer_.writeFile(fname_)) {
3811 // It is dangerous to do this in the child,
3812 // but safe in the parent, so...
3813 if (pid == -1) // emit message signal.
3814 buffer_.message(_("Autosave failed!"));
3818 if (pid == 0) // we are the child so...
3827 FileName Buffer::getEmergencyFileName() const
3829 return FileName(d->filename.absFileName() + ".emergency");
3833 FileName Buffer::getAutosaveFileName() const
3835 // if the document is unnamed try to save in the backup dir, else
3836 // in the default document path, and as a last try in the filePath,
3837 // which will most often be the temporary directory
3840 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3841 : lyxrc.backupdir_path;
3842 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3845 string const fname = "#" + d->filename.onlyFileName() + "#";
3847 return makeAbsPath(fname, fpath);
3851 void Buffer::removeAutosaveFile() const
3853 FileName const f = getAutosaveFileName();
3859 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3861 FileName const newauto = getAutosaveFileName();
3863 if (newauto != oldauto && oldauto.exists())
3864 if (!oldauto.moveTo(newauto))
3865 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3869 bool Buffer::autoSave() const
3871 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3872 if (buf->d->bak_clean || isReadonly())
3875 message(_("Autosaving current document..."));
3876 buf->d->bak_clean = true;
3878 FileName const fname = getAutosaveFileName();
3879 LASSERT(d->cloned_buffer_, return false);
3881 // If this buffer is cloned, we assume that
3882 // we are running in a separate thread already.
3883 TempFile tempfile("lyxautoXXXXXX.lyx");
3884 tempfile.setAutoRemove(false);
3885 FileName const tmp_ret = tempfile.name();
3886 if (!tmp_ret.empty()) {
3888 // assume successful write of tmp_ret
3889 if (tmp_ret.moveTo(fname))
3892 // failed to write/rename tmp_ret so try writing direct
3893 return writeFile(fname);
3897 void Buffer::setExportStatus(bool e) const
3899 d->doing_export = e;
3900 ListOfBuffers clist = getDescendents();
3901 ListOfBuffers::const_iterator cit = clist.begin();
3902 ListOfBuffers::const_iterator const cen = clist.end();
3903 for (; cit != cen; ++cit)
3904 (*cit)->d->doing_export = e;
3908 bool Buffer::isExporting() const
3910 return d->doing_export;
3914 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3918 return doExport(target, put_in_tempdir, result_file);
3921 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3922 string & result_file) const
3924 bool const update_unincluded =
3925 params().maintain_unincluded_children
3926 && !params().getIncludedChildren().empty();
3928 // (1) export with all included children (omit \includeonly)
3929 if (update_unincluded) {
3930 ExportStatus const status =
3931 doExport(target, put_in_tempdir, true, result_file);
3932 if (status != ExportSuccess)
3935 // (2) export with included children only
3936 return doExport(target, put_in_tempdir, false, result_file);
3940 void Buffer::setMathFlavor(OutputParams & op) const
3942 switch (params().html_math_output) {
3943 case BufferParams::MathML:
3944 op.math_flavor = OutputParams::MathAsMathML;
3946 case BufferParams::HTML:
3947 op.math_flavor = OutputParams::MathAsHTML;
3949 case BufferParams::Images:
3950 op.math_flavor = OutputParams::MathAsImages;
3952 case BufferParams::LaTeX:
3953 op.math_flavor = OutputParams::MathAsLaTeX;
3959 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3960 bool includeall, string & result_file) const
3962 LYXERR(Debug::FILES, "target=" << target);
3963 OutputParams runparams(¶ms().encoding());
3964 string format = target;
3965 string dest_filename;
3966 size_t pos = target.find(' ');
3967 if (pos != string::npos) {
3968 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3969 format = target.substr(0, pos);
3970 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3971 FileName(dest_filename).onlyPath().createPath();
3972 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3974 MarkAsExporting exporting(this);
3975 string backend_format;
3976 runparams.flavor = OutputParams::LATEX;
3977 runparams.linelen = lyxrc.plaintext_linelen;
3978 runparams.includeall = includeall;
3979 vector<string> backs = params().backends();
3980 Converters converters = theConverters();
3981 bool need_nice_file = false;
3982 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3983 // Get shortest path to format
3984 converters.buildGraph();
3985 Graph::EdgePath path;
3986 for (vector<string>::const_iterator it = backs.begin();
3987 it != backs.end(); ++it) {
3988 Graph::EdgePath p = converters.getPath(*it, format);
3989 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3990 backend_format = *it;
3995 if (!put_in_tempdir) {
3996 // Only show this alert if this is an export to a non-temporary
3997 // file (not for previewing).
3998 Alert::error(_("Couldn't export file"), bformat(
3999 _("No information for exporting the format %1$s."),
4000 formats.prettyName(format)));
4002 return ExportNoPathToFormat;
4004 runparams.flavor = converters.getFlavor(path, this);
4005 Graph::EdgePath::const_iterator it = path.begin();
4006 Graph::EdgePath::const_iterator en = path.end();
4007 for (; it != en; ++it)
4008 if (theConverters().get(*it).nice()) {
4009 need_nice_file = true;
4014 backend_format = format;
4015 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4016 // FIXME: Don't hardcode format names here, but use a flag
4017 if (backend_format == "pdflatex")
4018 runparams.flavor = OutputParams::PDFLATEX;
4019 else if (backend_format == "luatex")
4020 runparams.flavor = OutputParams::LUATEX;
4021 else if (backend_format == "dviluatex")
4022 runparams.flavor = OutputParams::DVILUATEX;
4023 else if (backend_format == "xetex")
4024 runparams.flavor = OutputParams::XETEX;
4027 string filename = latexName(false);
4028 filename = addName(temppath(), filename);
4029 filename = changeExtension(filename,
4030 formats.extension(backend_format));
4031 LYXERR(Debug::FILES, "filename=" << filename);
4033 // Plain text backend
4034 if (backend_format == "text") {
4035 runparams.flavor = OutputParams::TEXT;
4036 writePlaintextFile(*this, FileName(filename), runparams);
4039 else if (backend_format == "xhtml") {
4040 runparams.flavor = OutputParams::HTML;
4041 setMathFlavor(runparams);
4042 makeLyXHTMLFile(FileName(filename), runparams);
4043 } else if (backend_format == "lyx")
4044 writeFile(FileName(filename));
4046 else if (params().isDocBook()) {
4047 runparams.nice = !put_in_tempdir;
4048 makeDocBookFile(FileName(filename), runparams);
4051 else if (backend_format == format || need_nice_file) {
4052 runparams.nice = true;
4053 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4054 if (d->cloned_buffer_)
4055 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4058 } else if (!lyxrc.tex_allows_spaces
4059 && contains(filePath(), ' ')) {
4060 Alert::error(_("File name error"),
4061 _("The directory path to the document cannot contain spaces."));
4062 return ExportTexPathHasSpaces;
4064 runparams.nice = false;
4065 bool const success = makeLaTeXFile(
4066 FileName(filename), filePath(), runparams);
4067 if (d->cloned_buffer_)
4068 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4073 string const error_type = (format == "program")
4074 ? "Build" : params().bufferFormat();
4075 ErrorList & error_list = d->errorLists[error_type];
4076 string const ext = formats.extension(format);
4077 FileName const tmp_result_file(changeExtension(filename, ext));
4078 bool const success = converters.convert(this, FileName(filename),
4079 tmp_result_file, FileName(absFileName()), backend_format, format,
4082 // Emit the signal to show the error list or copy it back to the
4083 // cloned Buffer so that it can be emitted afterwards.
4084 if (format != backend_format) {
4085 if (runparams.silent)
4087 else if (d->cloned_buffer_)
4088 d->cloned_buffer_->d->errorLists[error_type] =
4089 d->errorLists[error_type];
4092 // also to the children, in case of master-buffer-view
4093 ListOfBuffers clist = getDescendents();
4094 ListOfBuffers::const_iterator cit = clist.begin();
4095 ListOfBuffers::const_iterator const cen = clist.end();
4096 for (; cit != cen; ++cit) {
4097 if (runparams.silent)
4098 (*cit)->d->errorLists[error_type].clear();
4099 else if (d->cloned_buffer_) {
4100 // Enable reverse search by copying back the
4101 // texrow object to the cloned buffer.
4102 // FIXME: this is not thread safe.
4103 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4104 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4105 (*cit)->d->errorLists[error_type];
4107 (*cit)->errors(error_type, true);
4111 if (d->cloned_buffer_) {
4112 // Enable reverse dvi or pdf to work by copying back the texrow
4113 // object to the cloned buffer.
4114 // FIXME: There is a possibility of concurrent access to texrow
4115 // here from the main GUI thread that should be securized.
4116 d->cloned_buffer_->d->texrow = d->texrow;
4117 string const error_type = params().bufferFormat();
4118 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4122 if (put_in_tempdir) {
4123 result_file = tmp_result_file.absFileName();
4124 return success ? ExportSuccess : ExportConverterError;
4127 if (dest_filename.empty())
4128 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4130 result_file = dest_filename;
4131 // We need to copy referenced files (e. g. included graphics
4132 // if format == "dvi") to the result dir.
4133 vector<ExportedFile> const files =
4134 runparams.exportdata->externalFiles(format);
4135 string const dest = runparams.export_folder.empty() ?
4136 onlyPath(result_file) : runparams.export_folder;
4137 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4138 : force_overwrite == ALL_FILES;
4139 CopyStatus status = use_force ? FORCE : SUCCESS;
4141 vector<ExportedFile>::const_iterator it = files.begin();
4142 vector<ExportedFile>::const_iterator const en = files.end();
4143 for (; it != en && status != CANCEL; ++it) {
4144 string const fmt = formats.getFormatFromFile(it->sourceName);
4145 string fixedName = it->exportName;
4146 if (!runparams.export_folder.empty()) {
4147 // Relative pathnames starting with ../ will be sanitized
4148 // if exporting to a different folder
4149 while (fixedName.substr(0, 3) == "../")
4150 fixedName = fixedName.substr(3, fixedName.length() - 3);
4152 FileName fixedFileName = makeAbsPath(fixedName, dest);
4153 fixedFileName.onlyPath().createPath();
4154 status = copyFile(fmt, it->sourceName,
4156 it->exportName, status == FORCE,
4157 runparams.export_folder.empty());
4160 if (status == CANCEL) {
4161 message(_("Document export cancelled."));
4162 return ExportCancel;
4165 if (tmp_result_file.exists()) {
4166 // Finally copy the main file
4167 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4168 : force_overwrite != NO_FILES;
4169 if (status == SUCCESS && use_force)
4171 status = copyFile(format, tmp_result_file,
4172 FileName(result_file), result_file,
4174 if (status == CANCEL) {
4175 message(_("Document export cancelled."));
4176 return ExportCancel;
4178 message(bformat(_("Document exported as %1$s "
4180 formats.prettyName(format),
4181 makeDisplayPath(result_file)));
4184 // This must be a dummy converter like fax (bug 1888)
4185 message(bformat(_("Document exported as %1$s"),
4186 formats.prettyName(format)));
4189 return success ? ExportSuccess : ExportConverterError;
4193 Buffer::ExportStatus Buffer::preview(string const & format) const
4195 bool const update_unincluded =
4196 params().maintain_unincluded_children
4197 && !params().getIncludedChildren().empty();
4198 return preview(format, update_unincluded);
4202 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4204 MarkAsExporting exporting(this);
4206 // (1) export with all included children (omit \includeonly)
4208 ExportStatus const status = doExport(format, true, true, result_file);
4209 if (status != ExportSuccess)
4212 // (2) export with included children only
4213 ExportStatus const status = doExport(format, true, false, result_file);
4214 FileName const previewFile(result_file);
4215 if (previewFile.exists()) {
4216 if (!formats.view(*this, previewFile, format))
4217 return PreviewError;
4218 else if (status == ExportSuccess)
4219 return PreviewSuccess;
4224 // Successful export but no output file?
4225 // Probably a bug in error detection.
4226 LATTEST (status != ExportSuccess);
4233 Buffer::ReadStatus Buffer::extractFromVC()
4235 bool const found = LyXVC::file_not_found_hook(d->filename);
4237 return ReadFileNotFound;
4238 if (!d->filename.isReadableFile())
4244 Buffer::ReadStatus Buffer::loadEmergency()
4246 FileName const emergencyFile = getEmergencyFileName();
4247 if (!emergencyFile.exists()
4248 || emergencyFile.lastModified() <= d->filename.lastModified())
4249 return ReadFileNotFound;
4251 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4252 docstring const text = bformat(_("An emergency save of the document "
4253 "%1$s exists.\n\nRecover emergency save?"), file);
4255 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4256 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4262 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4263 bool const success = (ret_llf == ReadSuccess);
4266 Alert::warning(_("File is read-only"),
4267 bformat(_("An emergency file is successfully loaded, "
4268 "but the original file %1$s is marked read-only. "
4269 "Please make sure to save the document as a different "
4270 "file."), from_utf8(d->filename.absFileName())));
4273 lyxvc().file_found_hook(d->filename);
4274 str = _("Document was successfully recovered.");
4276 str = _("Document was NOT successfully recovered.");
4277 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4278 makeDisplayPath(emergencyFile.absFileName()));
4280 int const del_emerg =
4281 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4282 _("&Remove"), _("&Keep"));
4283 if (del_emerg == 0) {
4284 emergencyFile.removeFile();
4286 Alert::warning(_("Emergency file deleted"),
4287 _("Do not forget to save your file now!"), true);
4289 return success ? ReadSuccess : ReadEmergencyFailure;
4292 int const del_emerg =
4293 Alert::prompt(_("Delete emergency file?"),
4294 _("Remove emergency file now?"), 1, 1,
4295 _("&Remove"), _("&Keep"));
4297 emergencyFile.removeFile();
4298 return ReadOriginal;
4308 Buffer::ReadStatus Buffer::loadAutosave()
4310 // Now check if autosave file is newer.
4311 FileName const autosaveFile = getAutosaveFileName();
4312 if (!autosaveFile.exists()
4313 || autosaveFile.lastModified() <= d->filename.lastModified())
4314 return ReadFileNotFound;
4316 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4317 docstring const text = bformat(_("The backup of the document %1$s "
4318 "is newer.\n\nLoad the backup instead?"), file);
4319 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4320 _("&Load backup"), _("Load &original"), _("&Cancel"));
4325 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4326 // the file is not saved if we load the autosave file.
4327 if (ret_llf == ReadSuccess) {
4329 Alert::warning(_("File is read-only"),
4330 bformat(_("A backup file is successfully loaded, "
4331 "but the original file %1$s is marked read-only. "
4332 "Please make sure to save the document as a "
4334 from_utf8(d->filename.absFileName())));
4337 lyxvc().file_found_hook(d->filename);
4340 return ReadAutosaveFailure;
4343 // Here we delete the autosave
4344 autosaveFile.removeFile();
4345 return ReadOriginal;
4353 Buffer::ReadStatus Buffer::loadLyXFile()
4355 if (!d->filename.isReadableFile()) {
4356 ReadStatus const ret_rvc = extractFromVC();
4357 if (ret_rvc != ReadSuccess)
4361 ReadStatus const ret_re = loadEmergency();
4362 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4365 ReadStatus const ret_ra = loadAutosave();
4366 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4369 return loadThisLyXFile(d->filename);
4373 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4375 return readFile(fn);
4379 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4381 TeXErrors::Errors::const_iterator it = terr.begin();
4382 TeXErrors::Errors::const_iterator end = terr.end();
4383 ListOfBuffers clist = getDescendents();
4384 ListOfBuffers::const_iterator cen = clist.end();
4386 for (; it != end; ++it) {
4389 int errorRow = it->error_in_line;
4390 Buffer const * buf = 0;
4392 if (it->child_name.empty())
4393 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4395 // The error occurred in a child
4396 ListOfBuffers::const_iterator cit = clist.begin();
4397 for (; cit != cen; ++cit) {
4398 string const child_name =
4399 DocFileName(changeExtension(
4400 (*cit)->absFileName(), "tex")).
4402 if (it->child_name != child_name)
4404 (*cit)->d->texrow.getIdFromRow(errorRow,
4405 id_start, pos_start);
4406 if (id_start != -1) {
4407 buf = d->cloned_buffer_
4408 ? (*cit)->d->cloned_buffer_->d->owner_
4409 : (*cit)->d->owner_;
4420 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4421 } while (found && id_start == id_end && pos_start == pos_end);
4423 if (id_start != id_end) {
4424 // Next registered position is outside the inset where
4425 // the error occurred, so signal end-of-paragraph
4429 errorList.push_back(ErrorItem(it->error_desc,
4430 it->error_text, id_start, pos_start, pos_end, buf));
4435 void Buffer::setBuffersForInsets() const
4437 inset().setBuffer(const_cast<Buffer &>(*this));
4441 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4443 LBUFERR(!text().paragraphs().empty());
4445 // Use the master text class also for child documents
4446 Buffer const * const master = masterBuffer();
4447 DocumentClass const & textclass = master->params().documentClass();
4449 // do this only if we are the top-level Buffer
4450 if (master == this) {
4451 textclass.counters().reset(from_ascii("bibitem"));
4452 reloadBibInfoCache();
4455 // keep the buffers to be children in this set. If the call from the
4456 // master comes back we can see which of them were actually seen (i.e.
4457 // via an InsetInclude). The remaining ones in the set need still be updated.
4458 static std::set<Buffer const *> bufToUpdate;
4459 if (scope == UpdateMaster) {
4460 // If this is a child document start with the master
4461 if (master != this) {
4462 bufToUpdate.insert(this);
4463 master->updateBuffer(UpdateMaster, utype);
4464 // If the master buffer has no gui associated with it, then the TocModel is
4465 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4466 // (bug 5699). The same happens if the master buffer is open in a different
4467 // window. This test catches both possibilities.
4468 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4469 // There remains a problem here: If there is another child open in yet a third
4470 // window, that TOC is not updated. So some more general solution is needed at
4472 if (master->d->gui_ != d->gui_)
4475 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4476 if (bufToUpdate.find(this) == bufToUpdate.end())
4480 // start over the counters in the master
4481 textclass.counters().reset();
4484 // update will be done below for this buffer
4485 bufToUpdate.erase(this);
4487 // update all caches
4488 clearReferenceCache();
4491 Buffer & cbuf = const_cast<Buffer &>(*this);
4494 ParIterator parit = cbuf.par_iterator_begin();
4495 updateBuffer(parit, utype);
4498 // TocBackend update will be done later.
4501 d->bibinfo_cache_valid_ = true;
4502 d->cite_labels_valid_ = true;
4503 cbuf.tocBackend().update(utype == OutputUpdate);
4504 if (scope == UpdateMaster)
4505 cbuf.structureChanged();
4509 static depth_type getDepth(DocIterator const & it)
4511 depth_type depth = 0;
4512 for (size_t i = 0 ; i < it.depth() ; ++i)
4513 if (!it[i].inset().inMathed())
4514 depth += it[i].paragraph().getDepth() + 1;
4515 // remove 1 since the outer inset does not count
4519 static depth_type getItemDepth(ParIterator const & it)
4521 Paragraph const & par = *it;
4522 LabelType const labeltype = par.layout().labeltype;
4524 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4527 // this will hold the lowest depth encountered up to now.
4528 depth_type min_depth = getDepth(it);
4529 ParIterator prev_it = it;
4532 --prev_it.top().pit();
4534 // start of nested inset: go to outer par
4536 if (prev_it.empty()) {
4537 // start of document: nothing to do
4542 // We search for the first paragraph with same label
4543 // that is not more deeply nested.
4544 Paragraph & prev_par = *prev_it;
4545 depth_type const prev_depth = getDepth(prev_it);
4546 if (labeltype == prev_par.layout().labeltype) {
4547 if (prev_depth < min_depth)
4548 return prev_par.itemdepth + 1;
4549 if (prev_depth == min_depth)
4550 return prev_par.itemdepth;
4552 min_depth = min(min_depth, prev_depth);
4553 // small optimization: if we are at depth 0, we won't
4554 // find anything else
4555 if (prev_depth == 0)
4561 static bool needEnumCounterReset(ParIterator const & it)
4563 Paragraph const & par = *it;
4564 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4565 depth_type const cur_depth = par.getDepth();
4566 ParIterator prev_it = it;
4567 while (prev_it.pit()) {
4568 --prev_it.top().pit();
4569 Paragraph const & prev_par = *prev_it;
4570 if (prev_par.getDepth() <= cur_depth)
4571 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4573 // start of nested inset: reset
4578 // set the label of a paragraph. This includes the counters.
4579 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4581 BufferParams const & bp = owner_->masterBuffer()->params();
4582 DocumentClass const & textclass = bp.documentClass();
4583 Paragraph & par = it.paragraph();
4584 Layout const & layout = par.layout();
4585 Counters & counters = textclass.counters();
4587 if (par.params().startOfAppendix()) {
4588 // We want to reset the counter corresponding to toplevel sectioning
4589 Layout const & lay = textclass.getTOCLayout();
4590 docstring const cnt = lay.counter;
4592 counters.reset(cnt);
4593 counters.appendix(true);
4595 par.params().appendix(counters.appendix());
4597 // Compute the item depth of the paragraph
4598 par.itemdepth = getItemDepth(it);
4600 if (layout.margintype == MARGIN_MANUAL) {
4601 if (par.params().labelWidthString().empty())
4602 par.params().labelWidthString(par.expandLabel(layout, bp));
4603 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4604 // we do not need to do anything here, since the empty case is
4605 // handled during export.
4607 par.params().labelWidthString(docstring());
4610 switch(layout.labeltype) {
4611 case LABEL_ITEMIZE: {
4612 // At some point of time we should do something more
4613 // clever here, like:
4614 // par.params().labelString(
4615 // bp.user_defined_bullet(par.itemdepth).getText());
4616 // for now, use a simple hardcoded label
4617 docstring itemlabel;
4618 switch (par.itemdepth) {
4620 itemlabel = char_type(0x2022);
4623 itemlabel = char_type(0x2013);
4626 itemlabel = char_type(0x2217);
4629 itemlabel = char_type(0x2219); // or 0x00b7
4632 par.params().labelString(itemlabel);
4636 case LABEL_ENUMERATE: {
4637 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4639 switch (par.itemdepth) {
4648 enumcounter += "iv";
4651 // not a valid enumdepth...
4655 // Maybe we have to reset the enumeration counter.
4656 if (needEnumCounterReset(it))
4657 counters.reset(enumcounter);
4658 counters.step(enumcounter, utype);
4660 string const & lang = par.getParLanguage(bp)->code();
4661 par.params().labelString(counters.theCounter(enumcounter, lang));
4666 case LABEL_SENSITIVE: {
4667 string const & type = counters.current_float();
4668 docstring full_label;
4670 full_label = owner_->B_("Senseless!!! ");
4672 docstring name = owner_->B_(textclass.floats().getType(type).name());
4673 if (counters.hasCounter(from_utf8(type))) {
4674 string const & lang = par.getParLanguage(bp)->code();
4675 counters.step(from_utf8(type), utype);
4676 full_label = bformat(from_ascii("%1$s %2$s:"),
4678 counters.theCounter(from_utf8(type), lang));
4680 full_label = bformat(from_ascii("%1$s #:"), name);
4682 par.params().labelString(full_label);
4686 case LABEL_NO_LABEL:
4687 par.params().labelString(docstring());
4691 case LABEL_CENTERED:
4692 case LABEL_STATIC: {
4693 docstring const & lcounter = layout.counter;
4694 if (!lcounter.empty()) {
4695 if (layout.toclevel <= bp.secnumdepth
4696 && (layout.latextype != LATEX_ENVIRONMENT
4697 || it.text()->isFirstInSequence(it.pit()))) {
4698 if (counters.hasCounter(lcounter))
4699 counters.step(lcounter, utype);
4700 par.params().labelString(par.expandLabel(layout, bp));
4702 par.params().labelString(docstring());
4704 par.params().labelString(par.expandLabel(layout, bp));
4710 par.params().labelString(par.expandLabel(layout, bp));
4715 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4717 // LASSERT: Is it safe to continue here, or should we just return?
4718 LASSERT(parit.pit() == 0, /**/);
4720 // Set the position of the text in the buffer to be able
4721 // to resolve macros in it.
4722 parit.text()->setMacrocontextPosition(parit);
4724 depth_type maxdepth = 0;
4725 pit_type const lastpit = parit.lastpit();
4726 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4727 // reduce depth if necessary
4728 if (parit->params().depth() > maxdepth) {
4729 /** FIXME: this function is const, but
4730 * nevertheless it modifies the buffer. To be
4731 * cleaner, one should modify the buffer in
4732 * another function, which is actually
4733 * non-const. This would however be costly in
4734 * terms of code duplication.
4736 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4737 parit->params().depth(maxdepth);
4739 maxdepth = parit->getMaxDepthAfter();
4741 if (utype == OutputUpdate) {
4742 // track the active counters
4743 // we have to do this for the master buffer, since the local
4744 // buffer isn't tracking anything.
4745 masterBuffer()->params().documentClass().counters().
4746 setActiveLayout(parit->layout());
4749 // set the counter for this paragraph
4750 d->setLabel(parit, utype);
4753 InsetList::const_iterator iit = parit->insetList().begin();
4754 InsetList::const_iterator end = parit->insetList().end();
4755 for (; iit != end; ++iit) {
4756 parit.pos() = iit->pos;
4757 iit->inset->updateBuffer(parit, utype);
4763 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4764 WordLangTuple & word_lang, docstring_list & suggestions) const
4768 suggestions.clear();
4769 word_lang = WordLangTuple();
4770 bool const to_end = to.empty();
4771 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4772 // OK, we start from here.
4773 for (; from != end; from.forwardPos()) {
4774 // We are only interested in text so remove the math CursorSlice.
4775 while (from.inMathed()) {
4779 // If from is at the end of the document (which is possible
4780 // when leaving the mathed) LyX will crash later otherwise.
4781 if (from.atEnd() || (!to_end && from >= end))
4784 from.paragraph().spellCheck();
4785 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4786 if (SpellChecker::misspelled(res)) {
4791 // Do not increase progress when from == to, otherwise the word
4792 // count will be wrong.
4802 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4804 bool inword = false;
4809 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4810 if (!dit.inTexted()) {
4815 Paragraph const & par = dit.paragraph();
4816 pos_type const pos = dit.pos();
4818 // Copied and adapted from isWordSeparator() in Paragraph
4819 if (pos == dit.lastpos()) {
4822 Inset const * ins = par.getInset(pos);
4823 if (ins && skipNoOutput && !ins->producesOutput()) {
4826 // stop if end of range was skipped
4827 if (!to.atEnd() && dit >= to)
4830 } else if (!par.isDeleted(pos)) {
4831 if (par.isWordSeparator(pos))
4837 if (ins && ins->isLetter())
4839 else if (ins && ins->isSpace())
4842 char_type const c = par.getChar(pos);
4843 if (isPrintableNonspace(c))
4845 else if (isSpace(c))
4855 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4857 d->updateStatistics(from, to, skipNoOutput);
4861 int Buffer::wordCount() const
4863 return d->wordCount();
4867 int Buffer::charCount(bool with_blanks) const
4869 return d->charCount(with_blanks);
4873 Buffer::ReadStatus Buffer::reload()
4876 // c.f. bug http://www.lyx.org/trac/ticket/6587
4877 removeAutosaveFile();
4878 // e.g., read-only status could have changed due to version control
4879 d->filename.refresh();
4880 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4882 // clear parent. this will get reset if need be.
4884 ReadStatus const status = loadLyXFile();
4885 if (status == ReadSuccess) {
4890 message(bformat(_("Document %1$s reloaded."), disp_fn));
4893 message(bformat(_("Could not reload document %1$s."), disp_fn));
4903 bool Buffer::saveAs(FileName const & fn)
4905 FileName const old_name = fileName();
4906 FileName const old_auto = getAutosaveFileName();
4907 bool const old_unnamed = isUnnamed();
4914 // bring the autosave file with us, just in case.
4915 moveAutosaveFile(old_auto);
4916 // validate version control data and
4917 // correct buffer title
4918 lyxvc().file_found_hook(fileName());
4920 // the file has now been saved to the new location.
4921 // we need to check that the locations of child buffers
4923 checkChildBuffers();
4924 checkMasterBuffer();
4928 // reset the old filename and unnamed state
4929 setFileName(old_name);
4930 setUnnamed(old_unnamed);
4936 // FIXME We could do better here, but it is complicated. What would be
4937 // nice is to offer either (a) to save the child buffer to an appropriate
4938 // location, so that it would "move with the master", or else (b) to update
4939 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4940 // complicated, because the code for this lives in GuiView.
4941 void Buffer::checkChildBuffers()
4943 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4944 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4945 for (; it != en; ++it) {
4946 DocIterator dit = it->second;
4947 Buffer * cbuf = const_cast<Buffer *>(it->first);
4948 if (!cbuf || !theBufferList().isLoaded(cbuf))
4950 Inset * inset = dit.nextInset();
4951 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4952 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4953 docstring const & incfile = inset_inc->getParam("filename");
4954 string oldloc = cbuf->absFileName();
4955 string newloc = makeAbsPath(to_utf8(incfile),
4956 onlyPath(absFileName())).absFileName();
4957 if (oldloc == newloc)
4959 // the location of the child file is incorrect.
4960 Alert::warning(_("Included File Invalid"),
4961 bformat(_("Saving this document to a new location has made the file:\n"
4963 "inaccessible. You will need to update the included filename."),
4964 from_utf8(oldloc)));
4966 inset_inc->setChildBuffer(0);
4968 // invalidate cache of children
4969 d->children_positions.clear();
4970 d->position_to_children.clear();
4974 // If a child has been saved under a different name/path, it might have been
4975 // orphaned. Therefore the master needs to be reset (bug 8161).
4976 void Buffer::checkMasterBuffer()
4978 Buffer const * const master = masterBuffer();
4982 // necessary to re-register the child (bug 5873)
4983 // FIXME: clean up updateMacros (here, only
4984 // child registering is needed).
4985 master->updateMacros();
4986 // (re)set master as master buffer, but only
4987 // if we are a real child
4988 if (master->isChild(this))