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...)?
198 /// is this an internal bufffer?
199 bool internal_buffer;
204 /// name of the file the buffer is associated with.
207 /** Set to true only when the file is fully loaded.
208 * Used to prevent the premature generation of previews
209 * and by the citation inset.
211 bool file_fully_loaded;
214 mutable TocBackend toc_backend;
217 typedef pair<DocIterator, MacroData> ScopeMacro;
218 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
219 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
220 /// map from the macro name to the position map,
221 /// which maps the macro definition position to the scope and the MacroData.
222 NamePositionScopeMacroMap macros;
223 /// This seem to change the way Buffer::getMacro() works
224 mutable bool macro_lock;
226 /// positions of child buffers in the buffer
227 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
228 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
229 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
230 /// position of children buffers in this buffer
231 BufferPositionMap children_positions;
232 /// map from children inclusion positions to their scope and their buffer
233 PositionScopeBufferMap position_to_children;
235 /// Container for all sort of Buffer dependant errors.
236 map<string, ErrorList> errorLists;
238 /// timestamp and checksum used to test if the file has been externally
239 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
241 unsigned long checksum_;
244 frontend::WorkAreaManager * wa_;
246 frontend::GuiBufferDelegate * gui_;
251 /// A cache for the bibfiles (including bibfiles of loaded child
252 /// documents), needed for appropriate update of natbib labels.
253 mutable support::FileNameList bibfiles_cache_;
255 // FIXME The caching mechanism could be improved. At present, we have a
256 // cache for each Buffer, that caches all the bibliography info for that
257 // Buffer. A more efficient solution would be to have a global cache per
258 // file, and then to construct the Buffer's bibinfo from that.
259 /// A cache for bibliography info
260 mutable BiblioInfo bibinfo_;
261 /// whether the bibinfo cache is valid
262 mutable bool bibinfo_cache_valid_;
263 /// whether the bibfile cache is valid
264 mutable bool bibfile_cache_valid_;
265 /// Cache of timestamps of .bib files
266 map<FileName, time_t> bibfile_status_;
267 /// Indicates whether the bibinfo has changed since the last time
268 /// we ran updateBuffer(), i.e., whether citation labels may need
270 mutable bool cite_labels_valid_;
272 mutable RefCache ref_cache_;
274 /// our Text that should be wrapped in an InsetText
278 PreviewLoader * preview_loader_;
280 /// This is here to force the test to be done whenever parent_buffer
282 Buffer const * parent() const {
283 // if parent_buffer is not loaded, then it has been unloaded,
284 // which means that parent_buffer is an invalid pointer. So we
285 // set it to null in that case.
286 // however, the BufferList doesn't know about cloned buffers, so
287 // they will always be regarded as unloaded. in that case, we hope
289 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
291 return parent_buffer;
295 void setParent(Buffer const * pb) {
296 if (parent_buffer == pb)
299 if (!cloned_buffer_ && parent_buffer && pb)
300 LYXERR0("Warning: a buffer should not have two parents!");
302 if (!cloned_buffer_ && parent_buffer) {
303 parent_buffer->invalidateBibfileCache();
304 parent_buffer->invalidateBibinfoCache();
308 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
309 /// This one is useful for preview detached in a thread.
310 Buffer const * cloned_buffer_;
312 CloneList * clone_list_;
313 /// are we in the process of exporting this buffer?
314 mutable bool doing_export;
316 /// compute statistics
317 /// \p from initial position
318 /// \p to points to the end position
319 void updateStatistics(DocIterator & from, DocIterator & to,
320 bool skipNoOutput = true);
321 /// statistics accessor functions
322 int wordCount() const { return word_count_; }
323 int charCount(bool with_blanks) const {
325 + (with_blanks ? blank_count_ : 0);
329 /// So we can force access via the accessors.
330 mutable Buffer const * parent_buffer;
339 /// Creates the per buffer temporary directory
340 static FileName createBufferTmpDir()
343 // We are in our own directory. Why bother to mangle name?
344 // In fact I wrote this code to circumvent a problematic behaviour
345 // (bug?) of EMX mkstemp().
346 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
347 convert<string>(count++));
349 if (!tmpfl.createDirectory(0777)) {
350 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
351 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
352 from_utf8(tmpfl.absFileName())));
358 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
359 Buffer const * cloned_buffer)
360 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
361 internal_buffer(false), read_only(readonly_), filename(file),
362 file_fully_loaded(false), toc_backend(owner), macro_lock(false),
363 timestamp_(0), checksum_(0), wa_(0), gui_(0), undo_(*owner),
364 bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
365 cite_labels_valid_(false), preview_loader_(0),
366 cloned_buffer_(cloned_buffer), clone_list_(0),
367 doing_export(false), parent_buffer(0)
369 if (!cloned_buffer_) {
370 temppath = createBufferTmpDir();
371 lyxvc.setBuffer(owner_);
373 wa_ = new frontend::WorkAreaManager;
376 temppath = cloned_buffer_->d->temppath;
377 file_fully_loaded = true;
378 params = cloned_buffer_->d->params;
379 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
380 bibinfo_ = cloned_buffer_->d->bibinfo_;
381 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
382 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
383 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
384 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
385 unnamed = cloned_buffer_->d->unnamed;
386 internal_buffer = cloned_buffer_->d->internal_buffer;
390 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
391 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
393 LYXERR(Debug::INFO, "Buffer::Buffer()");
395 d->inset = new InsetText(*cloned_buffer->d->inset);
396 d->inset->setBuffer(*this);
397 // FIXME: optimize this loop somewhat, maybe by creating a new
398 // general recursive Inset::setId().
399 DocIterator it = doc_iterator_begin(this);
400 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
401 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
402 it.paragraph().setId(cloned_it.paragraph().id());
404 d->inset = new InsetText(this);
405 d->inset->setAutoBreakRows(true);
406 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
412 LYXERR(Debug::INFO, "Buffer::~Buffer()");
413 // here the buffer should take care that it is
414 // saved properly, before it goes into the void.
416 // GuiView already destroyed
420 // No need to do additional cleanups for internal buffer.
426 // this is in case of recursive includes: we won't try to delete
427 // ourselves as a child.
428 d->clone_list_->erase(this);
429 // loop over children
430 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
431 Impl::BufferPositionMap::iterator end = d->children_positions.end();
432 for (; it != end; ++it) {
433 Buffer * child = const_cast<Buffer *>(it->first);
434 if (d->clone_list_->erase(child))
437 // if we're the master buffer, then we should get rid of the list
440 // if this is not empty, we have leaked something. worse, one of the
441 // children still has a reference to this list.
442 LASSERT(d->clone_list_->empty(), /* */);
443 list<CloneList *>::iterator it =
444 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
445 LASSERT(it != cloned_buffers.end(), /* */);
446 cloned_buffers.erase(it);
447 delete d->clone_list_;
449 // FIXME Do we really need to do this right before we delete d?
450 // clear references to children in macro tables
451 d->children_positions.clear();
452 d->position_to_children.clear();
454 // loop over children
455 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
456 Impl::BufferPositionMap::iterator end = d->children_positions.end();
457 for (; it != end; ++it) {
458 Buffer * child = const_cast<Buffer *>(it->first);
459 if (theBufferList().isLoaded(child))
460 theBufferList().releaseChild(this, child);
464 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
465 msg += emergencyWrite();
466 Alert::warning(_("Attempting to close changed document!"), msg);
469 // FIXME Do we really need to do this right before we delete d?
470 // clear references to children in macro tables
471 d->children_positions.clear();
472 d->position_to_children.clear();
474 if (!d->temppath.destroyDirectory()) {
475 Alert::warning(_("Could not remove temporary directory"),
476 bformat(_("Could not remove the temporary directory %1$s"),
477 from_utf8(d->temppath.absFileName())));
486 Buffer * Buffer::cloneFromMaster() const
489 cloned_buffers.push_back(new CloneList());
490 CloneList * clones = cloned_buffers.back();
492 masterBuffer()->cloneWithChildren(bufmap, clones);
494 // make sure we got cloned
495 BufferMap::const_iterator bit = bufmap.find(this);
496 LASSERT(bit != bufmap.end(), return 0);
497 Buffer * cloned_buffer = bit->second;
499 return cloned_buffer;
503 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
505 // have we already been cloned?
506 if (bufmap.find(this) != bufmap.end())
509 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
510 bufmap[this] = buffer_clone;
511 clones->insert(buffer_clone);
512 buffer_clone->d->clone_list_ = clones;
513 buffer_clone->d->macro_lock = true;
514 buffer_clone->d->children_positions.clear();
515 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
516 // math macro caches need to be rethought and simplified.
517 // I am not sure wether we should handle Buffer cloning here or in BufferList.
518 // Right now BufferList knows nothing about buffer clones.
519 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
520 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
521 for (; it != end; ++it) {
522 DocIterator dit = it->first.clone(buffer_clone);
523 dit.setBuffer(buffer_clone);
524 Buffer * child = const_cast<Buffer *>(it->second.second);
526 child->cloneWithChildren(bufmap, clones);
527 BufferMap::iterator const bit = bufmap.find(child);
528 LASSERT(bit != bufmap.end(), continue);
529 Buffer * child_clone = bit->second;
531 Inset * inset = dit.nextInset();
532 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
533 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
534 inset_inc->setChildBuffer(child_clone);
535 child_clone->d->setParent(buffer_clone);
536 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
537 buffer_clone->setChild(dit, child_clone);
539 buffer_clone->d->macro_lock = false;
544 Buffer * Buffer::cloneBufferOnly() const {
545 cloned_buffers.push_back(new CloneList());
546 CloneList * clones = cloned_buffers.back();
547 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
548 clones->insert(buffer_clone);
549 buffer_clone->d->clone_list_ = clones;
550 // we won't be cloning the children
551 buffer_clone->d->children_positions.clear();
556 bool Buffer::isClone() const
558 return d->cloned_buffer_;
562 void Buffer::changed(bool update_metrics) const
565 d->wa_->redrawAll(update_metrics);
569 frontend::WorkAreaManager & Buffer::workAreaManager() const
571 LASSERT(d->wa_, /**/);
576 Text & Buffer::text() const
578 return d->inset->text();
582 Inset & Buffer::inset() const
588 BufferParams & Buffer::params()
594 BufferParams const & Buffer::params() const
600 ParagraphList & Buffer::paragraphs()
602 return text().paragraphs();
606 ParagraphList const & Buffer::paragraphs() const
608 return text().paragraphs();
612 LyXVC & Buffer::lyxvc()
618 LyXVC const & Buffer::lyxvc() const
624 string const Buffer::temppath() const
626 return d->temppath.absFileName();
630 TexRow & Buffer::texrow()
636 TexRow const & Buffer::texrow() const
642 TocBackend & Buffer::tocBackend() const
644 return d->toc_backend;
648 Undo & Buffer::undo()
654 void Buffer::setChild(DocIterator const & dit, Buffer * child)
656 d->children_positions[child] = dit;
660 string Buffer::latexName(bool const no_path) const
662 FileName latex_name =
663 makeLatexName(d->exportFileName());
664 return no_path ? latex_name.onlyFileName()
665 : latex_name.absFileName();
669 FileName Buffer::Impl::exportFileName() const
671 docstring const branch_suffix =
672 params.branchlist().getFileNameSuffix();
673 if (branch_suffix.empty())
676 string const name = filename.onlyFileNameWithoutExt()
677 + to_utf8(branch_suffix);
678 FileName res(filename.onlyPath().absFileName() + "/" + name);
679 res.changeExtension(filename.extension());
685 string Buffer::logName(LogType * type) const
687 string const filename = latexName(false);
689 if (filename.empty()) {
695 string const path = temppath();
697 FileName const fname(addName(temppath(),
698 onlyFileName(changeExtension(filename,
701 // FIXME: how do we know this is the name of the build log?
702 FileName const bname(
703 addName(path, onlyFileName(
704 changeExtension(filename,
705 formats.extension(params().bufferFormat()) + ".out"))));
707 // Also consider the master buffer log file
708 FileName masterfname = fname;
710 if (masterBuffer() != this) {
711 string const mlogfile = masterBuffer()->logName(&mtype);
712 masterfname = FileName(mlogfile);
715 // If no Latex log or Build log is newer, show Build log
716 if (bname.exists() &&
717 ((!fname.exists() && !masterfname.exists())
718 || (fname.lastModified() < bname.lastModified()
719 && masterfname.lastModified() < bname.lastModified()))) {
720 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
723 return bname.absFileName();
724 // If we have a newer master file log or only a master log, show this
725 } else if (fname != masterfname
726 && (!fname.exists() && (masterfname.exists()
727 || fname.lastModified() < masterfname.lastModified()))) {
728 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
731 return masterfname.absFileName();
733 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
736 return fname.absFileName();
740 void Buffer::setReadonly(bool const flag)
742 if (d->read_only != flag) {
749 void Buffer::setFileName(FileName const & fname)
752 setReadonly(d->filename.isReadOnly());
758 int Buffer::readHeader(Lexer & lex)
760 int unknown_tokens = 0;
762 int begin_header_line = -1;
764 // Initialize parameters that may be/go lacking in header:
765 params().branchlist().clear();
766 params().preamble.erase();
767 params().options.erase();
768 params().master.erase();
769 params().float_placement.erase();
770 params().paperwidth.erase();
771 params().paperheight.erase();
772 params().leftmargin.erase();
773 params().rightmargin.erase();
774 params().topmargin.erase();
775 params().bottommargin.erase();
776 params().headheight.erase();
777 params().headsep.erase();
778 params().footskip.erase();
779 params().columnsep.erase();
780 params().fonts_cjk.erase();
781 params().listings_params.clear();
782 params().clearLayoutModules();
783 params().clearRemovedModules();
784 params().clearIncludedChildren();
785 params().pdfoptions().clear();
786 params().indiceslist().clear();
787 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
788 params().isbackgroundcolor = false;
789 params().fontcolor = RGBColor(0, 0, 0);
790 params().isfontcolor = false;
791 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
792 params().boxbgcolor = RGBColor(0xFF, 0, 0);
793 params().html_latex_start.clear();
794 params().html_latex_end.clear();
795 params().html_math_img_scale = 1.0;
796 params().output_sync_macro.erase();
797 params().local_layout.clear();
799 for (int i = 0; i < 4; ++i) {
800 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
801 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
804 ErrorList & errorList = d->errorLists["Parse"];
813 if (token == "\\end_header")
817 if (token == "\\begin_header") {
818 begin_header_line = line;
822 LYXERR(Debug::PARSER, "Handling document header token: `"
825 string unknown = params().readToken(lex, token, d->filename.onlyPath());
826 if (!unknown.empty()) {
827 if (unknown[0] != '\\' && token == "\\textclass") {
828 Alert::warning(_("Unknown document class"),
829 bformat(_("Using the default document class, because the "
830 "class %1$s is unknown."), from_utf8(unknown)));
833 docstring const s = bformat(_("Unknown token: "
837 errorList.push_back(ErrorItem(_("Document header error"),
842 if (begin_header_line) {
843 docstring const s = _("\\begin_header is missing");
844 errorList.push_back(ErrorItem(_("Document header error"),
848 params().makeDocumentClass();
850 return unknown_tokens;
855 // changed to be public and have one parameter
856 // Returns true if "\end_document" is not read (Asger)
857 bool Buffer::readDocument(Lexer & lex)
859 ErrorList & errorList = d->errorLists["Parse"];
862 // remove dummy empty par
863 paragraphs().clear();
865 if (!lex.checkFor("\\begin_document")) {
866 docstring const s = _("\\begin_document is missing");
867 errorList.push_back(ErrorItem(_("Document header error"),
873 if (params().outputChanges) {
874 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
875 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
876 LaTeXFeatures::isAvailable("xcolor");
878 if (!dvipost && !xcolorulem) {
879 Alert::warning(_("Changes not shown in LaTeX output"),
880 _("Changes will not be highlighted in LaTeX output, "
881 "because neither dvipost nor xcolor/ulem are installed.\n"
882 "Please install these packages or redefine "
883 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
884 } else if (!xcolorulem) {
885 Alert::warning(_("Changes not shown in LaTeX output"),
886 _("Changes will not be highlighted in LaTeX output "
887 "when using pdflatex, because xcolor and ulem are not installed.\n"
888 "Please install both packages or redefine "
889 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
893 if (!params().master.empty()) {
894 FileName const master_file = makeAbsPath(params().master,
895 onlyPath(absFileName()));
896 if (isLyXFileName(master_file.absFileName())) {
898 checkAndLoadLyXFile(master_file, true);
900 // necessary e.g. after a reload
901 // to re-register the child (bug 5873)
902 // FIXME: clean up updateMacros (here, only
903 // child registering is needed).
904 master->updateMacros();
905 // set master as master buffer, but only
906 // if we are a real child
907 if (master->isChild(this))
909 // if the master is not fully loaded
910 // it is probably just loading this
911 // child. No warning needed then.
912 else if (master->isFullyLoaded())
913 LYXERR0("The master '"
915 << "' assigned to this document ("
917 << ") does not include "
918 "this document. Ignoring the master assignment.");
923 // assure we have a default index
924 params().indiceslist().addDefault(B_("Index"));
927 bool const res = text().read(lex, errorList, d->inset);
929 // inform parent buffer about local macros
931 Buffer const * pbuf = parent();
932 UserMacroSet::const_iterator cit = usermacros.begin();
933 UserMacroSet::const_iterator end = usermacros.end();
934 for (; cit != end; ++cit)
935 pbuf->usermacros.insert(*cit);
939 updateMacroInstances(InternalUpdate);
944 bool Buffer::readString(string const & s)
946 params().compressed = false;
951 FileName const fn = FileName::tempName("Buffer_readString");
954 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
955 if (ret_plf != ReadSuccess)
958 if (file_format != LYX_FORMAT) {
959 // We need to call lyx2lyx, so write the input to a file
960 ofstream os(fn.toFilesystemEncoding().c_str());
964 return readFile(fn) == ReadSuccess;
967 if (readDocument(lex))
973 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
977 if (!lex.setFile(fname)) {
978 Alert::error(_("File Not Found"),
979 bformat(_("Unable to open file `%1$s'."),
980 from_utf8(fn.absFileName())));
981 return ReadFileNotFound;
985 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
986 if (ret_plf != ReadSuccess)
989 if (file_format != LYX_FORMAT) {
991 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
992 if (ret_clf != ReadSuccess)
994 return readFile(tmpFile);
997 // FIXME: InsetInfo needs to know whether the file is under VCS
998 // during the parse process, so this has to be done before.
999 lyxvc().file_found_hook(d->filename);
1001 if (readDocument(lex)) {
1002 Alert::error(_("Document format failure"),
1003 bformat(_("%1$s ended unexpectedly, which means"
1004 " that it is probably corrupted."),
1005 from_utf8(fn.absFileName())));
1006 return ReadDocumentFailure;
1009 d->file_fully_loaded = true;
1010 d->read_only = !d->filename.isWritable();
1011 params().compressed = formats.isZippedFile(d->filename);
1017 bool Buffer::isFullyLoaded() const
1019 return d->file_fully_loaded;
1023 void Buffer::setFullyLoaded(bool value)
1025 d->file_fully_loaded = value;
1029 PreviewLoader * Buffer::loader() const
1031 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1033 if (!d->preview_loader_)
1034 d->preview_loader_ = new PreviewLoader(*this);
1035 return d->preview_loader_;
1039 void Buffer::removePreviews() const
1041 delete d->preview_loader_;
1042 d->preview_loader_ = 0;
1046 void Buffer::updatePreviews() const
1048 PreviewLoader * ploader = loader();
1052 InsetIterator it = inset_iterator_begin(*d->inset);
1053 InsetIterator const end = inset_iterator_end(*d->inset);
1054 for (; it != end; ++it)
1055 it->addPreview(it, *ploader);
1057 ploader->startLoading();
1061 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1062 FileName const & fn, int & file_format) const
1064 if(!lex.checkFor("\\lyxformat")) {
1065 Alert::error(_("Document format failure"),
1066 bformat(_("%1$s is not a readable LyX document."),
1067 from_utf8(fn.absFileName())));
1068 return ReadNoLyXFormat;
1074 // LyX formats 217 and earlier were written as 2.17. This corresponds
1075 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1076 // these cases. See also: www.lyx.org/trac/changeset/1313.
1077 size_t dot = tmp_format.find_first_of(".,");
1078 if (dot != string::npos)
1079 tmp_format.erase(dot, 1);
1081 file_format = convert<int>(tmp_format);
1086 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1087 FileName & tmpfile, int from_format)
1089 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1090 if(tmpfile.empty()) {
1091 Alert::error(_("Conversion failed"),
1092 bformat(_("%1$s is from a different"
1093 " version of LyX, but a temporary"
1094 " file for converting it could"
1095 " not be created."),
1096 from_utf8(fn.absFileName())));
1097 return LyX2LyXNoTempFile;
1100 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1101 if (lyx2lyx.empty()) {
1102 Alert::error(_("Conversion script not found"),
1103 bformat(_("%1$s is from a different"
1104 " version of LyX, but the"
1105 " conversion script lyx2lyx"
1106 " could not be found."),
1107 from_utf8(fn.absFileName())));
1108 return LyX2LyXNotFound;
1112 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1113 ostringstream command;
1114 command << os::python()
1115 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1116 << " -t " << convert<string>(LYX_FORMAT)
1117 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1118 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1119 string const command_str = command.str();
1121 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1123 cmd_ret const ret = runCommand(command_str);
1124 if (ret.first != 0) {
1125 if (from_format < LYX_FORMAT) {
1126 Alert::error(_("Conversion script failed"),
1127 bformat(_("%1$s is from an older version"
1128 " of LyX and the lyx2lyx script"
1129 " failed to convert it."),
1130 from_utf8(fn.absFileName())));
1131 return LyX2LyXOlderFormat;
1133 Alert::error(_("Conversion script failed"),
1134 bformat(_("%1$s is from a newer version"
1135 " of LyX and the lyx2lyx script"
1136 " failed to convert it."),
1137 from_utf8(fn.absFileName())));
1138 return LyX2LyXNewerFormat;
1145 // Should probably be moved to somewhere else: BufferView? GuiView?
1146 bool Buffer::save() const
1148 docstring const file = makeDisplayPath(absFileName(), 20);
1149 d->filename.refresh();
1151 // check the read-only status before moving the file as a backup
1152 if (d->filename.exists()) {
1153 bool const read_only = !d->filename.isWritable();
1155 Alert::warning(_("File is read-only"),
1156 bformat(_("The file %1$s cannot be written because it "
1157 "is marked as read-only."), file));
1162 // ask if the disk file has been externally modified (use checksum method)
1163 if (fileName().exists() && isExternallyModified(checksum_method)) {
1165 bformat(_("Document %1$s has been externally modified. "
1166 "Are you sure you want to overwrite this file?"), file);
1167 int const ret = Alert::prompt(_("Overwrite modified file?"),
1168 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1173 // We don't need autosaves in the immediate future. (Asger)
1174 resetAutosaveTimers();
1176 FileName backupName;
1177 bool madeBackup = false;
1179 // make a backup if the file already exists
1180 if (lyxrc.make_backup && fileName().exists()) {
1181 backupName = FileName(absFileName() + '~');
1182 if (!lyxrc.backupdir_path.empty()) {
1183 string const mangledName =
1184 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1185 backupName = FileName(addName(lyxrc.backupdir_path,
1189 // Except file is symlink do not copy because of #6587.
1190 // Hard links have bad luck.
1191 if (fileName().isSymLink())
1192 madeBackup = fileName().copyTo(backupName);
1194 madeBackup = fileName().moveTo(backupName);
1197 Alert::error(_("Backup failure"),
1198 bformat(_("Cannot create backup file %1$s.\n"
1199 "Please check whether the directory exists and is writable."),
1200 from_utf8(backupName.absFileName())));
1201 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1205 if (writeFile(d->filename)) {
1209 // Saving failed, so backup is not backup
1211 backupName.moveTo(d->filename);
1217 bool Buffer::writeFile(FileName const & fname) const
1219 // FIXME Do we need to do these here? I don't think writing
1220 // the LyX file depends upon it. (RGH)
1222 // updateMacroInstances();
1224 if (d->read_only && fname == d->filename)
1227 bool retval = false;
1229 docstring const str = bformat(_("Saving document %1$s..."),
1230 makeDisplayPath(fname.absFileName()));
1233 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1235 if (params().compressed) {
1236 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1237 retval = ofs && write(ofs);
1239 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1240 retval = ofs && write(ofs);
1244 message(str + _(" could not write file!"));
1249 // removeAutosaveFile();
1252 message(str + _(" done."));
1258 docstring Buffer::emergencyWrite()
1260 // No need to save if the buffer has not changed.
1264 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1266 docstring user_message = bformat(
1267 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1269 // We try to save three places:
1270 // 1) Same place as document. Unless it is an unnamed doc.
1272 string s = absFileName();
1275 if (writeFile(FileName(s))) {
1277 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1278 return user_message;
1280 user_message += " " + _("Save failed! Trying again...\n");
1284 // 2) In HOME directory.
1285 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1287 lyxerr << ' ' << s << endl;
1288 if (writeFile(FileName(s))) {
1290 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1291 return user_message;
1294 user_message += " " + _("Save failed! Trying yet again...\n");
1296 // 3) In "/tmp" directory.
1297 // MakeAbsPath to prepend the current
1298 // drive letter on OS/2
1299 s = addName(package().temp_dir().absFileName(), absFileName());
1301 lyxerr << ' ' << s << endl;
1302 if (writeFile(FileName(s))) {
1304 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1305 return user_message;
1308 user_message += " " + _("Save failed! Bummer. Document is lost.");
1311 return user_message;
1315 bool Buffer::write(ostream & ofs) const
1318 // Use the standard "C" locale for file output.
1319 ofs.imbue(locale::classic());
1322 // The top of the file should not be written by params().
1324 // write out a comment in the top of the file
1325 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1326 << " created this file. For more info see http://www.lyx.org/\n"
1327 << "\\lyxformat " << LYX_FORMAT << "\n"
1328 << "\\begin_document\n";
1330 /// For each author, set 'used' to true if there is a change
1331 /// by this author in the document; otherwise set it to 'false'.
1332 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1333 AuthorList::Authors::const_iterator a_end = params().authors().end();
1334 for (; a_it != a_end; ++a_it)
1335 a_it->setUsed(false);
1337 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1338 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1339 for ( ; it != end; ++it)
1340 it->checkAuthors(params().authors());
1342 // now write out the buffer parameters.
1343 ofs << "\\begin_header\n";
1344 params().writeFile(ofs);
1345 ofs << "\\end_header\n";
1348 ofs << "\n\\begin_body\n";
1350 ofs << "\n\\end_body\n";
1352 // Write marker that shows file is complete
1353 ofs << "\\end_document" << endl;
1355 // Shouldn't really be needed....
1358 // how to check if close went ok?
1359 // Following is an attempt... (BE 20001011)
1361 // good() returns false if any error occured, including some
1362 // formatting error.
1363 // bad() returns true if something bad happened in the buffer,
1364 // which should include file system full errors.
1369 lyxerr << "File was not closed properly." << endl;
1376 bool Buffer::makeLaTeXFile(FileName const & fname,
1377 string const & original_path,
1378 OutputParams const & runparams_in,
1379 OutputWhat output) const
1381 OutputParams runparams = runparams_in;
1383 // This is necessary for LuaTeX/XeTeX with tex fonts.
1384 // See FIXME in BufferParams::encoding()
1385 if (runparams.isFullUnicode())
1386 runparams.encoding = encodings.fromLyXName("utf8-plain");
1388 string const encoding = runparams.encoding->iconvName();
1389 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1392 try { ofs.reset(encoding); }
1393 catch (iconv_codecvt_facet_exception & e) {
1394 lyxerr << "Caught iconv exception: " << e.what() << endl;
1395 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1396 "verify that the support software for your encoding (%1$s) is "
1397 "properly installed"), from_ascii(encoding)));
1400 if (!openFileWrite(ofs, fname))
1403 //TexStream ts(ofs.rdbuf(), &texrow());
1404 ErrorList & errorList = d->errorLists["Export"];
1406 bool failed_export = false;
1407 otexstream os(ofs, d->texrow);
1409 // make sure we are ready to export
1410 // this needs to be done before we validate
1411 // FIXME Do we need to do this all the time? I.e., in children
1412 // of a master we are exporting?
1414 updateMacroInstances(OutputUpdate);
1417 os.texrow().reset();
1418 writeLaTeXSource(os, original_path, runparams, output);
1420 catch (EncodingException & e) {
1421 odocstringstream ods;
1422 ods.put(e.failed_char);
1424 oss << "0x" << hex << e.failed_char << dec;
1425 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1426 " (code point %2$s)"),
1427 ods.str(), from_utf8(oss.str()));
1428 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1429 "representable in the chosen encoding.\n"
1430 "Changing the document encoding to utf8 could help."),
1431 e.par_id, e.pos, e.pos + 1));
1432 failed_export = true;
1434 catch (iconv_codecvt_facet_exception & e) {
1435 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1436 _(e.what()), -1, 0, 0));
1437 failed_export = true;
1439 catch (exception const & e) {
1440 errorList.push_back(ErrorItem(_("conversion failed"),
1441 _(e.what()), -1, 0, 0));
1442 failed_export = true;
1445 lyxerr << "Caught some really weird exception..." << endl;
1451 failed_export = true;
1452 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1456 return !failed_export;
1460 void Buffer::writeLaTeXSource(otexstream & os,
1461 string const & original_path,
1462 OutputParams const & runparams_in,
1463 OutputWhat output) const
1465 // The child documents, if any, shall be already loaded at this point.
1467 OutputParams runparams = runparams_in;
1469 // Classify the unicode characters appearing in math insets
1470 Encodings::initUnicodeMath(*this);
1472 // validate the buffer.
1473 LYXERR(Debug::LATEX, " Validating buffer...");
1474 LaTeXFeatures features(*this, params(), runparams);
1476 LYXERR(Debug::LATEX, " Buffer validation done.");
1478 bool const output_preamble =
1479 output == FullSource || output == OnlyPreamble;
1480 bool const output_body =
1481 output == FullSource || output == OnlyBody;
1483 // The starting paragraph of the coming rows is the
1484 // first paragraph of the document. (Asger)
1485 if (output_preamble && runparams.nice) {
1486 os << "%% LyX " << lyx_version << " created this file. "
1487 "For more info, see http://www.lyx.org/.\n"
1488 "%% Do not edit unless you really know what "
1491 LYXERR(Debug::INFO, "lyx document header finished");
1493 // There are a few differences between nice LaTeX and usual files:
1494 // usual files have \batchmode and special input@path to allow
1495 // inclusion of figures specified by an explicitly relative path
1496 // (i.e., a path starting with './' or '../') with either \input or
1497 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1498 // input@path is set when the actual parameter original_path is set.
1499 // This is done for usual tex-file, but not for nice-latex-file.
1500 // (Matthias 250696)
1501 // Note that input@path is only needed for something the user does
1502 // in the preamble, included .tex files or ERT, files included by
1503 // LyX work without it.
1504 if (output_preamble) {
1505 if (!runparams.nice) {
1506 // code for usual, NOT nice-latex-file
1507 os << "\\batchmode\n"; // changed from \nonstopmode
1509 if (!original_path.empty()) {
1511 // We don't know the encoding of inputpath
1512 docstring const inputpath = from_utf8(original_path);
1513 docstring uncodable_glyphs;
1514 Encoding const * const enc = runparams.encoding;
1516 for (size_t n = 0; n < inputpath.size(); ++n) {
1517 if (!enc->encodable(inputpath[n])) {
1518 docstring const glyph(1, inputpath[n]);
1519 LYXERR0("Uncodable character '"
1521 << "' in input path!");
1522 uncodable_glyphs += glyph;
1527 // warn user if we found uncodable glyphs.
1528 if (!uncodable_glyphs.empty()) {
1529 frontend::Alert::warning(
1530 _("Uncodable character in file path"),
1532 _("The path of your document\n"
1534 "contains glyphs that are unknown "
1535 "in the current document encoding "
1536 "(namely %2$s). This may result in "
1537 "incomplete output, unless "
1538 "TEXINPUTS contains the document "
1539 "directory and you don't use "
1540 "explicitly relative paths (i.e., "
1541 "paths starting with './' or "
1542 "'../') in the preamble or in ERT."
1543 "\n\nIn case of problems, choose "
1544 "an appropriate document encoding\n"
1545 "(such as utf8) or change the "
1547 inputpath, uncodable_glyphs));
1550 support::latex_path(original_path);
1551 if (contains(docdir, '#')) {
1552 docdir = subst(docdir, "#", "\\#");
1553 os << "\\catcode`\\#=11"
1554 "\\def\\#{#}\\catcode`\\#=6\n";
1556 if (contains(docdir, '%')) {
1557 docdir = subst(docdir, "%", "\\%");
1558 os << "\\catcode`\\%=11"
1559 "\\def\\%{%}\\catcode`\\%=14\n";
1561 os << "\\makeatletter\n"
1562 << "\\def\\input@path{{"
1563 << docdir << "/}}\n"
1564 << "\\makeatother\n";
1568 // get parent macros (if this buffer has a parent) which will be
1569 // written at the document begin further down.
1570 MacroSet parentMacros;
1571 listParentMacros(parentMacros, features);
1573 runparams.use_polyglossia = features.usePolyglossia();
1574 // Write the preamble
1575 runparams.use_babel = params().writeLaTeX(os, features,
1576 d->filename.onlyPath());
1578 runparams.use_japanese = features.isRequired("japanese");
1584 os << "\\begin{document}\n";
1586 // output the parent macros
1587 MacroSet::iterator it = parentMacros.begin();
1588 MacroSet::iterator end = parentMacros.end();
1589 for (; it != end; ++it) {
1590 int num_lines = (*it)->write(os.os(), true);
1591 os.texrow().newlines(num_lines);
1594 } // output_preamble
1596 os.texrow().start(paragraphs().begin()->id(), 0);
1598 LYXERR(Debug::INFO, "preamble finished, now the body.");
1600 // if we are doing a real file with body, even if this is the
1601 // child of some other buffer, let's cut the link here.
1602 // This happens for example if only a child document is printed.
1603 Buffer const * save_parent = 0;
1604 if (output_preamble) {
1605 save_parent = d->parent();
1610 latexParagraphs(*this, text(), os, runparams);
1612 // Restore the parenthood if needed
1613 if (output_preamble)
1614 d->setParent(save_parent);
1616 // add this just in case after all the paragraphs
1619 if (output_preamble) {
1620 os << "\\end{document}\n";
1621 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1623 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1625 runparams_in.encoding = runparams.encoding;
1627 // Just to be sure. (Asger)
1628 os.texrow().newline();
1630 //for (int i = 0; i<d->texrow.rows(); i++) {
1632 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1633 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1636 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1637 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1641 void Buffer::makeDocBookFile(FileName const & fname,
1642 OutputParams const & runparams,
1643 OutputWhat output) const
1645 LYXERR(Debug::LATEX, "makeDocBookFile...");
1648 if (!openFileWrite(ofs, fname))
1651 // make sure we are ready to export
1652 // this needs to be done before we validate
1654 updateMacroInstances(OutputUpdate);
1656 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1660 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1664 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1665 OutputParams const & runparams,
1666 OutputWhat output) const
1668 LaTeXFeatures features(*this, params(), runparams);
1673 DocumentClass const & tclass = params().documentClass();
1674 string const top_element = tclass.latexname();
1676 bool const output_preamble =
1677 output == FullSource || output == OnlyPreamble;
1678 bool const output_body =
1679 output == FullSource || output == OnlyBody;
1681 if (output_preamble) {
1682 if (runparams.flavor == OutputParams::XML)
1683 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1686 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1689 if (! tclass.class_header().empty())
1690 os << from_ascii(tclass.class_header());
1691 else if (runparams.flavor == OutputParams::XML)
1692 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1693 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1695 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1697 docstring preamble = from_utf8(params().preamble);
1698 if (runparams.flavor != OutputParams::XML ) {
1699 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1700 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1701 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1702 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1705 string const name = runparams.nice
1706 ? changeExtension(absFileName(), ".sgml") : fname;
1707 preamble += features.getIncludedFiles(name);
1708 preamble += features.getLyXSGMLEntities();
1710 if (!preamble.empty()) {
1711 os << "\n [ " << preamble << " ]";
1717 string top = top_element;
1719 if (runparams.flavor == OutputParams::XML)
1720 top += params().language->code();
1722 top += params().language->code().substr(0, 2);
1725 if (!params().options.empty()) {
1727 top += params().options;
1730 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1731 << " file was created by LyX " << lyx_version
1732 << "\n See http://www.lyx.org/ for more information -->\n";
1734 params().documentClass().counters().reset();
1736 sgml::openTag(os, top);
1738 docbookParagraphs(text(), *this, os, runparams);
1739 sgml::closeTag(os, top_element);
1744 void Buffer::makeLyXHTMLFile(FileName const & fname,
1745 OutputParams const & runparams) const
1747 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1750 if (!openFileWrite(ofs, fname))
1753 // make sure we are ready to export
1754 // this has to be done before we validate
1755 updateBuffer(UpdateMaster, OutputUpdate);
1756 updateMacroInstances(OutputUpdate);
1758 writeLyXHTMLSource(ofs, runparams, FullSource);
1762 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1766 void Buffer::writeLyXHTMLSource(odocstream & os,
1767 OutputParams const & runparams,
1768 OutputWhat output) const
1770 LaTeXFeatures features(*this, params(), runparams);
1772 d->bibinfo_.makeCitationLabels(*this);
1774 bool const output_preamble =
1775 output == FullSource || output == OnlyPreamble;
1776 bool const output_body =
1777 output == FullSource || output == OnlyBody || output == IncludedFile;
1779 if (output_preamble) {
1780 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1781 << "<!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"
1782 // FIXME Language should be set properly.
1783 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1785 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1786 // FIXME Presumably need to set this right
1787 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1789 docstring const & doctitle = features.htmlTitle();
1791 << (doctitle.empty() ?
1792 from_ascii("LyX Document") :
1793 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1796 docstring styles = features.getTClassHTMLPreamble();
1797 if (!styles.empty())
1798 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1800 styles = from_utf8(features.getPreambleSnippets());
1801 if (!styles.empty())
1802 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1804 // we will collect CSS information in a stream, and then output it
1805 // either here, as part of the header, or else in a separate file.
1806 odocstringstream css;
1807 styles = from_utf8(features.getCSSSnippets());
1808 if (!styles.empty())
1809 css << "/* LyX Provided Styles */\n" << styles << '\n';
1811 styles = features.getTClassHTMLStyles();
1812 if (!styles.empty())
1813 css << "/* Layout-provided Styles */\n" << styles << '\n';
1815 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1816 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1817 if (needfg || needbg) {
1818 css << "\nbody {\n";
1821 << from_ascii(X11hexname(params().fontcolor))
1824 css << " background-color: "
1825 << from_ascii(X11hexname(params().backgroundcolor))
1830 docstring const dstyles = css.str();
1831 if (!dstyles.empty()) {
1832 bool written = false;
1833 if (params().html_css_as_file) {
1834 // open a file for CSS info
1836 string const fcssname = addName(temppath(), "docstyle.css");
1837 FileName const fcssfile = FileName(fcssname);
1838 if (openFileWrite(ocss, fcssfile)) {
1842 // write link to header
1843 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1845 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1848 // we are here if the CSS is supposed to be written to the header
1849 // or if we failed to write it to an external file.
1851 os << "<style type='text/css'>\n"
1860 bool const output_body_tag = (output != IncludedFile);
1861 if (output_body_tag)
1864 params().documentClass().counters().reset();
1865 xhtmlParagraphs(text(), *this, xs, runparams);
1866 if (output_body_tag)
1870 if (output_preamble)
1875 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1876 // Other flags: -wall -v0 -x
1877 int Buffer::runChktex()
1881 // get LaTeX-Filename
1882 FileName const path(temppath());
1883 string const name = addName(path.absFileName(), latexName());
1884 string const org_path = filePath();
1886 PathChanger p(path); // path to LaTeX file
1887 message(_("Running chktex..."));
1889 // Generate the LaTeX file if neccessary
1890 OutputParams runparams(¶ms().encoding());
1891 runparams.flavor = OutputParams::LATEX;
1892 runparams.nice = false;
1893 runparams.linelen = lyxrc.plaintext_linelen;
1894 makeLaTeXFile(FileName(name), org_path, runparams);
1897 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1898 int const res = chktex.run(terr); // run chktex
1901 Alert::error(_("chktex failure"),
1902 _("Could not run chktex successfully."));
1903 } else if (res > 0) {
1904 ErrorList & errlist = d->errorLists["ChkTeX"];
1906 bufferErrors(terr, errlist);
1917 void Buffer::validate(LaTeXFeatures & features) const
1919 params().validate(features);
1921 for_each(paragraphs().begin(), paragraphs().end(),
1922 bind(&Paragraph::validate, _1, ref(features)));
1924 if (lyxerr.debugging(Debug::LATEX)) {
1925 features.showStruct();
1930 void Buffer::getLabelList(vector<docstring> & list) const
1932 // If this is a child document, use the master's list instead.
1934 masterBuffer()->getLabelList(list);
1939 Toc & toc = d->toc_backend.toc("label");
1940 TocIterator toc_it = toc.begin();
1941 TocIterator end = toc.end();
1942 for (; toc_it != end; ++toc_it) {
1943 if (toc_it->depth() == 0)
1944 list.push_back(toc_it->str());
1949 void Buffer::updateBibfilesCache(UpdateScope scope) const
1951 // FIXME This is probably unnecssary, given where we call this.
1952 // If this is a child document, use the parent's cache instead.
1953 if (parent() && scope != UpdateChildOnly) {
1954 masterBuffer()->updateBibfilesCache();
1958 d->bibfiles_cache_.clear();
1959 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1960 if (it->lyxCode() == BIBTEX_CODE) {
1961 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1962 support::FileNameList const bibfiles = inset.getBibFiles();
1963 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1966 } else if (it->lyxCode() == INCLUDE_CODE) {
1967 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1968 Buffer const * const incbuf = inset.getChildBuffer();
1971 support::FileNameList const & bibfiles =
1972 incbuf->getBibfilesCache(UpdateChildOnly);
1973 if (!bibfiles.empty()) {
1974 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1980 d->bibfile_cache_valid_ = true;
1981 d->bibinfo_cache_valid_ = false;
1982 d->cite_labels_valid_ = false;
1986 void Buffer::invalidateBibinfoCache() const
1988 d->bibinfo_cache_valid_ = false;
1989 d->cite_labels_valid_ = false;
1990 // also invalidate the cache for the parent buffer
1991 Buffer const * const pbuf = d->parent();
1993 pbuf->invalidateBibinfoCache();
1997 void Buffer::invalidateBibfileCache() const
1999 d->bibfile_cache_valid_ = false;
2000 d->bibinfo_cache_valid_ = false;
2001 d->cite_labels_valid_ = false;
2002 // also invalidate the cache for the parent buffer
2003 Buffer const * const pbuf = d->parent();
2005 pbuf->invalidateBibfileCache();
2009 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2011 // FIXME This is probably unnecessary, given where we call this.
2012 // If this is a child document, use the master's cache instead.
2013 Buffer const * const pbuf = masterBuffer();
2014 if (pbuf != this && scope != UpdateChildOnly)
2015 return pbuf->getBibfilesCache();
2017 if (!d->bibfile_cache_valid_)
2018 this->updateBibfilesCache(scope);
2020 return d->bibfiles_cache_;
2024 BiblioInfo const & Buffer::masterBibInfo() const
2026 Buffer const * const tmp = masterBuffer();
2028 return tmp->masterBibInfo();
2033 void Buffer::checkIfBibInfoCacheIsValid() const
2035 // use the master's cache
2036 Buffer const * const tmp = masterBuffer();
2038 tmp->checkIfBibInfoCacheIsValid();
2042 // compare the cached timestamps with the actual ones.
2043 FileNameList const & bibfiles_cache = getBibfilesCache();
2044 FileNameList::const_iterator ei = bibfiles_cache.begin();
2045 FileNameList::const_iterator en = bibfiles_cache.end();
2046 for (; ei != en; ++ ei) {
2047 time_t lastw = ei->lastModified();
2048 time_t prevw = d->bibfile_status_[*ei];
2049 if (lastw != prevw) {
2050 d->bibinfo_cache_valid_ = false;
2051 d->cite_labels_valid_ = false;
2052 d->bibfile_status_[*ei] = lastw;
2058 void Buffer::reloadBibInfoCache() const
2060 // use the master's cache
2061 Buffer const * const tmp = masterBuffer();
2063 tmp->reloadBibInfoCache();
2067 checkIfBibInfoCacheIsValid();
2068 if (d->bibinfo_cache_valid_)
2071 d->bibinfo_.clear();
2073 d->bibinfo_cache_valid_ = true;
2077 void Buffer::collectBibKeys() const
2079 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2080 it->collectBibKeys(it);
2084 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2086 Buffer const * tmp = masterBuffer();
2087 BiblioInfo & masterbi = (tmp == this) ?
2088 d->bibinfo_ : tmp->d->bibinfo_;
2089 masterbi.mergeBiblioInfo(bi);
2093 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2095 Buffer const * tmp = masterBuffer();
2096 BiblioInfo & masterbi = (tmp == this) ?
2097 d->bibinfo_ : tmp->d->bibinfo_;
2102 bool Buffer::citeLabelsValid() const
2104 return masterBuffer()->d->cite_labels_valid_;
2108 void Buffer::removeBiblioTempFiles() const
2110 // We remove files that contain LaTeX commands specific to the
2111 // particular bibliographic style being used, in order to avoid
2112 // LaTeX errors when we switch style.
2113 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2114 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2115 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2116 aux_file.removeFile();
2117 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2118 bbl_file.removeFile();
2119 // Also for the parent buffer
2120 Buffer const * const pbuf = parent();
2122 pbuf->removeBiblioTempFiles();
2126 bool Buffer::isDepClean(string const & name) const
2128 DepClean::const_iterator const it = d->dep_clean.find(name);
2129 if (it == d->dep_clean.end())
2135 void Buffer::markDepClean(string const & name)
2137 d->dep_clean[name] = true;
2141 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2144 // FIXME? if there is an Buffer LFUN that can be dispatched even
2145 // if internal, put a switch '(cmd.action)' here.
2151 switch (cmd.action()) {
2153 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2154 flag.setOnOff(isReadonly());
2157 // FIXME: There is need for a command-line import.
2158 //case LFUN_BUFFER_IMPORT:
2160 case LFUN_BUFFER_AUTO_SAVE:
2163 case LFUN_BUFFER_EXPORT_CUSTOM:
2164 // FIXME: Nothing to check here?
2167 case LFUN_BUFFER_EXPORT: {
2168 docstring const arg = cmd.argument();
2169 if (arg == "custom") {
2173 string format = to_utf8(arg);
2174 size_t pos = format.find(' ');
2175 if (pos != string::npos)
2176 format = format.substr(0, pos);
2177 enable = params().isExportable(format);
2179 flag.message(bformat(
2180 _("Don't know how to export to format: %1$s"), arg));
2184 case LFUN_BUFFER_CHKTEX:
2185 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2188 case LFUN_BUILD_PROGRAM:
2189 enable = params().isExportable("program");
2192 case LFUN_BRANCH_ADD:
2193 case LFUN_BRANCHES_RENAME:
2194 case LFUN_BUFFER_PRINT:
2195 // if no Buffer is present, then of course we won't be called!
2198 case LFUN_BUFFER_LANGUAGE:
2199 enable = !isReadonly();
2205 flag.setEnabled(enable);
2210 void Buffer::dispatch(string const & command, DispatchResult & result)
2212 return dispatch(lyxaction.lookupFunc(command), result);
2216 // NOTE We can end up here even if we have no GUI, because we are called
2217 // by LyX::exec to handled command-line requests. So we may need to check
2218 // whether we have a GUI or not. The boolean use_gui holds this information.
2219 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2222 // FIXME? if there is an Buffer LFUN that can be dispatched even
2223 // if internal, put a switch '(cmd.action())' here.
2224 dr.dispatched(false);
2227 string const argument = to_utf8(func.argument());
2228 // We'll set this back to false if need be.
2229 bool dispatched = true;
2230 undo().beginUndoGroup();
2232 switch (func.action()) {
2233 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2234 if (lyxvc().inUse())
2235 lyxvc().toggleReadOnly();
2237 setReadonly(!isReadonly());
2240 case LFUN_BUFFER_EXPORT: {
2241 ExportStatus const status = doExport(argument, false);
2242 dr.setError(status != ExportSuccess);
2243 if (status != ExportSuccess)
2244 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2249 case LFUN_BUILD_PROGRAM:
2250 doExport("program", true);
2253 case LFUN_BUFFER_CHKTEX:
2257 case LFUN_BUFFER_EXPORT_CUSTOM: {
2259 string command = split(argument, format_name, ' ');
2260 Format const * format = formats.getFormat(format_name);
2262 lyxerr << "Format \"" << format_name
2263 << "\" not recognized!"
2268 // The name of the file created by the conversion process
2271 // Output to filename
2272 if (format->name() == "lyx") {
2273 string const latexname = latexName(false);
2274 filename = changeExtension(latexname,
2275 format->extension());
2276 filename = addName(temppath(), filename);
2278 if (!writeFile(FileName(filename)))
2282 doExport(format_name, true, filename);
2285 // Substitute $$FName for filename
2286 if (!contains(command, "$$FName"))
2287 command = "( " + command + " ) < $$FName";
2288 command = subst(command, "$$FName", filename);
2290 // Execute the command in the background
2292 call.startscript(Systemcall::DontWait, command, filePath());
2296 // FIXME: There is need for a command-line import.
2298 case LFUN_BUFFER_IMPORT:
2303 case LFUN_BUFFER_AUTO_SAVE:
2305 resetAutosaveTimers();
2308 case LFUN_BRANCH_ADD: {
2309 docstring branch_name = func.argument();
2310 if (branch_name.empty()) {
2314 BranchList & branch_list = params().branchlist();
2315 vector<docstring> const branches =
2316 getVectorFromString(branch_name, branch_list.separator());
2318 for (vector<docstring>::const_iterator it = branches.begin();
2319 it != branches.end(); ++it) {
2321 Branch * branch = branch_list.find(branch_name);
2323 LYXERR0("Branch " << branch_name << " already exists.");
2327 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2329 branch_list.add(branch_name);
2330 branch = branch_list.find(branch_name);
2331 string const x11hexname = X11hexname(branch->color());
2332 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2333 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2335 dr.screenUpdate(Update::Force);
2343 case LFUN_BRANCHES_RENAME: {
2344 if (func.argument().empty())
2347 docstring const oldname = from_utf8(func.getArg(0));
2348 docstring const newname = from_utf8(func.getArg(1));
2349 InsetIterator it = inset_iterator_begin(inset());
2350 InsetIterator const end = inset_iterator_end(inset());
2351 bool success = false;
2352 for (; it != end; ++it) {
2353 if (it->lyxCode() == BRANCH_CODE) {
2354 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2355 if (ins.branch() == oldname) {
2356 undo().recordUndo(it);
2357 ins.rename(newname);
2362 if (it->lyxCode() == INCLUDE_CODE) {
2363 // get buffer of external file
2364 InsetInclude const & ins =
2365 static_cast<InsetInclude const &>(*it);
2366 Buffer * child = ins.getChildBuffer();
2369 child->dispatch(func, dr);
2374 dr.screenUpdate(Update::Force);
2375 dr.forceBufferUpdate();
2380 case LFUN_BUFFER_PRINT: {
2381 // we'll assume there's a problem until we succeed
2383 string target = func.getArg(0);
2384 string target_name = func.getArg(1);
2385 string command = func.getArg(2);
2388 || target_name.empty()
2389 || command.empty()) {
2390 LYXERR0("Unable to parse " << func.argument());
2391 docstring const msg =
2392 bformat(_("Unable to parse \"%1$s\""), func.argument());
2396 if (target != "printer" && target != "file") {
2397 LYXERR0("Unrecognized target \"" << target << '"');
2398 docstring const msg =
2399 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2404 if (!doExport("dvi", true)) {
2405 showPrintError(absFileName());
2406 dr.setMessage(_("Error exporting to DVI."));
2410 // Push directory path.
2411 string const path = temppath();
2412 // Prevent the compiler from optimizing away p
2416 // there are three cases here:
2417 // 1. we print to a file
2418 // 2. we print directly to a printer
2419 // 3. we print using a spool command (print to file first)
2422 string const dviname = changeExtension(latexName(true), "dvi");
2424 if (target == "printer") {
2425 if (!lyxrc.print_spool_command.empty()) {
2426 // case 3: print using a spool
2427 string const psname = changeExtension(dviname,".ps");
2428 command += ' ' + lyxrc.print_to_file
2431 + quoteName(dviname);
2433 string command2 = lyxrc.print_spool_command + ' ';
2434 if (target_name != "default") {
2435 command2 += lyxrc.print_spool_printerprefix
2439 command2 += quoteName(psname);
2441 // If successful, then spool command
2442 res = one.startscript(Systemcall::Wait, command,
2446 // If there's no GUI, we have to wait on this command. Otherwise,
2447 // LyX deletes the temporary directory, and with it the spooled
2448 // file, before it can be printed!!
2449 Systemcall::Starttype stype = use_gui ?
2450 Systemcall::DontWait : Systemcall::Wait;
2451 res = one.startscript(stype, command2,
2455 // case 2: print directly to a printer
2456 if (target_name != "default")
2457 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2459 Systemcall::Starttype stype = use_gui ?
2460 Systemcall::DontWait : Systemcall::Wait;
2461 res = one.startscript(stype, command +
2462 quoteName(dviname), filePath());
2466 // case 1: print to a file
2467 FileName const filename(makeAbsPath(target_name, filePath()));
2468 FileName const dvifile(makeAbsPath(dviname, path));
2469 if (filename.exists()) {
2470 docstring text = bformat(
2471 _("The file %1$s already exists.\n\n"
2472 "Do you want to overwrite that file?"),
2473 makeDisplayPath(filename.absFileName()));
2474 if (Alert::prompt(_("Overwrite file?"),
2475 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2478 command += ' ' + lyxrc.print_to_file
2479 + quoteName(filename.toFilesystemEncoding())
2481 + quoteName(dvifile.toFilesystemEncoding());
2483 Systemcall::Starttype stype = use_gui ?
2484 Systemcall::DontWait : Systemcall::Wait;
2485 res = one.startscript(stype, command, filePath());
2491 dr.setMessage(_("Error running external commands."));
2492 showPrintError(absFileName());
2501 dr.dispatched(dispatched);
2502 undo().endUndoGroup();
2506 void Buffer::changeLanguage(Language const * from, Language const * to)
2508 LASSERT(from, /**/);
2511 for_each(par_iterator_begin(),
2513 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2517 bool Buffer::isMultiLingual() const
2519 ParConstIterator end = par_iterator_end();
2520 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2521 if (it->isMultiLingual(params()))
2528 std::set<Language const *> Buffer::getLanguages() const
2530 std::set<Language const *> languages;
2531 getLanguages(languages);
2536 void Buffer::getLanguages(std::set<Language const *> & languages) const
2538 ParConstIterator end = par_iterator_end();
2539 // add the buffer language, even if it's not actively used
2540 languages.insert(language());
2541 // iterate over the paragraphs
2542 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2543 it->getLanguages(languages);
2545 ListOfBuffers clist = getDescendents();
2546 ListOfBuffers::const_iterator cit = clist.begin();
2547 ListOfBuffers::const_iterator const cen = clist.end();
2548 for (; cit != cen; ++cit)
2549 (*cit)->getLanguages(languages);
2553 DocIterator Buffer::getParFromID(int const id) const
2555 Buffer * buf = const_cast<Buffer *>(this);
2557 // John says this is called with id == -1 from undo
2558 lyxerr << "getParFromID(), id: " << id << endl;
2559 return doc_iterator_end(buf);
2562 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2563 if (it.paragraph().id() == id)
2566 return doc_iterator_end(buf);
2570 bool Buffer::hasParWithID(int const id) const
2572 return !getParFromID(id).atEnd();
2576 ParIterator Buffer::par_iterator_begin()
2578 return ParIterator(doc_iterator_begin(this));
2582 ParIterator Buffer::par_iterator_end()
2584 return ParIterator(doc_iterator_end(this));
2588 ParConstIterator Buffer::par_iterator_begin() const
2590 return ParConstIterator(doc_iterator_begin(this));
2594 ParConstIterator Buffer::par_iterator_end() const
2596 return ParConstIterator(doc_iterator_end(this));
2600 Language const * Buffer::language() const
2602 return params().language;
2606 docstring const Buffer::B_(string const & l10n) const
2608 return params().B_(l10n);
2612 bool Buffer::isClean() const
2614 return d->lyx_clean;
2618 bool Buffer::isExternallyModified(CheckMethod method) const
2620 LASSERT(d->filename.exists(), /**/);
2621 // if method == timestamp, check timestamp before checksum
2622 return (method == checksum_method
2623 || d->timestamp_ != d->filename.lastModified())
2624 && d->checksum_ != d->filename.checksum();
2628 void Buffer::saveCheckSum() const
2630 FileName const & file = d->filename;
2633 if (file.exists()) {
2634 d->timestamp_ = file.lastModified();
2635 d->checksum_ = file.checksum();
2637 // in the case of save to a new file.
2644 void Buffer::markClean() const
2646 if (!d->lyx_clean) {
2647 d->lyx_clean = true;
2650 // if the .lyx file has been saved, we don't need an
2652 d->bak_clean = true;
2653 d->undo_.markDirty();
2657 void Buffer::setUnnamed(bool flag)
2663 bool Buffer::isUnnamed() const
2670 /// Don't check unnamed, here: isInternal() is used in
2671 /// newBuffer(), where the unnamed flag has not been set by anyone
2672 /// yet. Also, for an internal buffer, there should be no need for
2673 /// retrieving fileName() nor for checking if it is unnamed or not.
2674 bool Buffer::isInternal() const
2676 return d->internal_buffer;
2680 void Buffer::setInternal(bool flag)
2682 d->internal_buffer = flag;
2686 void Buffer::markDirty()
2689 d->lyx_clean = false;
2692 d->bak_clean = false;
2694 DepClean::iterator it = d->dep_clean.begin();
2695 DepClean::const_iterator const end = d->dep_clean.end();
2697 for (; it != end; ++it)
2702 FileName Buffer::fileName() const
2708 string Buffer::absFileName() const
2710 return d->filename.absFileName();
2714 string Buffer::filePath() const
2716 int last = d->filename.onlyPath().absFileName().length() - 1;
2718 return d->filename.onlyPath().absFileName()[last] == '/'
2719 ? d->filename.onlyPath().absFileName()
2720 : d->filename.onlyPath().absFileName() + "/";
2724 bool Buffer::isReadonly() const
2726 return d->read_only;
2730 void Buffer::setParent(Buffer const * buffer)
2732 // Avoids recursive include.
2733 d->setParent(buffer == this ? 0 : buffer);
2738 Buffer const * Buffer::parent() const
2744 ListOfBuffers Buffer::allRelatives() const
2746 ListOfBuffers lb = masterBuffer()->getDescendents();
2747 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2752 Buffer const * Buffer::masterBuffer() const
2754 // FIXME Should be make sure we are not in some kind
2755 // of recursive include? A -> B -> A will crash this.
2756 Buffer const * const pbuf = d->parent();
2760 return pbuf->masterBuffer();
2764 bool Buffer::isChild(Buffer * child) const
2766 return d->children_positions.find(child) != d->children_positions.end();
2770 DocIterator Buffer::firstChildPosition(Buffer const * child)
2772 Impl::BufferPositionMap::iterator it;
2773 it = d->children_positions.find(child);
2774 if (it == d->children_positions.end())
2775 return DocIterator(this);
2780 bool Buffer::hasChildren() const
2782 return !d->children_positions.empty();
2786 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2788 // loop over children
2789 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2790 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2791 for (; it != end; ++it) {
2792 Buffer * child = const_cast<Buffer *>(it->first);
2794 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2795 if (bit != clist.end())
2797 clist.push_back(child);
2799 // there might be grandchildren
2800 child->collectChildren(clist, true);
2805 ListOfBuffers Buffer::getChildren() const
2808 collectChildren(v, false);
2809 // Make sure we have not included ourselves.
2810 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2811 if (bit != v.end()) {
2812 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2819 ListOfBuffers Buffer::getDescendents() const
2822 collectChildren(v, true);
2823 // Make sure we have not included ourselves.
2824 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2825 if (bit != v.end()) {
2826 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2833 template<typename M>
2834 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2839 typename M::const_iterator it = m.lower_bound(x);
2840 if (it == m.begin())
2848 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2849 DocIterator const & pos) const
2851 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2853 // if paragraphs have no macro context set, pos will be empty
2857 // we haven't found anything yet
2858 DocIterator bestPos = owner_->par_iterator_begin();
2859 MacroData const * bestData = 0;
2861 // find macro definitions for name
2862 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2863 if (nameIt != macros.end()) {
2864 // find last definition in front of pos or at pos itself
2865 PositionScopeMacroMap::const_iterator it
2866 = greatest_below(nameIt->second, pos);
2867 if (it != nameIt->second.end()) {
2869 // scope ends behind pos?
2870 if (pos < it->second.first) {
2871 // Looks good, remember this. If there
2872 // is no external macro behind this,
2873 // we found the right one already.
2874 bestPos = it->first;
2875 bestData = &it->second.second;
2879 // try previous macro if there is one
2880 if (it == nameIt->second.begin())
2887 // find macros in included files
2888 PositionScopeBufferMap::const_iterator it
2889 = greatest_below(position_to_children, pos);
2890 if (it == position_to_children.end())
2891 // no children before
2895 // do we know something better (i.e. later) already?
2896 if (it->first < bestPos )
2899 // scope ends behind pos?
2900 if (pos < it->second.first
2901 && (cloned_buffer_ ||
2902 theBufferList().isLoaded(it->second.second))) {
2903 // look for macro in external file
2905 MacroData const * data
2906 = it->second.second->getMacro(name, false);
2909 bestPos = it->first;
2915 // try previous file if there is one
2916 if (it == position_to_children.begin())
2921 // return the best macro we have found
2926 MacroData const * Buffer::getMacro(docstring const & name,
2927 DocIterator const & pos, bool global) const
2932 // query buffer macros
2933 MacroData const * data = d->getBufferMacro(name, pos);
2937 // If there is a master buffer, query that
2938 Buffer const * const pbuf = d->parent();
2940 d->macro_lock = true;
2941 MacroData const * macro = pbuf->getMacro(
2942 name, *this, false);
2943 d->macro_lock = false;
2949 data = MacroTable::globalMacros().get(name);
2958 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2960 // set scope end behind the last paragraph
2961 DocIterator scope = par_iterator_begin();
2962 scope.pit() = scope.lastpit() + 1;
2964 return getMacro(name, scope, global);
2968 MacroData const * Buffer::getMacro(docstring const & name,
2969 Buffer const & child, bool global) const
2971 // look where the child buffer is included first
2972 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2973 if (it == d->children_positions.end())
2976 // check for macros at the inclusion position
2977 return getMacro(name, it->second, global);
2981 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2983 pit_type const lastpit = it.lastpit();
2985 // look for macros in each paragraph
2986 while (it.pit() <= lastpit) {
2987 Paragraph & par = it.paragraph();
2989 // iterate over the insets of the current paragraph
2990 InsetList const & insets = par.insetList();
2991 InsetList::const_iterator iit = insets.begin();
2992 InsetList::const_iterator end = insets.end();
2993 for (; iit != end; ++iit) {
2994 it.pos() = iit->pos;
2996 // is it a nested text inset?
2997 if (iit->inset->asInsetText()) {
2998 // Inset needs its own scope?
2999 InsetText const * itext = iit->inset->asInsetText();
3000 bool newScope = itext->isMacroScope();
3002 // scope which ends just behind the inset
3003 DocIterator insetScope = it;
3006 // collect macros in inset
3007 it.push_back(CursorSlice(*iit->inset));
3008 updateMacros(it, newScope ? insetScope : scope);
3013 if (iit->inset->asInsetTabular()) {
3014 CursorSlice slice(*iit->inset);
3015 size_t const numcells = slice.nargs();
3016 for (; slice.idx() < numcells; slice.forwardIdx()) {
3017 it.push_back(slice);
3018 updateMacros(it, scope);
3024 // is it an external file?
3025 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3026 // get buffer of external file
3027 InsetInclude const & inset =
3028 static_cast<InsetInclude const &>(*iit->inset);
3030 Buffer * child = inset.getChildBuffer();
3035 // register its position, but only when it is
3036 // included first in the buffer
3037 if (children_positions.find(child) ==
3038 children_positions.end())
3039 children_positions[child] = it;
3041 // register child with its scope
3042 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3046 InsetMath * im = iit->inset->asInsetMath();
3047 if (doing_export && im) {
3048 InsetMathHull * hull = im->asHullInset();
3050 hull->recordLocation(it);
3053 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3057 MathMacroTemplate & macroTemplate =
3058 *iit->inset->asInsetMath()->asMacroTemplate();
3059 MacroContext mc(owner_, it);
3060 macroTemplate.updateToContext(mc);
3063 bool valid = macroTemplate.validMacro();
3064 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3065 // then the BufferView's cursor will be invalid in
3066 // some cases which leads to crashes.
3071 // FIXME (Abdel), I don't understandt why we pass 'it' here
3072 // instead of 'macroTemplate' defined above... is this correct?
3073 macros[macroTemplate.name()][it] =
3074 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3084 void Buffer::updateMacros() const
3089 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3091 // start with empty table
3093 d->children_positions.clear();
3094 d->position_to_children.clear();
3096 // Iterate over buffer, starting with first paragraph
3097 // The scope must be bigger than any lookup DocIterator
3098 // later. For the global lookup, lastpit+1 is used, hence
3099 // we use lastpit+2 here.
3100 DocIterator it = par_iterator_begin();
3101 DocIterator outerScope = it;
3102 outerScope.pit() = outerScope.lastpit() + 2;
3103 d->updateMacros(it, outerScope);
3107 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3109 InsetIterator it = inset_iterator_begin(inset());
3110 InsetIterator const end = inset_iterator_end(inset());
3111 for (; it != end; ++it) {
3112 if (it->lyxCode() == BRANCH_CODE) {
3113 InsetBranch & br = static_cast<InsetBranch &>(*it);
3114 docstring const name = br.branch();
3115 if (!from_master && !params().branchlist().find(name))
3116 result.push_back(name);
3117 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3118 result.push_back(name);
3121 if (it->lyxCode() == INCLUDE_CODE) {
3122 // get buffer of external file
3123 InsetInclude const & ins =
3124 static_cast<InsetInclude const &>(*it);
3125 Buffer * child = ins.getChildBuffer();
3128 child->getUsedBranches(result, true);
3131 // remove duplicates
3136 void Buffer::updateMacroInstances(UpdateType utype) const
3138 LYXERR(Debug::MACROS, "updateMacroInstances for "
3139 << d->filename.onlyFileName());
3140 DocIterator it = doc_iterator_begin(this);
3142 DocIterator const end = doc_iterator_end(this);
3143 for (; it != end; it.forwardInset()) {
3144 // look for MathData cells in InsetMathNest insets
3145 InsetMath * minset = it.nextInset()->asInsetMath();
3149 // update macro in all cells of the InsetMathNest
3150 DocIterator::idx_type n = minset->nargs();
3151 MacroContext mc = MacroContext(this, it);
3152 for (DocIterator::idx_type i = 0; i < n; ++i) {
3153 MathData & data = minset->cell(i);
3154 data.updateMacros(0, mc, utype);
3160 void Buffer::listMacroNames(MacroNameSet & macros) const
3165 d->macro_lock = true;
3167 // loop over macro names
3168 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3169 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3170 for (; nameIt != nameEnd; ++nameIt)
3171 macros.insert(nameIt->first);
3173 // loop over children
3174 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3175 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3176 for (; it != end; ++it)
3177 it->first->listMacroNames(macros);
3180 Buffer const * const pbuf = d->parent();
3182 pbuf->listMacroNames(macros);
3184 d->macro_lock = false;
3188 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3190 Buffer const * const pbuf = d->parent();
3195 pbuf->listMacroNames(names);
3198 MacroNameSet::iterator it = names.begin();
3199 MacroNameSet::iterator end = names.end();
3200 for (; it != end; ++it) {
3202 MacroData const * data =
3203 pbuf->getMacro(*it, *this, false);
3205 macros.insert(data);
3207 // we cannot access the original MathMacroTemplate anymore
3208 // here to calls validate method. So we do its work here manually.
3209 // FIXME: somehow make the template accessible here.
3210 if (data->optionals() > 0)
3211 features.require("xargs");
3217 Buffer::References & Buffer::references(docstring const & label)
3220 return const_cast<Buffer *>(masterBuffer())->references(label);
3222 RefCache::iterator it = d->ref_cache_.find(label);
3223 if (it != d->ref_cache_.end())
3224 return it->second.second;
3226 static InsetLabel const * dummy_il = 0;
3227 static References const dummy_refs;
3228 it = d->ref_cache_.insert(
3229 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3230 return it->second.second;
3234 Buffer::References const & Buffer::references(docstring const & label) const
3236 return const_cast<Buffer *>(this)->references(label);
3240 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3242 masterBuffer()->d->ref_cache_[label].first = il;
3246 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3248 return masterBuffer()->d->ref_cache_[label].first;
3252 void Buffer::clearReferenceCache() const
3255 d->ref_cache_.clear();
3259 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3262 //FIXME: This does not work for child documents yet.
3263 LASSERT(code == CITE_CODE, /**/);
3265 reloadBibInfoCache();
3267 // Check if the label 'from' appears more than once
3268 BiblioInfo const & keys = masterBibInfo();
3269 BiblioInfo::const_iterator bit = keys.begin();
3270 BiblioInfo::const_iterator bend = keys.end();
3271 vector<docstring> labels;
3273 for (; bit != bend; ++bit)
3275 labels.push_back(bit->first);
3277 if (count(labels.begin(), labels.end(), from) > 1)
3280 string const paramName = "key";
3281 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3282 if (it->lyxCode() == code) {
3283 InsetCommand * inset = it->asInsetCommand();
3286 docstring const oldValue = inset->getParam(paramName);
3287 if (oldValue == from)
3288 inset->setParam(paramName, to);
3294 void Buffer::getSourceCode(odocstream & os, string const format,
3295 pit_type par_begin, pit_type par_end,
3296 OutputWhat output) const
3298 OutputParams runparams(¶ms().encoding());
3299 runparams.nice = true;
3300 runparams.flavor = params().getOutputFlavor(format);
3301 runparams.linelen = lyxrc.plaintext_linelen;
3302 // No side effect of file copying and image conversion
3303 runparams.dryrun = true;
3305 if (output == CurrentParagraph) {
3306 runparams.par_begin = par_begin;
3307 runparams.par_end = par_end;
3308 if (par_begin + 1 == par_end) {
3310 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3314 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3315 convert<docstring>(par_begin),
3316 convert<docstring>(par_end - 1))
3323 // output paragraphs
3324 if (runparams.flavor == OutputParams::HTML) {
3326 setMathFlavor(runparams);
3327 xhtmlParagraphs(text(), *this, xs, runparams);
3328 } else if (runparams.flavor == OutputParams::TEXT) {
3330 // FIXME Handles only one paragraph, unlike the others.
3331 // Probably should have some routine with a signature like them.
3332 writePlaintextParagraph(*this,
3333 text().paragraphs()[par_begin], os, runparams, dummy);
3334 } else if (params().isDocBook()) {
3335 docbookParagraphs(text(), *this, os, runparams);
3337 // latex or literate
3338 otexstream ots(os, texrow);
3339 latexParagraphs(*this, text(), ots, runparams);
3343 if (output == FullSource)
3344 os << _("Preview source code");
3345 else if (output == OnlyPreamble)
3346 os << _("Preview preamble");
3347 else if (output == OnlyBody)
3348 os << _("Preview body");
3351 d->texrow.newline();
3352 d->texrow.newline();
3353 if (runparams.flavor == OutputParams::HTML) {
3354 writeLyXHTMLSource(os, runparams, output);
3355 } else if (runparams.flavor == OutputParams::TEXT) {
3356 if (output == OnlyPreamble) {
3357 os << _("% Plaintext does not have a preamble.");
3359 writePlaintextFile(*this, os, runparams);
3360 } else if (params().isDocBook()) {
3361 writeDocBookSource(os, absFileName(), runparams, output);
3363 // latex or literate
3364 otexstream ots(os, d->texrow);
3365 writeLaTeXSource(ots, string(), runparams, output);
3371 ErrorList & Buffer::errorList(string const & type) const
3373 return d->errorLists[type];
3377 void Buffer::updateTocItem(std::string const & type,
3378 DocIterator const & dit) const
3381 d->gui_->updateTocItem(type, dit);
3385 void Buffer::structureChanged() const
3388 d->gui_->structureChanged();
3392 void Buffer::errors(string const & err, bool from_master) const
3395 d->gui_->errors(err, from_master);
3399 void Buffer::message(docstring const & msg) const
3402 d->gui_->message(msg);
3406 void Buffer::setBusy(bool on) const
3409 d->gui_->setBusy(on);
3413 void Buffer::updateTitles() const
3416 d->wa_->updateTitles();
3420 void Buffer::resetAutosaveTimers() const
3423 d->gui_->resetAutosaveTimers();
3427 bool Buffer::hasGuiDelegate() const
3433 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3442 class AutoSaveBuffer : public ForkedProcess {
3445 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3446 : buffer_(buffer), fname_(fname) {}
3448 virtual shared_ptr<ForkedProcess> clone() const
3450 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3455 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3456 from_utf8(fname_.absFileName())));
3457 return run(DontWait);
3461 virtual int generateChild();
3463 Buffer const & buffer_;
3468 int AutoSaveBuffer::generateChild()
3470 #if defined(__APPLE__)
3471 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3472 * We should use something else like threads.
3474 * Since I do not know how to determine at run time what is the OS X
3475 * version, I just disable forking altogether for now (JMarc)
3477 pid_t const pid = -1;
3479 // tmp_ret will be located (usually) in /tmp
3480 // will that be a problem?
3481 // Note that this calls ForkedCalls::fork(), so it's
3482 // ok cross-platform.
3483 pid_t const pid = fork();
3484 // If you want to debug the autosave
3485 // you should set pid to -1, and comment out the fork.
3486 if (pid != 0 && pid != -1)
3490 // pid = -1 signifies that lyx was unable
3491 // to fork. But we will do the save
3493 bool failed = false;
3494 FileName const tmp_ret = FileName::tempName("lyxauto");
3495 if (!tmp_ret.empty()) {
3496 buffer_.writeFile(tmp_ret);
3497 // assume successful write of tmp_ret
3498 if (!tmp_ret.moveTo(fname_))
3504 // failed to write/rename tmp_ret so try writing direct
3505 if (!buffer_.writeFile(fname_)) {
3506 // It is dangerous to do this in the child,
3507 // but safe in the parent, so...
3508 if (pid == -1) // emit message signal.
3509 buffer_.message(_("Autosave failed!"));
3513 if (pid == 0) // we are the child so...
3522 FileName Buffer::getEmergencyFileName() const
3524 return FileName(d->filename.absFileName() + ".emergency");
3528 FileName Buffer::getAutosaveFileName() const
3530 // if the document is unnamed try to save in the backup dir, else
3531 // in the default document path, and as a last try in the filePath,
3532 // which will most often be the temporary directory
3535 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3536 : lyxrc.backupdir_path;
3537 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3540 string const fname = "#" + d->filename.onlyFileName() + "#";
3542 return makeAbsPath(fname, fpath);
3546 void Buffer::removeAutosaveFile() const
3548 FileName const f = getAutosaveFileName();
3554 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3556 FileName const newauto = getAutosaveFileName();
3558 if (newauto != oldauto && oldauto.exists())
3559 if (!oldauto.moveTo(newauto))
3560 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3564 bool Buffer::autoSave() const
3566 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3567 if (buf->d->bak_clean || isReadonly())
3570 message(_("Autosaving current document..."));
3571 buf->d->bak_clean = true;
3573 FileName const fname = getAutosaveFileName();
3574 if (d->cloned_buffer_) {
3575 // If this buffer is cloned, we assume that
3576 // we are running in a separate thread already.
3577 FileName const tmp_ret = FileName::tempName("lyxauto");
3578 if (!tmp_ret.empty()) {
3580 // assume successful write of tmp_ret
3581 if (tmp_ret.moveTo(fname))
3584 // failed to write/rename tmp_ret so try writing direct
3585 return writeFile(fname);
3587 /// This function is deprecated as the frontend needs to take care
3588 /// of cloning the buffer and autosaving it in another thread. It
3589 /// is still here to allow (QT_VERSION < 0x040400).
3590 AutoSaveBuffer autosave(*this, fname);
3597 // helper class, to guarantee this gets reset properly
3598 class Buffer::MarkAsExporting {
3600 MarkAsExporting(Buffer const * buf) : buf_(buf)
3602 LASSERT(buf_, /* */);
3603 buf_->setExportStatus(true);
3607 buf_->setExportStatus(false);
3610 Buffer const * const buf_;
3615 void Buffer::setExportStatus(bool e) const
3617 d->doing_export = e;
3618 ListOfBuffers clist = getDescendents();
3619 ListOfBuffers::const_iterator cit = clist.begin();
3620 ListOfBuffers::const_iterator const cen = clist.end();
3621 for (; cit != cen; ++cit)
3622 (*cit)->d->doing_export = e;
3626 bool Buffer::isExporting() const
3628 return d->doing_export;
3632 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3636 return doExport(target, put_in_tempdir, result_file);
3639 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3640 string & result_file) const
3642 bool const update_unincluded =
3643 params().maintain_unincluded_children
3644 && !params().getIncludedChildren().empty();
3646 // (1) export with all included children (omit \includeonly)
3647 if (update_unincluded) {
3648 ExportStatus const status =
3649 doExport(target, put_in_tempdir, true, result_file);
3650 if (status != ExportSuccess)
3653 // (2) export with included children only
3654 return doExport(target, put_in_tempdir, false, result_file);
3658 void Buffer::setMathFlavor(OutputParams & op) const
3660 switch (params().html_math_output) {
3661 case BufferParams::MathML:
3662 op.math_flavor = OutputParams::MathAsMathML;
3664 case BufferParams::HTML:
3665 op.math_flavor = OutputParams::MathAsHTML;
3667 case BufferParams::Images:
3668 op.math_flavor = OutputParams::MathAsImages;
3670 case BufferParams::LaTeX:
3671 op.math_flavor = OutputParams::MathAsLaTeX;
3677 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3678 bool includeall, string & result_file) const
3680 LYXERR(Debug::FILES, "target=" << target);
3681 OutputParams runparams(¶ms().encoding());
3682 string format = target;
3683 string dest_filename;
3684 size_t pos = target.find(' ');
3685 if (pos != string::npos) {
3686 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3687 format = target.substr(0, pos);
3688 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3689 FileName(dest_filename).onlyPath().createPath();
3690 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3692 MarkAsExporting exporting(this);
3693 string backend_format;
3694 runparams.flavor = OutputParams::LATEX;
3695 runparams.linelen = lyxrc.plaintext_linelen;
3696 runparams.includeall = includeall;
3697 vector<string> backs = params().backends();
3698 Converters converters = theConverters();
3699 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3700 // Get shortest path to format
3701 converters.buildGraph();
3702 Graph::EdgePath path;
3703 for (vector<string>::const_iterator it = backs.begin();
3704 it != backs.end(); ++it) {
3705 Graph::EdgePath p = converters.getPath(*it, format);
3706 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3707 backend_format = *it;
3712 if (!put_in_tempdir) {
3713 // Only show this alert if this is an export to a non-temporary
3714 // file (not for previewing).
3715 Alert::error(_("Couldn't export file"), bformat(
3716 _("No information for exporting the format %1$s."),
3717 formats.prettyName(format)));
3719 return ExportNoPathToFormat;
3721 runparams.flavor = converters.getFlavor(path, this);
3724 backend_format = format;
3725 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3726 // FIXME: Don't hardcode format names here, but use a flag
3727 if (backend_format == "pdflatex")
3728 runparams.flavor = OutputParams::PDFLATEX;
3729 else if (backend_format == "luatex")
3730 runparams.flavor = OutputParams::LUATEX;
3731 else if (backend_format == "dviluatex")
3732 runparams.flavor = OutputParams::DVILUATEX;
3733 else if (backend_format == "xetex")
3734 runparams.flavor = OutputParams::XETEX;
3737 string filename = latexName(false);
3738 filename = addName(temppath(), filename);
3739 filename = changeExtension(filename,
3740 formats.extension(backend_format));
3741 LYXERR(Debug::FILES, "filename=" << filename);
3743 // Plain text backend
3744 if (backend_format == "text") {
3745 runparams.flavor = OutputParams::TEXT;
3746 writePlaintextFile(*this, FileName(filename), runparams);
3749 else if (backend_format == "xhtml") {
3750 runparams.flavor = OutputParams::HTML;
3751 setMathFlavor(runparams);
3752 makeLyXHTMLFile(FileName(filename), runparams);
3753 } else if (backend_format == "lyx")
3754 writeFile(FileName(filename));
3756 else if (params().isDocBook()) {
3757 runparams.nice = !put_in_tempdir;
3758 makeDocBookFile(FileName(filename), runparams);
3761 else if (backend_format == format) {
3762 runparams.nice = true;
3763 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3764 if (d->cloned_buffer_)
3765 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3768 } else if (!lyxrc.tex_allows_spaces
3769 && contains(filePath(), ' ')) {
3770 Alert::error(_("File name error"),
3771 _("The directory path to the document cannot contain spaces."));
3772 return ExportTexPathHasSpaces;
3774 runparams.nice = false;
3775 bool const success = makeLaTeXFile(
3776 FileName(filename), filePath(), runparams);
3777 if (d->cloned_buffer_)
3778 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3783 string const error_type = (format == "program")
3784 ? "Build" : params().bufferFormat();
3785 ErrorList & error_list = d->errorLists[error_type];
3786 string const ext = formats.extension(format);
3787 FileName const tmp_result_file(changeExtension(filename, ext));
3788 bool const success = converters.convert(this, FileName(filename),
3789 tmp_result_file, FileName(absFileName()), backend_format, format,
3792 // Emit the signal to show the error list or copy it back to the
3793 // cloned Buffer so that it can be emitted afterwards.
3794 if (format != backend_format) {
3795 if (d->cloned_buffer_) {
3796 d->cloned_buffer_->d->errorLists[error_type] =
3797 d->errorLists[error_type];
3800 // also to the children, in case of master-buffer-view
3801 ListOfBuffers clist = getDescendents();
3802 ListOfBuffers::const_iterator cit = clist.begin();
3803 ListOfBuffers::const_iterator const cen = clist.end();
3804 for (; cit != cen; ++cit) {
3805 if (d->cloned_buffer_) {
3806 // Enable reverse search by copying back the
3807 // texrow object to the cloned buffer.
3808 // FIXME: this is not thread safe.
3809 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3810 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3811 (*cit)->d->errorLists[error_type];
3813 (*cit)->errors(error_type, true);
3817 if (d->cloned_buffer_) {
3818 // Enable reverse dvi or pdf to work by copying back the texrow
3819 // object to the cloned buffer.
3820 // FIXME: There is a possibility of concurrent access to texrow
3821 // here from the main GUI thread that should be securized.
3822 d->cloned_buffer_->d->texrow = d->texrow;
3823 string const error_type = params().bufferFormat();
3824 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3828 return ExportConverterError;
3830 if (put_in_tempdir) {
3831 result_file = tmp_result_file.absFileName();
3832 return ExportSuccess;
3835 if (dest_filename.empty())
3836 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3838 result_file = dest_filename;
3839 // We need to copy referenced files (e. g. included graphics
3840 // if format == "dvi") to the result dir.
3841 vector<ExportedFile> const files =
3842 runparams.exportdata->externalFiles(format);
3843 string const dest = runparams.export_folder.empty() ?
3844 onlyPath(result_file) : runparams.export_folder;
3845 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3846 : force_overwrite == ALL_FILES;
3847 CopyStatus status = use_force ? FORCE : SUCCESS;
3849 vector<ExportedFile>::const_iterator it = files.begin();
3850 vector<ExportedFile>::const_iterator const en = files.end();
3851 for (; it != en && status != CANCEL; ++it) {
3852 string const fmt = formats.getFormatFromFile(it->sourceName);
3853 string fixedName = it->exportName;
3854 if (!runparams.export_folder.empty()) {
3855 // Relative pathnames starting with ../ will be sanitized
3856 // if exporting to a different folder
3857 while (fixedName.substr(0, 3) == "../")
3858 fixedName = fixedName.substr(3, fixedName.length() - 3);
3860 FileName fixedFileName = makeAbsPath(fixedName, dest);
3861 fixedFileName.onlyPath().createPath();
3862 status = copyFile(fmt, it->sourceName,
3864 it->exportName, status == FORCE,
3865 runparams.export_folder.empty());
3868 if (status == CANCEL) {
3869 message(_("Document export cancelled."));
3870 return ExportCancel;
3873 if (tmp_result_file.exists()) {
3874 // Finally copy the main file
3875 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3876 : force_overwrite != NO_FILES;
3877 if (status == SUCCESS && use_force)
3879 status = copyFile(format, tmp_result_file,
3880 FileName(result_file), result_file,
3882 if (status == CANCEL) {
3883 message(_("Document export cancelled."));
3884 return ExportCancel;
3886 message(bformat(_("Document exported as %1$s "
3888 formats.prettyName(format),
3889 makeDisplayPath(result_file)));
3892 // This must be a dummy converter like fax (bug 1888)
3893 message(bformat(_("Document exported as %1$s"),
3894 formats.prettyName(format)));
3897 return ExportSuccess;
3901 Buffer::ExportStatus Buffer::preview(string const & format) const
3903 bool const update_unincluded =
3904 params().maintain_unincluded_children
3905 && !params().getIncludedChildren().empty();
3906 return preview(format, update_unincluded);
3909 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3911 MarkAsExporting exporting(this);
3913 // (1) export with all included children (omit \includeonly)
3915 ExportStatus const status = doExport(format, true, true, result_file);
3916 if (status != ExportSuccess)
3919 // (2) export with included children only
3920 ExportStatus const status = doExport(format, true, false, result_file);
3921 if (status != ExportSuccess)
3923 if (!formats.view(*this, FileName(result_file), format))
3924 return PreviewError;
3925 return PreviewSuccess;
3929 Buffer::ReadStatus Buffer::extractFromVC()
3931 bool const found = LyXVC::file_not_found_hook(d->filename);
3933 return ReadFileNotFound;
3934 if (!d->filename.isReadableFile())
3940 Buffer::ReadStatus Buffer::loadEmergency()
3942 FileName const emergencyFile = getEmergencyFileName();
3943 if (!emergencyFile.exists()
3944 || emergencyFile.lastModified() <= d->filename.lastModified())
3945 return ReadFileNotFound;
3947 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3948 docstring const text = bformat(_("An emergency save of the document "
3949 "%1$s exists.\n\nRecover emergency save?"), file);
3951 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3952 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3958 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3959 bool const success = (ret_llf == ReadSuccess);
3962 Alert::warning(_("File is read-only"),
3963 bformat(_("An emergency file is successfully loaded, "
3964 "but the original file %1$s is marked read-only. "
3965 "Please make sure to save the document as a different "
3966 "file."), from_utf8(d->filename.absFileName())));
3969 str = _("Document was successfully recovered.");
3971 str = _("Document was NOT successfully recovered.");
3972 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3973 makeDisplayPath(emergencyFile.absFileName()));
3975 int const del_emerg =
3976 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3977 _("&Remove"), _("&Keep"));
3978 if (del_emerg == 0) {
3979 emergencyFile.removeFile();
3981 Alert::warning(_("Emergency file deleted"),
3982 _("Do not forget to save your file now!"), true);
3984 return success ? ReadSuccess : ReadEmergencyFailure;
3987 int const del_emerg =
3988 Alert::prompt(_("Delete emergency file?"),
3989 _("Remove emergency file now?"), 1, 1,
3990 _("&Remove"), _("&Keep"));
3992 emergencyFile.removeFile();
3993 return ReadOriginal;
4003 Buffer::ReadStatus Buffer::loadAutosave()
4005 // Now check if autosave file is newer.
4006 FileName const autosaveFile = getAutosaveFileName();
4007 if (!autosaveFile.exists()
4008 || autosaveFile.lastModified() <= d->filename.lastModified())
4009 return ReadFileNotFound;
4011 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4012 docstring const text = bformat(_("The backup of the document %1$s "
4013 "is newer.\n\nLoad the backup instead?"), file);
4014 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4015 _("&Load backup"), _("Load &original"), _("&Cancel"));
4020 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4021 // the file is not saved if we load the autosave file.
4022 if (ret_llf == ReadSuccess) {
4024 Alert::warning(_("File is read-only"),
4025 bformat(_("A backup file is successfully loaded, "
4026 "but the original file %1$s is marked read-only. "
4027 "Please make sure to save the document as a "
4029 from_utf8(d->filename.absFileName())));
4034 return ReadAutosaveFailure;
4037 // Here we delete the autosave
4038 autosaveFile.removeFile();
4039 return ReadOriginal;
4047 Buffer::ReadStatus Buffer::loadLyXFile()
4049 if (!d->filename.isReadableFile()) {
4050 ReadStatus const ret_rvc = extractFromVC();
4051 if (ret_rvc != ReadSuccess)
4055 ReadStatus const ret_re = loadEmergency();
4056 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4059 ReadStatus const ret_ra = loadAutosave();
4060 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4063 return loadThisLyXFile(d->filename);
4067 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4069 return readFile(fn);
4073 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4075 TeXErrors::Errors::const_iterator it = terr.begin();
4076 TeXErrors::Errors::const_iterator end = terr.end();
4077 ListOfBuffers clist = getDescendents();
4078 ListOfBuffers::const_iterator cen = clist.end();
4080 for (; it != end; ++it) {
4083 int errorRow = it->error_in_line;
4084 Buffer const * buf = 0;
4086 if (it->child_name.empty())
4087 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4089 // The error occurred in a child
4090 ListOfBuffers::const_iterator cit = clist.begin();
4091 for (; cit != cen; ++cit) {
4092 string const child_name =
4093 DocFileName(changeExtension(
4094 (*cit)->absFileName(), "tex")).
4096 if (it->child_name != child_name)
4098 (*cit)->d->texrow.getIdFromRow(errorRow,
4099 id_start, pos_start);
4100 if (id_start != -1) {
4101 buf = d->cloned_buffer_
4102 ? (*cit)->d->cloned_buffer_->d->owner_
4103 : (*cit)->d->owner_;
4114 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4115 } while (found && id_start == id_end && pos_start == pos_end);
4117 if (id_start != id_end) {
4118 // Next registered position is outside the inset where
4119 // the error occurred, so signal end-of-paragraph
4123 errorList.push_back(ErrorItem(it->error_desc,
4124 it->error_text, id_start, pos_start, pos_end, buf));
4129 void Buffer::setBuffersForInsets() const
4131 inset().setBuffer(const_cast<Buffer &>(*this));
4135 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4137 // Use the master text class also for child documents
4138 Buffer const * const master = masterBuffer();
4139 DocumentClass const & textclass = master->params().documentClass();
4141 // do this only if we are the top-level Buffer
4143 reloadBibInfoCache();
4145 // keep the buffers to be children in this set. If the call from the
4146 // master comes back we can see which of them were actually seen (i.e.
4147 // via an InsetInclude). The remaining ones in the set need still be updated.
4148 static std::set<Buffer const *> bufToUpdate;
4149 if (scope == UpdateMaster) {
4150 // If this is a child document start with the master
4151 if (master != this) {
4152 bufToUpdate.insert(this);
4153 master->updateBuffer(UpdateMaster, utype);
4154 // Do this here in case the master has no gui associated with it. Then,
4155 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4156 if (!master->d->gui_)
4159 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4160 if (bufToUpdate.find(this) == bufToUpdate.end())
4164 // start over the counters in the master
4165 textclass.counters().reset();
4168 // update will be done below for this buffer
4169 bufToUpdate.erase(this);
4171 // update all caches
4172 clearReferenceCache();
4175 Buffer & cbuf = const_cast<Buffer &>(*this);
4177 LASSERT(!text().paragraphs().empty(), /**/);
4180 ParIterator parit = cbuf.par_iterator_begin();
4181 updateBuffer(parit, utype);
4184 // TocBackend update will be done later.
4187 d->bibinfo_cache_valid_ = true;
4188 d->cite_labels_valid_ = true;
4189 cbuf.tocBackend().update();
4190 if (scope == UpdateMaster)
4191 cbuf.structureChanged();
4195 static depth_type getDepth(DocIterator const & it)
4197 depth_type depth = 0;
4198 for (size_t i = 0 ; i < it.depth() ; ++i)
4199 if (!it[i].inset().inMathed())
4200 depth += it[i].paragraph().getDepth() + 1;
4201 // remove 1 since the outer inset does not count
4205 static depth_type getItemDepth(ParIterator const & it)
4207 Paragraph const & par = *it;
4208 LabelType const labeltype = par.layout().labeltype;
4210 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4213 // this will hold the lowest depth encountered up to now.
4214 depth_type min_depth = getDepth(it);
4215 ParIterator prev_it = it;
4218 --prev_it.top().pit();
4220 // start of nested inset: go to outer par
4222 if (prev_it.empty()) {
4223 // start of document: nothing to do
4228 // We search for the first paragraph with same label
4229 // that is not more deeply nested.
4230 Paragraph & prev_par = *prev_it;
4231 depth_type const prev_depth = getDepth(prev_it);
4232 if (labeltype == prev_par.layout().labeltype) {
4233 if (prev_depth < min_depth)
4234 return prev_par.itemdepth + 1;
4235 if (prev_depth == min_depth)
4236 return prev_par.itemdepth;
4238 min_depth = min(min_depth, prev_depth);
4239 // small optimization: if we are at depth 0, we won't
4240 // find anything else
4241 if (prev_depth == 0)
4247 static bool needEnumCounterReset(ParIterator const & it)
4249 Paragraph const & par = *it;
4250 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4251 depth_type const cur_depth = par.getDepth();
4252 ParIterator prev_it = it;
4253 while (prev_it.pit()) {
4254 --prev_it.top().pit();
4255 Paragraph const & prev_par = *prev_it;
4256 if (prev_par.getDepth() <= cur_depth)
4257 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4259 // start of nested inset: reset
4264 // set the label of a paragraph. This includes the counters.
4265 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4267 BufferParams const & bp = owner_->masterBuffer()->params();
4268 DocumentClass const & textclass = bp.documentClass();
4269 Paragraph & par = it.paragraph();
4270 Layout const & layout = par.layout();
4271 Counters & counters = textclass.counters();
4273 if (par.params().startOfAppendix()) {
4274 // FIXME: only the counter corresponding to toplevel
4275 // sectioning should be reset
4277 counters.appendix(true);
4279 par.params().appendix(counters.appendix());
4281 // Compute the item depth of the paragraph
4282 par.itemdepth = getItemDepth(it);
4284 if (layout.margintype == MARGIN_MANUAL) {
4285 if (par.params().labelWidthString().empty())
4286 par.params().labelWidthString(par.expandLabel(layout, bp));
4287 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4288 // we do not need to do anything here, since the empty case is
4289 // handled during export.
4291 par.params().labelWidthString(docstring());
4294 switch(layout.labeltype) {
4296 if (layout.toclevel <= bp.secnumdepth
4297 && (layout.latextype != LATEX_ENVIRONMENT
4298 || it.text()->isFirstInSequence(it.pit()))) {
4299 if (counters.hasCounter(layout.counter))
4300 counters.step(layout.counter, utype);
4301 par.params().labelString(par.expandLabel(layout, bp));
4303 par.params().labelString(docstring());
4306 case LABEL_ITEMIZE: {
4307 // At some point of time we should do something more
4308 // clever here, like:
4309 // par.params().labelString(
4310 // bp.user_defined_bullet(par.itemdepth).getText());
4311 // for now, use a simple hardcoded label
4312 docstring itemlabel;
4313 switch (par.itemdepth) {
4315 itemlabel = char_type(0x2022);
4318 itemlabel = char_type(0x2013);
4321 itemlabel = char_type(0x2217);
4324 itemlabel = char_type(0x2219); // or 0x00b7
4327 par.params().labelString(itemlabel);
4331 case LABEL_ENUMERATE: {
4332 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4334 switch (par.itemdepth) {
4343 enumcounter += "iv";
4346 // not a valid enumdepth...
4350 // Maybe we have to reset the enumeration counter.
4351 if (needEnumCounterReset(it))
4352 counters.reset(enumcounter);
4353 counters.step(enumcounter, utype);
4355 string const & lang = par.getParLanguage(bp)->code();
4356 par.params().labelString(counters.theCounter(enumcounter, lang));
4361 case LABEL_SENSITIVE: {
4362 string const & type = counters.current_float();
4363 docstring full_label;
4365 full_label = owner_->B_("Senseless!!! ");
4367 docstring name = owner_->B_(textclass.floats().getType(type).name());
4368 if (counters.hasCounter(from_utf8(type))) {
4369 string const & lang = par.getParLanguage(bp)->code();
4370 counters.step(from_utf8(type), utype);
4371 full_label = bformat(from_ascii("%1$s %2$s:"),
4373 counters.theCounter(from_utf8(type), lang));
4375 full_label = bformat(from_ascii("%1$s #:"), name);
4377 par.params().labelString(full_label);
4381 case LABEL_NO_LABEL:
4382 par.params().labelString(docstring());
4386 case LABEL_TOP_ENVIRONMENT:
4387 case LABEL_CENTERED_TOP_ENVIRONMENT:
4390 par.params().labelString(par.expandLabel(layout, bp));
4396 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4398 LASSERT(parit.pit() == 0, /**/);
4400 // Set the position of the text in the buffer to be able
4401 // to resolve macros in it.
4402 parit.text()->setMacrocontextPosition(parit);
4404 depth_type maxdepth = 0;
4405 pit_type const lastpit = parit.lastpit();
4406 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4407 // reduce depth if necessary
4408 parit->params().depth(min(parit->params().depth(), maxdepth));
4409 maxdepth = parit->getMaxDepthAfter();
4411 if (utype == OutputUpdate) {
4412 // track the active counters
4413 // we have to do this for the master buffer, since the local
4414 // buffer isn't tracking anything.
4415 masterBuffer()->params().documentClass().counters().
4416 setActiveLayout(parit->layout());
4419 // set the counter for this paragraph
4420 d->setLabel(parit, utype);
4423 InsetList::const_iterator iit = parit->insetList().begin();
4424 InsetList::const_iterator end = parit->insetList().end();
4425 for (; iit != end; ++iit) {
4426 parit.pos() = iit->pos;
4427 iit->inset->updateBuffer(parit, utype);
4433 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4434 WordLangTuple & word_lang, docstring_list & suggestions) const
4438 suggestions.clear();
4439 word_lang = WordLangTuple();
4440 bool const to_end = to.empty();
4441 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4442 // OK, we start from here.
4443 for (; from != end; from.forwardPos()) {
4444 // We are only interested in text so remove the math CursorSlice.
4445 while (from.inMathed()) {
4449 // If from is at the end of the document (which is possible
4450 // when leaving the mathed) LyX will crash later otherwise.
4451 if (from.atEnd() || (!to_end && from >= end))
4454 from.paragraph().spellCheck();
4455 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4456 if (SpellChecker::misspelled(res)) {
4461 // Do not increase progress when from == to, otherwise the word
4462 // count will be wrong.
4472 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4474 bool inword = false;
4479 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4480 if (!dit.inTexted()) {
4485 Paragraph const & par = dit.paragraph();
4486 pos_type const pos = dit.pos();
4488 // Copied and adapted from isWordSeparator() in Paragraph
4489 if (pos == dit.lastpos()) {
4492 Inset const * ins = par.getInset(pos);
4493 if (ins && skipNoOutput && !ins->producesOutput()) {
4496 // stop if end of range was skipped
4497 if (!to.atEnd() && dit >= to)
4500 } else if (!par.isDeleted(pos)) {
4501 if (par.isWordSeparator(pos))
4507 if (ins && ins->isLetter())
4509 else if (ins && ins->isSpace())
4512 char_type const c = par.getChar(pos);
4513 if (isPrintableNonspace(c))
4515 else if (isSpace(c))
4525 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4527 d->updateStatistics(from, to, skipNoOutput);
4531 int Buffer::wordCount() const
4533 return d->wordCount();
4537 int Buffer::charCount(bool with_blanks) const
4539 return d->charCount(with_blanks);
4543 Buffer::ReadStatus Buffer::reload()
4546 // c.f. bug http://www.lyx.org/trac/ticket/6587
4547 removeAutosaveFile();
4548 // e.g., read-only status could have changed due to version control
4549 d->filename.refresh();
4550 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4552 // clear parent. this will get reset if need be.
4554 ReadStatus const status = loadLyXFile();
4555 if (status == ReadSuccess) {
4560 message(bformat(_("Document %1$s reloaded."), disp_fn));
4563 message(bformat(_("Could not reload document %1$s."), disp_fn));
4573 bool Buffer::saveAs(FileName const & fn)
4575 FileName const old_name = fileName();
4576 FileName const old_auto = getAutosaveFileName();
4577 bool const old_unnamed = isUnnamed();
4584 // bring the autosave file with us, just in case.
4585 moveAutosaveFile(old_auto);
4586 // validate version control data and
4587 // correct buffer title
4588 lyxvc().file_found_hook(fileName());
4590 // the file has now been saved to the new location.
4591 // we need to check that the locations of child buffers
4593 checkChildBuffers();
4594 checkMasterBuffer();
4598 // reset the old filename and unnamed state
4599 setFileName(old_name);
4600 setUnnamed(old_unnamed);
4606 // FIXME We could do better here, but it is complicated. What would be
4607 // nice is to offer either (a) to save the child buffer to an appropriate
4608 // location, so that it would "move with the master", or else (b) to update
4609 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4610 // complicated, because the code for this lives in GuiView.
4611 void Buffer::checkChildBuffers()
4613 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4614 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4615 for (; it != en; ++it) {
4616 DocIterator dit = it->second;
4617 Buffer * cbuf = const_cast<Buffer *>(it->first);
4618 if (!cbuf || !theBufferList().isLoaded(cbuf))
4620 Inset * inset = dit.nextInset();
4621 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4622 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4623 docstring const & incfile = inset_inc->getParam("filename");
4624 string oldloc = cbuf->absFileName();
4625 string newloc = makeAbsPath(to_utf8(incfile),
4626 onlyPath(absFileName())).absFileName();
4627 if (oldloc == newloc)
4629 // the location of the child file is incorrect.
4630 Alert::warning(_("Included File Invalid"),
4631 bformat(_("Saving this document to a new location has made the file:\n"
4633 "inaccessible. You will need to update the included filename."),
4634 from_utf8(oldloc)));
4636 inset_inc->setChildBuffer(0);
4638 // invalidate cache of children
4639 d->children_positions.clear();
4640 d->position_to_children.clear();
4644 // If a child has been saved under a different name/path, it might have been
4645 // orphaned. Therefore the master needs to be reset (bug 8161).
4646 void Buffer::checkMasterBuffer()
4648 Buffer const * const master = masterBuffer();
4652 // necessary to re-register the child (bug 5873)
4653 // FIXME: clean up updateMacros (here, only
4654 // child registering is needed).
4655 master->updateMacros();
4656 // (re)set master as master buffer, but only
4657 // if we are a real child
4658 if (master->isChild(this))