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"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibtex.h"
70 #include "insets/InsetBranch.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetTabular.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "graphics/PreviewLoader.h"
82 #include "frontends/alert.h"
83 #include "frontends/Delegates.h"
84 #include "frontends/WorkAreaManager.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
120 using namespace lyx::graphics;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 int const LYX_FORMAT = LYX_FORMAT_LYX;
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
145 // A storehouse for the cloned buffers.
146 list<CloneList *> cloned_buffers;
152 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
156 delete preview_loader_;
164 /// search for macro in local (buffer) table or in children
165 MacroData const * getBufferMacro(docstring const & name,
166 DocIterator const & pos) const;
168 /// Update macro table starting with position of it \param it in some
170 void updateMacros(DocIterator & it, DocIterator & scope);
172 void setLabel(ParIterator & it, UpdateType utype) const;
174 /** If we have branches that use the file suffix
175 feature, return the file name with suffix appended.
177 support::FileName exportFileName() const;
184 mutable TexRow texrow;
186 /// need to regenerate .tex?
190 mutable bool lyx_clean;
192 /// is autosave needed?
193 mutable bool bak_clean;
195 /// is this an unnamed file (New...)?
201 /// name of the file the buffer is associated with.
204 /** Set to true only when the file is fully loaded.
205 * Used to prevent the premature generation of previews
206 * and by the citation inset.
208 bool file_fully_loaded;
211 mutable TocBackend toc_backend;
214 typedef pair<DocIterator, MacroData> ScopeMacro;
215 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
216 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
217 /// map from the macro name to the position map,
218 /// which maps the macro definition position to the scope and the MacroData.
219 NamePositionScopeMacroMap macros;
220 /// This seem to change the way Buffer::getMacro() works
221 mutable bool macro_lock;
223 /// positions of child buffers in the buffer
224 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
225 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
226 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
227 /// position of children buffers in this buffer
228 BufferPositionMap children_positions;
229 /// map from children inclusion positions to their scope and their buffer
230 PositionScopeBufferMap position_to_children;
232 /// Container for all sort of Buffer dependant errors.
233 map<string, ErrorList> errorLists;
235 /// timestamp and checksum used to test if the file has been externally
236 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
238 unsigned long checksum_;
241 frontend::WorkAreaManager * wa_;
243 frontend::GuiBufferDelegate * gui_;
248 /// A cache for the bibfiles (including bibfiles of loaded child
249 /// documents), needed for appropriate update of natbib labels.
250 mutable support::FileNameList bibfiles_cache_;
252 // FIXME The caching mechanism could be improved. At present, we have a
253 // cache for each Buffer, that caches all the bibliography info for that
254 // Buffer. A more efficient solution would be to have a global cache per
255 // file, and then to construct the Buffer's bibinfo from that.
256 /// A cache for bibliography info
257 mutable BiblioInfo bibinfo_;
258 /// whether the bibinfo cache is valid
259 mutable bool bibinfo_cache_valid_;
260 /// whether the bibfile cache is valid
261 mutable bool bibfile_cache_valid_;
262 /// Cache of timestamps of .bib files
263 map<FileName, time_t> bibfile_status_;
264 /// Indicates whether the bibinfo has changed since the last time
265 /// we ran updateBuffer(), i.e., whether citation labels may need
267 mutable bool cite_labels_valid_;
269 mutable RefCache ref_cache_;
271 /// our Text that should be wrapped in an InsetText
275 PreviewLoader * preview_loader_;
277 /// This is here to force the test to be done whenever parent_buffer
279 Buffer const * parent() const {
280 // if parent_buffer is not loaded, then it has been unloaded,
281 // which means that parent_buffer is an invalid pointer. So we
282 // set it to null in that case.
283 // however, the BufferList doesn't know about cloned buffers, so
284 // they will always be regarded as unloaded. in that case, we hope
286 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
288 return parent_buffer;
292 void setParent(Buffer const * pb) {
293 if (parent_buffer == pb)
296 if (!cloned_buffer_ && parent_buffer && pb)
297 LYXERR0("Warning: a buffer should not have two parents!");
299 if (!cloned_buffer_ && parent_buffer) {
300 parent_buffer->invalidateBibfileCache();
301 parent_buffer->invalidateBibinfoCache();
305 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
306 /// This one is useful for preview detached in a thread.
307 Buffer const * cloned_buffer_;
309 CloneList * clone_list_;
310 /// are we in the process of exporting this buffer?
311 mutable bool doing_export;
313 /// compute statistics
314 /// \p from initial position
315 /// \p to points to the end position
316 void updateStatistics(DocIterator & from, DocIterator & to,
317 bool skipNoOutput = true);
318 /// statistics accessor functions
319 int wordCount() const { return word_count_; }
320 int charCount(bool with_blanks) const {
322 + (with_blanks ? blank_count_ : 0);
326 /// So we can force access via the accessors.
327 mutable Buffer const * parent_buffer;
336 /// Creates the per buffer temporary directory
337 static FileName createBufferTmpDir()
340 // We are in our own directory. Why bother to mangle name?
341 // In fact I wrote this code to circumvent a problematic behaviour
342 // (bug?) of EMX mkstemp().
343 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
344 convert<string>(count++));
346 if (!tmpfl.createDirectory(0777)) {
347 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
348 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
349 from_utf8(tmpfl.absFileName())));
355 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
356 Buffer const * cloned_buffer)
357 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
358 read_only(readonly_), filename(file), file_fully_loaded(false),
359 toc_backend(owner), macro_lock(false), timestamp_(0), checksum_(0),
360 wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
361 bibfile_cache_valid_(false), cite_labels_valid_(false),
362 preview_loader_(0), cloned_buffer_(cloned_buffer), clone_list_(0),
363 doing_export(false), parent_buffer(0)
365 if (!cloned_buffer_) {
366 temppath = createBufferTmpDir();
367 lyxvc.setBuffer(owner_);
369 wa_ = new frontend::WorkAreaManager;
372 temppath = cloned_buffer_->d->temppath;
373 file_fully_loaded = true;
374 params = cloned_buffer_->d->params;
375 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
376 bibinfo_ = cloned_buffer_->d->bibinfo_;
377 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
378 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
379 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
380 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
381 unnamed = cloned_buffer_->d->unnamed;
385 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
386 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
388 LYXERR(Debug::INFO, "Buffer::Buffer()");
390 d->inset = new InsetText(*cloned_buffer->d->inset);
391 d->inset->setBuffer(*this);
392 // FIXME: optimize this loop somewhat, maybe by creating a new
393 // general recursive Inset::setId().
394 DocIterator it = doc_iterator_begin(this);
395 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
396 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
397 it.paragraph().setId(cloned_it.paragraph().id());
399 d->inset = new InsetText(this);
400 d->inset->setAutoBreakRows(true);
401 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
407 LYXERR(Debug::INFO, "Buffer::~Buffer()");
408 // here the buffer should take care that it is
409 // saved properly, before it goes into the void.
411 // GuiView already destroyed
415 // No need to do additional cleanups for internal buffer.
421 // this is in case of recursive includes: we won't try to delete
422 // ourselves as a child.
423 d->clone_list_->erase(this);
424 // loop over children
425 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
426 Impl::BufferPositionMap::iterator end = d->children_positions.end();
427 for (; it != end; ++it) {
428 Buffer * child = const_cast<Buffer *>(it->first);
429 if (d->clone_list_->erase(child))
432 // if we're the master buffer, then we should get rid of the list
435 // if this is not empty, we have leaked something. worse, one of the
436 // children still has a reference to this list.
437 LASSERT(d->clone_list_->empty(), /* */);
438 list<CloneList *>::iterator it =
439 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
440 LASSERT(it != cloned_buffers.end(), /* */);
441 cloned_buffers.erase(it);
442 delete d->clone_list_;
444 // FIXME Do we really need to do this right before we delete d?
445 // clear references to children in macro tables
446 d->children_positions.clear();
447 d->position_to_children.clear();
449 // loop over children
450 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
451 Impl::BufferPositionMap::iterator end = d->children_positions.end();
452 for (; it != end; ++it) {
453 Buffer * child = const_cast<Buffer *>(it->first);
454 if (theBufferList().isLoaded(child))
455 theBufferList().releaseChild(this, child);
459 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
460 msg += emergencyWrite();
461 Alert::warning(_("Attempting to close changed document!"), msg);
464 // FIXME Do we really need to do this right before we delete d?
465 // clear references to children in macro tables
466 d->children_positions.clear();
467 d->position_to_children.clear();
469 if (!d->temppath.destroyDirectory()) {
470 Alert::warning(_("Could not remove temporary directory"),
471 bformat(_("Could not remove the temporary directory %1$s"),
472 from_utf8(d->temppath.absFileName())));
481 Buffer * Buffer::cloneFromMaster() const
484 cloned_buffers.push_back(new CloneList());
485 CloneList * clones = cloned_buffers.back();
487 masterBuffer()->cloneWithChildren(bufmap, clones);
489 // make sure we got cloned
490 BufferMap::const_iterator bit = bufmap.find(this);
491 LASSERT(bit != bufmap.end(), return 0);
492 Buffer * cloned_buffer = bit->second;
494 return cloned_buffer;
498 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
500 // have we already been cloned?
501 if (bufmap.find(this) != bufmap.end())
504 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
505 bufmap[this] = buffer_clone;
506 clones->insert(buffer_clone);
507 buffer_clone->d->clone_list_ = clones;
508 buffer_clone->d->macro_lock = true;
509 buffer_clone->d->children_positions.clear();
510 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
511 // math macro caches need to be rethought and simplified.
512 // I am not sure wether we should handle Buffer cloning here or in BufferList.
513 // Right now BufferList knows nothing about buffer clones.
514 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
515 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
516 for (; it != end; ++it) {
517 DocIterator dit = it->first.clone(buffer_clone);
518 dit.setBuffer(buffer_clone);
519 Buffer * child = const_cast<Buffer *>(it->second.second);
521 child->cloneWithChildren(bufmap, clones);
522 BufferMap::iterator const bit = bufmap.find(child);
523 LASSERT(bit != bufmap.end(), continue);
524 Buffer * child_clone = bit->second;
526 Inset * inset = dit.nextInset();
527 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
528 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
529 inset_inc->setChildBuffer(child_clone);
530 child_clone->d->setParent(buffer_clone);
531 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
532 buffer_clone->setChild(dit, child_clone);
534 buffer_clone->d->macro_lock = false;
539 Buffer * Buffer::cloneBufferOnly() const {
540 cloned_buffers.push_back(new CloneList());
541 CloneList * clones = cloned_buffers.back();
542 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
543 clones->insert(buffer_clone);
544 buffer_clone->d->clone_list_ = clones;
545 // we won't be cloning the children
546 buffer_clone->d->children_positions.clear();
551 bool Buffer::isClone() const
553 return d->cloned_buffer_;
557 void Buffer::changed(bool update_metrics) const
560 d->wa_->redrawAll(update_metrics);
564 frontend::WorkAreaManager & Buffer::workAreaManager() const
566 LASSERT(d->wa_, /**/);
571 Text & Buffer::text() const
573 return d->inset->text();
577 Inset & Buffer::inset() const
583 BufferParams & Buffer::params()
589 BufferParams const & Buffer::params() const
595 ParagraphList & Buffer::paragraphs()
597 return text().paragraphs();
601 ParagraphList const & Buffer::paragraphs() const
603 return text().paragraphs();
607 LyXVC & Buffer::lyxvc()
613 LyXVC const & Buffer::lyxvc() const
619 string const Buffer::temppath() const
621 return d->temppath.absFileName();
625 TexRow & Buffer::texrow()
631 TexRow const & Buffer::texrow() const
637 TocBackend & Buffer::tocBackend() const
639 return d->toc_backend;
643 Undo & Buffer::undo()
649 void Buffer::setChild(DocIterator const & dit, Buffer * child)
651 d->children_positions[child] = dit;
655 string Buffer::latexName(bool const no_path) const
657 FileName latex_name =
658 makeLatexName(d->exportFileName());
659 return no_path ? latex_name.onlyFileName()
660 : latex_name.absFileName();
664 FileName Buffer::Impl::exportFileName() const
666 docstring const branch_suffix =
667 params.branchlist().getFileNameSuffix();
668 if (branch_suffix.empty())
671 string const name = filename.onlyFileNameWithoutExt()
672 + to_utf8(branch_suffix);
673 FileName res(filename.onlyPath().absFileName() + "/" + name);
674 res.changeExtension(filename.extension());
680 string Buffer::logName(LogType * type) const
682 string const filename = latexName(false);
684 if (filename.empty()) {
690 string const path = temppath();
692 FileName const fname(addName(temppath(),
693 onlyFileName(changeExtension(filename,
696 // FIXME: how do we know this is the name of the build log?
697 FileName const bname(
698 addName(path, onlyFileName(
699 changeExtension(filename,
700 formats.extension(params().bufferFormat()) + ".out"))));
702 // Also consider the master buffer log file
703 FileName masterfname = fname;
705 if (masterBuffer() != this) {
706 string const mlogfile = masterBuffer()->logName(&mtype);
707 masterfname = FileName(mlogfile);
710 // If no Latex log or Build log is newer, show Build log
711 if (bname.exists() &&
712 ((!fname.exists() && !masterfname.exists())
713 || (fname.lastModified() < bname.lastModified()
714 && masterfname.lastModified() < bname.lastModified()))) {
715 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
718 return bname.absFileName();
719 // If we have a newer master file log or only a master log, show this
720 } else if (fname != masterfname
721 && (!fname.exists() && (masterfname.exists()
722 || fname.lastModified() < masterfname.lastModified()))) {
723 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
726 return masterfname.absFileName();
728 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
731 return fname.absFileName();
735 void Buffer::setReadonly(bool const flag)
737 if (d->read_only != flag) {
744 void Buffer::setFileName(FileName const & fname)
747 setReadonly(d->filename.isReadOnly());
753 int Buffer::readHeader(Lexer & lex)
755 int unknown_tokens = 0;
757 int begin_header_line = -1;
759 // Initialize parameters that may be/go lacking in header:
760 params().branchlist().clear();
761 params().preamble.erase();
762 params().options.erase();
763 params().master.erase();
764 params().float_placement.erase();
765 params().paperwidth.erase();
766 params().paperheight.erase();
767 params().leftmargin.erase();
768 params().rightmargin.erase();
769 params().topmargin.erase();
770 params().bottommargin.erase();
771 params().headheight.erase();
772 params().headsep.erase();
773 params().footskip.erase();
774 params().columnsep.erase();
775 params().fonts_cjk.erase();
776 params().listings_params.clear();
777 params().clearLayoutModules();
778 params().clearRemovedModules();
779 params().clearIncludedChildren();
780 params().pdfoptions().clear();
781 params().indiceslist().clear();
782 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
783 params().isbackgroundcolor = false;
784 params().fontcolor = RGBColor(0, 0, 0);
785 params().isfontcolor = false;
786 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
787 params().boxbgcolor = RGBColor(0xFF, 0, 0);
788 params().html_latex_start.clear();
789 params().html_latex_end.clear();
790 params().html_math_img_scale = 1.0;
791 params().output_sync_macro.erase();
793 for (int i = 0; i < 4; ++i) {
794 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
795 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
798 ErrorList & errorList = d->errorLists["Parse"];
807 if (token == "\\end_header")
811 if (token == "\\begin_header") {
812 begin_header_line = line;
816 LYXERR(Debug::PARSER, "Handling document header token: `"
819 string unknown = params().readToken(lex, token, d->filename.onlyPath());
820 if (!unknown.empty()) {
821 if (unknown[0] != '\\' && token == "\\textclass") {
822 Alert::warning(_("Unknown document class"),
823 bformat(_("Using the default document class, because the "
824 "class %1$s is unknown."), from_utf8(unknown)));
827 docstring const s = bformat(_("Unknown token: "
831 errorList.push_back(ErrorItem(_("Document header error"),
836 if (begin_header_line) {
837 docstring const s = _("\\begin_header is missing");
838 errorList.push_back(ErrorItem(_("Document header error"),
842 params().makeDocumentClass();
844 return unknown_tokens;
849 // changed to be public and have one parameter
850 // Returns true if "\end_document" is not read (Asger)
851 bool Buffer::readDocument(Lexer & lex)
853 ErrorList & errorList = d->errorLists["Parse"];
856 // remove dummy empty par
857 paragraphs().clear();
859 if (!lex.checkFor("\\begin_document")) {
860 docstring const s = _("\\begin_document is missing");
861 errorList.push_back(ErrorItem(_("Document header error"),
867 if (params().outputChanges) {
868 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
869 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
870 LaTeXFeatures::isAvailable("xcolor");
872 if (!dvipost && !xcolorulem) {
873 Alert::warning(_("Changes not shown in LaTeX output"),
874 _("Changes will not be highlighted in LaTeX output, "
875 "because neither dvipost nor xcolor/ulem are installed.\n"
876 "Please install these packages or redefine "
877 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
878 } else if (!xcolorulem) {
879 Alert::warning(_("Changes not shown in LaTeX output"),
880 _("Changes will not be highlighted in LaTeX output "
881 "when using pdflatex, because xcolor and ulem are not installed.\n"
882 "Please install both packages or redefine "
883 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
887 if (!params().master.empty()) {
888 FileName const master_file = makeAbsPath(params().master,
889 onlyPath(absFileName()));
890 if (isLyXFileName(master_file.absFileName())) {
892 checkAndLoadLyXFile(master_file, true);
894 // necessary e.g. after a reload
895 // to re-register the child (bug 5873)
896 // FIXME: clean up updateMacros (here, only
897 // child registering is needed).
898 master->updateMacros();
899 // set master as master buffer, but only
900 // if we are a real child
901 if (master->isChild(this))
903 // if the master is not fully loaded
904 // it is probably just loading this
905 // child. No warning needed then.
906 else if (master->isFullyLoaded())
907 LYXERR0("The master '"
909 << "' assigned to this document ("
911 << ") does not include "
912 "this document. Ignoring the master assignment.");
917 // assure we have a default index
918 params().indiceslist().addDefault(B_("Index"));
921 bool const res = text().read(lex, errorList, d->inset);
923 // inform parent buffer about local macros
925 Buffer const * pbuf = parent();
926 UserMacroSet::const_iterator cit = usermacros.begin();
927 UserMacroSet::const_iterator end = usermacros.end();
928 for (; cit != end; ++cit)
929 pbuf->usermacros.insert(*cit);
933 updateMacroInstances(InternalUpdate);
938 bool Buffer::readString(string const & s)
940 params().compressed = false;
945 FileName const fn = FileName::tempName("Buffer_readString");
948 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
949 if (ret_plf != ReadSuccess)
952 if (file_format != LYX_FORMAT) {
953 // We need to call lyx2lyx, so write the input to a file
954 ofstream os(fn.toFilesystemEncoding().c_str());
958 return readFile(fn) == ReadSuccess;
961 if (readDocument(lex))
967 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
971 if (!lex.setFile(fname)) {
972 Alert::error(_("File Not Found"),
973 bformat(_("Unable to open file `%1$s'."),
974 from_utf8(fn.absFileName())));
975 return ReadFileNotFound;
979 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
980 if (ret_plf != ReadSuccess)
983 if (file_format != LYX_FORMAT) {
985 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
986 if (ret_clf != ReadSuccess)
988 return readFile(tmpFile);
991 // FIXME: InsetInfo needs to know whether the file is under VCS
992 // during the parse process, so this has to be done before.
993 lyxvc().file_found_hook(d->filename);
995 if (readDocument(lex)) {
996 Alert::error(_("Document format failure"),
997 bformat(_("%1$s ended unexpectedly, which means"
998 " that it is probably corrupted."),
999 from_utf8(fn.absFileName())));
1000 return ReadDocumentFailure;
1003 d->file_fully_loaded = true;
1004 d->read_only = !d->filename.isWritable();
1005 params().compressed = formats.isZippedFile(d->filename);
1011 bool Buffer::isFullyLoaded() const
1013 return d->file_fully_loaded;
1017 void Buffer::setFullyLoaded(bool value)
1019 d->file_fully_loaded = value;
1023 PreviewLoader * Buffer::loader() const
1025 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1027 if (!d->preview_loader_)
1028 d->preview_loader_ = new PreviewLoader(*this);
1029 return d->preview_loader_;
1033 void Buffer::removePreviews() const
1035 delete d->preview_loader_;
1036 d->preview_loader_ = 0;
1040 void Buffer::updatePreviews() const
1042 PreviewLoader * ploader = loader();
1046 InsetIterator it = inset_iterator_begin(*d->inset);
1047 InsetIterator const end = inset_iterator_end(*d->inset);
1048 for (; it != end; ++it)
1049 it->addPreview(it, *ploader);
1051 ploader->startLoading();
1055 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1056 FileName const & fn, int & file_format) const
1058 if(!lex.checkFor("\\lyxformat")) {
1059 Alert::error(_("Document format failure"),
1060 bformat(_("%1$s is not a readable LyX document."),
1061 from_utf8(fn.absFileName())));
1062 return ReadNoLyXFormat;
1068 // LyX formats 217 and earlier were written as 2.17. This corresponds
1069 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1070 // these cases. See also: www.lyx.org/trac/changeset/1313.
1071 size_t dot = tmp_format.find_first_of(".,");
1072 if (dot != string::npos)
1073 tmp_format.erase(dot, 1);
1075 file_format = convert<int>(tmp_format);
1080 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1081 FileName & tmpfile, int from_format)
1083 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1084 if(tmpfile.empty()) {
1085 Alert::error(_("Conversion failed"),
1086 bformat(_("%1$s is from a different"
1087 " version of LyX, but a temporary"
1088 " file for converting it could"
1089 " not be created."),
1090 from_utf8(fn.absFileName())));
1091 return LyX2LyXNoTempFile;
1094 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1095 if (lyx2lyx.empty()) {
1096 Alert::error(_("Conversion script not found"),
1097 bformat(_("%1$s is from a different"
1098 " version of LyX, but the"
1099 " conversion script lyx2lyx"
1100 " could not be found."),
1101 from_utf8(fn.absFileName())));
1102 return LyX2LyXNotFound;
1106 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1107 ostringstream command;
1108 command << os::python()
1109 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1110 << " -t " << convert<string>(LYX_FORMAT)
1111 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1112 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1113 string const command_str = command.str();
1115 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1117 cmd_ret const ret = runCommand(command_str);
1118 if (ret.first != 0) {
1119 if (from_format < LYX_FORMAT) {
1120 Alert::error(_("Conversion script failed"),
1121 bformat(_("%1$s is from an older version"
1122 " of LyX and the lyx2lyx script"
1123 " failed to convert it."),
1124 from_utf8(fn.absFileName())));
1125 return LyX2LyXOlderFormat;
1127 Alert::error(_("Conversion script failed"),
1128 bformat(_("%1$s is from a newer version"
1129 " of LyX and the lyx2lyx script"
1130 " failed to convert it."),
1131 from_utf8(fn.absFileName())));
1132 return LyX2LyXNewerFormat;
1139 // Should probably be moved to somewhere else: BufferView? GuiView?
1140 bool Buffer::save() const
1142 docstring const file = makeDisplayPath(absFileName(), 20);
1143 d->filename.refresh();
1145 // check the read-only status before moving the file as a backup
1146 if (d->filename.exists()) {
1147 bool const read_only = !d->filename.isWritable();
1149 Alert::warning(_("File is read-only"),
1150 bformat(_("The file %1$s cannot be written because it "
1151 "is marked as read-only."), file));
1156 // ask if the disk file has been externally modified (use checksum method)
1157 if (fileName().exists() && isExternallyModified(checksum_method)) {
1159 bformat(_("Document %1$s has been externally modified. "
1160 "Are you sure you want to overwrite this file?"), file);
1161 int const ret = Alert::prompt(_("Overwrite modified file?"),
1162 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1167 // We don't need autosaves in the immediate future. (Asger)
1168 resetAutosaveTimers();
1170 FileName backupName;
1171 bool madeBackup = false;
1173 // make a backup if the file already exists
1174 if (lyxrc.make_backup && fileName().exists()) {
1175 backupName = FileName(absFileName() + '~');
1176 if (!lyxrc.backupdir_path.empty()) {
1177 string const mangledName =
1178 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1179 backupName = FileName(addName(lyxrc.backupdir_path,
1183 // Except file is symlink do not copy because of #6587.
1184 // Hard links have bad luck.
1185 if (fileName().isSymLink())
1186 madeBackup = fileName().copyTo(backupName);
1188 madeBackup = fileName().moveTo(backupName);
1191 Alert::error(_("Backup failure"),
1192 bformat(_("Cannot create backup file %1$s.\n"
1193 "Please check whether the directory exists and is writable."),
1194 from_utf8(backupName.absFileName())));
1195 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1199 if (writeFile(d->filename)) {
1203 // Saving failed, so backup is not backup
1205 backupName.moveTo(d->filename);
1211 bool Buffer::writeFile(FileName const & fname) const
1213 // FIXME Do we need to do these here? I don't think writing
1214 // the LyX file depends upon it. (RGH)
1216 // updateMacroInstances();
1218 if (d->read_only && fname == d->filename)
1221 bool retval = false;
1223 docstring const str = bformat(_("Saving document %1$s..."),
1224 makeDisplayPath(fname.absFileName()));
1227 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1229 if (params().compressed) {
1230 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1231 retval = ofs && write(ofs);
1233 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1234 retval = ofs && write(ofs);
1238 message(str + _(" could not write file!"));
1243 // removeAutosaveFile();
1246 message(str + _(" done."));
1252 docstring Buffer::emergencyWrite()
1254 // No need to save if the buffer has not changed.
1258 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1260 docstring user_message = bformat(
1261 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1263 // We try to save three places:
1264 // 1) Same place as document. Unless it is an unnamed doc.
1266 string s = absFileName();
1269 if (writeFile(FileName(s))) {
1271 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1272 return user_message;
1274 user_message += " " + _("Save failed! Trying again...\n");
1278 // 2) In HOME directory.
1279 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1281 lyxerr << ' ' << s << endl;
1282 if (writeFile(FileName(s))) {
1284 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1285 return user_message;
1288 user_message += " " + _("Save failed! Trying yet again...\n");
1290 // 3) In "/tmp" directory.
1291 // MakeAbsPath to prepend the current
1292 // drive letter on OS/2
1293 s = addName(package().temp_dir().absFileName(), absFileName());
1295 lyxerr << ' ' << s << endl;
1296 if (writeFile(FileName(s))) {
1298 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1299 return user_message;
1302 user_message += " " + _("Save failed! Bummer. Document is lost.");
1305 return user_message;
1309 bool Buffer::write(ostream & ofs) const
1312 // Use the standard "C" locale for file output.
1313 ofs.imbue(locale::classic());
1316 // The top of the file should not be written by params().
1318 // write out a comment in the top of the file
1319 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1320 << " created this file. For more info see http://www.lyx.org/\n"
1321 << "\\lyxformat " << LYX_FORMAT << "\n"
1322 << "\\begin_document\n";
1324 /// For each author, set 'used' to true if there is a change
1325 /// by this author in the document; otherwise set it to 'false'.
1326 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1327 AuthorList::Authors::const_iterator a_end = params().authors().end();
1328 for (; a_it != a_end; ++a_it)
1329 a_it->setUsed(false);
1331 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1332 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1333 for ( ; it != end; ++it)
1334 it->checkAuthors(params().authors());
1336 // now write out the buffer parameters.
1337 ofs << "\\begin_header\n";
1338 params().writeFile(ofs);
1339 ofs << "\\end_header\n";
1342 ofs << "\n\\begin_body\n";
1344 ofs << "\n\\end_body\n";
1346 // Write marker that shows file is complete
1347 ofs << "\\end_document" << endl;
1349 // Shouldn't really be needed....
1352 // how to check if close went ok?
1353 // Following is an attempt... (BE 20001011)
1355 // good() returns false if any error occured, including some
1356 // formatting error.
1357 // bad() returns true if something bad happened in the buffer,
1358 // which should include file system full errors.
1363 lyxerr << "File was not closed properly." << endl;
1370 bool Buffer::makeLaTeXFile(FileName const & fname,
1371 string const & original_path,
1372 OutputParams const & runparams_in,
1373 OutputWhat output) const
1375 OutputParams runparams = runparams_in;
1377 // This is necessary for LuaTeX/XeTeX with tex fonts.
1378 // See FIXME in BufferParams::encoding()
1379 if (runparams.isFullUnicode())
1380 runparams.encoding = encodings.fromLyXName("utf8-plain");
1382 string const encoding = runparams.encoding->iconvName();
1383 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1386 try { ofs.reset(encoding); }
1387 catch (iconv_codecvt_facet_exception & e) {
1388 lyxerr << "Caught iconv exception: " << e.what() << endl;
1389 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1390 "verify that the support software for your encoding (%1$s) is "
1391 "properly installed"), from_ascii(encoding)));
1394 if (!openFileWrite(ofs, fname))
1397 //TexStream ts(ofs.rdbuf(), &texrow());
1398 ErrorList & errorList = d->errorLists["Export"];
1400 bool failed_export = false;
1401 otexstream os(ofs, d->texrow);
1403 // make sure we are ready to export
1404 // this needs to be done before we validate
1405 // FIXME Do we need to do this all the time? I.e., in children
1406 // of a master we are exporting?
1408 updateMacroInstances(OutputUpdate);
1411 os.texrow().reset();
1412 writeLaTeXSource(os, original_path, runparams, output);
1414 catch (EncodingException & e) {
1415 odocstringstream ods;
1416 ods.put(e.failed_char);
1418 oss << "0x" << hex << e.failed_char << dec;
1419 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1420 " (code point %2$s)"),
1421 ods.str(), from_utf8(oss.str()));
1422 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1423 "representable in the chosen encoding.\n"
1424 "Changing the document encoding to utf8 could help."),
1425 e.par_id, e.pos, e.pos + 1));
1426 failed_export = true;
1428 catch (iconv_codecvt_facet_exception & e) {
1429 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1430 _(e.what()), -1, 0, 0));
1431 failed_export = true;
1433 catch (exception const & e) {
1434 errorList.push_back(ErrorItem(_("conversion failed"),
1435 _(e.what()), -1, 0, 0));
1436 failed_export = true;
1439 lyxerr << "Caught some really weird exception..." << endl;
1445 failed_export = true;
1446 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1450 return !failed_export;
1454 void Buffer::writeLaTeXSource(otexstream & os,
1455 string const & original_path,
1456 OutputParams const & runparams_in,
1457 OutputWhat output) const
1459 // The child documents, if any, shall be already loaded at this point.
1461 OutputParams runparams = runparams_in;
1463 // Classify the unicode characters appearing in math insets
1464 Encodings::initUnicodeMath(*this);
1466 // validate the buffer.
1467 LYXERR(Debug::LATEX, " Validating buffer...");
1468 LaTeXFeatures features(*this, params(), runparams);
1470 LYXERR(Debug::LATEX, " Buffer validation done.");
1472 bool const output_preamble =
1473 output == FullSource || output == OnlyPreamble;
1474 bool const output_body =
1475 output == FullSource || output == OnlyBody;
1477 // The starting paragraph of the coming rows is the
1478 // first paragraph of the document. (Asger)
1479 if (output_preamble && runparams.nice) {
1480 os << "%% LyX " << lyx_version << " created this file. "
1481 "For more info, see http://www.lyx.org/.\n"
1482 "%% Do not edit unless you really know what "
1485 LYXERR(Debug::INFO, "lyx document header finished");
1487 // There are a few differences between nice LaTeX and usual files:
1488 // usual files have \batchmode and special input@path to allow
1489 // inclusion of figures specified by an explicitly relative path
1490 // (i.e., a path starting with './' or '../') with either \input or
1491 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1492 // input@path is set when the actual parameter original_path is set.
1493 // This is done for usual tex-file, but not for nice-latex-file.
1494 // (Matthias 250696)
1495 // Note that input@path is only needed for something the user does
1496 // in the preamble, included .tex files or ERT, files included by
1497 // LyX work without it.
1498 if (output_preamble) {
1499 if (!runparams.nice) {
1500 // code for usual, NOT nice-latex-file
1501 os << "\\batchmode\n"; // changed from \nonstopmode
1503 if (!original_path.empty()) {
1505 // We don't know the encoding of inputpath
1506 docstring const inputpath = from_utf8(original_path);
1507 docstring uncodable_glyphs;
1508 Encoding const * const enc = runparams.encoding;
1510 for (size_t n = 0; n < inputpath.size(); ++n) {
1511 docstring const glyph =
1512 docstring(1, inputpath[n]);
1513 if (enc->latexChar(inputpath[n], true) != glyph) {
1514 LYXERR0("Uncodable character '"
1516 << "' in input path!");
1517 uncodable_glyphs += glyph;
1522 // warn user if we found uncodable glyphs.
1523 if (!uncodable_glyphs.empty()) {
1524 frontend::Alert::warning(
1525 _("Uncodable character in file path"),
1527 _("The path of your document\n"
1529 "contains glyphs that are unknown "
1530 "in the current document encoding "
1531 "(namely %2$s). This may result in "
1532 "incomplete output, unless "
1533 "TEXINPUTS contains the document "
1534 "directory and you don't use "
1535 "explicitly relative paths (i.e., "
1536 "paths starting with './' or "
1537 "'../') in the preamble or in ERT."
1538 "\n\nIn case of problems, choose "
1539 "an appropriate document encoding\n"
1540 "(such as utf8) or change the "
1542 inputpath, uncodable_glyphs));
1545 support::latex_path(original_path);
1546 if (contains(docdir, '#')) {
1547 docdir = subst(docdir, "#", "\\#");
1548 os << "\\catcode`\\#=11"
1549 "\\def\\#{#}\\catcode`\\#=6\n";
1551 if (contains(docdir, '%')) {
1552 docdir = subst(docdir, "%", "\\%");
1553 os << "\\catcode`\\%=11"
1554 "\\def\\%{%}\\catcode`\\%=14\n";
1556 os << "\\makeatletter\n"
1557 << "\\def\\input@path{{"
1558 << docdir << "/}}\n"
1559 << "\\makeatother\n";
1563 // get parent macros (if this buffer has a parent) which will be
1564 // written at the document begin further down.
1565 MacroSet parentMacros;
1566 listParentMacros(parentMacros, features);
1568 runparams.use_polyglossia = features.usePolyglossia();
1569 // Write the preamble
1570 runparams.use_babel = params().writeLaTeX(os, features,
1571 d->filename.onlyPath());
1573 runparams.use_japanese = features.isRequired("japanese");
1579 os << "\\begin{document}\n";
1581 // output the parent macros
1582 MacroSet::iterator it = parentMacros.begin();
1583 MacroSet::iterator end = parentMacros.end();
1584 for (; it != end; ++it) {
1585 int num_lines = (*it)->write(os.os(), true);
1586 os.texrow().newlines(num_lines);
1589 } // output_preamble
1591 os.texrow().start(paragraphs().begin()->id(), 0);
1593 LYXERR(Debug::INFO, "preamble finished, now the body.");
1595 // if we are doing a real file with body, even if this is the
1596 // child of some other buffer, let's cut the link here.
1597 // This happens for example if only a child document is printed.
1598 Buffer const * save_parent = 0;
1599 if (output_preamble) {
1600 save_parent = d->parent();
1605 latexParagraphs(*this, text(), os, runparams);
1607 // Restore the parenthood if needed
1608 if (output_preamble)
1609 d->setParent(save_parent);
1611 // add this just in case after all the paragraphs
1614 if (output_preamble) {
1615 os << "\\end{document}\n";
1616 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1618 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1620 runparams_in.encoding = runparams.encoding;
1622 // Just to be sure. (Asger)
1623 os.texrow().newline();
1625 //for (int i = 0; i<d->texrow.rows(); i++) {
1627 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1628 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1631 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1632 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1636 void Buffer::makeDocBookFile(FileName const & fname,
1637 OutputParams const & runparams,
1638 OutputWhat output) const
1640 LYXERR(Debug::LATEX, "makeDocBookFile...");
1643 if (!openFileWrite(ofs, fname))
1646 // make sure we are ready to export
1647 // this needs to be done before we validate
1649 updateMacroInstances(OutputUpdate);
1651 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1655 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1659 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1660 OutputParams const & runparams,
1661 OutputWhat output) const
1663 LaTeXFeatures features(*this, params(), runparams);
1668 DocumentClass const & tclass = params().documentClass();
1669 string const top_element = tclass.latexname();
1671 bool const output_preamble =
1672 output == FullSource || output == OnlyPreamble;
1673 bool const output_body =
1674 output == FullSource || output == OnlyBody;
1676 if (output_preamble) {
1677 if (runparams.flavor == OutputParams::XML)
1678 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1681 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1684 if (! tclass.class_header().empty())
1685 os << from_ascii(tclass.class_header());
1686 else if (runparams.flavor == OutputParams::XML)
1687 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1688 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1690 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1692 docstring preamble = from_utf8(params().preamble);
1693 if (runparams.flavor != OutputParams::XML ) {
1694 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1695 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1696 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1697 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1700 string const name = runparams.nice
1701 ? changeExtension(absFileName(), ".sgml") : fname;
1702 preamble += features.getIncludedFiles(name);
1703 preamble += features.getLyXSGMLEntities();
1705 if (!preamble.empty()) {
1706 os << "\n [ " << preamble << " ]";
1712 string top = top_element;
1714 if (runparams.flavor == OutputParams::XML)
1715 top += params().language->code();
1717 top += params().language->code().substr(0, 2);
1720 if (!params().options.empty()) {
1722 top += params().options;
1725 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1726 << " file was created by LyX " << lyx_version
1727 << "\n See http://www.lyx.org/ for more information -->\n";
1729 params().documentClass().counters().reset();
1731 sgml::openTag(os, top);
1733 docbookParagraphs(text(), *this, os, runparams);
1734 sgml::closeTag(os, top_element);
1739 void Buffer::makeLyXHTMLFile(FileName const & fname,
1740 OutputParams const & runparams) const
1742 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1745 if (!openFileWrite(ofs, fname))
1748 // make sure we are ready to export
1749 // this has to be done before we validate
1750 updateBuffer(UpdateMaster, OutputUpdate);
1751 updateMacroInstances(OutputUpdate);
1753 writeLyXHTMLSource(ofs, runparams, FullSource);
1757 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1761 void Buffer::writeLyXHTMLSource(odocstream & os,
1762 OutputParams const & runparams,
1763 OutputWhat output) const
1765 LaTeXFeatures features(*this, params(), runparams);
1767 d->bibinfo_.makeCitationLabels(*this);
1769 bool const output_preamble =
1770 output == FullSource || output == OnlyPreamble;
1771 bool const output_body =
1772 output == FullSource || output == OnlyBody;
1774 if (output_preamble) {
1775 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1776 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n"
1777 // FIXME Language should be set properly.
1778 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1780 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1781 // FIXME Presumably need to set this right
1782 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1784 docstring const & doctitle = features.htmlTitle();
1786 << (doctitle.empty() ?
1787 from_ascii("LyX Document") :
1788 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1791 docstring styles = features.getTClassHTMLPreamble();
1792 if (!styles.empty())
1793 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1795 styles = from_utf8(features.getPreambleSnippets());
1796 if (!styles.empty())
1797 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1799 // we will collect CSS information in a stream, and then output it
1800 // either here, as part of the header, or else in a separate file.
1801 odocstringstream css;
1802 styles = from_utf8(features.getCSSSnippets());
1803 if (!styles.empty())
1804 css << "/* LyX Provided Styles */\n" << styles << '\n';
1806 styles = features.getTClassHTMLStyles();
1807 if (!styles.empty())
1808 css << "/* Layout-provided Styles */\n" << styles << '\n';
1810 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1811 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1812 if (needfg || needbg) {
1813 css << "\nbody {\n";
1816 << from_ascii(X11hexname(params().fontcolor))
1819 css << " background-color: "
1820 << from_ascii(X11hexname(params().backgroundcolor))
1825 docstring const dstyles = css.str();
1826 if (!dstyles.empty()) {
1827 bool written = false;
1828 if (params().html_css_as_file) {
1829 // open a file for CSS info
1831 string const fcssname = addName(temppath(), "docstyle.css");
1832 FileName const fcssfile = FileName(fcssname);
1833 if (openFileWrite(ocss, fcssfile)) {
1837 // write link to header
1838 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1840 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1843 // we are here if the CSS is supposed to be written to the header
1844 // or if we failed to write it to an external file.
1846 os << "<style type='text/css'>\n"
1857 params().documentClass().counters().reset();
1858 xhtmlParagraphs(text(), *this, xs, runparams);
1862 if (output_preamble)
1867 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1868 // Other flags: -wall -v0 -x
1869 int Buffer::runChktex()
1873 // get LaTeX-Filename
1874 FileName const path(temppath());
1875 string const name = addName(path.absFileName(), latexName());
1876 string const org_path = filePath();
1878 PathChanger p(path); // path to LaTeX file
1879 message(_("Running chktex..."));
1881 // Generate the LaTeX file if neccessary
1882 OutputParams runparams(¶ms().encoding());
1883 runparams.flavor = OutputParams::LATEX;
1884 runparams.nice = false;
1885 runparams.linelen = lyxrc.plaintext_linelen;
1886 makeLaTeXFile(FileName(name), org_path, runparams);
1889 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1890 int const res = chktex.run(terr); // run chktex
1893 Alert::error(_("chktex failure"),
1894 _("Could not run chktex successfully."));
1895 } else if (res > 0) {
1896 ErrorList & errlist = d->errorLists["ChkTeX"];
1898 bufferErrors(terr, errlist);
1909 void Buffer::validate(LaTeXFeatures & features) const
1911 params().validate(features);
1913 for_each(paragraphs().begin(), paragraphs().end(),
1914 bind(&Paragraph::validate, _1, ref(features)));
1916 if (lyxerr.debugging(Debug::LATEX)) {
1917 features.showStruct();
1922 void Buffer::getLabelList(vector<docstring> & list) const
1924 // If this is a child document, use the master's list instead.
1926 masterBuffer()->getLabelList(list);
1931 Toc & toc = d->toc_backend.toc("label");
1932 TocIterator toc_it = toc.begin();
1933 TocIterator end = toc.end();
1934 for (; toc_it != end; ++toc_it) {
1935 if (toc_it->depth() == 0)
1936 list.push_back(toc_it->str());
1941 void Buffer::updateBibfilesCache(UpdateScope scope) const
1943 // FIXME This is probably unnecssary, given where we call this.
1944 // If this is a child document, use the parent's cache instead.
1945 if (parent() && scope != UpdateChildOnly) {
1946 masterBuffer()->updateBibfilesCache();
1950 d->bibfiles_cache_.clear();
1951 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1952 if (it->lyxCode() == BIBTEX_CODE) {
1953 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1954 support::FileNameList const bibfiles = inset.getBibFiles();
1955 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1958 } else if (it->lyxCode() == INCLUDE_CODE) {
1959 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1960 Buffer const * const incbuf = inset.getChildBuffer();
1963 support::FileNameList const & bibfiles =
1964 incbuf->getBibfilesCache(UpdateChildOnly);
1965 if (!bibfiles.empty()) {
1966 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1972 d->bibfile_cache_valid_ = true;
1973 d->bibinfo_cache_valid_ = false;
1974 d->cite_labels_valid_ = false;
1978 void Buffer::invalidateBibinfoCache() const
1980 d->bibinfo_cache_valid_ = false;
1981 d->cite_labels_valid_ = false;
1982 // also invalidate the cache for the parent buffer
1983 Buffer const * const pbuf = d->parent();
1985 pbuf->invalidateBibinfoCache();
1989 void Buffer::invalidateBibfileCache() const
1991 d->bibfile_cache_valid_ = false;
1992 d->bibinfo_cache_valid_ = false;
1993 d->cite_labels_valid_ = false;
1994 // also invalidate the cache for the parent buffer
1995 Buffer const * const pbuf = d->parent();
1997 pbuf->invalidateBibfileCache();
2001 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2003 // FIXME This is probably unnecessary, given where we call this.
2004 // If this is a child document, use the master's cache instead.
2005 Buffer const * const pbuf = masterBuffer();
2006 if (pbuf != this && scope != UpdateChildOnly)
2007 return pbuf->getBibfilesCache();
2009 if (!d->bibfile_cache_valid_)
2010 this->updateBibfilesCache(scope);
2012 return d->bibfiles_cache_;
2016 BiblioInfo const & Buffer::masterBibInfo() const
2018 Buffer const * const tmp = masterBuffer();
2020 return tmp->masterBibInfo();
2025 void Buffer::checkIfBibInfoCacheIsValid() const
2027 // use the master's cache
2028 Buffer const * const tmp = masterBuffer();
2030 tmp->checkIfBibInfoCacheIsValid();
2034 // compare the cached timestamps with the actual ones.
2035 FileNameList const & bibfiles_cache = getBibfilesCache();
2036 FileNameList::const_iterator ei = bibfiles_cache.begin();
2037 FileNameList::const_iterator en = bibfiles_cache.end();
2038 for (; ei != en; ++ ei) {
2039 time_t lastw = ei->lastModified();
2040 time_t prevw = d->bibfile_status_[*ei];
2041 if (lastw != prevw) {
2042 d->bibinfo_cache_valid_ = false;
2043 d->cite_labels_valid_ = false;
2044 d->bibfile_status_[*ei] = lastw;
2050 void Buffer::reloadBibInfoCache() const
2052 // use the master's cache
2053 Buffer const * const tmp = masterBuffer();
2055 tmp->reloadBibInfoCache();
2059 checkIfBibInfoCacheIsValid();
2060 if (d->bibinfo_cache_valid_)
2063 d->bibinfo_.clear();
2065 d->bibinfo_cache_valid_ = true;
2069 void Buffer::collectBibKeys() const
2071 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2072 it->collectBibKeys(it);
2076 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2078 Buffer const * tmp = masterBuffer();
2079 BiblioInfo & masterbi = (tmp == this) ?
2080 d->bibinfo_ : tmp->d->bibinfo_;
2081 masterbi.mergeBiblioInfo(bi);
2085 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2087 Buffer const * tmp = masterBuffer();
2088 BiblioInfo & masterbi = (tmp == this) ?
2089 d->bibinfo_ : tmp->d->bibinfo_;
2094 bool Buffer::citeLabelsValid() const
2096 return masterBuffer()->d->cite_labels_valid_;
2100 void Buffer::removeBiblioTempFiles() const
2102 // We remove files that contain LaTeX commands specific to the
2103 // particular bibliographic style being used, in order to avoid
2104 // LaTeX errors when we switch style.
2105 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2106 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2107 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2108 aux_file.removeFile();
2109 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2110 bbl_file.removeFile();
2111 // Also for the parent buffer
2112 Buffer const * const pbuf = parent();
2114 pbuf->removeBiblioTempFiles();
2118 bool Buffer::isDepClean(string const & name) const
2120 DepClean::const_iterator const it = d->dep_clean.find(name);
2121 if (it == d->dep_clean.end())
2127 void Buffer::markDepClean(string const & name)
2129 d->dep_clean[name] = true;
2133 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2136 // FIXME? if there is an Buffer LFUN that can be dispatched even
2137 // if internal, put a switch '(cmd.action)' here.
2143 switch (cmd.action()) {
2145 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2146 flag.setOnOff(isReadonly());
2149 // FIXME: There is need for a command-line import.
2150 //case LFUN_BUFFER_IMPORT:
2152 case LFUN_BUFFER_AUTO_SAVE:
2155 case LFUN_BUFFER_EXPORT_CUSTOM:
2156 // FIXME: Nothing to check here?
2159 case LFUN_BUFFER_EXPORT: {
2160 docstring const arg = cmd.argument();
2161 if (arg == "custom") {
2165 string format = to_utf8(arg);
2166 size_t pos = format.find(' ');
2167 if (pos != string::npos)
2168 format = format.substr(0, pos);
2169 enable = params().isExportable(format);
2171 flag.message(bformat(
2172 _("Don't know how to export to format: %1$s"), arg));
2176 case LFUN_BUFFER_CHKTEX:
2177 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2180 case LFUN_BUILD_PROGRAM:
2181 enable = params().isExportable("program");
2184 case LFUN_BRANCH_ADD:
2185 case LFUN_BRANCHES_RENAME:
2186 case LFUN_BUFFER_PRINT:
2187 // if no Buffer is present, then of course we won't be called!
2190 case LFUN_BUFFER_LANGUAGE:
2191 enable = !isReadonly();
2197 flag.setEnabled(enable);
2202 void Buffer::dispatch(string const & command, DispatchResult & result)
2204 return dispatch(lyxaction.lookupFunc(command), result);
2208 // NOTE We can end up here even if we have no GUI, because we are called
2209 // by LyX::exec to handled command-line requests. So we may need to check
2210 // whether we have a GUI or not. The boolean use_gui holds this information.
2211 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2214 // FIXME? if there is an Buffer LFUN that can be dispatched even
2215 // if internal, put a switch '(cmd.action())' here.
2216 dr.dispatched(false);
2219 string const argument = to_utf8(func.argument());
2220 // We'll set this back to false if need be.
2221 bool dispatched = true;
2222 undo().beginUndoGroup();
2224 switch (func.action()) {
2225 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2226 if (lyxvc().inUse())
2227 lyxvc().toggleReadOnly();
2229 setReadonly(!isReadonly());
2232 case LFUN_BUFFER_EXPORT: {
2233 ExportStatus const status = doExport(argument, false);
2234 dr.setError(status != ExportSuccess);
2235 if (status != ExportSuccess)
2236 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2241 case LFUN_BUILD_PROGRAM:
2242 doExport("program", true);
2245 case LFUN_BUFFER_CHKTEX:
2249 case LFUN_BUFFER_EXPORT_CUSTOM: {
2251 string command = split(argument, format_name, ' ');
2252 Format const * format = formats.getFormat(format_name);
2254 lyxerr << "Format \"" << format_name
2255 << "\" not recognized!"
2260 // The name of the file created by the conversion process
2263 // Output to filename
2264 if (format->name() == "lyx") {
2265 string const latexname = latexName(false);
2266 filename = changeExtension(latexname,
2267 format->extension());
2268 filename = addName(temppath(), filename);
2270 if (!writeFile(FileName(filename)))
2274 doExport(format_name, true, filename);
2277 // Substitute $$FName for filename
2278 if (!contains(command, "$$FName"))
2279 command = "( " + command + " ) < $$FName";
2280 command = subst(command, "$$FName", filename);
2282 // Execute the command in the background
2284 call.startscript(Systemcall::DontWait, command, filePath());
2288 // FIXME: There is need for a command-line import.
2290 case LFUN_BUFFER_IMPORT:
2295 case LFUN_BUFFER_AUTO_SAVE:
2297 resetAutosaveTimers();
2300 case LFUN_BRANCH_ADD: {
2301 docstring branch_name = func.argument();
2302 if (branch_name.empty()) {
2306 BranchList & branch_list = params().branchlist();
2307 vector<docstring> const branches =
2308 getVectorFromString(branch_name, branch_list.separator());
2310 for (vector<docstring>::const_iterator it = branches.begin();
2311 it != branches.end(); ++it) {
2313 Branch * branch = branch_list.find(branch_name);
2315 LYXERR0("Branch " << branch_name << " already exists.");
2319 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2321 branch_list.add(branch_name);
2322 branch = branch_list.find(branch_name);
2323 string const x11hexname = X11hexname(branch->color());
2324 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2325 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2327 dr.screenUpdate(Update::Force);
2335 case LFUN_BRANCHES_RENAME: {
2336 if (func.argument().empty())
2339 docstring const oldname = from_utf8(func.getArg(0));
2340 docstring const newname = from_utf8(func.getArg(1));
2341 InsetIterator it = inset_iterator_begin(inset());
2342 InsetIterator const end = inset_iterator_end(inset());
2343 bool success = false;
2344 for (; it != end; ++it) {
2345 if (it->lyxCode() == BRANCH_CODE) {
2346 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2347 if (ins.branch() == oldname) {
2348 undo().recordUndo(it);
2349 ins.rename(newname);
2354 if (it->lyxCode() == INCLUDE_CODE) {
2355 // get buffer of external file
2356 InsetInclude const & ins =
2357 static_cast<InsetInclude const &>(*it);
2358 Buffer * child = ins.getChildBuffer();
2361 child->dispatch(func, dr);
2366 dr.screenUpdate(Update::Force);
2367 dr.forceBufferUpdate();
2372 case LFUN_BUFFER_PRINT: {
2373 // we'll assume there's a problem until we succeed
2375 string target = func.getArg(0);
2376 string target_name = func.getArg(1);
2377 string command = func.getArg(2);
2380 || target_name.empty()
2381 || command.empty()) {
2382 LYXERR0("Unable to parse " << func.argument());
2383 docstring const msg =
2384 bformat(_("Unable to parse \"%1$s\""), func.argument());
2388 if (target != "printer" && target != "file") {
2389 LYXERR0("Unrecognized target \"" << target << '"');
2390 docstring const msg =
2391 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2396 if (!doExport("dvi", true)) {
2397 showPrintError(absFileName());
2398 dr.setMessage(_("Error exporting to DVI."));
2402 // Push directory path.
2403 string const path = temppath();
2404 // Prevent the compiler from optimizing away p
2408 // there are three cases here:
2409 // 1. we print to a file
2410 // 2. we print directly to a printer
2411 // 3. we print using a spool command (print to file first)
2414 string const dviname = changeExtension(latexName(true), "dvi");
2416 if (target == "printer") {
2417 if (!lyxrc.print_spool_command.empty()) {
2418 // case 3: print using a spool
2419 string const psname = changeExtension(dviname,".ps");
2420 command += ' ' + lyxrc.print_to_file
2423 + quoteName(dviname);
2425 string command2 = lyxrc.print_spool_command + ' ';
2426 if (target_name != "default") {
2427 command2 += lyxrc.print_spool_printerprefix
2431 command2 += quoteName(psname);
2433 // If successful, then spool command
2434 res = one.startscript(Systemcall::Wait, command,
2438 // If there's no GUI, we have to wait on this command. Otherwise,
2439 // LyX deletes the temporary directory, and with it the spooled
2440 // file, before it can be printed!!
2441 Systemcall::Starttype stype = use_gui ?
2442 Systemcall::DontWait : Systemcall::Wait;
2443 res = one.startscript(stype, command2,
2447 // case 2: print directly to a printer
2448 if (target_name != "default")
2449 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2451 Systemcall::Starttype stype = use_gui ?
2452 Systemcall::DontWait : Systemcall::Wait;
2453 res = one.startscript(stype, command +
2454 quoteName(dviname), filePath());
2458 // case 1: print to a file
2459 FileName const filename(makeAbsPath(target_name, filePath()));
2460 FileName const dvifile(makeAbsPath(dviname, path));
2461 if (filename.exists()) {
2462 docstring text = bformat(
2463 _("The file %1$s already exists.\n\n"
2464 "Do you want to overwrite that file?"),
2465 makeDisplayPath(filename.absFileName()));
2466 if (Alert::prompt(_("Overwrite file?"),
2467 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2470 command += ' ' + lyxrc.print_to_file
2471 + quoteName(filename.toFilesystemEncoding())
2473 + quoteName(dvifile.toFilesystemEncoding());
2475 Systemcall::Starttype stype = use_gui ?
2476 Systemcall::DontWait : Systemcall::Wait;
2477 res = one.startscript(stype, command, filePath());
2483 dr.setMessage(_("Error running external commands."));
2484 showPrintError(absFileName());
2493 dr.dispatched(dispatched);
2494 undo().endUndoGroup();
2498 void Buffer::changeLanguage(Language const * from, Language const * to)
2500 LASSERT(from, /**/);
2503 for_each(par_iterator_begin(),
2505 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2509 bool Buffer::isMultiLingual() const
2511 ParConstIterator end = par_iterator_end();
2512 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2513 if (it->isMultiLingual(params()))
2520 std::set<Language const *> Buffer::getLanguages() const
2522 std::set<Language const *> languages;
2523 getLanguages(languages);
2528 void Buffer::getLanguages(std::set<Language const *> & languages) const
2530 ParConstIterator end = par_iterator_end();
2531 // add the buffer language, even if it's not actively used
2532 languages.insert(language());
2533 // iterate over the paragraphs
2534 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2535 it->getLanguages(languages);
2537 ListOfBuffers clist = getDescendents();
2538 ListOfBuffers::const_iterator cit = clist.begin();
2539 ListOfBuffers::const_iterator const cen = clist.end();
2540 for (; cit != cen; ++cit)
2541 (*cit)->getLanguages(languages);
2545 DocIterator Buffer::getParFromID(int const id) const
2547 Buffer * buf = const_cast<Buffer *>(this);
2549 // John says this is called with id == -1 from undo
2550 lyxerr << "getParFromID(), id: " << id << endl;
2551 return doc_iterator_end(buf);
2554 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2555 if (it.paragraph().id() == id)
2558 return doc_iterator_end(buf);
2562 bool Buffer::hasParWithID(int const id) const
2564 return !getParFromID(id).atEnd();
2568 ParIterator Buffer::par_iterator_begin()
2570 return ParIterator(doc_iterator_begin(this));
2574 ParIterator Buffer::par_iterator_end()
2576 return ParIterator(doc_iterator_end(this));
2580 ParConstIterator Buffer::par_iterator_begin() const
2582 return ParConstIterator(doc_iterator_begin(this));
2586 ParConstIterator Buffer::par_iterator_end() const
2588 return ParConstIterator(doc_iterator_end(this));
2592 Language const * Buffer::language() const
2594 return params().language;
2598 docstring const Buffer::B_(string const & l10n) const
2600 return params().B_(l10n);
2604 bool Buffer::isClean() const
2606 return d->lyx_clean;
2610 bool Buffer::isExternallyModified(CheckMethod method) const
2612 LASSERT(d->filename.exists(), /**/);
2613 // if method == timestamp, check timestamp before checksum
2614 return (method == checksum_method
2615 || d->timestamp_ != d->filename.lastModified())
2616 && d->checksum_ != d->filename.checksum();
2620 void Buffer::saveCheckSum() const
2622 FileName const & file = d->filename;
2625 if (file.exists()) {
2626 d->timestamp_ = file.lastModified();
2627 d->checksum_ = file.checksum();
2629 // in the case of save to a new file.
2636 void Buffer::markClean() const
2638 if (!d->lyx_clean) {
2639 d->lyx_clean = true;
2642 // if the .lyx file has been saved, we don't need an
2644 d->bak_clean = true;
2645 d->undo_.markDirty();
2649 void Buffer::setUnnamed(bool flag)
2655 bool Buffer::isUnnamed() const
2662 /// Don't check unnamed, here: isInternal() is used in
2663 /// newBuffer(), where the unnamed flag has not been set by anyone
2664 /// yet. Also, for an internal buffer, there should be no need for
2665 /// retrieving fileName() nor for checking if it is unnamed or not.
2666 bool Buffer::isInternal() const
2668 return fileName().extension() == "internal";
2672 void Buffer::markDirty()
2675 d->lyx_clean = false;
2678 d->bak_clean = false;
2680 DepClean::iterator it = d->dep_clean.begin();
2681 DepClean::const_iterator const end = d->dep_clean.end();
2683 for (; it != end; ++it)
2688 FileName Buffer::fileName() const
2694 string Buffer::absFileName() const
2696 return d->filename.absFileName();
2700 string Buffer::filePath() const
2702 return d->filename.onlyPath().absFileName() + "/";
2706 bool Buffer::isReadonly() const
2708 return d->read_only;
2712 void Buffer::setParent(Buffer const * buffer)
2714 // Avoids recursive include.
2715 d->setParent(buffer == this ? 0 : buffer);
2720 Buffer const * Buffer::parent() const
2726 ListOfBuffers Buffer::allRelatives() const
2728 ListOfBuffers lb = masterBuffer()->getDescendents();
2729 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2734 Buffer const * Buffer::masterBuffer() const
2736 // FIXME Should be make sure we are not in some kind
2737 // of recursive include? A -> B -> A will crash this.
2738 Buffer const * const pbuf = d->parent();
2742 return pbuf->masterBuffer();
2746 bool Buffer::isChild(Buffer * child) const
2748 return d->children_positions.find(child) != d->children_positions.end();
2752 DocIterator Buffer::firstChildPosition(Buffer const * child)
2754 Impl::BufferPositionMap::iterator it;
2755 it = d->children_positions.find(child);
2756 if (it == d->children_positions.end())
2757 return DocIterator(this);
2762 bool Buffer::hasChildren() const
2764 return !d->children_positions.empty();
2768 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2770 // loop over children
2771 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2772 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2773 for (; it != end; ++it) {
2774 Buffer * child = const_cast<Buffer *>(it->first);
2776 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2777 if (bit != clist.end())
2779 clist.push_back(child);
2781 // there might be grandchildren
2782 child->collectChildren(clist, true);
2787 ListOfBuffers Buffer::getChildren() const
2790 collectChildren(v, false);
2791 // Make sure we have not included ourselves.
2792 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2793 if (bit != v.end()) {
2794 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2801 ListOfBuffers Buffer::getDescendents() const
2804 collectChildren(v, true);
2805 // Make sure we have not included ourselves.
2806 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2807 if (bit != v.end()) {
2808 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2815 template<typename M>
2816 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2821 typename M::const_iterator it = m.lower_bound(x);
2822 if (it == m.begin())
2830 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2831 DocIterator const & pos) const
2833 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2835 // if paragraphs have no macro context set, pos will be empty
2839 // we haven't found anything yet
2840 DocIterator bestPos = owner_->par_iterator_begin();
2841 MacroData const * bestData = 0;
2843 // find macro definitions for name
2844 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2845 if (nameIt != macros.end()) {
2846 // find last definition in front of pos or at pos itself
2847 PositionScopeMacroMap::const_iterator it
2848 = greatest_below(nameIt->second, pos);
2849 if (it != nameIt->second.end()) {
2851 // scope ends behind pos?
2852 if (pos < it->second.first) {
2853 // Looks good, remember this. If there
2854 // is no external macro behind this,
2855 // we found the right one already.
2856 bestPos = it->first;
2857 bestData = &it->second.second;
2861 // try previous macro if there is one
2862 if (it == nameIt->second.begin())
2869 // find macros in included files
2870 PositionScopeBufferMap::const_iterator it
2871 = greatest_below(position_to_children, pos);
2872 if (it == position_to_children.end())
2873 // no children before
2877 // do we know something better (i.e. later) already?
2878 if (it->first < bestPos )
2881 // scope ends behind pos?
2882 if (pos < it->second.first
2883 && (cloned_buffer_ ||
2884 theBufferList().isLoaded(it->second.second))) {
2885 // look for macro in external file
2887 MacroData const * data
2888 = it->second.second->getMacro(name, false);
2891 bestPos = it->first;
2897 // try previous file if there is one
2898 if (it == position_to_children.begin())
2903 // return the best macro we have found
2908 MacroData const * Buffer::getMacro(docstring const & name,
2909 DocIterator const & pos, bool global) const
2914 // query buffer macros
2915 MacroData const * data = d->getBufferMacro(name, pos);
2919 // If there is a master buffer, query that
2920 Buffer const * const pbuf = d->parent();
2922 d->macro_lock = true;
2923 MacroData const * macro = pbuf->getMacro(
2924 name, *this, false);
2925 d->macro_lock = false;
2931 data = MacroTable::globalMacros().get(name);
2940 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2942 // set scope end behind the last paragraph
2943 DocIterator scope = par_iterator_begin();
2944 scope.pit() = scope.lastpit() + 1;
2946 return getMacro(name, scope, global);
2950 MacroData const * Buffer::getMacro(docstring const & name,
2951 Buffer const & child, bool global) const
2953 // look where the child buffer is included first
2954 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2955 if (it == d->children_positions.end())
2958 // check for macros at the inclusion position
2959 return getMacro(name, it->second, global);
2963 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2965 pit_type const lastpit = it.lastpit();
2967 // look for macros in each paragraph
2968 while (it.pit() <= lastpit) {
2969 Paragraph & par = it.paragraph();
2971 // iterate over the insets of the current paragraph
2972 InsetList const & insets = par.insetList();
2973 InsetList::const_iterator iit = insets.begin();
2974 InsetList::const_iterator end = insets.end();
2975 for (; iit != end; ++iit) {
2976 it.pos() = iit->pos;
2978 // is it a nested text inset?
2979 if (iit->inset->asInsetText()) {
2980 // Inset needs its own scope?
2981 InsetText const * itext = iit->inset->asInsetText();
2982 bool newScope = itext->isMacroScope();
2984 // scope which ends just behind the inset
2985 DocIterator insetScope = it;
2988 // collect macros in inset
2989 it.push_back(CursorSlice(*iit->inset));
2990 updateMacros(it, newScope ? insetScope : scope);
2995 if (iit->inset->asInsetTabular()) {
2996 CursorSlice slice(*iit->inset);
2997 size_t const numcells = slice.nargs();
2998 for (; slice.idx() < numcells; slice.forwardIdx()) {
2999 it.push_back(slice);
3000 updateMacros(it, scope);
3006 // is it an external file?
3007 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3008 // get buffer of external file
3009 InsetInclude const & inset =
3010 static_cast<InsetInclude const &>(*iit->inset);
3012 Buffer * child = inset.getChildBuffer();
3017 // register its position, but only when it is
3018 // included first in the buffer
3019 if (children_positions.find(child) ==
3020 children_positions.end())
3021 children_positions[child] = it;
3023 // register child with its scope
3024 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3028 InsetMath * im = iit->inset->asInsetMath();
3029 if (doing_export && im) {
3030 InsetMathHull * hull = im->asHullInset();
3032 hull->recordLocation(it);
3035 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3039 MathMacroTemplate & macroTemplate =
3040 *iit->inset->asInsetMath()->asMacroTemplate();
3041 MacroContext mc(owner_, it);
3042 macroTemplate.updateToContext(mc);
3045 bool valid = macroTemplate.validMacro();
3046 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3047 // then the BufferView's cursor will be invalid in
3048 // some cases which leads to crashes.
3053 // FIXME (Abdel), I don't understandt why we pass 'it' here
3054 // instead of 'macroTemplate' defined above... is this correct?
3055 macros[macroTemplate.name()][it] =
3056 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3066 void Buffer::updateMacros() const
3071 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3073 // start with empty table
3075 d->children_positions.clear();
3076 d->position_to_children.clear();
3078 // Iterate over buffer, starting with first paragraph
3079 // The scope must be bigger than any lookup DocIterator
3080 // later. For the global lookup, lastpit+1 is used, hence
3081 // we use lastpit+2 here.
3082 DocIterator it = par_iterator_begin();
3083 DocIterator outerScope = it;
3084 outerScope.pit() = outerScope.lastpit() + 2;
3085 d->updateMacros(it, outerScope);
3089 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3091 InsetIterator it = inset_iterator_begin(inset());
3092 InsetIterator const end = inset_iterator_end(inset());
3093 for (; it != end; ++it) {
3094 if (it->lyxCode() == BRANCH_CODE) {
3095 InsetBranch & br = static_cast<InsetBranch &>(*it);
3096 docstring const name = br.branch();
3097 if (!from_master && !params().branchlist().find(name))
3098 result.push_back(name);
3099 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3100 result.push_back(name);
3103 if (it->lyxCode() == INCLUDE_CODE) {
3104 // get buffer of external file
3105 InsetInclude const & ins =
3106 static_cast<InsetInclude const &>(*it);
3107 Buffer * child = ins.getChildBuffer();
3110 child->getUsedBranches(result, true);
3113 // remove duplicates
3118 void Buffer::updateMacroInstances(UpdateType utype) const
3120 LYXERR(Debug::MACROS, "updateMacroInstances for "
3121 << d->filename.onlyFileName());
3122 DocIterator it = doc_iterator_begin(this);
3124 DocIterator const end = doc_iterator_end(this);
3125 for (; it != end; it.forwardInset()) {
3126 // look for MathData cells in InsetMathNest insets
3127 InsetMath * minset = it.nextInset()->asInsetMath();
3131 // update macro in all cells of the InsetMathNest
3132 DocIterator::idx_type n = minset->nargs();
3133 MacroContext mc = MacroContext(this, it);
3134 for (DocIterator::idx_type i = 0; i < n; ++i) {
3135 MathData & data = minset->cell(i);
3136 data.updateMacros(0, mc, utype);
3142 void Buffer::listMacroNames(MacroNameSet & macros) const
3147 d->macro_lock = true;
3149 // loop over macro names
3150 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3151 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3152 for (; nameIt != nameEnd; ++nameIt)
3153 macros.insert(nameIt->first);
3155 // loop over children
3156 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3157 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3158 for (; it != end; ++it)
3159 it->first->listMacroNames(macros);
3162 Buffer const * const pbuf = d->parent();
3164 pbuf->listMacroNames(macros);
3166 d->macro_lock = false;
3170 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3172 Buffer const * const pbuf = d->parent();
3177 pbuf->listMacroNames(names);
3180 MacroNameSet::iterator it = names.begin();
3181 MacroNameSet::iterator end = names.end();
3182 for (; it != end; ++it) {
3184 MacroData const * data =
3185 pbuf->getMacro(*it, *this, false);
3187 macros.insert(data);
3189 // we cannot access the original MathMacroTemplate anymore
3190 // here to calls validate method. So we do its work here manually.
3191 // FIXME: somehow make the template accessible here.
3192 if (data->optionals() > 0)
3193 features.require("xargs");
3199 Buffer::References & Buffer::references(docstring const & label)
3202 return const_cast<Buffer *>(masterBuffer())->references(label);
3204 RefCache::iterator it = d->ref_cache_.find(label);
3205 if (it != d->ref_cache_.end())
3206 return it->second.second;
3208 static InsetLabel const * dummy_il = 0;
3209 static References const dummy_refs;
3210 it = d->ref_cache_.insert(
3211 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3212 return it->second.second;
3216 Buffer::References const & Buffer::references(docstring const & label) const
3218 return const_cast<Buffer *>(this)->references(label);
3222 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3224 masterBuffer()->d->ref_cache_[label].first = il;
3228 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3230 return masterBuffer()->d->ref_cache_[label].first;
3234 void Buffer::clearReferenceCache() const
3237 d->ref_cache_.clear();
3241 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3244 //FIXME: This does not work for child documents yet.
3245 LASSERT(code == CITE_CODE, /**/);
3247 reloadBibInfoCache();
3249 // Check if the label 'from' appears more than once
3250 BiblioInfo const & keys = masterBibInfo();
3251 BiblioInfo::const_iterator bit = keys.begin();
3252 BiblioInfo::const_iterator bend = keys.end();
3253 vector<docstring> labels;
3255 for (; bit != bend; ++bit)
3257 labels.push_back(bit->first);
3259 if (count(labels.begin(), labels.end(), from) > 1)
3262 string const paramName = "key";
3263 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3264 if (it->lyxCode() == code) {
3265 InsetCommand * inset = it->asInsetCommand();
3268 docstring const oldValue = inset->getParam(paramName);
3269 if (oldValue == from)
3270 inset->setParam(paramName, to);
3276 void Buffer::getSourceCode(odocstream & os, string const format,
3277 pit_type par_begin, pit_type par_end,
3278 OutputWhat output) const
3280 OutputParams runparams(¶ms().encoding());
3281 runparams.nice = true;
3282 runparams.flavor = params().getOutputFlavor(format);
3283 runparams.linelen = lyxrc.plaintext_linelen;
3284 // No side effect of file copying and image conversion
3285 runparams.dryrun = true;
3287 if (output == CurrentParagraph) {
3288 runparams.par_begin = par_begin;
3289 runparams.par_end = par_end;
3290 if (par_begin + 1 == par_end) {
3292 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3296 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3297 convert<docstring>(par_begin),
3298 convert<docstring>(par_end - 1))
3305 // output paragraphs
3306 if (params().isDocBook())
3307 docbookParagraphs(text(), *this, os, runparams);
3308 else if (runparams.flavor == OutputParams::HTML) {
3310 setMathFlavor(runparams);
3311 xhtmlParagraphs(text(), *this, xs, runparams);
3313 // latex or literate
3314 otexstream ots(os, texrow);
3315 latexParagraphs(*this, text(), ots, runparams);
3319 if (output == FullSource)
3320 os << _("Preview source code");
3321 else if (output == OnlyPreamble)
3322 os << _("Preview preamble");
3323 else if (output == OnlyBody)
3324 os << _("Preview body");
3327 d->texrow.newline();
3328 d->texrow.newline();
3329 if (params().isDocBook())
3330 writeDocBookSource(os, absFileName(), runparams, output);
3331 else if (runparams.flavor == OutputParams::HTML)
3332 writeLyXHTMLSource(os, runparams, output);
3334 // latex or literate
3335 otexstream ots(os, d->texrow);
3336 writeLaTeXSource(ots, string(), runparams, output);
3342 ErrorList & Buffer::errorList(string const & type) const
3344 return d->errorLists[type];
3348 void Buffer::updateTocItem(std::string const & type,
3349 DocIterator const & dit) const
3352 d->gui_->updateTocItem(type, dit);
3356 void Buffer::structureChanged() const
3359 d->gui_->structureChanged();
3363 void Buffer::errors(string const & err, bool from_master) const
3366 d->gui_->errors(err, from_master);
3370 void Buffer::message(docstring const & msg) const
3373 d->gui_->message(msg);
3377 void Buffer::setBusy(bool on) const
3380 d->gui_->setBusy(on);
3384 void Buffer::updateTitles() const
3387 d->wa_->updateTitles();
3391 void Buffer::resetAutosaveTimers() const
3394 d->gui_->resetAutosaveTimers();
3398 bool Buffer::hasGuiDelegate() const
3404 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3413 class AutoSaveBuffer : public ForkedProcess {
3416 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3417 : buffer_(buffer), fname_(fname) {}
3419 virtual shared_ptr<ForkedProcess> clone() const
3421 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3426 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3427 from_utf8(fname_.absFileName())));
3428 return run(DontWait);
3432 virtual int generateChild();
3434 Buffer const & buffer_;
3439 int AutoSaveBuffer::generateChild()
3441 #if defined(__APPLE__)
3442 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3443 * We should use something else like threads.
3445 * Since I do not know how to determine at run time what is the OS X
3446 * version, I just disable forking altogether for now (JMarc)
3448 pid_t const pid = -1;
3450 // tmp_ret will be located (usually) in /tmp
3451 // will that be a problem?
3452 // Note that this calls ForkedCalls::fork(), so it's
3453 // ok cross-platform.
3454 pid_t const pid = fork();
3455 // If you want to debug the autosave
3456 // you should set pid to -1, and comment out the fork.
3457 if (pid != 0 && pid != -1)
3461 // pid = -1 signifies that lyx was unable
3462 // to fork. But we will do the save
3464 bool failed = false;
3465 FileName const tmp_ret = FileName::tempName("lyxauto");
3466 if (!tmp_ret.empty()) {
3467 buffer_.writeFile(tmp_ret);
3468 // assume successful write of tmp_ret
3469 if (!tmp_ret.moveTo(fname_))
3475 // failed to write/rename tmp_ret so try writing direct
3476 if (!buffer_.writeFile(fname_)) {
3477 // It is dangerous to do this in the child,
3478 // but safe in the parent, so...
3479 if (pid == -1) // emit message signal.
3480 buffer_.message(_("Autosave failed!"));
3484 if (pid == 0) // we are the child so...
3493 FileName Buffer::getEmergencyFileName() const
3495 return FileName(d->filename.absFileName() + ".emergency");
3499 FileName Buffer::getAutosaveFileName() const
3501 // if the document is unnamed try to save in the backup dir, else
3502 // in the default document path, and as a last try in the filePath,
3503 // which will most often be the temporary directory
3506 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3507 : lyxrc.backupdir_path;
3508 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3511 string const fname = "#" + d->filename.onlyFileName() + "#";
3513 return makeAbsPath(fname, fpath);
3517 void Buffer::removeAutosaveFile() const
3519 FileName const f = getAutosaveFileName();
3525 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3527 FileName const newauto = getAutosaveFileName();
3529 if (newauto != oldauto && oldauto.exists())
3530 if (!oldauto.moveTo(newauto))
3531 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3535 bool Buffer::autoSave() const
3537 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3538 if (buf->d->bak_clean || isReadonly())
3541 message(_("Autosaving current document..."));
3542 buf->d->bak_clean = true;
3544 FileName const fname = getAutosaveFileName();
3545 if (d->cloned_buffer_) {
3546 // If this buffer is cloned, we assume that
3547 // we are running in a separate thread already.
3548 FileName const tmp_ret = FileName::tempName("lyxauto");
3549 if (!tmp_ret.empty()) {
3551 // assume successful write of tmp_ret
3552 if (tmp_ret.moveTo(fname))
3555 // failed to write/rename tmp_ret so try writing direct
3556 return writeFile(fname);
3558 /// This function is deprecated as the frontend needs to take care
3559 /// of cloning the buffer and autosaving it in another thread. It
3560 /// is still here to allow (QT_VERSION < 0x040400).
3561 AutoSaveBuffer autosave(*this, fname);
3568 // helper class, to guarantee this gets reset properly
3569 class Buffer::MarkAsExporting {
3571 MarkAsExporting(Buffer const * buf) : buf_(buf)
3573 LASSERT(buf_, /* */);
3574 buf_->setExportStatus(true);
3578 buf_->setExportStatus(false);
3581 Buffer const * const buf_;
3586 void Buffer::setExportStatus(bool e) const
3588 d->doing_export = e;
3589 ListOfBuffers clist = getDescendents();
3590 ListOfBuffers::const_iterator cit = clist.begin();
3591 ListOfBuffers::const_iterator const cen = clist.end();
3592 for (; cit != cen; ++cit)
3593 (*cit)->d->doing_export = e;
3597 bool Buffer::isExporting() const
3599 return d->doing_export;
3603 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3607 return doExport(target, put_in_tempdir, result_file);
3610 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3611 string & result_file) const
3613 bool const update_unincluded =
3614 params().maintain_unincluded_children
3615 && !params().getIncludedChildren().empty();
3617 // (1) export with all included children (omit \includeonly)
3618 if (update_unincluded) {
3619 ExportStatus const status =
3620 doExport(target, put_in_tempdir, true, result_file);
3621 if (status != ExportSuccess)
3624 // (2) export with included children only
3625 return doExport(target, put_in_tempdir, false, result_file);
3629 void Buffer::setMathFlavor(OutputParams & op) const
3631 switch (params().html_math_output) {
3632 case BufferParams::MathML:
3633 op.math_flavor = OutputParams::MathAsMathML;
3635 case BufferParams::HTML:
3636 op.math_flavor = OutputParams::MathAsHTML;
3638 case BufferParams::Images:
3639 op.math_flavor = OutputParams::MathAsImages;
3641 case BufferParams::LaTeX:
3642 op.math_flavor = OutputParams::MathAsLaTeX;
3648 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3649 bool includeall, string & result_file) const
3651 LYXERR(Debug::FILES, "target=" << target);
3652 OutputParams runparams(¶ms().encoding());
3653 string format = target;
3654 string dest_filename;
3655 size_t pos = target.find(' ');
3656 if (pos != string::npos) {
3657 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3658 format = target.substr(0, pos);
3659 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3660 FileName(dest_filename).onlyPath().createPath();
3661 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3663 MarkAsExporting exporting(this);
3664 string backend_format;
3665 runparams.flavor = OutputParams::LATEX;
3666 runparams.linelen = lyxrc.plaintext_linelen;
3667 runparams.includeall = includeall;
3668 vector<string> backs = params().backends();
3669 Converters converters = theConverters();
3670 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3671 // Get shortest path to format
3672 converters.buildGraph();
3673 Graph::EdgePath path;
3674 for (vector<string>::const_iterator it = backs.begin();
3675 it != backs.end(); ++it) {
3676 Graph::EdgePath p = converters.getPath(*it, format);
3677 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3678 backend_format = *it;
3683 if (!put_in_tempdir) {
3684 // Only show this alert if this is an export to a non-temporary
3685 // file (not for previewing).
3686 Alert::error(_("Couldn't export file"), bformat(
3687 _("No information for exporting the format %1$s."),
3688 formats.prettyName(format)));
3690 return ExportNoPathToFormat;
3692 runparams.flavor = converters.getFlavor(path);
3695 backend_format = format;
3696 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3697 // FIXME: Don't hardcode format names here, but use a flag
3698 if (backend_format == "pdflatex")
3699 runparams.flavor = OutputParams::PDFLATEX;
3700 else if (backend_format == "luatex")
3701 runparams.flavor = OutputParams::LUATEX;
3702 else if (backend_format == "dviluatex")
3703 runparams.flavor = OutputParams::DVILUATEX;
3704 else if (backend_format == "xetex")
3705 runparams.flavor = OutputParams::XETEX;
3708 string filename = latexName(false);
3709 filename = addName(temppath(), filename);
3710 filename = changeExtension(filename,
3711 formats.extension(backend_format));
3712 LYXERR(Debug::FILES, "filename=" << filename);
3714 // Plain text backend
3715 if (backend_format == "text") {
3716 runparams.flavor = OutputParams::TEXT;
3717 writePlaintextFile(*this, FileName(filename), runparams);
3720 else if (backend_format == "xhtml") {
3721 runparams.flavor = OutputParams::HTML;
3722 setMathFlavor(runparams);
3723 makeLyXHTMLFile(FileName(filename), runparams);
3724 } else if (backend_format == "lyx")
3725 writeFile(FileName(filename));
3727 else if (params().isDocBook()) {
3728 runparams.nice = !put_in_tempdir;
3729 makeDocBookFile(FileName(filename), runparams);
3732 else if (backend_format == format) {
3733 runparams.nice = true;
3734 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3735 if (d->cloned_buffer_) {
3736 d->cloned_buffer_->d->errorLists["Export"] =
3737 d->errorLists["Export"];
3741 } else if (!lyxrc.tex_allows_spaces
3742 && contains(filePath(), ' ')) {
3743 Alert::error(_("File name error"),
3744 _("The directory path to the document cannot contain spaces."));
3745 return ExportTexPathHasSpaces;
3747 runparams.nice = false;
3748 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3749 if (d->cloned_buffer_) {
3750 d->cloned_buffer_->d->errorLists["Export"] =
3751 d->errorLists["Export"];
3757 string const error_type = (format == "program")
3758 ? "Build" : params().bufferFormat();
3759 ErrorList & error_list = d->errorLists[error_type];
3760 string const ext = formats.extension(format);
3761 FileName const tmp_result_file(changeExtension(filename, ext));
3762 bool const success = converters.convert(this, FileName(filename),
3763 tmp_result_file, FileName(absFileName()), backend_format, format,
3766 // Emit the signal to show the error list or copy it back to the
3767 // cloned Buffer so that it can be emitted afterwards.
3768 if (format != backend_format) {
3769 if (d->cloned_buffer_) {
3770 d->cloned_buffer_->d->errorLists[error_type] =
3771 d->errorLists[error_type];
3774 // also to the children, in case of master-buffer-view
3775 ListOfBuffers clist = getDescendents();
3776 ListOfBuffers::const_iterator cit = clist.begin();
3777 ListOfBuffers::const_iterator const cen = clist.end();
3778 for (; cit != cen; ++cit) {
3779 if (d->cloned_buffer_) {
3780 // Enable reverse search by copying back the
3781 // texrow object to the cloned buffer.
3782 // FIXME: this is not thread safe.
3783 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3784 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3785 (*cit)->d->errorLists[error_type];
3787 (*cit)->errors(error_type, true);
3791 if (d->cloned_buffer_) {
3792 // Enable reverse dvi or pdf to work by copying back the texrow
3793 // object to the cloned buffer.
3794 // FIXME: There is a possibility of concurrent access to texrow
3795 // here from the main GUI thread that should be securized.
3796 d->cloned_buffer_->d->texrow = d->texrow;
3797 string const error_type = params().bufferFormat();
3798 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3802 return ExportConverterError;
3804 if (put_in_tempdir) {
3805 result_file = tmp_result_file.absFileName();
3806 return ExportSuccess;
3809 if (dest_filename.empty())
3810 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3812 result_file = dest_filename;
3813 // We need to copy referenced files (e. g. included graphics
3814 // if format == "dvi") to the result dir.
3815 vector<ExportedFile> const files =
3816 runparams.exportdata->externalFiles(format);
3817 string const dest = runparams.export_folder.empty() ?
3818 onlyPath(result_file) : runparams.export_folder;
3819 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3820 : force_overwrite == ALL_FILES;
3821 CopyStatus status = use_force ? FORCE : SUCCESS;
3823 vector<ExportedFile>::const_iterator it = files.begin();
3824 vector<ExportedFile>::const_iterator const en = files.end();
3825 for (; it != en && status != CANCEL; ++it) {
3826 string const fmt = formats.getFormatFromFile(it->sourceName);
3827 string fixedName = it->exportName;
3828 if (!runparams.export_folder.empty()) {
3829 // Relative pathnames starting with ../ will be sanitized
3830 // if exporting to a different folder
3831 while (fixedName.substr(0, 3) == "../")
3832 fixedName = fixedName.substr(3, fixedName.length() - 3);
3834 FileName fixedFileName = makeAbsPath(fixedName, dest);
3835 fixedFileName.onlyPath().createPath();
3836 status = copyFile(fmt, it->sourceName,
3838 it->exportName, status == FORCE,
3839 runparams.export_folder.empty());
3842 if (status == CANCEL) {
3843 message(_("Document export cancelled."));
3844 return ExportCancel;
3847 if (tmp_result_file.exists()) {
3848 // Finally copy the main file
3849 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3850 : force_overwrite != NO_FILES;
3851 if (status == SUCCESS && use_force)
3853 status = copyFile(format, tmp_result_file,
3854 FileName(result_file), result_file,
3856 if (status == CANCEL) {
3857 message(_("Document export cancelled."));
3858 return ExportCancel;
3860 message(bformat(_("Document exported as %1$s "
3862 formats.prettyName(format),
3863 makeDisplayPath(result_file)));
3866 // This must be a dummy converter like fax (bug 1888)
3867 message(bformat(_("Document exported as %1$s"),
3868 formats.prettyName(format)));
3871 return ExportSuccess;
3875 Buffer::ExportStatus Buffer::preview(string const & format) const
3877 bool const update_unincluded =
3878 params().maintain_unincluded_children
3879 && !params().getIncludedChildren().empty();
3880 return preview(format, update_unincluded);
3883 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3885 MarkAsExporting exporting(this);
3887 // (1) export with all included children (omit \includeonly)
3889 ExportStatus const status = doExport(format, true, true, result_file);
3890 if (status != ExportSuccess)
3893 // (2) export with included children only
3894 ExportStatus const status = doExport(format, true, false, result_file);
3895 if (status != ExportSuccess)
3897 if (!formats.view(*this, FileName(result_file), format))
3898 return PreviewError;
3899 return PreviewSuccess;
3903 Buffer::ReadStatus Buffer::extractFromVC()
3905 bool const found = LyXVC::file_not_found_hook(d->filename);
3907 return ReadFileNotFound;
3908 if (!d->filename.isReadableFile())
3914 Buffer::ReadStatus Buffer::loadEmergency()
3916 FileName const emergencyFile = getEmergencyFileName();
3917 if (!emergencyFile.exists()
3918 || emergencyFile.lastModified() <= d->filename.lastModified())
3919 return ReadFileNotFound;
3921 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3922 docstring const text = bformat(_("An emergency save of the document "
3923 "%1$s exists.\n\nRecover emergency save?"), file);
3925 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3926 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3932 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3933 bool const success = (ret_llf == ReadSuccess);
3936 Alert::warning(_("File is read-only"),
3937 bformat(_("An emergency file is successfully loaded, "
3938 "but the original file %1$s is marked read-only. "
3939 "Please make sure to save the document as a different "
3940 "file."), from_utf8(d->filename.absFileName())));
3943 str = _("Document was successfully recovered.");
3945 str = _("Document was NOT successfully recovered.");
3946 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3947 makeDisplayPath(emergencyFile.absFileName()));
3949 int const del_emerg =
3950 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3951 _("&Remove"), _("&Keep"));
3952 if (del_emerg == 0) {
3953 emergencyFile.removeFile();
3955 Alert::warning(_("Emergency file deleted"),
3956 _("Do not forget to save your file now!"), true);
3958 return success ? ReadSuccess : ReadEmergencyFailure;
3961 int const del_emerg =
3962 Alert::prompt(_("Delete emergency file?"),
3963 _("Remove emergency file now?"), 1, 1,
3964 _("&Remove"), _("&Keep"));
3966 emergencyFile.removeFile();
3967 return ReadOriginal;
3977 Buffer::ReadStatus Buffer::loadAutosave()
3979 // Now check if autosave file is newer.
3980 FileName const autosaveFile = getAutosaveFileName();
3981 if (!autosaveFile.exists()
3982 || autosaveFile.lastModified() <= d->filename.lastModified())
3983 return ReadFileNotFound;
3985 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3986 docstring const text = bformat(_("The backup of the document %1$s "
3987 "is newer.\n\nLoad the backup instead?"), file);
3988 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3989 _("&Load backup"), _("Load &original"), _("&Cancel"));
3994 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3995 // the file is not saved if we load the autosave file.
3996 if (ret_llf == ReadSuccess) {
3998 Alert::warning(_("File is read-only"),
3999 bformat(_("A backup file is successfully loaded, "
4000 "but the original file %1$s is marked read-only. "
4001 "Please make sure to save the document as a "
4003 from_utf8(d->filename.absFileName())));
4008 return ReadAutosaveFailure;
4011 // Here we delete the autosave
4012 autosaveFile.removeFile();
4013 return ReadOriginal;
4021 Buffer::ReadStatus Buffer::loadLyXFile()
4023 if (!d->filename.isReadableFile()) {
4024 ReadStatus const ret_rvc = extractFromVC();
4025 if (ret_rvc != ReadSuccess)
4029 ReadStatus const ret_re = loadEmergency();
4030 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4033 ReadStatus const ret_ra = loadAutosave();
4034 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4037 return loadThisLyXFile(d->filename);
4041 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4043 return readFile(fn);
4047 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4049 TeXErrors::Errors::const_iterator it = terr.begin();
4050 TeXErrors::Errors::const_iterator end = terr.end();
4051 ListOfBuffers clist = getDescendents();
4052 ListOfBuffers::const_iterator cen = clist.end();
4054 for (; it != end; ++it) {
4057 int errorRow = it->error_in_line;
4058 Buffer const * buf = 0;
4060 if (it->child_name.empty())
4061 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4063 // The error occurred in a child
4064 ListOfBuffers::const_iterator cit = clist.begin();
4065 for (; cit != cen; ++cit) {
4066 string const child_name =
4067 DocFileName(changeExtension(
4068 (*cit)->absFileName(), "tex")).
4070 if (it->child_name != child_name)
4072 (*cit)->d->texrow.getIdFromRow(errorRow,
4073 id_start, pos_start);
4074 if (id_start != -1) {
4075 buf = d->cloned_buffer_
4076 ? (*cit)->d->cloned_buffer_->d->owner_
4077 : (*cit)->d->owner_;
4088 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4089 } while (found && id_start == id_end && pos_start == pos_end);
4091 if (id_start != id_end) {
4092 // Next registered position is outside the inset where
4093 // the error occurred, so signal end-of-paragraph
4097 errorList.push_back(ErrorItem(it->error_desc,
4098 it->error_text, id_start, pos_start, pos_end, buf));
4103 void Buffer::setBuffersForInsets() const
4105 inset().setBuffer(const_cast<Buffer &>(*this));
4109 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4111 // Use the master text class also for child documents
4112 Buffer const * const master = masterBuffer();
4113 DocumentClass const & textclass = master->params().documentClass();
4115 // do this only if we are the top-level Buffer
4117 reloadBibInfoCache();
4119 // keep the buffers to be children in this set. If the call from the
4120 // master comes back we can see which of them were actually seen (i.e.
4121 // via an InsetInclude). The remaining ones in the set need still be updated.
4122 static std::set<Buffer const *> bufToUpdate;
4123 if (scope == UpdateMaster) {
4124 // If this is a child document start with the master
4125 if (master != this) {
4126 bufToUpdate.insert(this);
4127 master->updateBuffer(UpdateMaster, utype);
4128 // Do this here in case the master has no gui associated with it. Then,
4129 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4130 if (!master->d->gui_)
4133 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4134 if (bufToUpdate.find(this) == bufToUpdate.end())
4138 // start over the counters in the master
4139 textclass.counters().reset();
4142 // update will be done below for this buffer
4143 bufToUpdate.erase(this);
4145 // update all caches
4146 clearReferenceCache();
4149 Buffer & cbuf = const_cast<Buffer &>(*this);
4151 LASSERT(!text().paragraphs().empty(), /**/);
4154 ParIterator parit = cbuf.par_iterator_begin();
4155 updateBuffer(parit, utype);
4158 // TocBackend update will be done later.
4161 d->bibinfo_cache_valid_ = true;
4162 d->cite_labels_valid_ = true;
4163 cbuf.tocBackend().update();
4164 if (scope == UpdateMaster)
4165 cbuf.structureChanged();
4169 static depth_type getDepth(DocIterator const & it)
4171 depth_type depth = 0;
4172 for (size_t i = 0 ; i < it.depth() ; ++i)
4173 if (!it[i].inset().inMathed())
4174 depth += it[i].paragraph().getDepth() + 1;
4175 // remove 1 since the outer inset does not count
4179 static depth_type getItemDepth(ParIterator const & it)
4181 Paragraph const & par = *it;
4182 LabelType const labeltype = par.layout().labeltype;
4184 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4187 // this will hold the lowest depth encountered up to now.
4188 depth_type min_depth = getDepth(it);
4189 ParIterator prev_it = it;
4192 --prev_it.top().pit();
4194 // start of nested inset: go to outer par
4196 if (prev_it.empty()) {
4197 // start of document: nothing to do
4202 // We search for the first paragraph with same label
4203 // that is not more deeply nested.
4204 Paragraph & prev_par = *prev_it;
4205 depth_type const prev_depth = getDepth(prev_it);
4206 if (labeltype == prev_par.layout().labeltype) {
4207 if (prev_depth < min_depth)
4208 return prev_par.itemdepth + 1;
4209 if (prev_depth == min_depth)
4210 return prev_par.itemdepth;
4212 min_depth = min(min_depth, prev_depth);
4213 // small optimization: if we are at depth 0, we won't
4214 // find anything else
4215 if (prev_depth == 0)
4221 static bool needEnumCounterReset(ParIterator const & it)
4223 Paragraph const & par = *it;
4224 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4225 depth_type const cur_depth = par.getDepth();
4226 ParIterator prev_it = it;
4227 while (prev_it.pit()) {
4228 --prev_it.top().pit();
4229 Paragraph const & prev_par = *prev_it;
4230 if (prev_par.getDepth() <= cur_depth)
4231 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4233 // start of nested inset: reset
4238 // set the label of a paragraph. This includes the counters.
4239 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4241 BufferParams const & bp = owner_->masterBuffer()->params();
4242 DocumentClass const & textclass = bp.documentClass();
4243 Paragraph & par = it.paragraph();
4244 Layout const & layout = par.layout();
4245 Counters & counters = textclass.counters();
4247 if (par.params().startOfAppendix()) {
4248 // FIXME: only the counter corresponding to toplevel
4249 // sectioning should be reset
4251 counters.appendix(true);
4253 par.params().appendix(counters.appendix());
4255 // Compute the item depth of the paragraph
4256 par.itemdepth = getItemDepth(it);
4258 if (layout.margintype == MARGIN_MANUAL) {
4259 if (par.params().labelWidthString().empty())
4260 par.params().labelWidthString(par.expandLabel(layout, bp));
4261 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4262 // we do not need to do anything here, since the empty case is
4263 // handled during export.
4265 par.params().labelWidthString(docstring());
4268 switch(layout.labeltype) {
4270 if (layout.toclevel <= bp.secnumdepth
4271 && (layout.latextype != LATEX_ENVIRONMENT
4272 || it.text()->isFirstInSequence(it.pit()))) {
4273 if (counters.hasCounter(layout.counter))
4274 counters.step(layout.counter, utype);
4275 par.params().labelString(par.expandLabel(layout, bp));
4277 par.params().labelString(docstring());
4280 case LABEL_ITEMIZE: {
4281 // At some point of time we should do something more
4282 // clever here, like:
4283 // par.params().labelString(
4284 // bp.user_defined_bullet(par.itemdepth).getText());
4285 // for now, use a simple hardcoded label
4286 docstring itemlabel;
4287 switch (par.itemdepth) {
4289 itemlabel = char_type(0x2022);
4292 itemlabel = char_type(0x2013);
4295 itemlabel = char_type(0x2217);
4298 itemlabel = char_type(0x2219); // or 0x00b7
4301 par.params().labelString(itemlabel);
4305 case LABEL_ENUMERATE: {
4306 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4308 switch (par.itemdepth) {
4317 enumcounter += "iv";
4320 // not a valid enumdepth...
4324 // Maybe we have to reset the enumeration counter.
4325 if (needEnumCounterReset(it))
4326 counters.reset(enumcounter);
4327 counters.step(enumcounter, utype);
4329 string const & lang = par.getParLanguage(bp)->code();
4330 par.params().labelString(counters.theCounter(enumcounter, lang));
4335 case LABEL_SENSITIVE: {
4336 string const & type = counters.current_float();
4337 docstring full_label;
4339 full_label = owner_->B_("Senseless!!! ");
4341 docstring name = owner_->B_(textclass.floats().getType(type).name());
4342 if (counters.hasCounter(from_utf8(type))) {
4343 string const & lang = par.getParLanguage(bp)->code();
4344 counters.step(from_utf8(type), utype);
4345 full_label = bformat(from_ascii("%1$s %2$s:"),
4347 counters.theCounter(from_utf8(type), lang));
4349 full_label = bformat(from_ascii("%1$s #:"), name);
4351 par.params().labelString(full_label);
4355 case LABEL_NO_LABEL:
4356 par.params().labelString(docstring());
4360 case LABEL_TOP_ENVIRONMENT:
4361 case LABEL_CENTERED_TOP_ENVIRONMENT:
4364 par.params().labelString(par.expandLabel(layout, bp));
4370 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4372 LASSERT(parit.pit() == 0, /**/);
4374 // Set the position of the text in the buffer to be able
4375 // to resolve macros in it.
4376 parit.text()->setMacrocontextPosition(parit);
4378 depth_type maxdepth = 0;
4379 pit_type const lastpit = parit.lastpit();
4380 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4381 // reduce depth if necessary
4382 parit->params().depth(min(parit->params().depth(), maxdepth));
4383 maxdepth = parit->getMaxDepthAfter();
4385 if (utype == OutputUpdate) {
4386 // track the active counters
4387 // we have to do this for the master buffer, since the local
4388 // buffer isn't tracking anything.
4389 masterBuffer()->params().documentClass().counters().
4390 setActiveLayout(parit->layout());
4393 // set the counter for this paragraph
4394 d->setLabel(parit, utype);
4397 InsetList::const_iterator iit = parit->insetList().begin();
4398 InsetList::const_iterator end = parit->insetList().end();
4399 for (; iit != end; ++iit) {
4400 parit.pos() = iit->pos;
4401 iit->inset->updateBuffer(parit, utype);
4407 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4408 WordLangTuple & word_lang, docstring_list & suggestions) const
4412 suggestions.clear();
4413 word_lang = WordLangTuple();
4414 bool const to_end = to.empty();
4415 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4416 // OK, we start from here.
4417 for (; from != end; from.forwardPos()) {
4418 // We are only interested in text so remove the math CursorSlice.
4419 while (from.inMathed()) {
4423 // If from is at the end of the document (which is possible
4424 // when leaving the mathed) LyX will crash later otherwise.
4425 if (from.atEnd() || (!to_end && from >= end))
4428 from.paragraph().spellCheck();
4429 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4430 if (SpellChecker::misspelled(res)) {
4435 // Do not increase progress when from == to, otherwise the word
4436 // count will be wrong.
4446 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4448 bool inword = false;
4453 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4454 if (!dit.inTexted()) {
4459 Paragraph const & par = dit.paragraph();
4460 pos_type const pos = dit.pos();
4462 // Copied and adapted from isWordSeparator() in Paragraph
4463 if (pos == dit.lastpos()) {
4466 Inset const * ins = par.getInset(pos);
4467 if (ins && skipNoOutput && !ins->producesOutput()) {
4470 // stop if end of range was skipped
4471 if (!to.atEnd() && dit >= to)
4474 } else if (!par.isDeleted(pos)) {
4475 if (par.isWordSeparator(pos))
4481 if (ins && ins->isLetter())
4483 else if (ins && ins->isSpace())
4486 char_type const c = par.getChar(pos);
4487 if (isPrintableNonspace(c))
4489 else if (isSpace(c))
4499 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4501 d->updateStatistics(from, to, skipNoOutput);
4505 int Buffer::wordCount() const
4507 return d->wordCount();
4511 int Buffer::charCount(bool with_blanks) const
4513 return d->charCount(with_blanks);
4517 Buffer::ReadStatus Buffer::reload()
4520 // c.f. bug http://www.lyx.org/trac/ticket/6587
4521 removeAutosaveFile();
4522 // e.g., read-only status could have changed due to version control
4523 d->filename.refresh();
4524 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4526 // clear parent. this will get reset if need be.
4528 ReadStatus const status = loadLyXFile();
4529 if (status == ReadSuccess) {
4534 message(bformat(_("Document %1$s reloaded."), disp_fn));
4537 message(bformat(_("Could not reload document %1$s."), disp_fn));
4547 bool Buffer::saveAs(FileName const & fn)
4549 FileName const old_name = fileName();
4550 FileName const old_auto = getAutosaveFileName();
4551 bool const old_unnamed = isUnnamed();
4558 // bring the autosave file with us, just in case.
4559 moveAutosaveFile(old_auto);
4560 // validate version control data and
4561 // correct buffer title
4562 lyxvc().file_found_hook(fileName());
4564 // the file has now been saved to the new location.
4565 // we need to check that the locations of child buffers
4567 checkChildBuffers();
4571 // reset the old filename and unnamed state
4572 setFileName(old_name);
4573 setUnnamed(old_unnamed);
4579 // FIXME We could do better here, but it is complicated. What would be
4580 // nice is to offer either (a) to save the child buffer to an appropriate
4581 // location, so that it would "move with the master", or else (b) to update
4582 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4583 // complicated, because the code for this lives in GuiView.
4584 void Buffer::checkChildBuffers()
4586 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4587 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4588 for (; it != en; ++it) {
4589 DocIterator dit = it->second;
4590 Buffer * cbuf = const_cast<Buffer *>(it->first);
4591 if (!cbuf || !theBufferList().isLoaded(cbuf))
4593 Inset * inset = dit.nextInset();
4594 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4595 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4596 docstring const & incfile = inset_inc->getParam("filename");
4597 string oldloc = cbuf->absFileName();
4598 string newloc = makeAbsPath(to_utf8(incfile),
4599 onlyPath(absFileName())).absFileName();
4600 if (oldloc == newloc)
4602 // the location of the child file is incorrect.
4603 Alert::warning(_("Included File Invalid"),
4604 bformat(_("Saving this document to a new location has made the file:\n"
4606 "inaccessible. You will need to update the included filename."),
4607 from_utf8(oldloc)));
4609 inset_inc->setChildBuffer(0);
4611 // invalidate cache of children
4612 d->children_positions.clear();
4613 d->position_to_children.clear();