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;
222 typedef pair<DocIterator, MacroData> ScopeMacro;
223 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
224 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
225 /// map from the macro name to the position map,
226 /// which maps the macro definition position to the scope and the MacroData.
227 NamePositionScopeMacroMap macros;
228 /// This seem to change the way Buffer::getMacro() works
229 mutable bool macro_lock;
231 /// positions of child buffers in the buffer
232 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
233 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
234 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
235 /// position of children buffers in this buffer
236 BufferPositionMap children_positions;
237 /// map from children inclusion positions to their scope and their buffer
238 PositionScopeBufferMap position_to_children;
240 /// Container for all sort of Buffer dependant errors.
241 map<string, ErrorList> errorLists;
243 /// timestamp and checksum used to test if the file has been externally
244 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
246 unsigned long checksum_;
249 frontend::WorkAreaManager * wa_;
251 frontend::GuiBufferDelegate * gui_;
256 /// A cache for the bibfiles (including bibfiles of loaded child
257 /// documents), needed for appropriate update of natbib labels.
258 mutable support::FileNameList bibfiles_cache_;
260 // FIXME The caching mechanism could be improved. At present, we have a
261 // cache for each Buffer, that caches all the bibliography info for that
262 // Buffer. A more efficient solution would be to have a global cache per
263 // file, and then to construct the Buffer's bibinfo from that.
264 /// A cache for bibliography info
265 mutable BiblioInfo bibinfo_;
266 /// whether the bibinfo cache is valid
267 mutable bool bibinfo_cache_valid_;
268 /// whether the bibfile cache is valid
269 mutable bool bibfile_cache_valid_;
270 /// Cache of timestamps of .bib files
271 map<FileName, time_t> bibfile_status_;
272 /// Indicates whether the bibinfo has changed since the last time
273 /// we ran updateBuffer(), i.e., whether citation labels may need
275 mutable bool cite_labels_valid_;
277 mutable RefCache ref_cache_;
279 /// our Text that should be wrapped in an InsetText
283 PreviewLoader * preview_loader_;
285 /// This is here to force the test to be done whenever parent_buffer
287 Buffer const * parent() const
289 // ignore_parent temporarily "orphans" a buffer
290 // (e.g. if a child is compiled standalone)
293 // if parent_buffer is not loaded, then it has been unloaded,
294 // which means that parent_buffer is an invalid pointer. So we
295 // set it to null in that case.
296 // however, the BufferList doesn't know about cloned buffers, so
297 // they will always be regarded as unloaded. in that case, we hope
299 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
301 return parent_buffer;
305 void setParent(Buffer const * pb)
307 if (parent_buffer == pb)
310 if (!cloned_buffer_ && parent_buffer && pb)
311 LYXERR0("Warning: a buffer should not have two parents!");
313 if (!cloned_buffer_ && parent_buffer) {
314 parent_buffer->invalidateBibfileCache();
315 parent_buffer->invalidateBibinfoCache();
319 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
320 /// This one is useful for preview detached in a thread.
321 Buffer const * cloned_buffer_;
323 CloneList * clone_list_;
324 /// are we in the process of exporting this buffer?
325 mutable bool doing_export;
327 /// compute statistics
328 /// \p from initial position
329 /// \p to points to the end position
330 void updateStatistics(DocIterator & from, DocIterator & to,
331 bool skipNoOutput = true);
332 /// statistics accessor functions
333 int wordCount() const
337 int charCount(bool with_blanks) const
340 + (with_blanks ? blank_count_ : 0);
344 /// So we can force access via the accessors.
345 mutable Buffer const * parent_buffer;
354 /// Creates the per buffer temporary directory
355 static FileName createBufferTmpDir()
357 // FIXME This would be the ideal application for a TempDir class (like
358 // TempFile but for directories)
363 Mutex::Locker locker(&mutex);
364 counter = convert<string>(count++);
366 // We are in our own directory. Why bother to mangle name?
367 // In fact I wrote this code to circumvent a problematic behaviour
368 // (bug?) of EMX mkstemp().
369 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
372 if (!tmpfl.createDirectory(0777)) {
373 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
374 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
375 from_utf8(tmpfl.absFileName())));
381 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
382 Buffer const * cloned_buffer)
383 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
384 internal_buffer(false), read_only(readonly_), filename(file),
385 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
386 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
387 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
388 cite_labels_valid_(false), preview_loader_(0),
389 cloned_buffer_(cloned_buffer), clone_list_(0),
390 doing_export(false), parent_buffer(0)
392 if (!cloned_buffer_) {
393 temppath = createBufferTmpDir();
394 lyxvc.setBuffer(owner_);
396 wa_ = new frontend::WorkAreaManager;
399 temppath = cloned_buffer_->d->temppath;
400 file_fully_loaded = true;
401 params = cloned_buffer_->d->params;
402 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
403 bibinfo_ = cloned_buffer_->d->bibinfo_;
404 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
405 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
406 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
407 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
408 unnamed = cloned_buffer_->d->unnamed;
409 internal_buffer = cloned_buffer_->d->internal_buffer;
413 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
414 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
416 LYXERR(Debug::INFO, "Buffer::Buffer()");
418 d->inset = new InsetText(*cloned_buffer->d->inset);
419 d->inset->setBuffer(*this);
420 // FIXME: optimize this loop somewhat, maybe by creating a new
421 // general recursive Inset::setId().
422 DocIterator it = doc_iterator_begin(this);
423 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
424 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
425 it.paragraph().setId(cloned_it.paragraph().id());
427 d->inset = new InsetText(this);
428 d->inset->setAutoBreakRows(true);
429 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
435 LYXERR(Debug::INFO, "Buffer::~Buffer()");
436 // here the buffer should take care that it is
437 // saved properly, before it goes into the void.
439 // GuiView already destroyed
443 // No need to do additional cleanups for internal buffer.
449 // this is in case of recursive includes: we won't try to delete
450 // ourselves as a child.
451 d->clone_list_->erase(this);
452 // loop over children
453 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
454 Impl::BufferPositionMap::iterator end = d->children_positions.end();
455 for (; it != end; ++it) {
456 Buffer * child = const_cast<Buffer *>(it->first);
457 if (d->clone_list_->erase(child))
460 // if we're the master buffer, then we should get rid of the list
463 // If this is not empty, we have leaked something. Worse, one of the
464 // children still has a reference to this list. But we will try to
465 // continue, rather than shut down.
466 LATTEST(d->clone_list_->empty());
467 list<CloneList *>::iterator it =
468 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
469 if (it == cloned_buffers.end()) {
470 // We will leak in this case, but it is safe to continue.
473 cloned_buffers.erase(it);
474 delete d->clone_list_;
476 // FIXME Do we really need to do this right before we delete d?
477 // clear references to children in macro tables
478 d->children_positions.clear();
479 d->position_to_children.clear();
481 // loop over children
482 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
483 Impl::BufferPositionMap::iterator end = d->children_positions.end();
484 for (; it != end; ++it) {
485 Buffer * child = const_cast<Buffer *>(it->first);
486 if (theBufferList().isLoaded(child))
487 theBufferList().releaseChild(this, child);
491 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
492 msg += emergencyWrite();
493 Alert::warning(_("Attempting to close changed document!"), msg);
496 // FIXME Do we really need to do this right before we delete d?
497 // clear references to children in macro tables
498 d->children_positions.clear();
499 d->position_to_children.clear();
501 if (!d->temppath.destroyDirectory()) {
502 Alert::warning(_("Could not remove temporary directory"),
503 bformat(_("Could not remove the temporary directory %1$s"),
504 from_utf8(d->temppath.absFileName())));
513 Buffer * Buffer::cloneFromMaster() const
516 cloned_buffers.push_back(new CloneList);
517 CloneList * clones = cloned_buffers.back();
519 masterBuffer()->cloneWithChildren(bufmap, clones);
521 // make sure we got cloned
522 BufferMap::const_iterator bit = bufmap.find(this);
523 LASSERT(bit != bufmap.end(), return 0);
524 Buffer * cloned_buffer = bit->second;
526 return cloned_buffer;
530 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
532 // have we already been cloned?
533 if (bufmap.find(this) != bufmap.end())
536 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
538 // The clone needs its own DocumentClass, since running updateBuffer() will
539 // modify it, and we would otherwise be sharing it with the original Buffer.
540 buffer_clone->params().makeDocumentClass(true);
542 cap::switchBetweenClasses(
543 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
544 static_cast<InsetText &>(buffer_clone->inset()), el);
546 bufmap[this] = buffer_clone;
547 clones->insert(buffer_clone);
548 buffer_clone->d->clone_list_ = clones;
549 buffer_clone->d->macro_lock = true;
550 buffer_clone->d->children_positions.clear();
552 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
553 // math macro caches need to be rethought and simplified.
554 // I am not sure wether we should handle Buffer cloning here or in BufferList.
555 // Right now BufferList knows nothing about buffer clones.
556 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
557 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
558 for (; it != end; ++it) {
559 DocIterator dit = it->first.clone(buffer_clone);
560 dit.setBuffer(buffer_clone);
561 Buffer * child = const_cast<Buffer *>(it->second.second);
563 child->cloneWithChildren(bufmap, clones);
564 BufferMap::iterator const bit = bufmap.find(child);
565 LASSERT(bit != bufmap.end(), continue);
566 Buffer * child_clone = bit->second;
568 Inset * inset = dit.nextInset();
569 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
570 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
571 inset_inc->setChildBuffer(child_clone);
572 child_clone->d->setParent(buffer_clone);
573 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
574 buffer_clone->setChild(dit, child_clone);
576 buffer_clone->d->macro_lock = false;
581 Buffer * Buffer::cloneBufferOnly() const {
582 cloned_buffers.push_back(new CloneList);
583 CloneList * clones = cloned_buffers.back();
584 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
586 // The clone needs its own DocumentClass, since running updateBuffer() will
587 // modify it, and we would otherwise be sharing it with the original Buffer.
588 buffer_clone->params().makeDocumentClass(true);
590 cap::switchBetweenClasses(
591 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
592 static_cast<InsetText &>(buffer_clone->inset()), el);
594 clones->insert(buffer_clone);
595 buffer_clone->d->clone_list_ = clones;
597 // we won't be cloning the children
598 buffer_clone->d->children_positions.clear();
603 bool Buffer::isClone() const
605 return d->cloned_buffer_;
609 void Buffer::changed(bool update_metrics) const
612 d->wa_->redrawAll(update_metrics);
616 frontend::WorkAreaManager & Buffer::workAreaManager() const
623 Text & Buffer::text() const
625 return d->inset->text();
629 Inset & Buffer::inset() const
635 BufferParams & Buffer::params()
641 BufferParams const & Buffer::params() const
647 BufferParams const & Buffer::masterParams() const
649 if (masterBuffer() == this)
652 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
653 // Copy child authors to the params. We need those pointers.
654 AuthorList const & child_authors = params().authors();
655 AuthorList::Authors::const_iterator it = child_authors.begin();
656 for (; it != child_authors.end(); ++it)
657 mparams.authors().record(*it);
662 double Buffer::fontScalingFactor() const
664 return isExporting() ? 75.0 * params().html_math_img_scale
665 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
669 ParagraphList & Buffer::paragraphs()
671 return text().paragraphs();
675 ParagraphList const & Buffer::paragraphs() const
677 return text().paragraphs();
681 LyXVC & Buffer::lyxvc()
687 LyXVC const & Buffer::lyxvc() const
693 string const Buffer::temppath() const
695 return d->temppath.absFileName();
699 TexRow & Buffer::texrow()
705 TexRow const & Buffer::texrow() const
711 TocBackend & Buffer::tocBackend() const
713 return d->toc_backend;
717 Undo & Buffer::undo()
723 void Buffer::setChild(DocIterator const & dit, Buffer * child)
725 d->children_positions[child] = dit;
729 string Buffer::latexName(bool const no_path) const
731 FileName latex_name =
732 makeLatexName(d->exportFileName());
733 return no_path ? latex_name.onlyFileName()
734 : latex_name.absFileName();
738 FileName Buffer::Impl::exportFileName() const
740 docstring const branch_suffix =
741 params.branchlist().getFileNameSuffix();
742 if (branch_suffix.empty())
745 string const name = filename.onlyFileNameWithoutExt()
746 + to_utf8(branch_suffix);
747 FileName res(filename.onlyPath().absFileName() + "/" + name);
748 res.changeExtension(filename.extension());
754 string Buffer::logName(LogType * type) const
756 string const filename = latexName(false);
758 if (filename.empty()) {
764 string const path = temppath();
766 FileName const fname(addName(temppath(),
767 onlyFileName(changeExtension(filename,
770 // FIXME: how do we know this is the name of the build log?
771 FileName const bname(
772 addName(path, onlyFileName(
773 changeExtension(filename,
774 formats.extension(params().bufferFormat()) + ".out"))));
776 // Also consider the master buffer log file
777 FileName masterfname = fname;
779 if (masterBuffer() != this) {
780 string const mlogfile = masterBuffer()->logName(&mtype);
781 masterfname = FileName(mlogfile);
784 // If no Latex log or Build log is newer, show Build log
785 if (bname.exists() &&
786 ((!fname.exists() && !masterfname.exists())
787 || (fname.lastModified() < bname.lastModified()
788 && masterfname.lastModified() < bname.lastModified()))) {
789 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
792 return bname.absFileName();
793 // If we have a newer master file log or only a master log, show this
794 } else if (fname != masterfname
795 && (!fname.exists() && (masterfname.exists()
796 || fname.lastModified() < masterfname.lastModified()))) {
797 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
800 return masterfname.absFileName();
802 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
805 return fname.absFileName();
809 void Buffer::setReadonly(bool const flag)
811 if (d->read_only != flag) {
818 void Buffer::setFileName(FileName const & fname)
820 bool const changed = fname != d->filename;
823 lyxvc().file_found_hook(fname);
824 setReadonly(d->filename.isReadOnly());
830 int Buffer::readHeader(Lexer & lex)
832 int unknown_tokens = 0;
834 int begin_header_line = -1;
836 // Initialize parameters that may be/go lacking in header:
837 params().branchlist().clear();
838 params().preamble.erase();
839 params().options.erase();
840 params().master.erase();
841 params().float_placement.erase();
842 params().paperwidth.erase();
843 params().paperheight.erase();
844 params().leftmargin.erase();
845 params().rightmargin.erase();
846 params().topmargin.erase();
847 params().bottommargin.erase();
848 params().headheight.erase();
849 params().headsep.erase();
850 params().footskip.erase();
851 params().columnsep.erase();
852 params().fonts_cjk.erase();
853 params().listings_params.clear();
854 params().clearLayoutModules();
855 params().clearRemovedModules();
856 params().clearIncludedChildren();
857 params().pdfoptions().clear();
858 params().indiceslist().clear();
859 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
860 params().isbackgroundcolor = false;
861 params().fontcolor = RGBColor(0, 0, 0);
862 params().isfontcolor = false;
863 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
864 params().boxbgcolor = RGBColor(0xFF, 0, 0);
865 params().html_latex_start.clear();
866 params().html_latex_end.clear();
867 params().html_math_img_scale = 1.0;
868 params().output_sync_macro.erase();
869 params().setLocalLayout(string(), false);
870 params().setLocalLayout(string(), true);
872 for (int i = 0; i < 4; ++i) {
873 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
874 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
877 ErrorList & errorList = d->errorLists["Parse"];
886 if (token == "\\end_header")
890 if (token == "\\begin_header") {
891 begin_header_line = line;
895 LYXERR(Debug::PARSER, "Handling document header token: `"
898 string unknown = params().readToken(lex, token, d->filename.onlyPath());
899 if (!unknown.empty()) {
900 if (unknown[0] != '\\' && token == "\\textclass") {
901 Alert::warning(_("Unknown document class"),
902 bformat(_("Using the default document class, because the "
903 "class %1$s is unknown."), from_utf8(unknown)));
906 docstring const s = bformat(_("Unknown token: "
910 errorList.push_back(ErrorItem(_("Document header error"),
915 if (begin_header_line) {
916 docstring const s = _("\\begin_header is missing");
917 errorList.push_back(ErrorItem(_("Document header error"),
921 params().makeDocumentClass();
923 return unknown_tokens;
928 // changed to be public and have one parameter
929 // Returns true if "\end_document" is not read (Asger)
930 bool Buffer::readDocument(Lexer & lex)
932 ErrorList & errorList = d->errorLists["Parse"];
935 // remove dummy empty par
936 paragraphs().clear();
938 if (!lex.checkFor("\\begin_document")) {
939 docstring const s = _("\\begin_document is missing");
940 errorList.push_back(ErrorItem(_("Document header error"),
946 if (params().output_changes) {
947 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
948 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
949 LaTeXFeatures::isAvailable("xcolor");
951 if (!dvipost && !xcolorulem) {
952 Alert::warning(_("Changes not shown in LaTeX output"),
953 _("Changes will not be highlighted in LaTeX output, "
954 "because neither dvipost nor xcolor/ulem are installed.\n"
955 "Please install these packages or redefine "
956 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
957 } else if (!xcolorulem) {
958 Alert::warning(_("Changes not shown in LaTeX output"),
959 _("Changes will not be highlighted in LaTeX output "
960 "when using pdflatex, because xcolor and ulem are not installed.\n"
961 "Please install both packages or redefine "
962 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
966 if (!parent() && !params().master.empty()) {
967 FileName const master_file = makeAbsPath(params().master,
968 onlyPath(absFileName()));
969 if (isLyXFileName(master_file.absFileName())) {
971 checkAndLoadLyXFile(master_file, true);
973 // necessary e.g. after a reload
974 // to re-register the child (bug 5873)
975 // FIXME: clean up updateMacros (here, only
976 // child registering is needed).
977 master->updateMacros();
978 // set master as master buffer, but only
979 // if we are a real child
980 if (master->isChild(this))
982 // if the master is not fully loaded
983 // it is probably just loading this
984 // child. No warning needed then.
985 else if (master->isFullyLoaded())
986 LYXERR0("The master '"
988 << "' assigned to this document ("
990 << ") does not include "
991 "this document. Ignoring the master assignment.");
996 // assure we have a default index
997 params().indiceslist().addDefault(B_("Index"));
1000 bool const res = text().read(lex, errorList, d->inset);
1002 // inform parent buffer about local macros
1004 Buffer const * pbuf = parent();
1005 UserMacroSet::const_iterator cit = usermacros.begin();
1006 UserMacroSet::const_iterator end = usermacros.end();
1007 for (; cit != end; ++cit)
1008 pbuf->usermacros.insert(*cit);
1012 updateMacroInstances(InternalUpdate);
1017 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1019 Format const * fmt = formats.getFormat(format);
1022 // It is important to use the correct extension here, since some
1023 // converters create a wrong output file otherwise (e.g. html2latex)
1024 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1025 FileName const name(tempfile.name());
1026 ofdocstream os(name.toFilesystemEncoding().c_str());
1027 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1028 bool const success = !(os << contents).fail();
1031 bool converted = false;
1033 params().compressed = false;
1035 // remove dummy empty par
1036 paragraphs().clear();
1038 converted = importFile(format, name, errorList);
1047 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1049 if (!theConverters().isReachable(format, "lyx"))
1052 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1053 FileName const lyx(tempfile.name());
1054 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1055 return readFile(lyx) == ReadSuccess;
1061 bool Buffer::readString(string const & s)
1063 params().compressed = false;
1066 istringstream is(s);
1068 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1069 FileName const fn = tempfile.name();
1072 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1074 if (success && file_format != LYX_FORMAT) {
1075 // We need to call lyx2lyx, so write the input to a file
1076 ofstream os(fn.toFilesystemEncoding().c_str());
1079 // lyxvc in readFile
1080 if (readFile(fn) != ReadSuccess)
1084 if (readDocument(lex))
1090 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1094 if (!lex.setFile(fname)) {
1095 Alert::error(_("File Not Found"),
1096 bformat(_("Unable to open file `%1$s'."),
1097 from_utf8(fn.absFileName())));
1098 return ReadFileNotFound;
1102 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1103 if (ret_plf != ReadSuccess)
1106 if (file_format != LYX_FORMAT) {
1108 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1109 if (ret_clf != ReadSuccess)
1111 return readFile(tmpFile);
1114 // FIXME: InsetInfo needs to know whether the file is under VCS
1115 // during the parse process, so this has to be done before.
1116 lyxvc().file_found_hook(d->filename);
1118 if (readDocument(lex)) {
1119 Alert::error(_("Document format failure"),
1120 bformat(_("%1$s ended unexpectedly, which means"
1121 " that it is probably corrupted."),
1122 from_utf8(fn.absFileName())));
1123 return ReadDocumentFailure;
1126 d->file_fully_loaded = true;
1127 d->read_only = !d->filename.isWritable();
1128 params().compressed = formats.isZippedFile(d->filename);
1134 bool Buffer::isFullyLoaded() const
1136 return d->file_fully_loaded;
1140 void Buffer::setFullyLoaded(bool value)
1142 d->file_fully_loaded = value;
1146 PreviewLoader * Buffer::loader() const
1148 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1150 if (!d->preview_loader_)
1151 d->preview_loader_ = new PreviewLoader(*this);
1152 return d->preview_loader_;
1156 void Buffer::removePreviews() const
1158 delete d->preview_loader_;
1159 d->preview_loader_ = 0;
1163 void Buffer::updatePreviews() const
1165 PreviewLoader * ploader = loader();
1169 InsetIterator it = inset_iterator_begin(*d->inset);
1170 InsetIterator const end = inset_iterator_end(*d->inset);
1171 for (; it != end; ++it)
1172 it->addPreview(it, *ploader);
1174 ploader->startLoading();
1178 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1179 FileName const & fn, int & file_format) const
1181 if(!lex.checkFor("\\lyxformat")) {
1182 Alert::error(_("Document format failure"),
1183 bformat(_("%1$s is not a readable LyX document."),
1184 from_utf8(fn.absFileName())));
1185 return ReadNoLyXFormat;
1191 // LyX formats 217 and earlier were written as 2.17. This corresponds
1192 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1193 // these cases. See also: www.lyx.org/trac/changeset/1313.
1194 size_t dot = tmp_format.find_first_of(".,");
1195 if (dot != string::npos)
1196 tmp_format.erase(dot, 1);
1198 file_format = convert<int>(tmp_format);
1203 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1204 FileName & tmpfile, int from_format)
1206 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1207 tempfile.setAutoRemove(false);
1208 tmpfile = tempfile.name();
1209 if(tmpfile.empty()) {
1210 Alert::error(_("Conversion failed"),
1211 bformat(_("%1$s is from a different"
1212 " version of LyX, but a temporary"
1213 " file for converting it could"
1214 " not be created."),
1215 from_utf8(fn.absFileName())));
1216 return LyX2LyXNoTempFile;
1219 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1220 if (lyx2lyx.empty()) {
1221 Alert::error(_("Conversion script not found"),
1222 bformat(_("%1$s is from a different"
1223 " version of LyX, but the"
1224 " conversion script lyx2lyx"
1225 " could not be found."),
1226 from_utf8(fn.absFileName())));
1227 return LyX2LyXNotFound;
1231 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1232 ostringstream command;
1233 command << os::python()
1234 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1235 << " -t " << convert<string>(LYX_FORMAT)
1236 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1237 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1238 string const command_str = command.str();
1240 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1242 cmd_ret const ret = runCommand(command_str);
1243 if (ret.first != 0) {
1244 if (from_format < LYX_FORMAT) {
1245 Alert::error(_("Conversion script failed"),
1246 bformat(_("%1$s is from an older version"
1247 " of LyX and the lyx2lyx script"
1248 " failed to convert it."),
1249 from_utf8(fn.absFileName())));
1250 return LyX2LyXOlderFormat;
1252 Alert::error(_("Conversion script failed"),
1253 bformat(_("%1$s is from a newer version"
1254 " of LyX and the lyx2lyx script"
1255 " failed to convert it."),
1256 from_utf8(fn.absFileName())));
1257 return LyX2LyXNewerFormat;
1264 // Should probably be moved to somewhere else: BufferView? GuiView?
1265 bool Buffer::save() const
1267 docstring const file = makeDisplayPath(absFileName(), 20);
1268 d->filename.refresh();
1270 // check the read-only status before moving the file as a backup
1271 if (d->filename.exists()) {
1272 bool const read_only = !d->filename.isWritable();
1274 Alert::warning(_("File is read-only"),
1275 bformat(_("The file %1$s cannot be written because it "
1276 "is marked as read-only."), file));
1281 // ask if the disk file has been externally modified (use checksum method)
1282 if (fileName().exists() && isExternallyModified(checksum_method)) {
1284 bformat(_("Document %1$s has been externally modified. "
1285 "Are you sure you want to overwrite this file?"), file);
1286 int const ret = Alert::prompt(_("Overwrite modified file?"),
1287 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1292 // We don't need autosaves in the immediate future. (Asger)
1293 resetAutosaveTimers();
1295 // if the file does not yet exist, none of the backup activity
1296 // that follows is necessary
1297 if (!fileName().exists())
1298 return writeFile(fileName());
1300 // we first write the file to a new name, then move it to its
1301 // proper location once that has been done successfully. that
1302 // way we preserve the original file if something goes wrong.
1303 TempFile tempfile(fileName().onlyPath(), "tmpXXXXXX.lyx");
1304 bool const symlink = fileName().isSymLink();
1306 tempfile.setAutoRemove(false);
1308 FileName savefile(tempfile.name());
1309 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1310 if (!writeFile(savefile))
1313 // we will set this to false if we fail
1314 bool made_backup = true;
1316 FileName backupName(absFileName() + '~');
1317 if (lyxrc.make_backup) {
1318 if (!lyxrc.backupdir_path.empty()) {
1319 string const mangledName =
1320 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1321 backupName = FileName(addName(lyxrc.backupdir_path,
1325 LYXERR(Debug::FILES, "Backing up original file to " <<
1326 backupName.absFileName());
1327 // Except file is symlink do not copy because of #6587.
1328 // Hard links have bad luck.
1329 made_backup = symlink ?
1330 fileName().copyTo(backupName):
1331 fileName().moveTo(backupName);
1334 Alert::error(_("Backup failure"),
1335 bformat(_("Cannot create backup file %1$s.\n"
1336 "Please check whether the directory exists and is writable."),
1337 from_utf8(backupName.absFileName())));
1338 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1342 // If we have no symlink, we can simply rename the temp file.
1343 // Otherwise, we need to copy it so the symlink stays intact.
1344 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1345 savefile.moveTo(fileName()))
1347 // saveCheckSum() was already called by writeFile(), but the
1348 // time stamp is invalidated by copying/moving
1353 // else we saved the file, but failed to move it to the right location.
1355 if (lyxrc.make_backup && made_backup && !symlink) {
1356 // the original file was moved to filename.lyx~, so it will look
1357 // to the user as if it was deleted. (see bug #9234.) we could try
1358 // to restore it, but that would basically mean trying to do again
1359 // what we just failed to do. better to leave things as they are.
1360 Alert::error(_("Write failure"),
1361 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1362 "But LyX could not move it to:\n %2$s.\n"
1363 "Your original file has been backed up to:\n %3$s"),
1364 from_utf8(savefile.absFileName()),
1365 from_utf8(fileName().absFileName()),
1366 from_utf8(backupName.absFileName())));
1368 // either we did not try to make a backup, or else we tried and failed,
1369 // or else the original file was a symlink, in which case it was copied,
1370 // not moved. so the original file is intact.
1371 Alert::error(_("Write failure"),
1372 bformat(_("Cannot move saved file to:\n %1$s.\n"
1373 "But the file has successfully been saved as:\n %2$s."),
1374 from_utf8(fileName().absFileName()),
1375 from_utf8(savefile.absFileName())));
1381 bool Buffer::writeFile(FileName const & fname) const
1383 if (d->read_only && fname == d->filename)
1386 bool retval = false;
1388 docstring const str = bformat(_("Saving document %1$s..."),
1389 makeDisplayPath(fname.absFileName()));
1392 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1394 if (params().compressed) {
1395 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1396 retval = ofs && write(ofs);
1398 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1399 retval = ofs && write(ofs);
1403 message(str + _(" could not write file!"));
1408 // removeAutosaveFile();
1411 message(str + _(" done."));
1417 docstring Buffer::emergencyWrite()
1419 // No need to save if the buffer has not changed.
1423 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1425 docstring user_message = bformat(
1426 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1428 // We try to save three places:
1429 // 1) Same place as document. Unless it is an unnamed doc.
1431 string s = absFileName();
1434 if (writeFile(FileName(s))) {
1436 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1437 return user_message;
1439 user_message += " " + _("Save failed! Trying again...\n");
1443 // 2) In HOME directory.
1444 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1446 lyxerr << ' ' << s << endl;
1447 if (writeFile(FileName(s))) {
1449 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1450 return user_message;
1453 user_message += " " + _("Save failed! Trying yet again...\n");
1455 // 3) In "/tmp" directory.
1456 // MakeAbsPath to prepend the current
1457 // drive letter on OS/2
1458 s = addName(package().temp_dir().absFileName(), absFileName());
1460 lyxerr << ' ' << s << endl;
1461 if (writeFile(FileName(s))) {
1463 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1464 return user_message;
1467 user_message += " " + _("Save failed! Bummer. Document is lost.");
1470 return user_message;
1474 bool Buffer::write(ostream & ofs) const
1477 // Use the standard "C" locale for file output.
1478 ofs.imbue(locale::classic());
1481 // The top of the file should not be written by params().
1483 // write out a comment in the top of the file
1484 // Important: Keep the version formatting in sync with lyx2lyx and
1485 // tex2lyx (bug 7951)
1486 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1487 << " created this file. For more info see http://www.lyx.org/\n"
1488 << "\\lyxformat " << LYX_FORMAT << "\n"
1489 << "\\begin_document\n";
1491 /// For each author, set 'used' to true if there is a change
1492 /// by this author in the document; otherwise set it to 'false'.
1493 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1494 AuthorList::Authors::const_iterator a_end = params().authors().end();
1495 for (; a_it != a_end; ++a_it)
1496 a_it->setUsed(false);
1498 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1499 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1500 for ( ; it != end; ++it)
1501 it->checkAuthors(params().authors());
1503 // now write out the buffer parameters.
1504 ofs << "\\begin_header\n";
1505 params().writeFile(ofs);
1506 ofs << "\\end_header\n";
1509 ofs << "\n\\begin_body\n";
1511 ofs << "\n\\end_body\n";
1513 // Write marker that shows file is complete
1514 ofs << "\\end_document" << endl;
1516 // Shouldn't really be needed....
1519 // how to check if close went ok?
1520 // Following is an attempt... (BE 20001011)
1522 // good() returns false if any error occured, including some
1523 // formatting error.
1524 // bad() returns true if something bad happened in the buffer,
1525 // which should include file system full errors.
1530 lyxerr << "File was not closed properly." << endl;
1537 bool Buffer::makeLaTeXFile(FileName const & fname,
1538 string const & original_path,
1539 OutputParams const & runparams_in,
1540 OutputWhat output) const
1542 OutputParams runparams = runparams_in;
1544 // This is necessary for LuaTeX/XeTeX with tex fonts.
1545 // See FIXME in BufferParams::encoding()
1546 if (runparams.isFullUnicode())
1547 runparams.encoding = encodings.fromLyXName("utf8-plain");
1549 string const encoding = runparams.encoding->iconvName();
1550 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1553 try { ofs.reset(encoding); }
1554 catch (iconv_codecvt_facet_exception const & e) {
1555 lyxerr << "Caught iconv exception: " << e.what() << endl;
1556 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1557 "verify that the support software for your encoding (%1$s) is "
1558 "properly installed"), from_ascii(encoding)));
1561 if (!openFileWrite(ofs, fname))
1564 ErrorList & errorList = d->errorLists["Export"];
1566 bool failed_export = false;
1567 otexstream os(ofs, d->texrow);
1569 // make sure we are ready to export
1570 // this needs to be done before we validate
1571 // FIXME Do we need to do this all the time? I.e., in children
1572 // of a master we are exporting?
1574 updateMacroInstances(OutputUpdate);
1577 os.texrow().reset();
1578 writeLaTeXSource(os, original_path, runparams, output);
1580 catch (EncodingException const & e) {
1581 odocstringstream ods;
1582 ods.put(e.failed_char);
1584 oss << "0x" << hex << e.failed_char << dec;
1585 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1586 " (code point %2$s)"),
1587 ods.str(), from_utf8(oss.str()));
1588 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1589 "representable in the chosen encoding.\n"
1590 "Changing the document encoding to utf8 could help."),
1591 e.par_id, e.pos, e.pos + 1));
1592 failed_export = true;
1594 catch (iconv_codecvt_facet_exception const & e) {
1595 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1596 _(e.what()), -1, 0, 0));
1597 failed_export = true;
1599 catch (exception const & e) {
1600 errorList.push_back(ErrorItem(_("conversion failed"),
1601 _(e.what()), -1, 0, 0));
1602 failed_export = true;
1605 lyxerr << "Caught some really weird exception..." << endl;
1611 failed_export = true;
1612 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1615 if (runparams_in.silent)
1619 return !failed_export;
1623 void Buffer::writeLaTeXSource(otexstream & os,
1624 string const & original_path,
1625 OutputParams const & runparams_in,
1626 OutputWhat output) const
1628 // The child documents, if any, shall be already loaded at this point.
1630 OutputParams runparams = runparams_in;
1632 // If we are compiling a file standalone, even if this is the
1633 // child of some other buffer, let's cut the link here, so the
1634 // file is really independent and no concurring settings from
1635 // the master (e.g. branch state) interfere (see #8100).
1636 if (!runparams.is_child)
1637 d->ignore_parent = true;
1639 // Classify the unicode characters appearing in math insets
1640 BufferEncodings::initUnicodeMath(*this);
1642 // validate the buffer.
1643 LYXERR(Debug::LATEX, " Validating buffer...");
1644 LaTeXFeatures features(*this, params(), runparams);
1646 // This is only set once per document (in master)
1647 if (!runparams.is_child)
1648 runparams.use_polyglossia = features.usePolyglossia();
1649 LYXERR(Debug::LATEX, " Buffer validation done.");
1651 bool const output_preamble =
1652 output == FullSource || output == OnlyPreamble;
1653 bool const output_body =
1654 output == FullSource || output == OnlyBody;
1656 // The starting paragraph of the coming rows is the
1657 // first paragraph of the document. (Asger)
1658 if (output_preamble && runparams.nice) {
1659 os << "%% LyX " << lyx_version << " created this file. "
1660 "For more info, see http://www.lyx.org/.\n"
1661 "%% Do not edit unless you really know what "
1664 LYXERR(Debug::INFO, "lyx document header finished");
1666 // There are a few differences between nice LaTeX and usual files:
1667 // usual files have \batchmode and special input@path to allow
1668 // inclusion of figures specified by an explicitly relative path
1669 // (i.e., a path starting with './' or '../') with either \input or
1670 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1671 // input@path is set when the actual parameter original_path is set.
1672 // This is done for usual tex-file, but not for nice-latex-file.
1673 // (Matthias 250696)
1674 // Note that input@path is only needed for something the user does
1675 // in the preamble, included .tex files or ERT, files included by
1676 // LyX work without it.
1677 if (output_preamble) {
1678 if (!runparams.nice) {
1679 // code for usual, NOT nice-latex-file
1680 os << "\\batchmode\n"; // changed from \nonstopmode
1682 if (!original_path.empty()) {
1684 // We don't know the encoding of inputpath
1685 docstring const inputpath = from_utf8(original_path);
1686 docstring uncodable_glyphs;
1687 Encoding const * const enc = runparams.encoding;
1689 for (size_t n = 0; n < inputpath.size(); ++n) {
1690 if (!enc->encodable(inputpath[n])) {
1691 docstring const glyph(1, inputpath[n]);
1692 LYXERR0("Uncodable character '"
1694 << "' in input path!");
1695 uncodable_glyphs += glyph;
1700 // warn user if we found uncodable glyphs.
1701 if (!uncodable_glyphs.empty()) {
1702 frontend::Alert::warning(
1703 _("Uncodable character in file path"),
1705 _("The path of your document\n"
1707 "contains glyphs that are unknown "
1708 "in the current document encoding "
1709 "(namely %2$s). This may result in "
1710 "incomplete output, unless "
1711 "TEXINPUTS contains the document "
1712 "directory and you don't use "
1713 "explicitly relative paths (i.e., "
1714 "paths starting with './' or "
1715 "'../') in the preamble or in ERT."
1716 "\n\nIn case of problems, choose "
1717 "an appropriate document encoding\n"
1718 "(such as utf8) or change the "
1720 inputpath, uncodable_glyphs));
1723 support::latex_path(original_path);
1724 if (contains(docdir, '#')) {
1725 docdir = subst(docdir, "#", "\\#");
1726 os << "\\catcode`\\#=11"
1727 "\\def\\#{#}\\catcode`\\#=6\n";
1729 if (contains(docdir, '%')) {
1730 docdir = subst(docdir, "%", "\\%");
1731 os << "\\catcode`\\%=11"
1732 "\\def\\%{%}\\catcode`\\%=14\n";
1734 os << "\\makeatletter\n"
1735 << "\\def\\input@path{{"
1736 << docdir << "/}}\n"
1737 << "\\makeatother\n";
1741 // get parent macros (if this buffer has a parent) which will be
1742 // written at the document begin further down.
1743 MacroSet parentMacros;
1744 listParentMacros(parentMacros, features);
1746 // Write the preamble
1747 runparams.use_babel = params().writeLaTeX(os, features,
1748 d->filename.onlyPath());
1750 // Japanese might be required only in some children of a document,
1751 // but once required, we must keep use_japanese true.
1752 runparams.use_japanese |= features.isRequired("japanese");
1755 // Restore the parenthood if needed
1756 if (!runparams.is_child)
1757 d->ignore_parent = false;
1762 os << "\\begin{document}\n";
1764 // output the parent macros
1765 MacroSet::iterator it = parentMacros.begin();
1766 MacroSet::iterator end = parentMacros.end();
1767 for (; it != end; ++it) {
1768 int num_lines = (*it)->write(os.os(), true);
1769 os.texrow().newlines(num_lines);
1772 } // output_preamble
1774 os.texrow().start(paragraphs().begin()->id(), 0);
1776 LYXERR(Debug::INFO, "preamble finished, now the body.");
1779 latexParagraphs(*this, text(), os, runparams);
1781 // Restore the parenthood if needed
1782 if (!runparams.is_child)
1783 d->ignore_parent = false;
1785 // add this just in case after all the paragraphs
1788 if (output_preamble) {
1789 os << "\\end{document}\n";
1790 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1792 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1794 runparams_in.encoding = runparams.encoding;
1796 // Just to be sure. (Asger)
1797 os.texrow().newline();
1799 //for (int i = 0; i<d->texrow.rows(); i++) {
1801 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1802 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1805 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1806 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1810 void Buffer::makeDocBookFile(FileName const & fname,
1811 OutputParams const & runparams,
1812 OutputWhat output) const
1814 LYXERR(Debug::LATEX, "makeDocBookFile...");
1817 if (!openFileWrite(ofs, fname))
1820 // make sure we are ready to export
1821 // this needs to be done before we validate
1823 updateMacroInstances(OutputUpdate);
1825 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1829 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1833 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1834 OutputParams const & runparams,
1835 OutputWhat output) const
1837 LaTeXFeatures features(*this, params(), runparams);
1842 DocumentClass const & tclass = params().documentClass();
1843 string const top_element = tclass.latexname();
1845 bool const output_preamble =
1846 output == FullSource || output == OnlyPreamble;
1847 bool const output_body =
1848 output == FullSource || output == OnlyBody;
1850 if (output_preamble) {
1851 if (runparams.flavor == OutputParams::XML)
1852 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1855 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1858 if (! tclass.class_header().empty())
1859 os << from_ascii(tclass.class_header());
1860 else if (runparams.flavor == OutputParams::XML)
1861 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1862 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1864 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1866 docstring preamble = from_utf8(params().preamble);
1867 if (runparams.flavor != OutputParams::XML ) {
1868 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1869 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1870 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1871 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1874 string const name = runparams.nice
1875 ? changeExtension(absFileName(), ".sgml") : fname;
1876 preamble += features.getIncludedFiles(name);
1877 preamble += features.getLyXSGMLEntities();
1879 if (!preamble.empty()) {
1880 os << "\n [ " << preamble << " ]";
1886 string top = top_element;
1888 if (runparams.flavor == OutputParams::XML)
1889 top += params().language->code();
1891 top += params().language->code().substr(0, 2);
1894 if (!params().options.empty()) {
1896 top += params().options;
1899 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1900 << " file was created by LyX " << lyx_version
1901 << "\n See http://www.lyx.org/ for more information -->\n";
1903 params().documentClass().counters().reset();
1905 sgml::openTag(os, top);
1907 docbookParagraphs(text(), *this, os, runparams);
1908 sgml::closeTag(os, top_element);
1913 void Buffer::makeLyXHTMLFile(FileName const & fname,
1914 OutputParams const & runparams) const
1916 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1919 if (!openFileWrite(ofs, fname))
1922 // make sure we are ready to export
1923 // this has to be done before we validate
1924 updateBuffer(UpdateMaster, OutputUpdate);
1925 updateMacroInstances(OutputUpdate);
1927 writeLyXHTMLSource(ofs, runparams, FullSource);
1931 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1935 void Buffer::writeLyXHTMLSource(odocstream & os,
1936 OutputParams const & runparams,
1937 OutputWhat output) const
1939 LaTeXFeatures features(*this, params(), runparams);
1941 d->bibinfo_.makeCitationLabels(*this);
1943 bool const output_preamble =
1944 output == FullSource || output == OnlyPreamble;
1945 bool const output_body =
1946 output == FullSource || output == OnlyBody || output == IncludedFile;
1948 if (output_preamble) {
1949 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1950 << "<!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"
1951 // FIXME Language should be set properly.
1952 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1954 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1955 // FIXME Presumably need to set this right
1956 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1958 docstring const & doctitle = features.htmlTitle();
1960 << (doctitle.empty() ?
1961 from_ascii("LyX Document") :
1962 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1965 docstring styles = features.getTClassHTMLPreamble();
1966 if (!styles.empty())
1967 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1969 styles = from_utf8(features.getPreambleSnippets());
1970 if (!styles.empty())
1971 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1973 // we will collect CSS information in a stream, and then output it
1974 // either here, as part of the header, or else in a separate file.
1975 odocstringstream css;
1976 styles = from_utf8(features.getCSSSnippets());
1977 if (!styles.empty())
1978 css << "/* LyX Provided Styles */\n" << styles << '\n';
1980 styles = features.getTClassHTMLStyles();
1981 if (!styles.empty())
1982 css << "/* Layout-provided Styles */\n" << styles << '\n';
1984 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1985 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1986 if (needfg || needbg) {
1987 css << "\nbody {\n";
1990 << from_ascii(X11hexname(params().fontcolor))
1993 css << " background-color: "
1994 << from_ascii(X11hexname(params().backgroundcolor))
1999 docstring const dstyles = css.str();
2000 if (!dstyles.empty()) {
2001 bool written = false;
2002 if (params().html_css_as_file) {
2003 // open a file for CSS info
2005 string const fcssname = addName(temppath(), "docstyle.css");
2006 FileName const fcssfile = FileName(fcssname);
2007 if (openFileWrite(ocss, fcssfile)) {
2011 // write link to header
2012 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2014 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2017 // we are here if the CSS is supposed to be written to the header
2018 // or if we failed to write it to an external file.
2020 os << "<style type='text/css'>\n"
2029 bool const output_body_tag = (output != IncludedFile);
2030 if (output_body_tag)
2033 if (output != IncludedFile)
2034 // if we're an included file, the counters are in the master.
2035 params().documentClass().counters().reset();
2036 xhtmlParagraphs(text(), *this, xs, runparams);
2037 if (output_body_tag)
2041 if (output_preamble)
2046 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2047 // Other flags: -wall -v0 -x
2048 int Buffer::runChktex()
2052 // get LaTeX-Filename
2053 FileName const path(temppath());
2054 string const name = addName(path.absFileName(), latexName());
2055 string const org_path = filePath();
2057 PathChanger p(path); // path to LaTeX file
2058 message(_("Running chktex..."));
2060 // Generate the LaTeX file if neccessary
2061 OutputParams runparams(¶ms().encoding());
2062 runparams.flavor = OutputParams::LATEX;
2063 runparams.nice = false;
2064 runparams.linelen = lyxrc.plaintext_linelen;
2065 makeLaTeXFile(FileName(name), org_path, runparams);
2068 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2069 int const res = chktex.run(terr); // run chktex
2072 Alert::error(_("chktex failure"),
2073 _("Could not run chktex successfully."));
2075 ErrorList & errlist = d->errorLists["ChkTeX"];
2077 bufferErrors(terr, errlist);
2082 if (runparams.silent)
2083 d->errorLists["ChkTeX"].clear();
2091 void Buffer::validate(LaTeXFeatures & features) const
2093 // Validate the buffer params, but not for included
2094 // files, since they also use the parent buffer's
2096 if (!features.runparams().is_child)
2097 params().validate(features);
2099 for_each(paragraphs().begin(), paragraphs().end(),
2100 bind(&Paragraph::validate, _1, ref(features)));
2102 if (lyxerr.debugging(Debug::LATEX)) {
2103 features.showStruct();
2108 void Buffer::getLabelList(vector<docstring> & list) const
2110 // If this is a child document, use the master's list instead.
2112 masterBuffer()->getLabelList(list);
2117 Toc & toc = d->toc_backend.toc("label");
2118 TocIterator toc_it = toc.begin();
2119 TocIterator end = toc.end();
2120 for (; toc_it != end; ++toc_it) {
2121 if (toc_it->depth() == 0)
2122 list.push_back(toc_it->str());
2127 void Buffer::updateBibfilesCache(UpdateScope scope) const
2129 // FIXME This is probably unnecssary, given where we call this.
2130 // If this is a child document, use the parent's cache instead.
2131 if (parent() && scope != UpdateChildOnly) {
2132 masterBuffer()->updateBibfilesCache();
2136 d->bibfiles_cache_.clear();
2137 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2138 if (it->lyxCode() == BIBTEX_CODE) {
2139 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2140 support::FileNameList const bibfiles = inset.getBibFiles();
2141 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2144 } else if (it->lyxCode() == INCLUDE_CODE) {
2145 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2146 Buffer const * const incbuf = inset.getChildBuffer();
2149 support::FileNameList const & bibfiles =
2150 incbuf->getBibfilesCache(UpdateChildOnly);
2151 if (!bibfiles.empty()) {
2152 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2158 d->bibfile_cache_valid_ = true;
2159 d->bibinfo_cache_valid_ = false;
2160 d->cite_labels_valid_ = false;
2164 void Buffer::invalidateBibinfoCache() const
2166 d->bibinfo_cache_valid_ = false;
2167 d->cite_labels_valid_ = false;
2168 // also invalidate the cache for the parent buffer
2169 Buffer const * const pbuf = d->parent();
2171 pbuf->invalidateBibinfoCache();
2175 void Buffer::invalidateBibfileCache() const
2177 d->bibfile_cache_valid_ = false;
2178 d->bibinfo_cache_valid_ = false;
2179 d->cite_labels_valid_ = false;
2180 // also invalidate the cache for the parent buffer
2181 Buffer const * const pbuf = d->parent();
2183 pbuf->invalidateBibfileCache();
2187 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2189 // FIXME This is probably unnecessary, given where we call this.
2190 // If this is a child document, use the master's cache instead.
2191 Buffer const * const pbuf = masterBuffer();
2192 if (pbuf != this && scope != UpdateChildOnly)
2193 return pbuf->getBibfilesCache();
2195 if (!d->bibfile_cache_valid_)
2196 this->updateBibfilesCache(scope);
2198 return d->bibfiles_cache_;
2202 BiblioInfo const & Buffer::masterBibInfo() const
2204 Buffer const * const tmp = masterBuffer();
2206 return tmp->masterBibInfo();
2211 void Buffer::checkIfBibInfoCacheIsValid() const
2213 // use the master's cache
2214 Buffer const * const tmp = masterBuffer();
2216 tmp->checkIfBibInfoCacheIsValid();
2220 // compare the cached timestamps with the actual ones.
2221 FileNameList const & bibfiles_cache = getBibfilesCache();
2222 FileNameList::const_iterator ei = bibfiles_cache.begin();
2223 FileNameList::const_iterator en = bibfiles_cache.end();
2224 for (; ei != en; ++ ei) {
2225 time_t lastw = ei->lastModified();
2226 time_t prevw = d->bibfile_status_[*ei];
2227 if (lastw != prevw) {
2228 d->bibinfo_cache_valid_ = false;
2229 d->cite_labels_valid_ = false;
2230 d->bibfile_status_[*ei] = lastw;
2236 void Buffer::reloadBibInfoCache() const
2238 // use the master's cache
2239 Buffer const * const tmp = masterBuffer();
2241 tmp->reloadBibInfoCache();
2245 checkIfBibInfoCacheIsValid();
2246 if (d->bibinfo_cache_valid_)
2249 d->bibinfo_.clear();
2251 d->bibinfo_cache_valid_ = true;
2255 void Buffer::collectBibKeys() const
2257 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2258 it->collectBibKeys(it);
2262 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2264 Buffer const * tmp = masterBuffer();
2265 BiblioInfo & masterbi = (tmp == this) ?
2266 d->bibinfo_ : tmp->d->bibinfo_;
2267 masterbi.mergeBiblioInfo(bi);
2271 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2273 Buffer const * tmp = masterBuffer();
2274 BiblioInfo & masterbi = (tmp == this) ?
2275 d->bibinfo_ : tmp->d->bibinfo_;
2280 void Buffer::makeCitationLabels() const
2282 Buffer const * const master = masterBuffer();
2283 return d->bibinfo_.makeCitationLabels(*master);
2287 bool Buffer::citeLabelsValid() const
2289 return masterBuffer()->d->cite_labels_valid_;
2293 void Buffer::removeBiblioTempFiles() const
2295 // We remove files that contain LaTeX commands specific to the
2296 // particular bibliographic style being used, in order to avoid
2297 // LaTeX errors when we switch style.
2298 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2299 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2300 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2301 aux_file.removeFile();
2302 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2303 bbl_file.removeFile();
2304 // Also for the parent buffer
2305 Buffer const * const pbuf = parent();
2307 pbuf->removeBiblioTempFiles();
2311 bool Buffer::isDepClean(string const & name) const
2313 DepClean::const_iterator const it = d->dep_clean.find(name);
2314 if (it == d->dep_clean.end())
2320 void Buffer::markDepClean(string const & name)
2322 d->dep_clean[name] = true;
2326 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2329 // FIXME? if there is an Buffer LFUN that can be dispatched even
2330 // if internal, put a switch '(cmd.action)' here.
2336 switch (cmd.action()) {
2338 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2339 flag.setOnOff(isReadonly());
2342 // FIXME: There is need for a command-line import.
2343 //case LFUN_BUFFER_IMPORT:
2345 case LFUN_BUFFER_AUTO_SAVE:
2348 case LFUN_BUFFER_EXPORT_CUSTOM:
2349 // FIXME: Nothing to check here?
2352 case LFUN_BUFFER_EXPORT: {
2353 docstring const arg = cmd.argument();
2354 if (arg == "custom") {
2358 string format = to_utf8(arg);
2359 size_t pos = format.find(' ');
2360 if (pos != string::npos)
2361 format = format.substr(0, pos);
2362 enable = params().isExportable(format);
2364 flag.message(bformat(
2365 _("Don't know how to export to format: %1$s"), arg));
2369 case LFUN_BUFFER_CHKTEX:
2370 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2373 case LFUN_BUILD_PROGRAM:
2374 enable = params().isExportable("program");
2377 case LFUN_BRANCH_ACTIVATE:
2378 case LFUN_BRANCH_DEACTIVATE:
2379 case LFUN_BRANCH_MASTER_ACTIVATE:
2380 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2381 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2382 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2383 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2384 : params().branchlist();
2385 docstring const branchName = cmd.argument();
2386 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2390 case LFUN_BRANCH_ADD:
2391 case LFUN_BRANCHES_RENAME:
2392 case LFUN_BUFFER_PRINT:
2393 // if no Buffer is present, then of course we won't be called!
2396 case LFUN_BUFFER_LANGUAGE:
2397 enable = !isReadonly();
2403 flag.setEnabled(enable);
2408 void Buffer::dispatch(string const & command, DispatchResult & result)
2410 return dispatch(lyxaction.lookupFunc(command), result);
2414 // NOTE We can end up here even if we have no GUI, because we are called
2415 // by LyX::exec to handled command-line requests. So we may need to check
2416 // whether we have a GUI or not. The boolean use_gui holds this information.
2417 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2420 // FIXME? if there is an Buffer LFUN that can be dispatched even
2421 // if internal, put a switch '(cmd.action())' here.
2422 dr.dispatched(false);
2425 string const argument = to_utf8(func.argument());
2426 // We'll set this back to false if need be.
2427 bool dispatched = true;
2428 undo().beginUndoGroup();
2430 switch (func.action()) {
2431 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2432 if (lyxvc().inUse()) {
2433 string log = lyxvc().toggleReadOnly();
2438 setReadonly(!isReadonly());
2441 case LFUN_BUFFER_EXPORT: {
2442 ExportStatus const status = doExport(argument, false);
2443 dr.setError(status != ExportSuccess);
2444 if (status != ExportSuccess)
2445 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2450 case LFUN_BUILD_PROGRAM: {
2451 ExportStatus const status = doExport("program", true);
2452 dr.setError(status != ExportSuccess);
2453 if (status != ExportSuccess)
2454 dr.setMessage(_("Error generating literate programming code."));
2458 case LFUN_BUFFER_CHKTEX:
2462 case LFUN_BUFFER_EXPORT_CUSTOM: {
2464 string command = split(argument, format_name, ' ');
2465 Format const * format = formats.getFormat(format_name);
2467 lyxerr << "Format \"" << format_name
2468 << "\" not recognized!"
2473 // The name of the file created by the conversion process
2476 // Output to filename
2477 if (format->name() == "lyx") {
2478 string const latexname = latexName(false);
2479 filename = changeExtension(latexname,
2480 format->extension());
2481 filename = addName(temppath(), filename);
2483 if (!writeFile(FileName(filename)))
2487 doExport(format_name, true, filename);
2490 // Substitute $$FName for filename
2491 if (!contains(command, "$$FName"))
2492 command = "( " + command + " ) < $$FName";
2493 command = subst(command, "$$FName", filename);
2495 // Execute the command in the background
2497 call.startscript(Systemcall::DontWait, command, filePath());
2501 // FIXME: There is need for a command-line import.
2503 case LFUN_BUFFER_IMPORT:
2508 case LFUN_BUFFER_AUTO_SAVE:
2510 resetAutosaveTimers();
2513 case LFUN_BRANCH_ACTIVATE:
2514 case LFUN_BRANCH_DEACTIVATE:
2515 case LFUN_BRANCH_MASTER_ACTIVATE:
2516 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2517 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2518 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2519 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2522 docstring const branch_name = func.argument();
2523 // the case without a branch name is handled elsewhere
2524 if (branch_name.empty()) {
2528 Branch * branch = buf->params().branchlist().find(branch_name);
2530 LYXERR0("Branch " << branch_name << " does not exist.");
2532 docstring const msg =
2533 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2537 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2538 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2539 if (branch->isSelected() != activate) {
2540 buf->undo().recordUndoFullDocument(CursorData());
2541 branch->setSelected(activate);
2543 dr.screenUpdate(Update::Force);
2544 dr.forceBufferUpdate();
2549 case LFUN_BRANCH_ADD: {
2550 docstring branch_name = func.argument();
2551 if (branch_name.empty()) {
2555 BranchList & branch_list = params().branchlist();
2556 vector<docstring> const branches =
2557 getVectorFromString(branch_name, branch_list.separator());
2559 for (vector<docstring>::const_iterator it = branches.begin();
2560 it != branches.end(); ++it) {
2562 Branch * branch = branch_list.find(branch_name);
2564 LYXERR0("Branch " << branch_name << " already exists.");
2568 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2570 undo().recordUndoFullDocument(CursorData());
2571 branch_list.add(branch_name);
2572 branch = branch_list.find(branch_name);
2573 string const x11hexname = X11hexname(branch->color());
2574 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2575 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2577 dr.screenUpdate(Update::Force);
2585 case LFUN_BRANCHES_RENAME: {
2586 if (func.argument().empty())
2589 docstring const oldname = from_utf8(func.getArg(0));
2590 docstring const newname = from_utf8(func.getArg(1));
2591 InsetIterator it = inset_iterator_begin(inset());
2592 InsetIterator const end = inset_iterator_end(inset());
2593 bool success = false;
2594 for (; it != end; ++it) {
2595 if (it->lyxCode() == BRANCH_CODE) {
2596 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2597 if (ins.branch() == oldname) {
2598 undo().recordUndo(CursorData(it));
2599 ins.rename(newname);
2604 if (it->lyxCode() == INCLUDE_CODE) {
2605 // get buffer of external file
2606 InsetInclude const & ins =
2607 static_cast<InsetInclude const &>(*it);
2608 Buffer * child = ins.getChildBuffer();
2611 child->dispatch(func, dr);
2616 dr.screenUpdate(Update::Force);
2617 dr.forceBufferUpdate();
2622 case LFUN_BUFFER_PRINT: {
2623 // we'll assume there's a problem until we succeed
2625 string target = func.getArg(0);
2626 string target_name = func.getArg(1);
2627 string command = func.getArg(2);
2630 || target_name.empty()
2631 || command.empty()) {
2632 LYXERR0("Unable to parse " << func.argument());
2633 docstring const msg =
2634 bformat(_("Unable to parse \"%1$s\""), func.argument());
2638 if (target != "printer" && target != "file") {
2639 LYXERR0("Unrecognized target \"" << target << '"');
2640 docstring const msg =
2641 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2646 if (doExport("dvi", true) != ExportSuccess) {
2647 showPrintError(absFileName());
2648 dr.setMessage(_("Error exporting to DVI."));
2652 // Push directory path.
2653 string const path = temppath();
2654 // Prevent the compiler from optimizing away p
2658 // there are three cases here:
2659 // 1. we print to a file
2660 // 2. we print directly to a printer
2661 // 3. we print using a spool command (print to file first)
2664 string const dviname = changeExtension(latexName(true), "dvi");
2666 if (target == "printer") {
2667 if (!lyxrc.print_spool_command.empty()) {
2668 // case 3: print using a spool
2669 string const psname = changeExtension(dviname,".ps");
2670 command += ' ' + lyxrc.print_to_file
2673 + quoteName(dviname);
2675 string command2 = lyxrc.print_spool_command + ' ';
2676 if (target_name != "default") {
2677 command2 += lyxrc.print_spool_printerprefix
2681 command2 += quoteName(psname);
2683 // If successful, then spool command
2684 res = one.startscript(Systemcall::Wait, command,
2688 // If there's no GUI, we have to wait on this command. Otherwise,
2689 // LyX deletes the temporary directory, and with it the spooled
2690 // file, before it can be printed!!
2691 Systemcall::Starttype stype = use_gui ?
2692 Systemcall::DontWait : Systemcall::Wait;
2693 res = one.startscript(stype, command2,
2697 // case 2: print directly to a printer
2698 if (target_name != "default")
2699 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2701 Systemcall::Starttype stype = use_gui ?
2702 Systemcall::DontWait : Systemcall::Wait;
2703 res = one.startscript(stype, command +
2704 quoteName(dviname), filePath());
2708 // case 1: print to a file
2709 FileName const filename(makeAbsPath(target_name, filePath()));
2710 FileName const dvifile(makeAbsPath(dviname, path));
2711 if (filename.exists()) {
2712 docstring text = bformat(
2713 _("The file %1$s already exists.\n\n"
2714 "Do you want to overwrite that file?"),
2715 makeDisplayPath(filename.absFileName()));
2716 if (Alert::prompt(_("Overwrite file?"),
2717 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2720 command += ' ' + lyxrc.print_to_file
2721 + quoteName(filename.toFilesystemEncoding())
2723 + quoteName(dvifile.toFilesystemEncoding());
2725 Systemcall::Starttype stype = use_gui ?
2726 Systemcall::DontWait : Systemcall::Wait;
2727 res = one.startscript(stype, command, filePath());
2733 dr.setMessage(_("Error running external commands."));
2734 showPrintError(absFileName());
2743 dr.dispatched(dispatched);
2744 undo().endUndoGroup();
2748 void Buffer::changeLanguage(Language const * from, Language const * to)
2750 LASSERT(from, return);
2751 LASSERT(to, return);
2753 for_each(par_iterator_begin(),
2755 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2759 bool Buffer::isMultiLingual() const
2761 ParConstIterator end = par_iterator_end();
2762 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2763 if (it->isMultiLingual(params()))
2770 std::set<Language const *> Buffer::getLanguages() const
2772 std::set<Language const *> languages;
2773 getLanguages(languages);
2778 void Buffer::getLanguages(std::set<Language const *> & languages) const
2780 ParConstIterator end = par_iterator_end();
2781 // add the buffer language, even if it's not actively used
2782 languages.insert(language());
2783 // iterate over the paragraphs
2784 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2785 it->getLanguages(languages);
2787 ListOfBuffers clist = getDescendents();
2788 ListOfBuffers::const_iterator cit = clist.begin();
2789 ListOfBuffers::const_iterator const cen = clist.end();
2790 for (; cit != cen; ++cit)
2791 (*cit)->getLanguages(languages);
2795 DocIterator Buffer::getParFromID(int const id) const
2797 Buffer * buf = const_cast<Buffer *>(this);
2799 // John says this is called with id == -1 from undo
2800 lyxerr << "getParFromID(), id: " << id << endl;
2801 return doc_iterator_end(buf);
2804 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2805 if (it.paragraph().id() == id)
2808 return doc_iterator_end(buf);
2812 bool Buffer::hasParWithID(int const id) const
2814 return !getParFromID(id).atEnd();
2818 ParIterator Buffer::par_iterator_begin()
2820 return ParIterator(doc_iterator_begin(this));
2824 ParIterator Buffer::par_iterator_end()
2826 return ParIterator(doc_iterator_end(this));
2830 ParConstIterator Buffer::par_iterator_begin() const
2832 return ParConstIterator(doc_iterator_begin(this));
2836 ParConstIterator Buffer::par_iterator_end() const
2838 return ParConstIterator(doc_iterator_end(this));
2842 Language const * Buffer::language() const
2844 return params().language;
2848 docstring const Buffer::B_(string const & l10n) const
2850 return params().B_(l10n);
2854 bool Buffer::isClean() const
2856 return d->lyx_clean;
2860 bool Buffer::isExternallyModified(CheckMethod method) const
2862 LASSERT(d->filename.exists(), return false);
2863 // if method == timestamp, check timestamp before checksum
2864 return (method == checksum_method
2865 || d->timestamp_ != d->filename.lastModified())
2866 && d->checksum_ != d->filename.checksum();
2870 void Buffer::saveCheckSum() const
2872 FileName const & file = d->filename;
2875 if (file.exists()) {
2876 d->timestamp_ = file.lastModified();
2877 d->checksum_ = file.checksum();
2879 // in the case of save to a new file.
2886 void Buffer::markClean() const
2888 if (!d->lyx_clean) {
2889 d->lyx_clean = true;
2892 // if the .lyx file has been saved, we don't need an
2894 d->bak_clean = true;
2895 d->undo_.markDirty();
2899 void Buffer::setUnnamed(bool flag)
2905 bool Buffer::isUnnamed() const
2912 /// Don't check unnamed, here: isInternal() is used in
2913 /// newBuffer(), where the unnamed flag has not been set by anyone
2914 /// yet. Also, for an internal buffer, there should be no need for
2915 /// retrieving fileName() nor for checking if it is unnamed or not.
2916 bool Buffer::isInternal() const
2918 return d->internal_buffer;
2922 void Buffer::setInternal(bool flag)
2924 d->internal_buffer = flag;
2928 void Buffer::markDirty()
2931 d->lyx_clean = false;
2934 d->bak_clean = false;
2936 DepClean::iterator it = d->dep_clean.begin();
2937 DepClean::const_iterator const end = d->dep_clean.end();
2939 for (; it != end; ++it)
2944 FileName Buffer::fileName() const
2950 string Buffer::absFileName() const
2952 return d->filename.absFileName();
2956 string Buffer::filePath() const
2958 string const abs = d->filename.onlyPath().absFileName();
2961 int last = abs.length() - 1;
2963 return abs[last] == '/' ? abs : abs + '/';
2967 bool Buffer::isReadonly() const
2969 return d->read_only;
2973 void Buffer::setParent(Buffer const * buffer)
2975 // Avoids recursive include.
2976 d->setParent(buffer == this ? 0 : buffer);
2981 Buffer const * Buffer::parent() const
2987 ListOfBuffers Buffer::allRelatives() const
2989 ListOfBuffers lb = masterBuffer()->getDescendents();
2990 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2995 Buffer const * Buffer::masterBuffer() const
2997 // FIXME Should be make sure we are not in some kind
2998 // of recursive include? A -> B -> A will crash this.
2999 Buffer const * const pbuf = d->parent();
3003 return pbuf->masterBuffer();
3007 bool Buffer::isChild(Buffer * child) const
3009 return d->children_positions.find(child) != d->children_positions.end();
3013 DocIterator Buffer::firstChildPosition(Buffer const * child)
3015 Impl::BufferPositionMap::iterator it;
3016 it = d->children_positions.find(child);
3017 if (it == d->children_positions.end())
3018 return DocIterator(this);
3023 bool Buffer::hasChildren() const
3025 return !d->children_positions.empty();
3029 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3031 // loop over children
3032 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3033 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3034 for (; it != end; ++it) {
3035 Buffer * child = const_cast<Buffer *>(it->first);
3037 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3038 if (bit != clist.end())
3040 clist.push_back(child);
3042 // there might be grandchildren
3043 child->collectChildren(clist, true);
3048 ListOfBuffers Buffer::getChildren() const
3051 collectChildren(v, false);
3052 // Make sure we have not included ourselves.
3053 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3054 if (bit != v.end()) {
3055 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3062 ListOfBuffers Buffer::getDescendents() const
3065 collectChildren(v, true);
3066 // Make sure we have not included ourselves.
3067 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3068 if (bit != v.end()) {
3069 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3076 template<typename M>
3077 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3082 typename M::const_iterator it = m.lower_bound(x);
3083 if (it == m.begin())
3091 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3092 DocIterator const & pos) const
3094 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3096 // if paragraphs have no macro context set, pos will be empty
3100 // we haven't found anything yet
3101 DocIterator bestPos = owner_->par_iterator_begin();
3102 MacroData const * bestData = 0;
3104 // find macro definitions for name
3105 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3106 if (nameIt != macros.end()) {
3107 // find last definition in front of pos or at pos itself
3108 PositionScopeMacroMap::const_iterator it
3109 = greatest_below(nameIt->second, pos);
3110 if (it != nameIt->second.end()) {
3112 // scope ends behind pos?
3113 if (pos < it->second.first) {
3114 // Looks good, remember this. If there
3115 // is no external macro behind this,
3116 // we found the right one already.
3117 bestPos = it->first;
3118 bestData = &it->second.second;
3122 // try previous macro if there is one
3123 if (it == nameIt->second.begin())
3130 // find macros in included files
3131 PositionScopeBufferMap::const_iterator it
3132 = greatest_below(position_to_children, pos);
3133 if (it == position_to_children.end())
3134 // no children before
3138 // do we know something better (i.e. later) already?
3139 if (it->first < bestPos )
3142 // scope ends behind pos?
3143 if (pos < it->second.first
3144 && (cloned_buffer_ ||
3145 theBufferList().isLoaded(it->second.second))) {
3146 // look for macro in external file
3148 MacroData const * data
3149 = it->second.second->getMacro(name, false);
3152 bestPos = it->first;
3158 // try previous file if there is one
3159 if (it == position_to_children.begin())
3164 // return the best macro we have found
3169 MacroData const * Buffer::getMacro(docstring const & name,
3170 DocIterator const & pos, bool global) const
3175 // query buffer macros
3176 MacroData const * data = d->getBufferMacro(name, pos);
3180 // If there is a master buffer, query that
3181 Buffer const * const pbuf = d->parent();
3183 d->macro_lock = true;
3184 MacroData const * macro = pbuf->getMacro(
3185 name, *this, false);
3186 d->macro_lock = false;
3192 data = MacroTable::globalMacros().get(name);
3201 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3203 // set scope end behind the last paragraph
3204 DocIterator scope = par_iterator_begin();
3205 scope.pit() = scope.lastpit() + 1;
3207 return getMacro(name, scope, global);
3211 MacroData const * Buffer::getMacro(docstring const & name,
3212 Buffer const & child, bool global) const
3214 // look where the child buffer is included first
3215 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3216 if (it == d->children_positions.end())
3219 // check for macros at the inclusion position
3220 return getMacro(name, it->second, global);
3224 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3226 pit_type const lastpit = it.lastpit();
3228 // look for macros in each paragraph
3229 while (it.pit() <= lastpit) {
3230 Paragraph & par = it.paragraph();
3232 // iterate over the insets of the current paragraph
3233 InsetList const & insets = par.insetList();
3234 InsetList::const_iterator iit = insets.begin();
3235 InsetList::const_iterator end = insets.end();
3236 for (; iit != end; ++iit) {
3237 it.pos() = iit->pos;
3239 // is it a nested text inset?
3240 if (iit->inset->asInsetText()) {
3241 // Inset needs its own scope?
3242 InsetText const * itext = iit->inset->asInsetText();
3243 bool newScope = itext->isMacroScope();
3245 // scope which ends just behind the inset
3246 DocIterator insetScope = it;
3249 // collect macros in inset
3250 it.push_back(CursorSlice(*iit->inset));
3251 updateMacros(it, newScope ? insetScope : scope);
3256 if (iit->inset->asInsetTabular()) {
3257 CursorSlice slice(*iit->inset);
3258 size_t const numcells = slice.nargs();
3259 for (; slice.idx() < numcells; slice.forwardIdx()) {
3260 it.push_back(slice);
3261 updateMacros(it, scope);
3267 // is it an external file?
3268 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3269 // get buffer of external file
3270 InsetInclude const & inset =
3271 static_cast<InsetInclude const &>(*iit->inset);
3273 Buffer * child = inset.getChildBuffer();
3278 // register its position, but only when it is
3279 // included first in the buffer
3280 if (children_positions.find(child) ==
3281 children_positions.end())
3282 children_positions[child] = it;
3284 // register child with its scope
3285 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3289 InsetMath * im = iit->inset->asInsetMath();
3290 if (doing_export && im) {
3291 InsetMathHull * hull = im->asHullInset();
3293 hull->recordLocation(it);
3296 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3300 MathMacroTemplate & macroTemplate =
3301 *iit->inset->asInsetMath()->asMacroTemplate();
3302 MacroContext mc(owner_, it);
3303 macroTemplate.updateToContext(mc);
3306 bool valid = macroTemplate.validMacro();
3307 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3308 // then the BufferView's cursor will be invalid in
3309 // some cases which leads to crashes.
3314 // FIXME (Abdel), I don't understandt why we pass 'it' here
3315 // instead of 'macroTemplate' defined above... is this correct?
3316 macros[macroTemplate.name()][it] =
3317 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3327 void Buffer::updateMacros() const
3332 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3334 // start with empty table
3336 d->children_positions.clear();
3337 d->position_to_children.clear();
3339 // Iterate over buffer, starting with first paragraph
3340 // The scope must be bigger than any lookup DocIterator
3341 // later. For the global lookup, lastpit+1 is used, hence
3342 // we use lastpit+2 here.
3343 DocIterator it = par_iterator_begin();
3344 DocIterator outerScope = it;
3345 outerScope.pit() = outerScope.lastpit() + 2;
3346 d->updateMacros(it, outerScope);
3350 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3352 InsetIterator it = inset_iterator_begin(inset());
3353 InsetIterator const end = inset_iterator_end(inset());
3354 for (; it != end; ++it) {
3355 if (it->lyxCode() == BRANCH_CODE) {
3356 InsetBranch & br = static_cast<InsetBranch &>(*it);
3357 docstring const name = br.branch();
3358 if (!from_master && !params().branchlist().find(name))
3359 result.push_back(name);
3360 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3361 result.push_back(name);
3364 if (it->lyxCode() == INCLUDE_CODE) {
3365 // get buffer of external file
3366 InsetInclude const & ins =
3367 static_cast<InsetInclude const &>(*it);
3368 Buffer * child = ins.getChildBuffer();
3371 child->getUsedBranches(result, true);
3374 // remove duplicates
3379 void Buffer::updateMacroInstances(UpdateType utype) const
3381 LYXERR(Debug::MACROS, "updateMacroInstances for "
3382 << d->filename.onlyFileName());
3383 DocIterator it = doc_iterator_begin(this);
3385 DocIterator const end = doc_iterator_end(this);
3386 for (; it != end; it.forwardInset()) {
3387 // look for MathData cells in InsetMathNest insets
3388 InsetMath * minset = it.nextInset()->asInsetMath();
3392 // update macro in all cells of the InsetMathNest
3393 DocIterator::idx_type n = minset->nargs();
3394 MacroContext mc = MacroContext(this, it);
3395 for (DocIterator::idx_type i = 0; i < n; ++i) {
3396 MathData & data = minset->cell(i);
3397 data.updateMacros(0, mc, utype);
3403 void Buffer::listMacroNames(MacroNameSet & macros) const
3408 d->macro_lock = true;
3410 // loop over macro names
3411 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3412 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3413 for (; nameIt != nameEnd; ++nameIt)
3414 macros.insert(nameIt->first);
3416 // loop over children
3417 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3418 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3419 for (; it != end; ++it)
3420 it->first->listMacroNames(macros);
3423 Buffer const * const pbuf = d->parent();
3425 pbuf->listMacroNames(macros);
3427 d->macro_lock = false;
3431 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3433 Buffer const * const pbuf = d->parent();
3438 pbuf->listMacroNames(names);
3441 MacroNameSet::iterator it = names.begin();
3442 MacroNameSet::iterator end = names.end();
3443 for (; it != end; ++it) {
3445 MacroData const * data =
3446 pbuf->getMacro(*it, *this, false);
3448 macros.insert(data);
3450 // we cannot access the original MathMacroTemplate anymore
3451 // here to calls validate method. So we do its work here manually.
3452 // FIXME: somehow make the template accessible here.
3453 if (data->optionals() > 0)
3454 features.require("xargs");
3460 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3463 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3465 RefCache::iterator it = d->ref_cache_.find(label);
3466 if (it != d->ref_cache_.end())
3467 return it->second.second;
3469 static InsetLabel const * dummy_il = 0;
3470 static References const dummy_refs;
3471 it = d->ref_cache_.insert(
3472 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3473 return it->second.second;
3477 Buffer::References const & Buffer::references(docstring const & label) const
3479 return const_cast<Buffer *>(this)->getReferenceCache(label);
3483 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3485 References & refs = getReferenceCache(label);
3486 refs.push_back(make_pair(inset, it));
3490 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3492 masterBuffer()->d->ref_cache_[label].first = il;
3496 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3498 return masterBuffer()->d->ref_cache_[label].first;
3502 void Buffer::clearReferenceCache() const
3505 d->ref_cache_.clear();
3509 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3511 //FIXME: This does not work for child documents yet.
3512 reloadBibInfoCache();
3514 // Check if the label 'from' appears more than once
3515 BiblioInfo const & keys = masterBibInfo();
3516 BiblioInfo::const_iterator bit = keys.begin();
3517 BiblioInfo::const_iterator bend = keys.end();
3518 vector<docstring> labels;
3520 for (; bit != bend; ++bit)
3522 labels.push_back(bit->first);
3524 if (count(labels.begin(), labels.end(), from) > 1)
3527 string const paramName = "key";
3528 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3529 if (it->lyxCode() != CITE_CODE)
3531 InsetCommand * inset = it->asInsetCommand();
3532 docstring const oldValue = inset->getParam(paramName);
3533 if (oldValue == from)
3534 inset->setParam(paramName, to);
3539 void Buffer::getSourceCode(odocstream & os, string const & format,
3540 pit_type par_begin, pit_type par_end,
3541 OutputWhat output, bool master) const
3543 OutputParams runparams(¶ms().encoding());
3544 runparams.nice = true;
3545 runparams.flavor = params().getOutputFlavor(format);
3546 runparams.linelen = lyxrc.plaintext_linelen;
3547 // No side effect of file copying and image conversion
3548 runparams.dryrun = true;
3550 if (output == CurrentParagraph) {
3551 runparams.par_begin = par_begin;
3552 runparams.par_end = par_end;
3553 if (par_begin + 1 == par_end) {
3555 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3559 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3560 convert<docstring>(par_begin),
3561 convert<docstring>(par_end - 1))
3564 // output paragraphs
3565 if (runparams.flavor == OutputParams::LYX) {
3566 Paragraph const & par = text().paragraphs()[par_begin];
3568 depth_type dt = par.getDepth();
3569 par.write(ods, params(), dt);
3570 os << from_utf8(ods.str());
3571 } else if (runparams.flavor == OutputParams::HTML) {
3573 setMathFlavor(runparams);
3574 xhtmlParagraphs(text(), *this, xs, runparams);
3575 } else if (runparams.flavor == OutputParams::TEXT) {
3577 // FIXME Handles only one paragraph, unlike the others.
3578 // Probably should have some routine with a signature like them.
3579 writePlaintextParagraph(*this,
3580 text().paragraphs()[par_begin], os, runparams, dummy);
3581 } else if (params().isDocBook()) {
3582 docbookParagraphs(text(), *this, os, runparams);
3584 // If we are previewing a paragraph, even if this is the
3585 // child of some other buffer, let's cut the link here,
3586 // so that no concurring settings from the master
3587 // (e.g. branch state) interfere (see #8101).
3589 d->ignore_parent = true;
3590 // We need to validate the Buffer params' features here
3591 // in order to know if we should output polyglossia
3592 // macros (instead of babel macros)
3593 LaTeXFeatures features(*this, params(), runparams);
3594 params().validate(features);
3595 runparams.use_polyglossia = features.usePolyglossia();
3600 // latex or literate
3601 otexstream ots(os, texrow);
3604 latexParagraphs(*this, text(), ots, runparams);
3606 // Restore the parenthood
3608 d->ignore_parent = false;
3612 if (output == FullSource)
3613 os << _("Preview source code");
3614 else if (output == OnlyPreamble)
3615 os << _("Preview preamble");
3616 else if (output == OnlyBody)
3617 os << _("Preview body");
3619 if (runparams.flavor == OutputParams::LYX) {
3621 if (output == FullSource)
3623 else if (output == OnlyPreamble)
3624 params().writeFile(ods);
3625 else if (output == OnlyBody)
3627 os << from_utf8(ods.str());
3628 } else if (runparams.flavor == OutputParams::HTML) {
3629 writeLyXHTMLSource(os, runparams, output);
3630 } else if (runparams.flavor == OutputParams::TEXT) {
3631 if (output == OnlyPreamble) {
3632 os << "% "<< _("Plain text does not have a preamble.");
3634 writePlaintextFile(*this, os, runparams);
3635 } else if (params().isDocBook()) {
3636 writeDocBookSource(os, absFileName(), runparams, output);
3638 // latex or literate
3640 d->texrow.newline();
3641 d->texrow.newline();
3642 otexstream ots(os, d->texrow);
3644 runparams.is_child = true;
3645 writeLaTeXSource(ots, string(), runparams, output);
3651 ErrorList & Buffer::errorList(string const & type) const
3653 return d->errorLists[type];
3657 void Buffer::updateTocItem(std::string const & type,
3658 DocIterator const & dit) const
3661 d->gui_->updateTocItem(type, dit);
3665 void Buffer::structureChanged() const
3668 d->gui_->structureChanged();
3672 void Buffer::errors(string const & err, bool from_master) const
3675 d->gui_->errors(err, from_master);
3679 void Buffer::message(docstring const & msg) const
3682 d->gui_->message(msg);
3686 void Buffer::setBusy(bool on) const
3689 d->gui_->setBusy(on);
3693 void Buffer::updateTitles() const
3696 d->wa_->updateTitles();
3700 void Buffer::resetAutosaveTimers() const
3703 d->gui_->resetAutosaveTimers();
3707 bool Buffer::hasGuiDelegate() const
3713 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3722 class AutoSaveBuffer : public ForkedProcess {
3725 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3726 : buffer_(buffer), fname_(fname) {}
3728 virtual shared_ptr<ForkedProcess> clone() const
3730 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3735 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3736 from_utf8(fname_.absFileName())));
3737 return run(DontWait);
3741 virtual int generateChild();
3743 Buffer const & buffer_;
3748 int AutoSaveBuffer::generateChild()
3750 #if defined(__APPLE__)
3751 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3752 * We should use something else like threads.
3754 * Since I do not know how to determine at run time what is the OS X
3755 * version, I just disable forking altogether for now (JMarc)
3757 pid_t const pid = -1;
3759 // tmp_ret will be located (usually) in /tmp
3760 // will that be a problem?
3761 // Note that this calls ForkedCalls::fork(), so it's
3762 // ok cross-platform.
3763 pid_t const pid = fork();
3764 // If you want to debug the autosave
3765 // you should set pid to -1, and comment out the fork.
3766 if (pid != 0 && pid != -1)
3770 // pid = -1 signifies that lyx was unable
3771 // to fork. But we will do the save
3773 bool failed = false;
3774 TempFile tempfile("lyxautoXXXXXX.lyx");
3775 tempfile.setAutoRemove(false);
3776 FileName const tmp_ret = tempfile.name();
3777 if (!tmp_ret.empty()) {
3778 if (!buffer_.writeFile(tmp_ret))
3780 else if (!tmp_ret.moveTo(fname_))
3786 // failed to write/rename tmp_ret so try writing direct
3787 if (!buffer_.writeFile(fname_)) {
3788 // It is dangerous to do this in the child,
3789 // but safe in the parent, so...
3790 if (pid == -1) // emit message signal.
3791 buffer_.message(_("Autosave failed!"));
3795 if (pid == 0) // we are the child so...
3804 FileName Buffer::getEmergencyFileName() const
3806 return FileName(d->filename.absFileName() + ".emergency");
3810 FileName Buffer::getAutosaveFileName() const
3812 // if the document is unnamed try to save in the backup dir, else
3813 // in the default document path, and as a last try in the filePath,
3814 // which will most often be the temporary directory
3817 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3818 : lyxrc.backupdir_path;
3819 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3822 string const fname = "#" + d->filename.onlyFileName() + "#";
3824 return makeAbsPath(fname, fpath);
3828 void Buffer::removeAutosaveFile() const
3830 FileName const f = getAutosaveFileName();
3836 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3838 FileName const newauto = getAutosaveFileName();
3840 if (newauto != oldauto && oldauto.exists())
3841 if (!oldauto.moveTo(newauto))
3842 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3846 bool Buffer::autoSave() const
3848 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3849 if (buf->d->bak_clean || isReadonly())
3852 message(_("Autosaving current document..."));
3853 buf->d->bak_clean = true;
3855 FileName const fname = getAutosaveFileName();
3856 LASSERT(d->cloned_buffer_, return false);
3858 // If this buffer is cloned, we assume that
3859 // we are running in a separate thread already.
3860 TempFile tempfile("lyxautoXXXXXX.lyx");
3861 tempfile.setAutoRemove(false);
3862 FileName const tmp_ret = tempfile.name();
3863 if (!tmp_ret.empty()) {
3865 // assume successful write of tmp_ret
3866 if (tmp_ret.moveTo(fname))
3869 // failed to write/rename tmp_ret so try writing direct
3870 return writeFile(fname);
3874 void Buffer::setExportStatus(bool e) const
3876 d->doing_export = e;
3877 ListOfBuffers clist = getDescendents();
3878 ListOfBuffers::const_iterator cit = clist.begin();
3879 ListOfBuffers::const_iterator const cen = clist.end();
3880 for (; cit != cen; ++cit)
3881 (*cit)->d->doing_export = e;
3885 bool Buffer::isExporting() const
3887 return d->doing_export;
3891 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3895 return doExport(target, put_in_tempdir, result_file);
3898 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3899 string & result_file) const
3901 bool const update_unincluded =
3902 params().maintain_unincluded_children
3903 && !params().getIncludedChildren().empty();
3905 // (1) export with all included children (omit \includeonly)
3906 if (update_unincluded) {
3907 ExportStatus const status =
3908 doExport(target, put_in_tempdir, true, result_file);
3909 if (status != ExportSuccess)
3912 // (2) export with included children only
3913 return doExport(target, put_in_tempdir, false, result_file);
3917 void Buffer::setMathFlavor(OutputParams & op) const
3919 switch (params().html_math_output) {
3920 case BufferParams::MathML:
3921 op.math_flavor = OutputParams::MathAsMathML;
3923 case BufferParams::HTML:
3924 op.math_flavor = OutputParams::MathAsHTML;
3926 case BufferParams::Images:
3927 op.math_flavor = OutputParams::MathAsImages;
3929 case BufferParams::LaTeX:
3930 op.math_flavor = OutputParams::MathAsLaTeX;
3936 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3937 bool includeall, string & result_file) const
3939 LYXERR(Debug::FILES, "target=" << target);
3940 OutputParams runparams(¶ms().encoding());
3941 string format = target;
3942 string dest_filename;
3943 size_t pos = target.find(' ');
3944 if (pos != string::npos) {
3945 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3946 format = target.substr(0, pos);
3947 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3948 FileName(dest_filename).onlyPath().createPath();
3949 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3951 MarkAsExporting exporting(this);
3952 string backend_format;
3953 runparams.flavor = OutputParams::LATEX;
3954 runparams.linelen = lyxrc.plaintext_linelen;
3955 runparams.includeall = includeall;
3956 vector<string> backs = params().backends();
3957 Converters converters = theConverters();
3958 bool need_nice_file = false;
3959 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3960 // Get shortest path to format
3961 converters.buildGraph();
3962 Graph::EdgePath path;
3963 for (vector<string>::const_iterator it = backs.begin();
3964 it != backs.end(); ++it) {
3965 Graph::EdgePath p = converters.getPath(*it, format);
3966 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3967 backend_format = *it;
3972 if (!put_in_tempdir) {
3973 // Only show this alert if this is an export to a non-temporary
3974 // file (not for previewing).
3975 Alert::error(_("Couldn't export file"), bformat(
3976 _("No information for exporting the format %1$s."),
3977 formats.prettyName(format)));
3979 return ExportNoPathToFormat;
3981 runparams.flavor = converters.getFlavor(path, this);
3982 Graph::EdgePath::const_iterator it = path.begin();
3983 Graph::EdgePath::const_iterator en = path.end();
3984 for (; it != en; ++it)
3985 if (theConverters().get(*it).nice) {
3986 need_nice_file = true;
3991 backend_format = format;
3992 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3993 // FIXME: Don't hardcode format names here, but use a flag
3994 if (backend_format == "pdflatex")
3995 runparams.flavor = OutputParams::PDFLATEX;
3996 else if (backend_format == "luatex")
3997 runparams.flavor = OutputParams::LUATEX;
3998 else if (backend_format == "dviluatex")
3999 runparams.flavor = OutputParams::DVILUATEX;
4000 else if (backend_format == "xetex")
4001 runparams.flavor = OutputParams::XETEX;
4004 string filename = latexName(false);
4005 filename = addName(temppath(), filename);
4006 filename = changeExtension(filename,
4007 formats.extension(backend_format));
4008 LYXERR(Debug::FILES, "filename=" << filename);
4010 // Plain text backend
4011 if (backend_format == "text") {
4012 runparams.flavor = OutputParams::TEXT;
4013 writePlaintextFile(*this, FileName(filename), runparams);
4016 else if (backend_format == "xhtml") {
4017 runparams.flavor = OutputParams::HTML;
4018 setMathFlavor(runparams);
4019 makeLyXHTMLFile(FileName(filename), runparams);
4020 } else if (backend_format == "lyx")
4021 writeFile(FileName(filename));
4023 else if (params().isDocBook()) {
4024 runparams.nice = !put_in_tempdir;
4025 makeDocBookFile(FileName(filename), runparams);
4028 else if (backend_format == format || need_nice_file) {
4029 runparams.nice = true;
4030 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4031 if (d->cloned_buffer_)
4032 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4035 } else if (!lyxrc.tex_allows_spaces
4036 && contains(filePath(), ' ')) {
4037 Alert::error(_("File name error"),
4038 _("The directory path to the document cannot contain spaces."));
4039 return ExportTexPathHasSpaces;
4041 runparams.nice = false;
4042 bool const success = makeLaTeXFile(
4043 FileName(filename), filePath(), runparams);
4044 if (d->cloned_buffer_)
4045 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4050 string const error_type = (format == "program")
4051 ? "Build" : params().bufferFormat();
4052 ErrorList & error_list = d->errorLists[error_type];
4053 string const ext = formats.extension(format);
4054 FileName const tmp_result_file(changeExtension(filename, ext));
4055 bool const success = converters.convert(this, FileName(filename),
4056 tmp_result_file, FileName(absFileName()), backend_format, format,
4059 // Emit the signal to show the error list or copy it back to the
4060 // cloned Buffer so that it can be emitted afterwards.
4061 if (format != backend_format) {
4062 if (runparams.silent)
4064 else if (d->cloned_buffer_)
4065 d->cloned_buffer_->d->errorLists[error_type] =
4066 d->errorLists[error_type];
4069 // also to the children, in case of master-buffer-view
4070 ListOfBuffers clist = getDescendents();
4071 ListOfBuffers::const_iterator cit = clist.begin();
4072 ListOfBuffers::const_iterator const cen = clist.end();
4073 for (; cit != cen; ++cit) {
4074 if (runparams.silent)
4075 (*cit)->d->errorLists[error_type].clear();
4076 else if (d->cloned_buffer_) {
4077 // Enable reverse search by copying back the
4078 // texrow object to the cloned buffer.
4079 // FIXME: this is not thread safe.
4080 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4081 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4082 (*cit)->d->errorLists[error_type];
4084 (*cit)->errors(error_type, true);
4088 if (d->cloned_buffer_) {
4089 // Enable reverse dvi or pdf to work by copying back the texrow
4090 // object to the cloned buffer.
4091 // FIXME: There is a possibility of concurrent access to texrow
4092 // here from the main GUI thread that should be securized.
4093 d->cloned_buffer_->d->texrow = d->texrow;
4094 string const error_type = params().bufferFormat();
4095 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4099 return ExportConverterError;
4101 if (put_in_tempdir) {
4102 result_file = tmp_result_file.absFileName();
4103 return ExportSuccess;
4106 if (dest_filename.empty())
4107 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4109 result_file = dest_filename;
4110 // We need to copy referenced files (e. g. included graphics
4111 // if format == "dvi") to the result dir.
4112 vector<ExportedFile> const files =
4113 runparams.exportdata->externalFiles(format);
4114 string const dest = runparams.export_folder.empty() ?
4115 onlyPath(result_file) : runparams.export_folder;
4116 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4117 : force_overwrite == ALL_FILES;
4118 CopyStatus status = use_force ? FORCE : SUCCESS;
4120 vector<ExportedFile>::const_iterator it = files.begin();
4121 vector<ExportedFile>::const_iterator const en = files.end();
4122 for (; it != en && status != CANCEL; ++it) {
4123 string const fmt = formats.getFormatFromFile(it->sourceName);
4124 string fixedName = it->exportName;
4125 if (!runparams.export_folder.empty()) {
4126 // Relative pathnames starting with ../ will be sanitized
4127 // if exporting to a different folder
4128 while (fixedName.substr(0, 3) == "../")
4129 fixedName = fixedName.substr(3, fixedName.length() - 3);
4131 FileName fixedFileName = makeAbsPath(fixedName, dest);
4132 fixedFileName.onlyPath().createPath();
4133 status = copyFile(fmt, it->sourceName,
4135 it->exportName, status == FORCE,
4136 runparams.export_folder.empty());
4139 if (status == CANCEL) {
4140 message(_("Document export cancelled."));
4141 return ExportCancel;
4144 if (tmp_result_file.exists()) {
4145 // Finally copy the main file
4146 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4147 : force_overwrite != NO_FILES;
4148 if (status == SUCCESS && use_force)
4150 status = copyFile(format, tmp_result_file,
4151 FileName(result_file), result_file,
4153 if (status == CANCEL) {
4154 message(_("Document export cancelled."));
4155 return ExportCancel;
4157 message(bformat(_("Document exported as %1$s "
4159 formats.prettyName(format),
4160 makeDisplayPath(result_file)));
4163 // This must be a dummy converter like fax (bug 1888)
4164 message(bformat(_("Document exported as %1$s"),
4165 formats.prettyName(format)));
4168 return ExportSuccess;
4172 Buffer::ExportStatus Buffer::preview(string const & format) const
4174 bool const update_unincluded =
4175 params().maintain_unincluded_children
4176 && !params().getIncludedChildren().empty();
4177 return preview(format, update_unincluded);
4180 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4182 MarkAsExporting exporting(this);
4184 // (1) export with all included children (omit \includeonly)
4186 ExportStatus const status = doExport(format, true, true, result_file);
4187 if (status != ExportSuccess)
4190 // (2) export with included children only
4191 ExportStatus const status = doExport(format, true, false, result_file);
4192 if (status != ExportSuccess)
4194 if (!formats.view(*this, FileName(result_file), format))
4195 return PreviewError;
4196 return PreviewSuccess;
4200 Buffer::ReadStatus Buffer::extractFromVC()
4202 bool const found = LyXVC::file_not_found_hook(d->filename);
4204 return ReadFileNotFound;
4205 if (!d->filename.isReadableFile())
4211 Buffer::ReadStatus Buffer::loadEmergency()
4213 FileName const emergencyFile = getEmergencyFileName();
4214 if (!emergencyFile.exists()
4215 || emergencyFile.lastModified() <= d->filename.lastModified())
4216 return ReadFileNotFound;
4218 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4219 docstring const text = bformat(_("An emergency save of the document "
4220 "%1$s exists.\n\nRecover emergency save?"), file);
4222 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4223 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4229 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4230 bool const success = (ret_llf == ReadSuccess);
4233 Alert::warning(_("File is read-only"),
4234 bformat(_("An emergency file is successfully loaded, "
4235 "but the original file %1$s is marked read-only. "
4236 "Please make sure to save the document as a different "
4237 "file."), from_utf8(d->filename.absFileName())));
4240 lyxvc().file_found_hook(d->filename);
4241 str = _("Document was successfully recovered.");
4243 str = _("Document was NOT successfully recovered.");
4244 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4245 makeDisplayPath(emergencyFile.absFileName()));
4247 int const del_emerg =
4248 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4249 _("&Remove"), _("&Keep"));
4250 if (del_emerg == 0) {
4251 emergencyFile.removeFile();
4253 Alert::warning(_("Emergency file deleted"),
4254 _("Do not forget to save your file now!"), true);
4256 return success ? ReadSuccess : ReadEmergencyFailure;
4259 int const del_emerg =
4260 Alert::prompt(_("Delete emergency file?"),
4261 _("Remove emergency file now?"), 1, 1,
4262 _("&Remove"), _("&Keep"));
4264 emergencyFile.removeFile();
4265 return ReadOriginal;
4275 Buffer::ReadStatus Buffer::loadAutosave()
4277 // Now check if autosave file is newer.
4278 FileName const autosaveFile = getAutosaveFileName();
4279 if (!autosaveFile.exists()
4280 || autosaveFile.lastModified() <= d->filename.lastModified())
4281 return ReadFileNotFound;
4283 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4284 docstring const text = bformat(_("The backup of the document %1$s "
4285 "is newer.\n\nLoad the backup instead?"), file);
4286 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4287 _("&Load backup"), _("Load &original"), _("&Cancel"));
4292 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4293 // the file is not saved if we load the autosave file.
4294 if (ret_llf == ReadSuccess) {
4296 Alert::warning(_("File is read-only"),
4297 bformat(_("A backup file is successfully loaded, "
4298 "but the original file %1$s is marked read-only. "
4299 "Please make sure to save the document as a "
4301 from_utf8(d->filename.absFileName())));
4304 lyxvc().file_found_hook(d->filename);
4307 return ReadAutosaveFailure;
4310 // Here we delete the autosave
4311 autosaveFile.removeFile();
4312 return ReadOriginal;
4320 Buffer::ReadStatus Buffer::loadLyXFile()
4322 if (!d->filename.isReadableFile()) {
4323 ReadStatus const ret_rvc = extractFromVC();
4324 if (ret_rvc != ReadSuccess)
4328 ReadStatus const ret_re = loadEmergency();
4329 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4332 ReadStatus const ret_ra = loadAutosave();
4333 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4336 return loadThisLyXFile(d->filename);
4340 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4342 return readFile(fn);
4346 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4348 TeXErrors::Errors::const_iterator it = terr.begin();
4349 TeXErrors::Errors::const_iterator end = terr.end();
4350 ListOfBuffers clist = getDescendents();
4351 ListOfBuffers::const_iterator cen = clist.end();
4353 for (; it != end; ++it) {
4356 int errorRow = it->error_in_line;
4357 Buffer const * buf = 0;
4359 if (it->child_name.empty())
4360 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4362 // The error occurred in a child
4363 ListOfBuffers::const_iterator cit = clist.begin();
4364 for (; cit != cen; ++cit) {
4365 string const child_name =
4366 DocFileName(changeExtension(
4367 (*cit)->absFileName(), "tex")).
4369 if (it->child_name != child_name)
4371 (*cit)->d->texrow.getIdFromRow(errorRow,
4372 id_start, pos_start);
4373 if (id_start != -1) {
4374 buf = d->cloned_buffer_
4375 ? (*cit)->d->cloned_buffer_->d->owner_
4376 : (*cit)->d->owner_;
4387 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4388 } while (found && id_start == id_end && pos_start == pos_end);
4390 if (id_start != id_end) {
4391 // Next registered position is outside the inset where
4392 // the error occurred, so signal end-of-paragraph
4396 errorList.push_back(ErrorItem(it->error_desc,
4397 it->error_text, id_start, pos_start, pos_end, buf));
4402 void Buffer::setBuffersForInsets() const
4404 inset().setBuffer(const_cast<Buffer &>(*this));
4408 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4410 LBUFERR(!text().paragraphs().empty());
4412 // Use the master text class also for child documents
4413 Buffer const * const master = masterBuffer();
4414 DocumentClass const & textclass = master->params().documentClass();
4416 // do this only if we are the top-level Buffer
4417 if (master == this) {
4418 textclass.counters().reset(from_ascii("bibitem"));
4419 reloadBibInfoCache();
4422 // keep the buffers to be children in this set. If the call from the
4423 // master comes back we can see which of them were actually seen (i.e.
4424 // via an InsetInclude). The remaining ones in the set need still be updated.
4425 static std::set<Buffer const *> bufToUpdate;
4426 if (scope == UpdateMaster) {
4427 // If this is a child document start with the master
4428 if (master != this) {
4429 bufToUpdate.insert(this);
4430 master->updateBuffer(UpdateMaster, utype);
4431 // If the master buffer has no gui associated with it, then the TocModel is
4432 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4433 // (bug 5699). The same happens if the master buffer is open in a different
4434 // window. This test catches both possibilities.
4435 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4436 // There remains a problem here: If there is another child open in yet a third
4437 // window, that TOC is not updated. So some more general solution is needed at
4439 if (master->d->gui_ != d->gui_)
4442 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4443 if (bufToUpdate.find(this) == bufToUpdate.end())
4447 // start over the counters in the master
4448 textclass.counters().reset();
4451 // update will be done below for this buffer
4452 bufToUpdate.erase(this);
4454 // update all caches
4455 clearReferenceCache();
4458 Buffer & cbuf = const_cast<Buffer &>(*this);
4461 ParIterator parit = cbuf.par_iterator_begin();
4462 updateBuffer(parit, utype);
4465 // TocBackend update will be done later.
4468 d->bibinfo_cache_valid_ = true;
4469 d->cite_labels_valid_ = true;
4470 cbuf.tocBackend().update(utype == OutputUpdate);
4471 if (scope == UpdateMaster)
4472 cbuf.structureChanged();
4476 static depth_type getDepth(DocIterator const & it)
4478 depth_type depth = 0;
4479 for (size_t i = 0 ; i < it.depth() ; ++i)
4480 if (!it[i].inset().inMathed())
4481 depth += it[i].paragraph().getDepth() + 1;
4482 // remove 1 since the outer inset does not count
4486 static depth_type getItemDepth(ParIterator const & it)
4488 Paragraph const & par = *it;
4489 LabelType const labeltype = par.layout().labeltype;
4491 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4494 // this will hold the lowest depth encountered up to now.
4495 depth_type min_depth = getDepth(it);
4496 ParIterator prev_it = it;
4499 --prev_it.top().pit();
4501 // start of nested inset: go to outer par
4503 if (prev_it.empty()) {
4504 // start of document: nothing to do
4509 // We search for the first paragraph with same label
4510 // that is not more deeply nested.
4511 Paragraph & prev_par = *prev_it;
4512 depth_type const prev_depth = getDepth(prev_it);
4513 if (labeltype == prev_par.layout().labeltype) {
4514 if (prev_depth < min_depth)
4515 return prev_par.itemdepth + 1;
4516 if (prev_depth == min_depth)
4517 return prev_par.itemdepth;
4519 min_depth = min(min_depth, prev_depth);
4520 // small optimization: if we are at depth 0, we won't
4521 // find anything else
4522 if (prev_depth == 0)
4528 static bool needEnumCounterReset(ParIterator const & it)
4530 Paragraph const & par = *it;
4531 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4532 depth_type const cur_depth = par.getDepth();
4533 ParIterator prev_it = it;
4534 while (prev_it.pit()) {
4535 --prev_it.top().pit();
4536 Paragraph const & prev_par = *prev_it;
4537 if (prev_par.getDepth() <= cur_depth)
4538 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4540 // start of nested inset: reset
4545 // set the label of a paragraph. This includes the counters.
4546 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4548 BufferParams const & bp = owner_->masterBuffer()->params();
4549 DocumentClass const & textclass = bp.documentClass();
4550 Paragraph & par = it.paragraph();
4551 Layout const & layout = par.layout();
4552 Counters & counters = textclass.counters();
4554 if (par.params().startOfAppendix()) {
4555 // We want to reset the counter corresponding to toplevel sectioning
4556 Layout const & lay = textclass.getTOCLayout();
4557 docstring const cnt = lay.counter;
4559 counters.reset(cnt);
4560 counters.appendix(true);
4562 par.params().appendix(counters.appendix());
4564 // Compute the item depth of the paragraph
4565 par.itemdepth = getItemDepth(it);
4567 if (layout.margintype == MARGIN_MANUAL) {
4568 if (par.params().labelWidthString().empty())
4569 par.params().labelWidthString(par.expandLabel(layout, bp));
4570 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4571 // we do not need to do anything here, since the empty case is
4572 // handled during export.
4574 par.params().labelWidthString(docstring());
4577 switch(layout.labeltype) {
4578 case LABEL_ITEMIZE: {
4579 // At some point of time we should do something more
4580 // clever here, like:
4581 // par.params().labelString(
4582 // bp.user_defined_bullet(par.itemdepth).getText());
4583 // for now, use a simple hardcoded label
4584 docstring itemlabel;
4585 switch (par.itemdepth) {
4587 itemlabel = char_type(0x2022);
4590 itemlabel = char_type(0x2013);
4593 itemlabel = char_type(0x2217);
4596 itemlabel = char_type(0x2219); // or 0x00b7
4599 par.params().labelString(itemlabel);
4603 case LABEL_ENUMERATE: {
4604 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4606 switch (par.itemdepth) {
4615 enumcounter += "iv";
4618 // not a valid enumdepth...
4622 // Maybe we have to reset the enumeration counter.
4623 if (needEnumCounterReset(it))
4624 counters.reset(enumcounter);
4625 counters.step(enumcounter, utype);
4627 string const & lang = par.getParLanguage(bp)->code();
4628 par.params().labelString(counters.theCounter(enumcounter, lang));
4633 case LABEL_SENSITIVE: {
4634 string const & type = counters.current_float();
4635 docstring full_label;
4637 full_label = owner_->B_("Senseless!!! ");
4639 docstring name = owner_->B_(textclass.floats().getType(type).name());
4640 if (counters.hasCounter(from_utf8(type))) {
4641 string const & lang = par.getParLanguage(bp)->code();
4642 counters.step(from_utf8(type), utype);
4643 full_label = bformat(from_ascii("%1$s %2$s:"),
4645 counters.theCounter(from_utf8(type), lang));
4647 full_label = bformat(from_ascii("%1$s #:"), name);
4649 par.params().labelString(full_label);
4653 case LABEL_NO_LABEL:
4654 par.params().labelString(docstring());
4658 case LABEL_CENTERED:
4659 case LABEL_STATIC: {
4660 docstring const & lcounter = layout.counter;
4661 if (!lcounter.empty()) {
4662 if (layout.toclevel <= bp.secnumdepth
4663 && (layout.latextype != LATEX_ENVIRONMENT
4664 || it.text()->isFirstInSequence(it.pit()))) {
4665 if (counters.hasCounter(lcounter))
4666 counters.step(lcounter, utype);
4667 par.params().labelString(par.expandLabel(layout, bp));
4669 par.params().labelString(docstring());
4671 par.params().labelString(par.expandLabel(layout, bp));
4677 par.params().labelString(par.expandLabel(layout, bp));
4682 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4684 // LASSERT: Is it safe to continue here, or should we just return?
4685 LASSERT(parit.pit() == 0, /**/);
4687 // Set the position of the text in the buffer to be able
4688 // to resolve macros in it.
4689 parit.text()->setMacrocontextPosition(parit);
4691 depth_type maxdepth = 0;
4692 pit_type const lastpit = parit.lastpit();
4693 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4694 // reduce depth if necessary
4695 if (parit->params().depth() > maxdepth) {
4696 /** FIXME: this function is const, but
4697 * nevertheless it modifies the buffer. To be
4698 * cleaner, one should modify the buffer in
4699 * another function, which is actually
4700 * non-const. This would however be costly in
4701 * terms of code duplication.
4703 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4704 parit->params().depth(maxdepth);
4706 maxdepth = parit->getMaxDepthAfter();
4708 if (utype == OutputUpdate) {
4709 // track the active counters
4710 // we have to do this for the master buffer, since the local
4711 // buffer isn't tracking anything.
4712 masterBuffer()->params().documentClass().counters().
4713 setActiveLayout(parit->layout());
4716 // set the counter for this paragraph
4717 d->setLabel(parit, utype);
4720 InsetList::const_iterator iit = parit->insetList().begin();
4721 InsetList::const_iterator end = parit->insetList().end();
4722 for (; iit != end; ++iit) {
4723 parit.pos() = iit->pos;
4724 iit->inset->updateBuffer(parit, utype);
4730 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4731 WordLangTuple & word_lang, docstring_list & suggestions) const
4735 suggestions.clear();
4736 word_lang = WordLangTuple();
4737 bool const to_end = to.empty();
4738 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4739 // OK, we start from here.
4740 for (; from != end; from.forwardPos()) {
4741 // We are only interested in text so remove the math CursorSlice.
4742 while (from.inMathed()) {
4746 // If from is at the end of the document (which is possible
4747 // when leaving the mathed) LyX will crash later otherwise.
4748 if (from.atEnd() || (!to_end && from >= end))
4751 from.paragraph().spellCheck();
4752 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4753 if (SpellChecker::misspelled(res)) {
4758 // Do not increase progress when from == to, otherwise the word
4759 // count will be wrong.
4769 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4771 bool inword = false;
4776 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4777 if (!dit.inTexted()) {
4782 Paragraph const & par = dit.paragraph();
4783 pos_type const pos = dit.pos();
4785 // Copied and adapted from isWordSeparator() in Paragraph
4786 if (pos == dit.lastpos()) {
4789 Inset const * ins = par.getInset(pos);
4790 if (ins && skipNoOutput && !ins->producesOutput()) {
4793 // stop if end of range was skipped
4794 if (!to.atEnd() && dit >= to)
4797 } else if (!par.isDeleted(pos)) {
4798 if (par.isWordSeparator(pos))
4804 if (ins && ins->isLetter())
4806 else if (ins && ins->isSpace())
4809 char_type const c = par.getChar(pos);
4810 if (isPrintableNonspace(c))
4812 else if (isSpace(c))
4822 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4824 d->updateStatistics(from, to, skipNoOutput);
4828 int Buffer::wordCount() const
4830 return d->wordCount();
4834 int Buffer::charCount(bool with_blanks) const
4836 return d->charCount(with_blanks);
4840 Buffer::ReadStatus Buffer::reload()
4843 // c.f. bug http://www.lyx.org/trac/ticket/6587
4844 removeAutosaveFile();
4845 // e.g., read-only status could have changed due to version control
4846 d->filename.refresh();
4847 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4849 // clear parent. this will get reset if need be.
4851 ReadStatus const status = loadLyXFile();
4852 if (status == ReadSuccess) {
4857 message(bformat(_("Document %1$s reloaded."), disp_fn));
4860 message(bformat(_("Could not reload document %1$s."), disp_fn));
4870 bool Buffer::saveAs(FileName const & fn)
4872 FileName const old_name = fileName();
4873 FileName const old_auto = getAutosaveFileName();
4874 bool const old_unnamed = isUnnamed();
4881 // bring the autosave file with us, just in case.
4882 moveAutosaveFile(old_auto);
4883 // validate version control data and
4884 // correct buffer title
4885 lyxvc().file_found_hook(fileName());
4887 // the file has now been saved to the new location.
4888 // we need to check that the locations of child buffers
4890 checkChildBuffers();
4891 checkMasterBuffer();
4895 // reset the old filename and unnamed state
4896 setFileName(old_name);
4897 setUnnamed(old_unnamed);
4903 // FIXME We could do better here, but it is complicated. What would be
4904 // nice is to offer either (a) to save the child buffer to an appropriate
4905 // location, so that it would "move with the master", or else (b) to update
4906 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4907 // complicated, because the code for this lives in GuiView.
4908 void Buffer::checkChildBuffers()
4910 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4911 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4912 for (; it != en; ++it) {
4913 DocIterator dit = it->second;
4914 Buffer * cbuf = const_cast<Buffer *>(it->first);
4915 if (!cbuf || !theBufferList().isLoaded(cbuf))
4917 Inset * inset = dit.nextInset();
4918 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4919 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4920 docstring const & incfile = inset_inc->getParam("filename");
4921 string oldloc = cbuf->absFileName();
4922 string newloc = makeAbsPath(to_utf8(incfile),
4923 onlyPath(absFileName())).absFileName();
4924 if (oldloc == newloc)
4926 // the location of the child file is incorrect.
4927 Alert::warning(_("Included File Invalid"),
4928 bformat(_("Saving this document to a new location has made the file:\n"
4930 "inaccessible. You will need to update the included filename."),
4931 from_utf8(oldloc)));
4933 inset_inc->setChildBuffer(0);
4935 // invalidate cache of children
4936 d->children_positions.clear();
4937 d->position_to_children.clear();
4941 // If a child has been saved under a different name/path, it might have been
4942 // orphaned. Therefore the master needs to be reset (bug 8161).
4943 void Buffer::checkMasterBuffer()
4945 Buffer const * const master = masterBuffer();
4949 // necessary to re-register the child (bug 5873)
4950 // FIXME: clean up updateMacros (here, only
4951 // child registering is needed).
4952 master->updateMacros();
4953 // (re)set master as master buffer, but only
4954 // if we are a real child
4955 if (master->isChild(this))