3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibtex.h"
70 #include "insets/InsetBranch.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetTabular.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "graphics/PreviewLoader.h"
82 #include "frontends/alert.h"
83 #include "frontends/Delegates.h"
84 #include "frontends/WorkAreaManager.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
120 using namespace lyx::graphics;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 int const LYX_FORMAT = LYX_FORMAT_LYX;
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
145 // A storehouse for the cloned buffers.
146 list<CloneList *> cloned_buffers;
152 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
156 delete preview_loader_;
164 /// search for macro in local (buffer) table or in children
165 MacroData const * getBufferMacro(docstring const & name,
166 DocIterator const & pos) const;
168 /// Update macro table starting with position of it \param it in some
170 void updateMacros(DocIterator & it, DocIterator & scope);
172 void setLabel(ParIterator & it, UpdateType utype) const;
174 /** If we have branches that use the file suffix
175 feature, return the file name with suffix appended.
177 support::FileName exportFileName() const;
184 mutable TexRow texrow;
186 /// need to regenerate .tex?
190 mutable bool lyx_clean;
192 /// is autosave needed?
193 mutable bool bak_clean;
195 /// is this an unnamed file (New...)?
201 /// name of the file the buffer is associated with.
204 /** Set to true only when the file is fully loaded.
205 * Used to prevent the premature generation of previews
206 * and by the citation inset.
208 bool file_fully_loaded;
211 mutable TocBackend toc_backend;
214 typedef pair<DocIterator, MacroData> ScopeMacro;
215 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
216 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
217 /// map from the macro name to the position map,
218 /// which maps the macro definition position to the scope and the MacroData.
219 NamePositionScopeMacroMap macros;
220 /// This seem to change the way Buffer::getMacro() works
221 mutable bool macro_lock;
223 /// positions of child buffers in the buffer
224 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
225 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
226 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
227 /// position of children buffers in this buffer
228 BufferPositionMap children_positions;
229 /// map from children inclusion positions to their scope and their buffer
230 PositionScopeBufferMap position_to_children;
232 /// Container for all sort of Buffer dependant errors.
233 map<string, ErrorList> errorLists;
235 /// timestamp and checksum used to test if the file has been externally
236 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
238 unsigned long checksum_;
241 frontend::WorkAreaManager * wa_;
243 frontend::GuiBufferDelegate * gui_;
248 /// A cache for the bibfiles (including bibfiles of loaded child
249 /// documents), needed for appropriate update of natbib labels.
250 mutable support::FileNameList bibfiles_cache_;
252 // FIXME The caching mechanism could be improved. At present, we have a
253 // cache for each Buffer, that caches all the bibliography info for that
254 // Buffer. A more efficient solution would be to have a global cache per
255 // file, and then to construct the Buffer's bibinfo from that.
256 /// A cache for bibliography info
257 mutable BiblioInfo bibinfo_;
258 /// whether the bibinfo cache is valid
259 mutable bool bibinfo_cache_valid_;
260 /// whether the bibfile cache is valid
261 mutable bool bibfile_cache_valid_;
262 /// Cache of timestamps of .bib files
263 map<FileName, time_t> bibfile_status_;
264 /// Indicates whether the bibinfo has changed since the last time
265 /// we ran updateBuffer(), i.e., whether citation labels may need
267 mutable bool cite_labels_valid_;
269 mutable RefCache ref_cache_;
271 /// our Text that should be wrapped in an InsetText
275 PreviewLoader * preview_loader_;
277 /// This is here to force the test to be done whenever parent_buffer
279 Buffer const * parent() const {
280 // if parent_buffer is not loaded, then it has been unloaded,
281 // which means that parent_buffer is an invalid pointer. So we
282 // set it to null in that case.
283 // however, the BufferList doesn't know about cloned buffers, so
284 // they will always be regarded as unloaded. in that case, we hope
286 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
288 return parent_buffer;
292 void setParent(Buffer const * pb) {
293 if (parent_buffer == pb)
296 if (!cloned_buffer_ && parent_buffer && pb)
297 LYXERR0("Warning: a buffer should not have two parents!");
299 if (!cloned_buffer_ && parent_buffer) {
300 parent_buffer->invalidateBibfileCache();
301 parent_buffer->invalidateBibinfoCache();
305 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
306 /// This one is useful for preview detached in a thread.
307 Buffer const * cloned_buffer_;
309 CloneList * clone_list_;
310 /// are we in the process of exporting this buffer?
311 mutable bool doing_export;
314 /// So we can force access via the accessors.
315 mutable Buffer const * parent_buffer;
320 /// Creates the per buffer temporary directory
321 static FileName createBufferTmpDir()
324 // We are in our own directory. Why bother to mangle name?
325 // In fact I wrote this code to circumvent a problematic behaviour
326 // (bug?) of EMX mkstemp().
327 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
328 convert<string>(count++));
330 if (!tmpfl.createDirectory(0777)) {
331 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
332 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
333 from_utf8(tmpfl.absFileName())));
339 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
340 Buffer const * cloned_buffer)
341 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
342 read_only(readonly_), filename(file), file_fully_loaded(false),
343 toc_backend(owner), macro_lock(false), timestamp_(0), checksum_(0),
344 wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
345 bibfile_cache_valid_(false), cite_labels_valid_(false),
346 preview_loader_(0), cloned_buffer_(cloned_buffer), clone_list_(0),
347 doing_export(false), parent_buffer(0)
349 if (!cloned_buffer_) {
350 temppath = createBufferTmpDir();
351 lyxvc.setBuffer(owner_);
353 wa_ = new frontend::WorkAreaManager;
356 temppath = cloned_buffer_->d->temppath;
357 file_fully_loaded = true;
358 params = cloned_buffer_->d->params;
359 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
360 bibinfo_ = cloned_buffer_->d->bibinfo_;
361 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
362 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
363 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
364 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
365 unnamed = cloned_buffer_->d->unnamed;
369 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
370 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
372 LYXERR(Debug::INFO, "Buffer::Buffer()");
374 d->inset = new InsetText(*cloned_buffer->d->inset);
375 d->inset->setBuffer(*this);
376 // FIXME: optimize this loop somewhat, maybe by creating a new
377 // general recursive Inset::setId().
378 DocIterator it = doc_iterator_begin(this);
379 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
380 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
381 it.paragraph().setId(cloned_it.paragraph().id());
383 d->inset = new InsetText(this);
384 d->inset->setAutoBreakRows(true);
385 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
391 LYXERR(Debug::INFO, "Buffer::~Buffer()");
392 // here the buffer should take care that it is
393 // saved properly, before it goes into the void.
395 // GuiView already destroyed
399 // No need to do additional cleanups for internal buffer.
405 // this is in case of recursive includes: we won't try to delete
406 // ourselves as a child.
407 d->clone_list_->erase(this);
408 // loop over children
409 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
410 Impl::BufferPositionMap::iterator end = d->children_positions.end();
411 for (; it != end; ++it) {
412 Buffer * child = const_cast<Buffer *>(it->first);
413 if (d->clone_list_->erase(child))
416 // if we're the master buffer, then we should get rid of the list
419 // if this is not empty, we have leaked something. worse, one of the
420 // children still has a reference to this list.
421 LASSERT(d->clone_list_->empty(), /* */);
422 list<CloneList *>::iterator it =
423 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
424 LASSERT(it != cloned_buffers.end(), /* */);
425 cloned_buffers.erase(it);
426 delete d->clone_list_;
428 // FIXME Do we really need to do this right before we delete d?
429 // clear references to children in macro tables
430 d->children_positions.clear();
431 d->position_to_children.clear();
433 // loop over children
434 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
435 Impl::BufferPositionMap::iterator end = d->children_positions.end();
436 for (; it != end; ++it) {
437 Buffer * child = const_cast<Buffer *>(it->first);
438 if (theBufferList().isLoaded(child))
439 theBufferList().releaseChild(this, child);
443 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
444 msg += emergencyWrite();
445 Alert::warning(_("Attempting to close changed document!"), msg);
448 // FIXME Do we really need to do this right before we delete d?
449 // clear references to children in macro tables
450 d->children_positions.clear();
451 d->position_to_children.clear();
453 if (!d->temppath.destroyDirectory()) {
454 Alert::warning(_("Could not remove temporary directory"),
455 bformat(_("Could not remove the temporary directory %1$s"),
456 from_utf8(d->temppath.absFileName())));
465 Buffer * Buffer::cloneFromMaster() const
468 cloned_buffers.push_back(new CloneList());
469 CloneList * clones = cloned_buffers.back();
471 masterBuffer()->cloneWithChildren(bufmap, clones);
473 // make sure we got cloned
474 BufferMap::const_iterator bit = bufmap.find(this);
475 LASSERT(bit != bufmap.end(), return 0);
476 Buffer * cloned_buffer = bit->second;
478 return cloned_buffer;
482 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
484 // have we already been cloned?
485 if (bufmap.find(this) != bufmap.end())
488 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
489 bufmap[this] = buffer_clone;
490 clones->insert(buffer_clone);
491 buffer_clone->d->clone_list_ = clones;
492 buffer_clone->d->macro_lock = true;
493 buffer_clone->d->children_positions.clear();
494 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
495 // math macro caches need to be rethought and simplified.
496 // I am not sure wether we should handle Buffer cloning here or in BufferList.
497 // Right now BufferList knows nothing about buffer clones.
498 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
499 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
500 for (; it != end; ++it) {
501 DocIterator dit = it->first.clone(buffer_clone);
502 dit.setBuffer(buffer_clone);
503 Buffer * child = const_cast<Buffer *>(it->second.second);
505 child->cloneWithChildren(bufmap, clones);
506 BufferMap::iterator const bit = bufmap.find(child);
507 LASSERT(bit != bufmap.end(), continue);
508 Buffer * child_clone = bit->second;
510 Inset * inset = dit.nextInset();
511 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
512 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
513 inset_inc->setChildBuffer(child_clone);
514 child_clone->d->setParent(buffer_clone);
515 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
516 buffer_clone->setChild(dit, child_clone);
518 buffer_clone->d->macro_lock = false;
523 Buffer * Buffer::cloneBufferOnly() const {
524 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
525 // we won't be cloning the children
526 buffer_clone->d->children_positions.clear();
531 bool Buffer::isClone() const
533 return d->cloned_buffer_;
537 void Buffer::changed(bool update_metrics) const
540 d->wa_->redrawAll(update_metrics);
544 frontend::WorkAreaManager & Buffer::workAreaManager() const
546 LASSERT(d->wa_, /**/);
551 Text & Buffer::text() const
553 return d->inset->text();
557 Inset & Buffer::inset() const
563 BufferParams & Buffer::params()
569 BufferParams const & Buffer::params() const
575 ParagraphList & Buffer::paragraphs()
577 return text().paragraphs();
581 ParagraphList const & Buffer::paragraphs() const
583 return text().paragraphs();
587 LyXVC & Buffer::lyxvc()
593 LyXVC const & Buffer::lyxvc() const
599 string const Buffer::temppath() const
601 return d->temppath.absFileName();
605 TexRow & Buffer::texrow()
611 TexRow const & Buffer::texrow() const
617 TocBackend & Buffer::tocBackend() const
619 return d->toc_backend;
623 Undo & Buffer::undo()
629 void Buffer::setChild(DocIterator const & dit, Buffer * child)
631 d->children_positions[child] = dit;
635 string Buffer::latexName(bool const no_path) const
637 FileName latex_name =
638 makeLatexName(d->exportFileName());
639 return no_path ? latex_name.onlyFileName()
640 : latex_name.absFileName();
644 FileName Buffer::Impl::exportFileName() const
646 docstring const branch_suffix =
647 params.branchlist().getFileNameSuffix();
648 if (branch_suffix.empty())
651 string const name = filename.onlyFileNameWithoutExt()
652 + to_utf8(branch_suffix);
653 FileName res(filename.onlyPath().absFileName() + "/" + name);
654 res.changeExtension(filename.extension());
660 string Buffer::logName(LogType * type) const
662 string const filename = latexName(false);
664 if (filename.empty()) {
670 string const path = temppath();
672 FileName const fname(addName(temppath(),
673 onlyFileName(changeExtension(filename,
676 // FIXME: how do we know this is the name of the build log?
677 FileName const bname(
678 addName(path, onlyFileName(
679 changeExtension(filename,
680 formats.extension(params().bufferFormat()) + ".out"))));
682 // Also consider the master buffer log file
683 FileName masterfname = fname;
685 if (masterBuffer() != this) {
686 string const mlogfile = masterBuffer()->logName(&mtype);
687 masterfname = FileName(mlogfile);
690 // If no Latex log or Build log is newer, show Build log
691 if (bname.exists() &&
692 ((!fname.exists() && !masterfname.exists())
693 || (fname.lastModified() < bname.lastModified()
694 && masterfname.lastModified() < bname.lastModified()))) {
695 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
698 return bname.absFileName();
699 // If we have a newer master file log or only a master log, show this
700 } else if (fname != masterfname
701 && (!fname.exists() && (masterfname.exists()
702 || fname.lastModified() < masterfname.lastModified()))) {
703 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
706 return masterfname.absFileName();
708 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
711 return fname.absFileName();
715 void Buffer::setReadonly(bool const flag)
717 if (d->read_only != flag) {
724 void Buffer::setFileName(FileName const & fname)
727 setReadonly(d->filename.isReadOnly());
733 int Buffer::readHeader(Lexer & lex)
735 int unknown_tokens = 0;
737 int begin_header_line = -1;
739 // Initialize parameters that may be/go lacking in header:
740 params().branchlist().clear();
741 params().preamble.erase();
742 params().options.erase();
743 params().master.erase();
744 params().float_placement.erase();
745 params().paperwidth.erase();
746 params().paperheight.erase();
747 params().leftmargin.erase();
748 params().rightmargin.erase();
749 params().topmargin.erase();
750 params().bottommargin.erase();
751 params().headheight.erase();
752 params().headsep.erase();
753 params().footskip.erase();
754 params().columnsep.erase();
755 params().fonts_cjk.erase();
756 params().listings_params.clear();
757 params().clearLayoutModules();
758 params().clearRemovedModules();
759 params().clearIncludedChildren();
760 params().pdfoptions().clear();
761 params().indiceslist().clear();
762 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
763 params().isbackgroundcolor = false;
764 params().fontcolor = RGBColor(0, 0, 0);
765 params().isfontcolor = false;
766 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
767 params().boxbgcolor = RGBColor(0xFF, 0, 0);
768 params().html_latex_start.clear();
769 params().html_latex_end.clear();
770 params().html_math_img_scale = 1.0;
771 params().output_sync_macro.erase();
773 for (int i = 0; i < 4; ++i) {
774 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
775 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
778 ErrorList & errorList = d->errorLists["Parse"];
787 if (token == "\\end_header")
791 if (token == "\\begin_header") {
792 begin_header_line = line;
796 LYXERR(Debug::PARSER, "Handling document header token: `"
799 string unknown = params().readToken(lex, token, d->filename.onlyPath());
800 if (!unknown.empty()) {
801 if (unknown[0] != '\\' && token == "\\textclass") {
802 Alert::warning(_("Unknown document class"),
803 bformat(_("Using the default document class, because the "
804 "class %1$s is unknown."), from_utf8(unknown)));
807 docstring const s = bformat(_("Unknown token: "
811 errorList.push_back(ErrorItem(_("Document header error"),
816 if (begin_header_line) {
817 docstring const s = _("\\begin_header is missing");
818 errorList.push_back(ErrorItem(_("Document header error"),
822 params().makeDocumentClass();
824 return unknown_tokens;
829 // changed to be public and have one parameter
830 // Returns true if "\end_document" is not read (Asger)
831 bool Buffer::readDocument(Lexer & lex)
833 ErrorList & errorList = d->errorLists["Parse"];
836 // remove dummy empty par
837 paragraphs().clear();
839 if (!lex.checkFor("\\begin_document")) {
840 docstring const s = _("\\begin_document is missing");
841 errorList.push_back(ErrorItem(_("Document header error"),
847 if (params().outputChanges) {
848 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
849 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
850 LaTeXFeatures::isAvailable("xcolor");
852 if (!dvipost && !xcolorulem) {
853 Alert::warning(_("Changes not shown in LaTeX output"),
854 _("Changes will not be highlighted in LaTeX output, "
855 "because neither dvipost nor xcolor/ulem are installed.\n"
856 "Please install these packages or redefine "
857 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
858 } else if (!xcolorulem) {
859 Alert::warning(_("Changes not shown in LaTeX output"),
860 _("Changes will not be highlighted in LaTeX output "
861 "when using pdflatex, because xcolor and ulem are not installed.\n"
862 "Please install both packages or redefine "
863 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
867 if (!params().master.empty()) {
868 FileName const master_file = makeAbsPath(params().master,
869 onlyPath(absFileName()));
870 if (isLyXFileName(master_file.absFileName())) {
872 checkAndLoadLyXFile(master_file, true);
874 // necessary e.g. after a reload
875 // to re-register the child (bug 5873)
876 // FIXME: clean up updateMacros (here, only
877 // child registering is needed).
878 master->updateMacros();
879 // set master as master buffer, but only
880 // if we are a real child
881 if (master->isChild(this))
883 // if the master is not fully loaded
884 // it is probably just loading this
885 // child. No warning needed then.
886 else if (master->isFullyLoaded())
887 LYXERR0("The master '"
889 << "' assigned to this document ("
891 << ") does not include "
892 "this document. Ignoring the master assignment.");
897 // assure we have a default index
898 params().indiceslist().addDefault(B_("Index"));
901 bool const res = text().read(lex, errorList, d->inset);
903 // inform parent buffer about local macros
905 Buffer const * pbuf = parent();
906 UserMacroSet::const_iterator cit = usermacros.begin();
907 UserMacroSet::const_iterator end = usermacros.end();
908 for (; cit != end; ++cit)
909 pbuf->usermacros.insert(*cit);
913 updateMacroInstances(InternalUpdate);
918 bool Buffer::readString(string const & s)
920 params().compressed = false;
925 FileName const fn = FileName::tempName("Buffer_readString");
928 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
929 if (ret_plf != ReadSuccess)
932 if (file_format != LYX_FORMAT) {
933 // We need to call lyx2lyx, so write the input to a file
934 ofstream os(fn.toFilesystemEncoding().c_str());
938 return readFile(fn) == ReadSuccess;
941 if (readDocument(lex))
947 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
951 if (!lex.setFile(fname)) {
952 Alert::error(_("File Not Found"),
953 bformat(_("Unable to open file `%1$s'."),
954 from_utf8(fn.absFileName())));
955 return ReadFileNotFound;
959 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
960 if (ret_plf != ReadSuccess)
963 if (file_format != LYX_FORMAT) {
965 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
966 if (ret_clf != ReadSuccess)
968 return readFile(tmpFile);
971 // FIXME: InsetInfo needs to know whether the file is under VCS
972 // during the parse process, so this has to be done before.
973 lyxvc().file_found_hook(d->filename);
975 if (readDocument(lex)) {
976 Alert::error(_("Document format failure"),
977 bformat(_("%1$s ended unexpectedly, which means"
978 " that it is probably corrupted."),
979 from_utf8(fn.absFileName())));
980 return ReadDocumentFailure;
983 d->file_fully_loaded = true;
984 d->read_only = !d->filename.isWritable();
985 params().compressed = d->filename.isZippedFile();
991 bool Buffer::isFullyLoaded() const
993 return d->file_fully_loaded;
997 void Buffer::setFullyLoaded(bool value)
999 d->file_fully_loaded = value;
1003 PreviewLoader * Buffer::loader() const
1005 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1007 if (!d->preview_loader_)
1008 d->preview_loader_ = new PreviewLoader(*this);
1009 return d->preview_loader_;
1013 void Buffer::removePreviews() const
1015 delete d->preview_loader_;
1016 d->preview_loader_ = 0;
1020 void Buffer::updatePreviews() const
1022 PreviewLoader * ploader = loader();
1026 InsetIterator it = inset_iterator_begin(*d->inset);
1027 InsetIterator const end = inset_iterator_end(*d->inset);
1028 for (; it != end; ++it)
1029 it->addPreview(it, *ploader);
1031 ploader->startLoading();
1035 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1036 FileName const & fn, int & file_format) const
1038 if(!lex.checkFor("\\lyxformat")) {
1039 Alert::error(_("Document format failure"),
1040 bformat(_("%1$s is not a readable LyX document."),
1041 from_utf8(fn.absFileName())));
1042 return ReadNoLyXFormat;
1048 // LyX formats 217 and earlier were written as 2.17. This corresponds
1049 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1050 // these cases. See also: www.lyx.org/trac/changeset/1313.
1051 size_t dot = tmp_format.find_first_of(".,");
1052 if (dot != string::npos)
1053 tmp_format.erase(dot, 1);
1055 file_format = convert<int>(tmp_format);
1060 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1061 FileName & tmpfile, int from_format)
1063 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1064 if(tmpfile.empty()) {
1065 Alert::error(_("Conversion failed"),
1066 bformat(_("%1$s is from a different"
1067 " version of LyX, but a temporary"
1068 " file for converting it could"
1069 " not be created."),
1070 from_utf8(fn.absFileName())));
1071 return LyX2LyXNoTempFile;
1074 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1075 if (lyx2lyx.empty()) {
1076 Alert::error(_("Conversion script not found"),
1077 bformat(_("%1$s is from a different"
1078 " version of LyX, but the"
1079 " conversion script lyx2lyx"
1080 " could not be found."),
1081 from_utf8(fn.absFileName())));
1082 return LyX2LyXNotFound;
1086 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1087 ostringstream command;
1088 command << os::python()
1089 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1090 << " -t " << convert<string>(LYX_FORMAT)
1091 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1092 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1093 string const command_str = command.str();
1095 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1097 cmd_ret const ret = runCommand(command_str);
1098 if (ret.first != 0) {
1099 if (from_format < LYX_FORMAT) {
1100 Alert::error(_("Conversion script failed"),
1101 bformat(_("%1$s is from an older version"
1102 " of LyX and the lyx2lyx script"
1103 " failed to convert it."),
1104 from_utf8(fn.absFileName())));
1105 return LyX2LyXOlderFormat;
1107 Alert::error(_("Conversion script failed"),
1108 bformat(_("%1$s is from a newer version"
1109 " of LyX and the lyx2lyx script"
1110 " failed to convert it."),
1111 from_utf8(fn.absFileName())));
1112 return LyX2LyXNewerFormat;
1119 // Should probably be moved to somewhere else: BufferView? GuiView?
1120 bool Buffer::save() const
1122 docstring const file = makeDisplayPath(absFileName(), 20);
1123 d->filename.refresh();
1125 // check the read-only status before moving the file as a backup
1126 if (d->filename.exists()) {
1127 bool const read_only = !d->filename.isWritable();
1129 Alert::warning(_("File is read-only"),
1130 bformat(_("The file %1$s cannot be written because it "
1131 "is marked as read-only."), file));
1136 // ask if the disk file has been externally modified (use checksum method)
1137 if (fileName().exists() && isExternallyModified(checksum_method)) {
1139 bformat(_("Document %1$s has been externally modified. "
1140 "Are you sure you want to overwrite this file?"), file);
1141 int const ret = Alert::prompt(_("Overwrite modified file?"),
1142 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1147 // We don't need autosaves in the immediate future. (Asger)
1148 resetAutosaveTimers();
1150 FileName backupName;
1151 bool madeBackup = false;
1153 // make a backup if the file already exists
1154 if (lyxrc.make_backup && fileName().exists()) {
1155 backupName = FileName(absFileName() + '~');
1156 if (!lyxrc.backupdir_path.empty()) {
1157 string const mangledName =
1158 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1159 backupName = FileName(addName(lyxrc.backupdir_path,
1163 // Except file is symlink do not copy because of #6587.
1164 // Hard links have bad luck.
1165 if (fileName().isSymLink())
1166 madeBackup = fileName().copyTo(backupName);
1168 madeBackup = fileName().moveTo(backupName);
1171 Alert::error(_("Backup failure"),
1172 bformat(_("Cannot create backup file %1$s.\n"
1173 "Please check whether the directory exists and is writable."),
1174 from_utf8(backupName.absFileName())));
1175 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1179 if (writeFile(d->filename)) {
1183 // Saving failed, so backup is not backup
1185 backupName.moveTo(d->filename);
1191 bool Buffer::writeFile(FileName const & fname) const
1193 // FIXME Do we need to do these here? I don't think writing
1194 // the LyX file depends upon it. (RGH)
1196 // updateMacroInstances();
1198 if (d->read_only && fname == d->filename)
1201 bool retval = false;
1203 docstring const str = bformat(_("Saving document %1$s..."),
1204 makeDisplayPath(fname.absFileName()));
1207 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1209 if (params().compressed) {
1210 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1211 retval = ofs && write(ofs);
1213 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1214 retval = ofs && write(ofs);
1218 message(str + _(" could not write file!"));
1223 // removeAutosaveFile();
1226 message(str + _(" done."));
1232 docstring Buffer::emergencyWrite()
1234 // No need to save if the buffer has not changed.
1238 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1240 docstring user_message = bformat(
1241 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1243 // We try to save three places:
1244 // 1) Same place as document. Unless it is an unnamed doc.
1246 string s = absFileName();
1249 if (writeFile(FileName(s))) {
1251 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1252 return user_message;
1254 user_message += " " + _("Save failed! Trying again...\n");
1258 // 2) In HOME directory.
1259 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1261 lyxerr << ' ' << s << endl;
1262 if (writeFile(FileName(s))) {
1264 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1265 return user_message;
1268 user_message += " " + _("Save failed! Trying yet again...\n");
1270 // 3) In "/tmp" directory.
1271 // MakeAbsPath to prepend the current
1272 // drive letter on OS/2
1273 s = addName(package().temp_dir().absFileName(), absFileName());
1275 lyxerr << ' ' << s << endl;
1276 if (writeFile(FileName(s))) {
1278 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1279 return user_message;
1282 user_message += " " + _("Save failed! Bummer. Document is lost.");
1285 return user_message;
1289 bool Buffer::write(ostream & ofs) const
1292 // Use the standard "C" locale for file output.
1293 ofs.imbue(locale::classic());
1296 // The top of the file should not be written by params().
1298 // write out a comment in the top of the file
1299 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1300 << " created this file. For more info see http://www.lyx.org/\n"
1301 << "\\lyxformat " << LYX_FORMAT << "\n"
1302 << "\\begin_document\n";
1304 /// For each author, set 'used' to true if there is a change
1305 /// by this author in the document; otherwise set it to 'false'.
1306 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1307 AuthorList::Authors::const_iterator a_end = params().authors().end();
1308 for (; a_it != a_end; ++a_it)
1309 a_it->setUsed(false);
1311 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1312 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1313 for ( ; it != end; ++it)
1314 it->checkAuthors(params().authors());
1316 // now write out the buffer parameters.
1317 ofs << "\\begin_header\n";
1318 params().writeFile(ofs);
1319 ofs << "\\end_header\n";
1322 ofs << "\n\\begin_body\n";
1324 ofs << "\n\\end_body\n";
1326 // Write marker that shows file is complete
1327 ofs << "\\end_document" << endl;
1329 // Shouldn't really be needed....
1332 // how to check if close went ok?
1333 // Following is an attempt... (BE 20001011)
1335 // good() returns false if any error occured, including some
1336 // formatting error.
1337 // bad() returns true if something bad happened in the buffer,
1338 // which should include file system full errors.
1343 lyxerr << "File was not closed properly." << endl;
1350 bool Buffer::makeLaTeXFile(FileName const & fname,
1351 string const & original_path,
1352 OutputParams const & runparams_in,
1353 OutputWhat output) const
1355 OutputParams runparams = runparams_in;
1357 // This is necessary for LuaTeX/XeTeX with tex fonts.
1358 // See FIXME in BufferParams::encoding()
1359 if (runparams.isFullUnicode())
1360 runparams.encoding = encodings.fromLyXName("utf8-plain");
1362 string const encoding = runparams.encoding->iconvName();
1363 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1366 try { ofs.reset(encoding); }
1367 catch (iconv_codecvt_facet_exception & e) {
1368 lyxerr << "Caught iconv exception: " << e.what() << endl;
1369 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1370 "verify that the support software for your encoding (%1$s) is "
1371 "properly installed"), from_ascii(encoding)));
1374 if (!openFileWrite(ofs, fname))
1377 //TexStream ts(ofs.rdbuf(), &texrow());
1378 ErrorList & errorList = d->errorLists["Export"];
1380 bool failed_export = false;
1381 otexstream os(ofs, d->texrow);
1383 // make sure we are ready to export
1384 // this needs to be done before we validate
1385 // FIXME Do we need to do this all the time? I.e., in children
1386 // of a master we are exporting?
1388 updateMacroInstances(OutputUpdate);
1391 os.texrow().reset();
1392 writeLaTeXSource(os, original_path, runparams, output);
1394 catch (EncodingException & e) {
1395 odocstringstream ods;
1396 ods.put(e.failed_char);
1398 oss << "0x" << hex << e.failed_char << dec;
1399 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1400 " (code point %2$s)"),
1401 ods.str(), from_utf8(oss.str()));
1402 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1403 "representable in the chosen encoding.\n"
1404 "Changing the document encoding to utf8 could help."),
1405 e.par_id, e.pos, e.pos + 1));
1406 failed_export = true;
1408 catch (iconv_codecvt_facet_exception & e) {
1409 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1410 _(e.what()), -1, 0, 0));
1411 failed_export = true;
1413 catch (exception const & e) {
1414 errorList.push_back(ErrorItem(_("conversion failed"),
1415 _(e.what()), -1, 0, 0));
1416 failed_export = true;
1419 lyxerr << "Caught some really weird exception..." << endl;
1425 failed_export = true;
1426 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1430 return !failed_export;
1434 void Buffer::writeLaTeXSource(otexstream & os,
1435 string const & original_path,
1436 OutputParams const & runparams_in,
1437 OutputWhat output) const
1439 // The child documents, if any, shall be already loaded at this point.
1441 OutputParams runparams = runparams_in;
1443 // Classify the unicode characters appearing in math insets
1444 Encodings::initUnicodeMath(*this);
1446 // validate the buffer.
1447 LYXERR(Debug::LATEX, " Validating buffer...");
1448 LaTeXFeatures features(*this, params(), runparams);
1450 LYXERR(Debug::LATEX, " Buffer validation done.");
1452 bool const output_preamble =
1453 output == FullSource || output == OnlyPreamble;
1454 bool const output_body =
1455 output == FullSource || output == OnlyBody;
1457 // The starting paragraph of the coming rows is the
1458 // first paragraph of the document. (Asger)
1459 if (output_preamble && runparams.nice) {
1460 os << "%% LyX " << lyx_version << " created this file. "
1461 "For more info, see http://www.lyx.org/.\n"
1462 "%% Do not edit unless you really know what "
1465 LYXERR(Debug::INFO, "lyx document header finished");
1467 // There are a few differences between nice LaTeX and usual files:
1468 // usual files have \batchmode and special input@path to allow
1469 // inclusion of figures specified by an explicitly relative path
1470 // (i.e., a path starting with './' or '../') with either \input or
1471 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1472 // input@path is set when the actual parameter original_path is set.
1473 // This is done for usual tex-file, but not for nice-latex-file.
1474 // (Matthias 250696)
1475 // Note that input@path is only needed for something the user does
1476 // in the preamble, included .tex files or ERT, files included by
1477 // LyX work without it.
1478 if (output_preamble) {
1479 if (!runparams.nice) {
1480 // code for usual, NOT nice-latex-file
1481 os << "\\batchmode\n"; // changed from \nonstopmode
1483 if (!original_path.empty()) {
1485 // We don't know the encoding of inputpath
1486 docstring const inputpath = from_utf8(original_path);
1487 docstring uncodable_glyphs;
1488 Encoding const * const enc = runparams.encoding;
1490 for (size_t n = 0; n < inputpath.size(); ++n) {
1491 docstring const glyph =
1492 docstring(1, inputpath[n]);
1493 if (enc->latexChar(inputpath[n], true) != glyph) {
1494 LYXERR0("Uncodable character '"
1496 << "' in input path!");
1497 uncodable_glyphs += glyph;
1502 // warn user if we found uncodable glyphs.
1503 if (!uncodable_glyphs.empty()) {
1504 frontend::Alert::warning(
1505 _("Uncodable character in file path"),
1507 _("The path of your document\n"
1509 "contains glyphs that are unknown "
1510 "in the current document encoding "
1511 "(namely %2$s). This may result in "
1512 "incomplete output, unless "
1513 "TEXINPUTS contains the document "
1514 "directory and you don't use "
1515 "explicitly relative paths (i.e., "
1516 "paths starting with './' or "
1517 "'../') in the preamble or in ERT."
1518 "\n\nIn case of problems, choose "
1519 "an appropriate document encoding\n"
1520 "(such as utf8) or change the "
1522 inputpath, uncodable_glyphs));
1525 support::latex_path(original_path);
1526 if (contains(docdir, '#')) {
1527 docdir = subst(docdir, "#", "\\#");
1528 os << "\\catcode`\\#=11"
1529 "\\def\\#{#}\\catcode`\\#=6\n";
1531 if (contains(docdir, '%')) {
1532 docdir = subst(docdir, "%", "\\%");
1533 os << "\\catcode`\\%=11"
1534 "\\def\\%{%}\\catcode`\\%=14\n";
1536 os << "\\makeatletter\n"
1537 << "\\def\\input@path{{"
1538 << docdir << "/}}\n"
1539 << "\\makeatother\n";
1543 // get parent macros (if this buffer has a parent) which will be
1544 // written at the document begin further down.
1545 MacroSet parentMacros;
1546 listParentMacros(parentMacros, features);
1548 runparams.use_polyglossia = features.usePolyglossia();
1549 // Write the preamble
1550 runparams.use_babel = params().writeLaTeX(os, features,
1551 d->filename.onlyPath());
1553 runparams.use_japanese = features.isRequired("japanese");
1559 os << "\\begin{document}\n";
1561 // output the parent macros
1562 MacroSet::iterator it = parentMacros.begin();
1563 MacroSet::iterator end = parentMacros.end();
1564 for (; it != end; ++it) {
1565 int num_lines = (*it)->write(os.os(), true);
1566 os.texrow().newlines(num_lines);
1569 } // output_preamble
1571 os.texrow().start(paragraphs().begin()->id(), 0);
1573 LYXERR(Debug::INFO, "preamble finished, now the body.");
1575 // if we are doing a real file with body, even if this is the
1576 // child of some other buffer, let's cut the link here.
1577 // This happens for example if only a child document is printed.
1578 Buffer const * save_parent = 0;
1579 if (output_preamble) {
1580 save_parent = d->parent();
1585 latexParagraphs(*this, text(), os, runparams);
1587 // Restore the parenthood if needed
1588 if (output_preamble)
1589 d->setParent(save_parent);
1591 // add this just in case after all the paragraphs
1594 if (output_preamble) {
1595 os << "\\end{document}\n";
1596 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1598 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1600 runparams_in.encoding = runparams.encoding;
1602 // Just to be sure. (Asger)
1603 os.texrow().newline();
1605 //for (int i = 0; i<d->texrow.rows(); i++) {
1607 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1608 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1611 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1612 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1616 void Buffer::makeDocBookFile(FileName const & fname,
1617 OutputParams const & runparams,
1618 OutputWhat output) const
1620 LYXERR(Debug::LATEX, "makeDocBookFile...");
1623 if (!openFileWrite(ofs, fname))
1626 // make sure we are ready to export
1627 // this needs to be done before we validate
1629 updateMacroInstances(OutputUpdate);
1631 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1635 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1639 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1640 OutputParams const & runparams,
1641 OutputWhat output) const
1643 LaTeXFeatures features(*this, params(), runparams);
1648 DocumentClass const & tclass = params().documentClass();
1649 string const top_element = tclass.latexname();
1651 bool const output_preamble =
1652 output == FullSource || output == OnlyPreamble;
1653 bool const output_body =
1654 output == FullSource || output == OnlyBody;
1656 if (output_preamble) {
1657 if (runparams.flavor == OutputParams::XML)
1658 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1661 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1664 if (! tclass.class_header().empty())
1665 os << from_ascii(tclass.class_header());
1666 else if (runparams.flavor == OutputParams::XML)
1667 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1668 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1670 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1672 docstring preamble = from_utf8(params().preamble);
1673 if (runparams.flavor != OutputParams::XML ) {
1674 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1675 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1676 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1677 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1680 string const name = runparams.nice
1681 ? changeExtension(absFileName(), ".sgml") : fname;
1682 preamble += features.getIncludedFiles(name);
1683 preamble += features.getLyXSGMLEntities();
1685 if (!preamble.empty()) {
1686 os << "\n [ " << preamble << " ]";
1692 string top = top_element;
1694 if (runparams.flavor == OutputParams::XML)
1695 top += params().language->code();
1697 top += params().language->code().substr(0, 2);
1700 if (!params().options.empty()) {
1702 top += params().options;
1705 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1706 << " file was created by LyX " << lyx_version
1707 << "\n See http://www.lyx.org/ for more information -->\n";
1709 params().documentClass().counters().reset();
1711 sgml::openTag(os, top);
1713 docbookParagraphs(text(), *this, os, runparams);
1714 sgml::closeTag(os, top_element);
1719 void Buffer::makeLyXHTMLFile(FileName const & fname,
1720 OutputParams const & runparams) const
1722 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1725 if (!openFileWrite(ofs, fname))
1728 // make sure we are ready to export
1729 // this has to be done before we validate
1730 updateBuffer(UpdateMaster, OutputUpdate);
1731 updateMacroInstances(OutputUpdate);
1733 writeLyXHTMLSource(ofs, runparams, FullSource);
1737 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1741 void Buffer::writeLyXHTMLSource(odocstream & os,
1742 OutputParams const & runparams,
1743 OutputWhat output) const
1745 LaTeXFeatures features(*this, params(), runparams);
1747 d->bibinfo_.makeCitationLabels(*this);
1749 bool const output_preamble =
1750 output == FullSource || output == OnlyPreamble;
1751 bool const output_body =
1752 output == FullSource || output == OnlyBody;
1754 if (output_preamble) {
1755 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1756 << "<!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"
1757 // FIXME Language should be set properly.
1758 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1760 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1761 // FIXME Presumably need to set this right
1762 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1764 docstring const & doctitle = features.htmlTitle();
1766 << (doctitle.empty() ?
1767 from_ascii("LyX Document") :
1768 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1771 os << "\n<!-- Text Class Preamble -->\n"
1772 << features.getTClassHTMLPreamble()
1773 << "\n<!-- Preamble Snippets -->\n"
1774 << from_utf8(features.getPreambleSnippets());
1776 os << "\n<!-- Layout-provided Styles -->\n";
1777 docstring const styleinfo = features.getTClassHTMLStyles();
1778 if (!styleinfo.empty()) {
1779 os << "<style type='text/css'>\n"
1784 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1785 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1786 if (needfg || needbg) {
1787 os << "<style type='text/css'>\nbody {\n";
1790 << from_ascii(X11hexname(params().fontcolor))
1793 os << " background-color: "
1794 << from_ascii(X11hexname(params().backgroundcolor))
1796 os << "}\n</style>\n";
1804 params().documentClass().counters().reset();
1805 xhtmlParagraphs(text(), *this, xs, runparams);
1809 if (output_preamble)
1814 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1815 // Other flags: -wall -v0 -x
1816 int Buffer::runChktex()
1820 // get LaTeX-Filename
1821 FileName const path(temppath());
1822 string const name = addName(path.absFileName(), latexName());
1823 string const org_path = filePath();
1825 PathChanger p(path); // path to LaTeX file
1826 message(_("Running chktex..."));
1828 // Generate the LaTeX file if neccessary
1829 OutputParams runparams(¶ms().encoding());
1830 runparams.flavor = OutputParams::LATEX;
1831 runparams.nice = false;
1832 runparams.linelen = lyxrc.plaintext_linelen;
1833 makeLaTeXFile(FileName(name), org_path, runparams);
1836 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1837 int const res = chktex.run(terr); // run chktex
1840 Alert::error(_("chktex failure"),
1841 _("Could not run chktex successfully."));
1842 } else if (res > 0) {
1843 ErrorList & errlist = d->errorLists["ChkTeX"];
1845 bufferErrors(terr, errlist);
1856 void Buffer::validate(LaTeXFeatures & features) const
1858 params().validate(features);
1860 for_each(paragraphs().begin(), paragraphs().end(),
1861 bind(&Paragraph::validate, _1, ref(features)));
1863 if (lyxerr.debugging(Debug::LATEX)) {
1864 features.showStruct();
1869 void Buffer::getLabelList(vector<docstring> & list) const
1871 // If this is a child document, use the master's list instead.
1873 masterBuffer()->getLabelList(list);
1878 Toc & toc = d->toc_backend.toc("label");
1879 TocIterator toc_it = toc.begin();
1880 TocIterator end = toc.end();
1881 for (; toc_it != end; ++toc_it) {
1882 if (toc_it->depth() == 0)
1883 list.push_back(toc_it->str());
1888 void Buffer::updateBibfilesCache(UpdateScope scope) const
1890 // FIXME This is probably unnecssary, given where we call this.
1891 // If this is a child document, use the parent's cache instead.
1892 if (parent() && scope != UpdateChildOnly) {
1893 masterBuffer()->updateBibfilesCache();
1897 d->bibfiles_cache_.clear();
1898 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1899 if (it->lyxCode() == BIBTEX_CODE) {
1900 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1901 support::FileNameList const bibfiles = inset.getBibFiles();
1902 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1905 } else if (it->lyxCode() == INCLUDE_CODE) {
1906 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1907 Buffer const * const incbuf = inset.getChildBuffer();
1910 support::FileNameList const & bibfiles =
1911 incbuf->getBibfilesCache(UpdateChildOnly);
1912 if (!bibfiles.empty()) {
1913 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1919 d->bibfile_cache_valid_ = true;
1920 d->bibinfo_cache_valid_ = false;
1921 d->cite_labels_valid_ = false;
1925 void Buffer::invalidateBibinfoCache() const
1927 d->bibinfo_cache_valid_ = false;
1928 d->cite_labels_valid_ = false;
1929 // also invalidate the cache for the parent buffer
1930 Buffer const * const pbuf = d->parent();
1932 pbuf->invalidateBibinfoCache();
1936 void Buffer::invalidateBibfileCache() const
1938 d->bibfile_cache_valid_ = false;
1939 d->bibinfo_cache_valid_ = false;
1940 d->cite_labels_valid_ = false;
1941 // also invalidate the cache for the parent buffer
1942 Buffer const * const pbuf = d->parent();
1944 pbuf->invalidateBibfileCache();
1948 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1950 // FIXME This is probably unnecessary, given where we call this.
1951 // If this is a child document, use the master's cache instead.
1952 Buffer const * const pbuf = masterBuffer();
1953 if (pbuf != this && scope != UpdateChildOnly)
1954 return pbuf->getBibfilesCache();
1956 if (!d->bibfile_cache_valid_)
1957 this->updateBibfilesCache(scope);
1959 return d->bibfiles_cache_;
1963 BiblioInfo const & Buffer::masterBibInfo() const
1965 Buffer const * const tmp = masterBuffer();
1967 return tmp->masterBibInfo();
1972 void Buffer::checkIfBibInfoCacheIsValid() const
1974 // use the master's cache
1975 Buffer const * const tmp = masterBuffer();
1977 tmp->checkIfBibInfoCacheIsValid();
1981 // compare the cached timestamps with the actual ones.
1982 FileNameList const & bibfiles_cache = getBibfilesCache();
1983 FileNameList::const_iterator ei = bibfiles_cache.begin();
1984 FileNameList::const_iterator en = bibfiles_cache.end();
1985 for (; ei != en; ++ ei) {
1986 time_t lastw = ei->lastModified();
1987 time_t prevw = d->bibfile_status_[*ei];
1988 if (lastw != prevw) {
1989 d->bibinfo_cache_valid_ = false;
1990 d->cite_labels_valid_ = false;
1991 d->bibfile_status_[*ei] = lastw;
1997 void Buffer::reloadBibInfoCache() const
1999 // use the master's cache
2000 Buffer const * const tmp = masterBuffer();
2002 tmp->reloadBibInfoCache();
2006 checkIfBibInfoCacheIsValid();
2007 if (d->bibinfo_cache_valid_)
2010 d->bibinfo_.clear();
2012 d->bibinfo_cache_valid_ = true;
2016 void Buffer::collectBibKeys() const
2018 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2019 it->collectBibKeys(it);
2023 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2025 Buffer const * tmp = masterBuffer();
2026 BiblioInfo & masterbi = (tmp == this) ?
2027 d->bibinfo_ : tmp->d->bibinfo_;
2028 masterbi.mergeBiblioInfo(bi);
2032 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2034 Buffer const * tmp = masterBuffer();
2035 BiblioInfo & masterbi = (tmp == this) ?
2036 d->bibinfo_ : tmp->d->bibinfo_;
2041 bool Buffer::citeLabelsValid() const
2043 return masterBuffer()->d->cite_labels_valid_;
2047 void Buffer::removeBiblioTempFiles() const
2049 // We remove files that contain LaTeX commands specific to the
2050 // particular bibliographic style being used, in order to avoid
2051 // LaTeX errors when we switch style.
2052 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2053 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2054 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2055 aux_file.removeFile();
2056 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2057 bbl_file.removeFile();
2058 // Also for the parent buffer
2059 Buffer const * const pbuf = parent();
2061 pbuf->removeBiblioTempFiles();
2065 bool Buffer::isDepClean(string const & name) const
2067 DepClean::const_iterator const it = d->dep_clean.find(name);
2068 if (it == d->dep_clean.end())
2074 void Buffer::markDepClean(string const & name)
2076 d->dep_clean[name] = true;
2080 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2083 // FIXME? if there is an Buffer LFUN that can be dispatched even
2084 // if internal, put a switch '(cmd.action)' here.
2090 switch (cmd.action()) {
2092 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2093 flag.setOnOff(isReadonly());
2096 // FIXME: There is need for a command-line import.
2097 //case LFUN_BUFFER_IMPORT:
2099 case LFUN_BUFFER_AUTO_SAVE:
2102 case LFUN_BUFFER_EXPORT_CUSTOM:
2103 // FIXME: Nothing to check here?
2106 case LFUN_BUFFER_EXPORT: {
2107 docstring const arg = cmd.argument();
2108 if (arg == "custom") {
2112 string format = to_utf8(arg);
2113 size_t pos = format.find(' ');
2114 if (pos != string::npos)
2115 format = format.substr(0, pos);
2116 enable = params().isExportable(format);
2118 flag.message(bformat(
2119 _("Don't know how to export to format: %1$s"), arg));
2123 case LFUN_BUFFER_CHKTEX:
2124 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2127 case LFUN_BUILD_PROGRAM:
2128 enable = params().isExportable("program");
2131 case LFUN_BRANCH_ADD:
2132 case LFUN_BRANCHES_RENAME:
2133 case LFUN_BUFFER_PRINT:
2134 // if no Buffer is present, then of course we won't be called!
2137 case LFUN_BUFFER_LANGUAGE:
2138 enable = !isReadonly();
2144 flag.setEnabled(enable);
2149 void Buffer::dispatch(string const & command, DispatchResult & result)
2151 return dispatch(lyxaction.lookupFunc(command), result);
2155 // NOTE We can end up here even if we have no GUI, because we are called
2156 // by LyX::exec to handled command-line requests. So we may need to check
2157 // whether we have a GUI or not. The boolean use_gui holds this information.
2158 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2161 // FIXME? if there is an Buffer LFUN that can be dispatched even
2162 // if internal, put a switch '(cmd.action())' here.
2163 dr.dispatched(false);
2166 string const argument = to_utf8(func.argument());
2167 // We'll set this back to false if need be.
2168 bool dispatched = true;
2169 undo().beginUndoGroup();
2171 switch (func.action()) {
2172 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2173 if (lyxvc().inUse())
2174 lyxvc().toggleReadOnly();
2176 setReadonly(!isReadonly());
2179 case LFUN_BUFFER_EXPORT: {
2180 ExportStatus const status = doExport(argument, false);
2181 dr.setError(status != ExportSuccess);
2182 if (status != ExportSuccess)
2183 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2188 case LFUN_BUILD_PROGRAM:
2189 doExport("program", true);
2192 case LFUN_BUFFER_CHKTEX:
2196 case LFUN_BUFFER_EXPORT_CUSTOM: {
2198 string command = split(argument, format_name, ' ');
2199 Format const * format = formats.getFormat(format_name);
2201 lyxerr << "Format \"" << format_name
2202 << "\" not recognized!"
2207 // The name of the file created by the conversion process
2210 // Output to filename
2211 if (format->name() == "lyx") {
2212 string const latexname = latexName(false);
2213 filename = changeExtension(latexname,
2214 format->extension());
2215 filename = addName(temppath(), filename);
2217 if (!writeFile(FileName(filename)))
2221 doExport(format_name, true, filename);
2224 // Substitute $$FName for filename
2225 if (!contains(command, "$$FName"))
2226 command = "( " + command + " ) < $$FName";
2227 command = subst(command, "$$FName", filename);
2229 // Execute the command in the background
2231 call.startscript(Systemcall::DontWait, command, filePath());
2235 // FIXME: There is need for a command-line import.
2237 case LFUN_BUFFER_IMPORT:
2242 case LFUN_BUFFER_AUTO_SAVE:
2244 resetAutosaveTimers();
2247 case LFUN_BRANCH_ADD: {
2248 docstring branch_name = func.argument();
2249 if (branch_name.empty()) {
2253 BranchList & branch_list = params().branchlist();
2254 vector<docstring> const branches =
2255 getVectorFromString(branch_name, branch_list.separator());
2257 for (vector<docstring>::const_iterator it = branches.begin();
2258 it != branches.end(); ++it) {
2260 Branch * branch = branch_list.find(branch_name);
2262 LYXERR0("Branch " << branch_name << " already exists.");
2266 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2268 branch_list.add(branch_name);
2269 branch = branch_list.find(branch_name);
2270 string const x11hexname = X11hexname(branch->color());
2271 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2272 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2274 dr.screenUpdate(Update::Force);
2282 case LFUN_BRANCHES_RENAME: {
2283 if (func.argument().empty())
2286 docstring const oldname = from_utf8(func.getArg(0));
2287 docstring const newname = from_utf8(func.getArg(1));
2288 InsetIterator it = inset_iterator_begin(inset());
2289 InsetIterator const end = inset_iterator_end(inset());
2290 bool success = false;
2291 for (; it != end; ++it) {
2292 if (it->lyxCode() == BRANCH_CODE) {
2293 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2294 if (ins.branch() == oldname) {
2295 undo().recordUndo(it);
2296 ins.rename(newname);
2301 if (it->lyxCode() == INCLUDE_CODE) {
2302 // get buffer of external file
2303 InsetInclude const & ins =
2304 static_cast<InsetInclude const &>(*it);
2305 Buffer * child = ins.getChildBuffer();
2308 child->dispatch(func, dr);
2313 dr.screenUpdate(Update::Force);
2314 dr.forceBufferUpdate();
2319 case LFUN_BUFFER_PRINT: {
2320 // we'll assume there's a problem until we succeed
2322 string target = func.getArg(0);
2323 string target_name = func.getArg(1);
2324 string command = func.getArg(2);
2327 || target_name.empty()
2328 || command.empty()) {
2329 LYXERR0("Unable to parse " << func.argument());
2330 docstring const msg =
2331 bformat(_("Unable to parse \"%1$s\""), func.argument());
2335 if (target != "printer" && target != "file") {
2336 LYXERR0("Unrecognized target \"" << target << '"');
2337 docstring const msg =
2338 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2343 if (!doExport("dvi", true)) {
2344 showPrintError(absFileName());
2345 dr.setMessage(_("Error exporting to DVI."));
2349 // Push directory path.
2350 string const path = temppath();
2351 // Prevent the compiler from optimizing away p
2355 // there are three cases here:
2356 // 1. we print to a file
2357 // 2. we print directly to a printer
2358 // 3. we print using a spool command (print to file first)
2361 string const dviname = changeExtension(latexName(true), "dvi");
2363 if (target == "printer") {
2364 if (!lyxrc.print_spool_command.empty()) {
2365 // case 3: print using a spool
2366 string const psname = changeExtension(dviname,".ps");
2367 command += ' ' + lyxrc.print_to_file
2370 + quoteName(dviname);
2372 string command2 = lyxrc.print_spool_command + ' ';
2373 if (target_name != "default") {
2374 command2 += lyxrc.print_spool_printerprefix
2378 command2 += quoteName(psname);
2380 // If successful, then spool command
2381 res = one.startscript(Systemcall::Wait, command,
2385 // If there's no GUI, we have to wait on this command. Otherwise,
2386 // LyX deletes the temporary directory, and with it the spooled
2387 // file, before it can be printed!!
2388 Systemcall::Starttype stype = use_gui ?
2389 Systemcall::DontWait : Systemcall::Wait;
2390 res = one.startscript(stype, command2,
2394 // case 2: print directly to a printer
2395 if (target_name != "default")
2396 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2398 Systemcall::Starttype stype = use_gui ?
2399 Systemcall::DontWait : Systemcall::Wait;
2400 res = one.startscript(stype, command +
2401 quoteName(dviname), filePath());
2405 // case 1: print to a file
2406 FileName const filename(makeAbsPath(target_name, filePath()));
2407 FileName const dvifile(makeAbsPath(dviname, path));
2408 if (filename.exists()) {
2409 docstring text = bformat(
2410 _("The file %1$s already exists.\n\n"
2411 "Do you want to overwrite that file?"),
2412 makeDisplayPath(filename.absFileName()));
2413 if (Alert::prompt(_("Overwrite file?"),
2414 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2417 command += ' ' + lyxrc.print_to_file
2418 + quoteName(filename.toFilesystemEncoding())
2420 + quoteName(dvifile.toFilesystemEncoding());
2422 Systemcall::Starttype stype = use_gui ?
2423 Systemcall::DontWait : Systemcall::Wait;
2424 res = one.startscript(stype, command, filePath());
2430 dr.setMessage(_("Error running external commands."));
2431 showPrintError(absFileName());
2440 dr.dispatched(dispatched);
2441 undo().endUndoGroup();
2445 void Buffer::changeLanguage(Language const * from, Language const * to)
2447 LASSERT(from, /**/);
2450 for_each(par_iterator_begin(),
2452 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2456 bool Buffer::isMultiLingual() const
2458 ParConstIterator end = par_iterator_end();
2459 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2460 if (it->isMultiLingual(params()))
2467 std::set<Language const *> Buffer::getLanguages() const
2469 std::set<Language const *> languages;
2470 getLanguages(languages);
2475 void Buffer::getLanguages(std::set<Language const *> & languages) const
2477 ParConstIterator end = par_iterator_end();
2478 // add the buffer language, even if it's not actively used
2479 languages.insert(language());
2480 // iterate over the paragraphs
2481 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2482 it->getLanguages(languages);
2484 ListOfBuffers clist = getDescendents();
2485 ListOfBuffers::const_iterator cit = clist.begin();
2486 ListOfBuffers::const_iterator const cen = clist.end();
2487 for (; cit != cen; ++cit)
2488 (*cit)->getLanguages(languages);
2492 DocIterator Buffer::getParFromID(int const id) const
2494 Buffer * buf = const_cast<Buffer *>(this);
2496 // John says this is called with id == -1 from undo
2497 lyxerr << "getParFromID(), id: " << id << endl;
2498 return doc_iterator_end(buf);
2501 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2502 if (it.paragraph().id() == id)
2505 return doc_iterator_end(buf);
2509 bool Buffer::hasParWithID(int const id) const
2511 return !getParFromID(id).atEnd();
2515 ParIterator Buffer::par_iterator_begin()
2517 return ParIterator(doc_iterator_begin(this));
2521 ParIterator Buffer::par_iterator_end()
2523 return ParIterator(doc_iterator_end(this));
2527 ParConstIterator Buffer::par_iterator_begin() const
2529 return ParConstIterator(doc_iterator_begin(this));
2533 ParConstIterator Buffer::par_iterator_end() const
2535 return ParConstIterator(doc_iterator_end(this));
2539 Language const * Buffer::language() const
2541 return params().language;
2545 docstring const Buffer::B_(string const & l10n) const
2547 return params().B_(l10n);
2551 bool Buffer::isClean() const
2553 return d->lyx_clean;
2557 bool Buffer::isExternallyModified(CheckMethod method) const
2559 LASSERT(d->filename.exists(), /**/);
2560 // if method == timestamp, check timestamp before checksum
2561 return (method == checksum_method
2562 || d->timestamp_ != d->filename.lastModified())
2563 && d->checksum_ != d->filename.checksum();
2567 void Buffer::saveCheckSum() const
2569 FileName const & file = d->filename;
2572 if (file.exists()) {
2573 d->timestamp_ = file.lastModified();
2574 d->checksum_ = file.checksum();
2576 // in the case of save to a new file.
2583 void Buffer::markClean() const
2585 if (!d->lyx_clean) {
2586 d->lyx_clean = true;
2589 // if the .lyx file has been saved, we don't need an
2591 d->bak_clean = true;
2592 d->undo_.markDirty();
2596 void Buffer::setUnnamed(bool flag)
2602 bool Buffer::isUnnamed() const
2609 /// Don't check unnamed, here: isInternal() is used in
2610 /// newBuffer(), where the unnamed flag has not been set by anyone
2611 /// yet. Also, for an internal buffer, there should be no need for
2612 /// retrieving fileName() nor for checking if it is unnamed or not.
2613 bool Buffer::isInternal() const
2615 return fileName().extension() == "internal";
2619 void Buffer::markDirty()
2622 d->lyx_clean = false;
2625 d->bak_clean = false;
2627 DepClean::iterator it = d->dep_clean.begin();
2628 DepClean::const_iterator const end = d->dep_clean.end();
2630 for (; it != end; ++it)
2635 FileName Buffer::fileName() const
2641 string Buffer::absFileName() const
2643 return d->filename.absFileName();
2647 string Buffer::filePath() const
2649 return d->filename.onlyPath().absFileName() + "/";
2653 bool Buffer::isReadonly() const
2655 return d->read_only;
2659 void Buffer::setParent(Buffer const * buffer)
2661 // Avoids recursive include.
2662 d->setParent(buffer == this ? 0 : buffer);
2667 Buffer const * Buffer::parent() const
2673 ListOfBuffers Buffer::allRelatives() const
2675 ListOfBuffers lb = masterBuffer()->getDescendents();
2676 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2681 Buffer const * Buffer::masterBuffer() const
2683 // FIXME Should be make sure we are not in some kind
2684 // of recursive include? A -> B -> A will crash this.
2685 Buffer const * const pbuf = d->parent();
2689 return pbuf->masterBuffer();
2693 bool Buffer::isChild(Buffer * child) const
2695 return d->children_positions.find(child) != d->children_positions.end();
2699 DocIterator Buffer::firstChildPosition(Buffer const * child)
2701 Impl::BufferPositionMap::iterator it;
2702 it = d->children_positions.find(child);
2703 if (it == d->children_positions.end())
2704 return DocIterator(this);
2709 bool Buffer::hasChildren() const
2711 return !d->children_positions.empty();
2715 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2717 // loop over children
2718 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2719 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2720 for (; it != end; ++it) {
2721 Buffer * child = const_cast<Buffer *>(it->first);
2723 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2724 if (bit != clist.end())
2726 clist.push_back(child);
2728 // there might be grandchildren
2729 child->collectChildren(clist, true);
2734 ListOfBuffers Buffer::getChildren() const
2737 collectChildren(v, false);
2738 // Make sure we have not included ourselves.
2739 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2740 if (bit != v.end()) {
2741 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2748 ListOfBuffers Buffer::getDescendents() const
2751 collectChildren(v, true);
2752 // Make sure we have not included ourselves.
2753 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2754 if (bit != v.end()) {
2755 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2762 template<typename M>
2763 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2768 typename M::const_iterator it = m.lower_bound(x);
2769 if (it == m.begin())
2777 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2778 DocIterator const & pos) const
2780 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2782 // if paragraphs have no macro context set, pos will be empty
2786 // we haven't found anything yet
2787 DocIterator bestPos = owner_->par_iterator_begin();
2788 MacroData const * bestData = 0;
2790 // find macro definitions for name
2791 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2792 if (nameIt != macros.end()) {
2793 // find last definition in front of pos or at pos itself
2794 PositionScopeMacroMap::const_iterator it
2795 = greatest_below(nameIt->second, pos);
2796 if (it != nameIt->second.end()) {
2798 // scope ends behind pos?
2799 if (pos < it->second.first) {
2800 // Looks good, remember this. If there
2801 // is no external macro behind this,
2802 // we found the right one already.
2803 bestPos = it->first;
2804 bestData = &it->second.second;
2808 // try previous macro if there is one
2809 if (it == nameIt->second.begin())
2816 // find macros in included files
2817 PositionScopeBufferMap::const_iterator it
2818 = greatest_below(position_to_children, pos);
2819 if (it == position_to_children.end())
2820 // no children before
2824 // do we know something better (i.e. later) already?
2825 if (it->first < bestPos )
2828 // scope ends behind pos?
2829 if (pos < it->second.first
2830 && (cloned_buffer_ ||
2831 theBufferList().isLoaded(it->second.second))) {
2832 // look for macro in external file
2834 MacroData const * data
2835 = it->second.second->getMacro(name, false);
2838 bestPos = it->first;
2844 // try previous file if there is one
2845 if (it == position_to_children.begin())
2850 // return the best macro we have found
2855 MacroData const * Buffer::getMacro(docstring const & name,
2856 DocIterator const & pos, bool global) const
2861 // query buffer macros
2862 MacroData const * data = d->getBufferMacro(name, pos);
2866 // If there is a master buffer, query that
2867 Buffer const * const pbuf = d->parent();
2869 d->macro_lock = true;
2870 MacroData const * macro = pbuf->getMacro(
2871 name, *this, false);
2872 d->macro_lock = false;
2878 data = MacroTable::globalMacros().get(name);
2887 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2889 // set scope end behind the last paragraph
2890 DocIterator scope = par_iterator_begin();
2891 scope.pit() = scope.lastpit() + 1;
2893 return getMacro(name, scope, global);
2897 MacroData const * Buffer::getMacro(docstring const & name,
2898 Buffer const & child, bool global) const
2900 // look where the child buffer is included first
2901 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2902 if (it == d->children_positions.end())
2905 // check for macros at the inclusion position
2906 return getMacro(name, it->second, global);
2910 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2912 pit_type const lastpit = it.lastpit();
2914 // look for macros in each paragraph
2915 while (it.pit() <= lastpit) {
2916 Paragraph & par = it.paragraph();
2918 // iterate over the insets of the current paragraph
2919 InsetList const & insets = par.insetList();
2920 InsetList::const_iterator iit = insets.begin();
2921 InsetList::const_iterator end = insets.end();
2922 for (; iit != end; ++iit) {
2923 it.pos() = iit->pos;
2925 // is it a nested text inset?
2926 if (iit->inset->asInsetText()) {
2927 // Inset needs its own scope?
2928 InsetText const * itext = iit->inset->asInsetText();
2929 bool newScope = itext->isMacroScope();
2931 // scope which ends just behind the inset
2932 DocIterator insetScope = it;
2935 // collect macros in inset
2936 it.push_back(CursorSlice(*iit->inset));
2937 updateMacros(it, newScope ? insetScope : scope);
2942 if (iit->inset->asInsetTabular()) {
2943 CursorSlice slice(*iit->inset);
2944 size_t const numcells = slice.nargs();
2945 for (; slice.idx() < numcells; slice.forwardIdx()) {
2946 it.push_back(slice);
2947 updateMacros(it, scope);
2953 // is it an external file?
2954 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2955 // get buffer of external file
2956 InsetInclude const & inset =
2957 static_cast<InsetInclude const &>(*iit->inset);
2959 Buffer * child = inset.getChildBuffer();
2964 // register its position, but only when it is
2965 // included first in the buffer
2966 if (children_positions.find(child) ==
2967 children_positions.end())
2968 children_positions[child] = it;
2970 // register child with its scope
2971 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2975 InsetMath * im = iit->inset->asInsetMath();
2976 if (doing_export && im) {
2977 InsetMathHull * hull = im->asHullInset();
2979 hull->recordLocation(it);
2982 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2986 MathMacroTemplate & macroTemplate =
2987 *iit->inset->asInsetMath()->asMacroTemplate();
2988 MacroContext mc(owner_, it);
2989 macroTemplate.updateToContext(mc);
2992 bool valid = macroTemplate.validMacro();
2993 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2994 // then the BufferView's cursor will be invalid in
2995 // some cases which leads to crashes.
3000 // FIXME (Abdel), I don't understandt why we pass 'it' here
3001 // instead of 'macroTemplate' defined above... is this correct?
3002 macros[macroTemplate.name()][it] =
3003 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3013 void Buffer::updateMacros() const
3018 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3020 // start with empty table
3022 d->children_positions.clear();
3023 d->position_to_children.clear();
3025 // Iterate over buffer, starting with first paragraph
3026 // The scope must be bigger than any lookup DocIterator
3027 // later. For the global lookup, lastpit+1 is used, hence
3028 // we use lastpit+2 here.
3029 DocIterator it = par_iterator_begin();
3030 DocIterator outerScope = it;
3031 outerScope.pit() = outerScope.lastpit() + 2;
3032 d->updateMacros(it, outerScope);
3036 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3038 InsetIterator it = inset_iterator_begin(inset());
3039 InsetIterator const end = inset_iterator_end(inset());
3040 for (; it != end; ++it) {
3041 if (it->lyxCode() == BRANCH_CODE) {
3042 InsetBranch & br = static_cast<InsetBranch &>(*it);
3043 docstring const name = br.branch();
3044 if (!from_master && !params().branchlist().find(name))
3045 result.push_back(name);
3046 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3047 result.push_back(name);
3050 if (it->lyxCode() == INCLUDE_CODE) {
3051 // get buffer of external file
3052 InsetInclude const & ins =
3053 static_cast<InsetInclude const &>(*it);
3054 Buffer * child = ins.getChildBuffer();
3057 child->getUsedBranches(result, true);
3060 // remove duplicates
3065 void Buffer::updateMacroInstances(UpdateType utype) const
3067 LYXERR(Debug::MACROS, "updateMacroInstances for "
3068 << d->filename.onlyFileName());
3069 DocIterator it = doc_iterator_begin(this);
3071 DocIterator const end = doc_iterator_end(this);
3072 for (; it != end; it.forwardInset()) {
3073 // look for MathData cells in InsetMathNest insets
3074 InsetMath * minset = it.nextInset()->asInsetMath();
3078 // update macro in all cells of the InsetMathNest
3079 DocIterator::idx_type n = minset->nargs();
3080 MacroContext mc = MacroContext(this, it);
3081 for (DocIterator::idx_type i = 0; i < n; ++i) {
3082 MathData & data = minset->cell(i);
3083 data.updateMacros(0, mc, utype);
3089 void Buffer::listMacroNames(MacroNameSet & macros) const
3094 d->macro_lock = true;
3096 // loop over macro names
3097 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3098 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3099 for (; nameIt != nameEnd; ++nameIt)
3100 macros.insert(nameIt->first);
3102 // loop over children
3103 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3104 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3105 for (; it != end; ++it)
3106 it->first->listMacroNames(macros);
3109 Buffer const * const pbuf = d->parent();
3111 pbuf->listMacroNames(macros);
3113 d->macro_lock = false;
3117 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3119 Buffer const * const pbuf = d->parent();
3124 pbuf->listMacroNames(names);
3127 MacroNameSet::iterator it = names.begin();
3128 MacroNameSet::iterator end = names.end();
3129 for (; it != end; ++it) {
3131 MacroData const * data =
3132 pbuf->getMacro(*it, *this, false);
3134 macros.insert(data);
3136 // we cannot access the original MathMacroTemplate anymore
3137 // here to calls validate method. So we do its work here manually.
3138 // FIXME: somehow make the template accessible here.
3139 if (data->optionals() > 0)
3140 features.require("xargs");
3146 Buffer::References & Buffer::references(docstring const & label)
3149 return const_cast<Buffer *>(masterBuffer())->references(label);
3151 RefCache::iterator it = d->ref_cache_.find(label);
3152 if (it != d->ref_cache_.end())
3153 return it->second.second;
3155 static InsetLabel const * dummy_il = 0;
3156 static References const dummy_refs;
3157 it = d->ref_cache_.insert(
3158 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3159 return it->second.second;
3163 Buffer::References const & Buffer::references(docstring const & label) const
3165 return const_cast<Buffer *>(this)->references(label);
3169 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3171 masterBuffer()->d->ref_cache_[label].first = il;
3175 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3177 return masterBuffer()->d->ref_cache_[label].first;
3181 void Buffer::clearReferenceCache() const
3184 d->ref_cache_.clear();
3188 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3191 //FIXME: This does not work for child documents yet.
3192 LASSERT(code == CITE_CODE, /**/);
3194 reloadBibInfoCache();
3196 // Check if the label 'from' appears more than once
3197 BiblioInfo const & keys = masterBibInfo();
3198 BiblioInfo::const_iterator bit = keys.begin();
3199 BiblioInfo::const_iterator bend = keys.end();
3200 vector<docstring> labels;
3202 for (; bit != bend; ++bit)
3204 labels.push_back(bit->first);
3206 if (count(labels.begin(), labels.end(), from) > 1)
3209 string const paramName = "key";
3210 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3211 if (it->lyxCode() == code) {
3212 InsetCommand * inset = it->asInsetCommand();
3215 docstring const oldValue = inset->getParam(paramName);
3216 if (oldValue == from)
3217 inset->setParam(paramName, to);
3223 void Buffer::getSourceCode(odocstream & os, string const format,
3224 pit_type par_begin, pit_type par_end,
3225 OutputWhat output) const
3227 OutputParams runparams(¶ms().encoding());
3228 runparams.nice = true;
3229 runparams.flavor = params().getOutputFlavor(format);
3230 runparams.linelen = lyxrc.plaintext_linelen;
3231 // No side effect of file copying and image conversion
3232 runparams.dryrun = true;
3234 if (output == CurrentParagraph) {
3235 runparams.par_begin = par_begin;
3236 runparams.par_end = par_end;
3237 if (par_begin + 1 == par_end) {
3239 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3243 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3244 convert<docstring>(par_begin),
3245 convert<docstring>(par_end - 1))
3252 // output paragraphs
3253 if (params().isDocBook())
3254 docbookParagraphs(text(), *this, os, runparams);
3255 else if (runparams.flavor == OutputParams::HTML) {
3257 xhtmlParagraphs(text(), *this, xs, runparams);
3259 // latex or literate
3260 otexstream ots(os, texrow);
3261 latexParagraphs(*this, text(), ots, runparams);
3265 if (output == FullSource)
3266 os << _("Preview source code");
3267 else if (output == OnlyPreamble)
3268 os << _("Preview preamble");
3269 else if (output == OnlyBody)
3270 os << _("Preview body");
3273 d->texrow.newline();
3274 d->texrow.newline();
3275 if (params().isDocBook())
3276 writeDocBookSource(os, absFileName(), runparams, output);
3277 else if (runparams.flavor == OutputParams::HTML)
3278 writeLyXHTMLSource(os, runparams, output);
3280 // latex or literate
3281 otexstream ots(os, d->texrow);
3282 writeLaTeXSource(ots, string(), runparams, output);
3288 ErrorList & Buffer::errorList(string const & type) const
3290 return d->errorLists[type];
3294 void Buffer::updateTocItem(std::string const & type,
3295 DocIterator const & dit) const
3298 d->gui_->updateTocItem(type, dit);
3302 void Buffer::structureChanged() const
3305 d->gui_->structureChanged();
3309 void Buffer::errors(string const & err, bool from_master) const
3312 d->gui_->errors(err, from_master);
3316 void Buffer::message(docstring const & msg) const
3319 d->gui_->message(msg);
3323 void Buffer::setBusy(bool on) const
3326 d->gui_->setBusy(on);
3330 void Buffer::updateTitles() const
3333 d->wa_->updateTitles();
3337 void Buffer::resetAutosaveTimers() const
3340 d->gui_->resetAutosaveTimers();
3344 bool Buffer::hasGuiDelegate() const
3350 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3359 class AutoSaveBuffer : public ForkedProcess {
3362 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3363 : buffer_(buffer), fname_(fname) {}
3365 virtual shared_ptr<ForkedProcess> clone() const
3367 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3372 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3373 from_utf8(fname_.absFileName())));
3374 return run(DontWait);
3378 virtual int generateChild();
3380 Buffer const & buffer_;
3385 int AutoSaveBuffer::generateChild()
3387 #if defined(__APPLE__)
3388 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3389 * We should use something else like threads.
3391 * Since I do not know how to determine at run time what is the OS X
3392 * version, I just disable forking altogether for now (JMarc)
3394 pid_t const pid = -1;
3396 // tmp_ret will be located (usually) in /tmp
3397 // will that be a problem?
3398 // Note that this calls ForkedCalls::fork(), so it's
3399 // ok cross-platform.
3400 pid_t const pid = fork();
3401 // If you want to debug the autosave
3402 // you should set pid to -1, and comment out the fork.
3403 if (pid != 0 && pid != -1)
3407 // pid = -1 signifies that lyx was unable
3408 // to fork. But we will do the save
3410 bool failed = false;
3411 FileName const tmp_ret = FileName::tempName("lyxauto");
3412 if (!tmp_ret.empty()) {
3413 buffer_.writeFile(tmp_ret);
3414 // assume successful write of tmp_ret
3415 if (!tmp_ret.moveTo(fname_))
3421 // failed to write/rename tmp_ret so try writing direct
3422 if (!buffer_.writeFile(fname_)) {
3423 // It is dangerous to do this in the child,
3424 // but safe in the parent, so...
3425 if (pid == -1) // emit message signal.
3426 buffer_.message(_("Autosave failed!"));
3430 if (pid == 0) // we are the child so...
3439 FileName Buffer::getEmergencyFileName() const
3441 return FileName(d->filename.absFileName() + ".emergency");
3445 FileName Buffer::getAutosaveFileName() const
3447 // if the document is unnamed try to save in the backup dir, else
3448 // in the default document path, and as a last try in the filePath,
3449 // which will most often be the temporary directory
3452 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3453 : lyxrc.backupdir_path;
3454 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3457 string const fname = "#" + d->filename.onlyFileName() + "#";
3459 return makeAbsPath(fname, fpath);
3463 void Buffer::removeAutosaveFile() const
3465 FileName const f = getAutosaveFileName();
3471 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3473 FileName const newauto = getAutosaveFileName();
3475 if (newauto != oldauto && oldauto.exists())
3476 if (!oldauto.moveTo(newauto))
3477 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3481 bool Buffer::autoSave() const
3483 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3484 if (buf->d->bak_clean || isReadonly())
3487 message(_("Autosaving current document..."));
3488 buf->d->bak_clean = true;
3490 FileName const fname = getAutosaveFileName();
3491 if (d->cloned_buffer_) {
3492 // If this buffer is cloned, we assume that
3493 // we are running in a separate thread already.
3494 FileName const tmp_ret = FileName::tempName("lyxauto");
3495 if (!tmp_ret.empty()) {
3497 // assume successful write of tmp_ret
3498 if (tmp_ret.moveTo(fname))
3501 // failed to write/rename tmp_ret so try writing direct
3502 return writeFile(fname);
3504 /// This function is deprecated as the frontend needs to take care
3505 /// of cloning the buffer and autosaving it in another thread. It
3506 /// is still here to allow (QT_VERSION < 0x040400).
3507 AutoSaveBuffer autosave(*this, fname);
3514 // helper class, to guarantee this gets reset properly
3515 class Buffer::MarkAsExporting {
3517 MarkAsExporting(Buffer const * buf) : buf_(buf)
3519 LASSERT(buf_, /* */);
3520 buf_->setExportStatus(true);
3524 buf_->setExportStatus(false);
3527 Buffer const * const buf_;
3532 void Buffer::setExportStatus(bool e) const
3534 d->doing_export = e;
3535 ListOfBuffers clist = getDescendents();
3536 ListOfBuffers::const_iterator cit = clist.begin();
3537 ListOfBuffers::const_iterator const cen = clist.end();
3538 for (; cit != cen; ++cit)
3539 (*cit)->d->doing_export = e;
3543 bool Buffer::isExporting() const
3545 return d->doing_export;
3549 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3553 return doExport(target, put_in_tempdir, result_file);
3556 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3557 string & result_file) const
3559 bool const update_unincluded =
3560 params().maintain_unincluded_children
3561 && !params().getIncludedChildren().empty();
3563 // (1) export with all included children (omit \includeonly)
3564 if (update_unincluded) {
3565 ExportStatus const status =
3566 doExport(target, put_in_tempdir, true, result_file);
3567 if (status != ExportSuccess)
3570 // (2) export with included children only
3571 return doExport(target, put_in_tempdir, false, result_file);
3575 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3576 bool includeall, string & result_file) const
3578 LYXERR(Debug::FILES, "target=" << target);
3579 OutputParams runparams(¶ms().encoding());
3580 string format = target;
3581 string dest_filename;
3582 size_t pos = target.find(' ');
3583 if (pos != string::npos) {
3584 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3585 format = target.substr(0, pos);
3586 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3587 FileName(dest_filename).onlyPath().createPath();
3588 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3590 MarkAsExporting exporting(this);
3591 string backend_format;
3592 runparams.flavor = OutputParams::LATEX;
3593 runparams.linelen = lyxrc.plaintext_linelen;
3594 runparams.includeall = includeall;
3595 vector<string> backs = params().backends();
3596 Converters converters = theConverters();
3597 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3598 // Get shortest path to format
3599 converters.buildGraph();
3600 Graph::EdgePath path;
3601 for (vector<string>::const_iterator it = backs.begin();
3602 it != backs.end(); ++it) {
3603 Graph::EdgePath p = converters.getPath(*it, format);
3604 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3605 backend_format = *it;
3610 if (!put_in_tempdir) {
3611 // Only show this alert if this is an export to a non-temporary
3612 // file (not for previewing).
3613 Alert::error(_("Couldn't export file"), bformat(
3614 _("No information for exporting the format %1$s."),
3615 formats.prettyName(format)));
3617 return ExportNoPathToFormat;
3619 runparams.flavor = converters.getFlavor(path);
3622 backend_format = format;
3623 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3624 // FIXME: Don't hardcode format names here, but use a flag
3625 if (backend_format == "pdflatex")
3626 runparams.flavor = OutputParams::PDFLATEX;
3627 else if (backend_format == "luatex")
3628 runparams.flavor = OutputParams::LUATEX;
3629 else if (backend_format == "dviluatex")
3630 runparams.flavor = OutputParams::DVILUATEX;
3631 else if (backend_format == "xetex")
3632 runparams.flavor = OutputParams::XETEX;
3635 string filename = latexName(false);
3636 filename = addName(temppath(), filename);
3637 filename = changeExtension(filename,
3638 formats.extension(backend_format));
3639 LYXERR(Debug::FILES, "filename=" << filename);
3641 // Plain text backend
3642 if (backend_format == "text") {
3643 runparams.flavor = OutputParams::TEXT;
3644 writePlaintextFile(*this, FileName(filename), runparams);
3647 else if (backend_format == "xhtml") {
3648 runparams.flavor = OutputParams::HTML;
3649 switch (params().html_math_output) {
3650 case BufferParams::MathML:
3651 runparams.math_flavor = OutputParams::MathAsMathML;
3653 case BufferParams::HTML:
3654 runparams.math_flavor = OutputParams::MathAsHTML;
3656 case BufferParams::Images:
3657 runparams.math_flavor = OutputParams::MathAsImages;
3659 case BufferParams::LaTeX:
3660 runparams.math_flavor = OutputParams::MathAsLaTeX;
3663 makeLyXHTMLFile(FileName(filename), runparams);
3664 } else if (backend_format == "lyx")
3665 writeFile(FileName(filename));
3667 else if (params().isDocBook()) {
3668 runparams.nice = !put_in_tempdir;
3669 makeDocBookFile(FileName(filename), runparams);
3672 else if (backend_format == format) {
3673 runparams.nice = true;
3674 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3675 if (d->cloned_buffer_) {
3676 d->cloned_buffer_->d->errorLists["Export"] =
3677 d->errorLists["Export"];
3681 } else if (!lyxrc.tex_allows_spaces
3682 && contains(filePath(), ' ')) {
3683 Alert::error(_("File name error"),
3684 _("The directory path to the document cannot contain spaces."));
3685 return ExportTexPathHasSpaces;
3687 runparams.nice = false;
3688 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3689 if (d->cloned_buffer_) {
3690 d->cloned_buffer_->d->errorLists["Export"] =
3691 d->errorLists["Export"];
3697 string const error_type = (format == "program")
3698 ? "Build" : params().bufferFormat();
3699 ErrorList & error_list = d->errorLists[error_type];
3700 string const ext = formats.extension(format);
3701 FileName const tmp_result_file(changeExtension(filename, ext));
3702 bool const success = converters.convert(this, FileName(filename),
3703 tmp_result_file, FileName(absFileName()), backend_format, format,
3706 // Emit the signal to show the error list or copy it back to the
3707 // cloned Buffer so that it can be emitted afterwards.
3708 if (format != backend_format) {
3709 if (d->cloned_buffer_) {
3710 d->cloned_buffer_->d->errorLists[error_type] =
3711 d->errorLists[error_type];
3714 // also to the children, in case of master-buffer-view
3715 ListOfBuffers clist = getDescendents();
3716 ListOfBuffers::const_iterator cit = clist.begin();
3717 ListOfBuffers::const_iterator const cen = clist.end();
3718 for (; cit != cen; ++cit) {
3719 if (d->cloned_buffer_) {
3720 // Enable reverse search by copying back the
3721 // texrow object to the cloned buffer.
3722 // FIXME: this is not thread safe.
3723 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3724 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3725 (*cit)->d->errorLists[error_type];
3727 (*cit)->errors(error_type, true);
3731 if (d->cloned_buffer_) {
3732 // Enable reverse dvi or pdf to work by copying back the texrow
3733 // object to the cloned buffer.
3734 // FIXME: There is a possibility of concurrent access to texrow
3735 // here from the main GUI thread that should be securized.
3736 d->cloned_buffer_->d->texrow = d->texrow;
3737 string const error_type = params().bufferFormat();
3738 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3742 return ExportConverterError;
3744 if (put_in_tempdir) {
3745 result_file = tmp_result_file.absFileName();
3746 return ExportSuccess;
3749 if (dest_filename.empty())
3750 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3752 result_file = dest_filename;
3753 // We need to copy referenced files (e. g. included graphics
3754 // if format == "dvi") to the result dir.
3755 vector<ExportedFile> const files =
3756 runparams.exportdata->externalFiles(format);
3757 string const dest = runparams.export_folder.empty() ?
3758 onlyPath(result_file) : runparams.export_folder;
3759 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3760 : force_overwrite == ALL_FILES;
3761 CopyStatus status = use_force ? FORCE : SUCCESS;
3763 vector<ExportedFile>::const_iterator it = files.begin();
3764 vector<ExportedFile>::const_iterator const en = files.end();
3765 for (; it != en && status != CANCEL; ++it) {
3766 string const fmt = formats.getFormatFromFile(it->sourceName);
3767 string fixedName = it->exportName;
3768 if (!runparams.export_folder.empty()) {
3769 // Relative pathnames starting with ../ will be sanitized
3770 // if exporting to a different folder
3771 while (fixedName.substr(0, 3) == "../")
3772 fixedName = fixedName.substr(3, fixedName.length() - 3);
3774 FileName fixedFileName = makeAbsPath(fixedName, dest);
3775 fixedFileName.onlyPath().createPath();
3776 status = copyFile(fmt, it->sourceName,
3778 it->exportName, status == FORCE,
3779 runparams.export_folder.empty());
3782 if (status == CANCEL) {
3783 message(_("Document export cancelled."));
3784 return ExportCancel;
3787 if (tmp_result_file.exists()) {
3788 // Finally copy the main file
3789 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3790 : force_overwrite != NO_FILES;
3791 if (status == SUCCESS && use_force)
3793 status = copyFile(format, tmp_result_file,
3794 FileName(result_file), result_file,
3796 if (status == CANCEL) {
3797 message(_("Document export cancelled."));
3798 return ExportCancel;
3800 message(bformat(_("Document exported as %1$s "
3802 formats.prettyName(format),
3803 makeDisplayPath(result_file)));
3806 // This must be a dummy converter like fax (bug 1888)
3807 message(bformat(_("Document exported as %1$s"),
3808 formats.prettyName(format)));
3811 return ExportSuccess;
3815 Buffer::ExportStatus Buffer::preview(string const & format) const
3817 bool const update_unincluded =
3818 params().maintain_unincluded_children
3819 && !params().getIncludedChildren().empty();
3820 return preview(format, update_unincluded);
3823 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3825 MarkAsExporting exporting(this);
3827 // (1) export with all included children (omit \includeonly)
3829 ExportStatus const status = doExport(format, true, true, result_file);
3830 if (status != ExportSuccess)
3833 // (2) export with included children only
3834 ExportStatus const status = doExport(format, true, false, result_file);
3835 if (status != ExportSuccess)
3837 if (!formats.view(*this, FileName(result_file), format))
3838 return PreviewError;
3839 return PreviewSuccess;
3843 Buffer::ReadStatus Buffer::extractFromVC()
3845 bool const found = LyXVC::file_not_found_hook(d->filename);
3847 return ReadFileNotFound;
3848 if (!d->filename.isReadableFile())
3854 Buffer::ReadStatus Buffer::loadEmergency()
3856 FileName const emergencyFile = getEmergencyFileName();
3857 if (!emergencyFile.exists()
3858 || emergencyFile.lastModified() <= d->filename.lastModified())
3859 return ReadFileNotFound;
3861 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3862 docstring const text = bformat(_("An emergency save of the document "
3863 "%1$s exists.\n\nRecover emergency save?"), file);
3865 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3866 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3872 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3873 bool const success = (ret_llf == ReadSuccess);
3876 Alert::warning(_("File is read-only"),
3877 bformat(_("An emergency file is successfully loaded, "
3878 "but the original file %1$s is marked read-only. "
3879 "Please make sure to save the document as a different "
3880 "file."), from_utf8(d->filename.absFileName())));
3883 str = _("Document was successfully recovered.");
3885 str = _("Document was NOT successfully recovered.");
3886 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3887 makeDisplayPath(emergencyFile.absFileName()));
3889 int const del_emerg =
3890 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3891 _("&Remove"), _("&Keep"));
3892 if (del_emerg == 0) {
3893 emergencyFile.removeFile();
3895 Alert::warning(_("Emergency file deleted"),
3896 _("Do not forget to save your file now!"), true);
3898 return success ? ReadSuccess : ReadEmergencyFailure;
3901 int const del_emerg =
3902 Alert::prompt(_("Delete emergency file?"),
3903 _("Remove emergency file now?"), 1, 1,
3904 _("&Remove"), _("&Keep"));
3906 emergencyFile.removeFile();
3907 return ReadOriginal;
3917 Buffer::ReadStatus Buffer::loadAutosave()
3919 // Now check if autosave file is newer.
3920 FileName const autosaveFile = getAutosaveFileName();
3921 if (!autosaveFile.exists()
3922 || autosaveFile.lastModified() <= d->filename.lastModified())
3923 return ReadFileNotFound;
3925 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3926 docstring const text = bformat(_("The backup of the document %1$s "
3927 "is newer.\n\nLoad the backup instead?"), file);
3928 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3929 _("&Load backup"), _("Load &original"), _("&Cancel"));
3934 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3935 // the file is not saved if we load the autosave file.
3936 if (ret_llf == ReadSuccess) {
3938 Alert::warning(_("File is read-only"),
3939 bformat(_("A backup file is successfully loaded, "
3940 "but the original file %1$s is marked read-only. "
3941 "Please make sure to save the document as a "
3943 from_utf8(d->filename.absFileName())));
3948 return ReadAutosaveFailure;
3951 // Here we delete the autosave
3952 autosaveFile.removeFile();
3953 return ReadOriginal;
3961 Buffer::ReadStatus Buffer::loadLyXFile()
3963 if (!d->filename.isReadableFile()) {
3964 ReadStatus const ret_rvc = extractFromVC();
3965 if (ret_rvc != ReadSuccess)
3969 ReadStatus const ret_re = loadEmergency();
3970 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3973 ReadStatus const ret_ra = loadAutosave();
3974 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3977 return loadThisLyXFile(d->filename);
3981 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3983 return readFile(fn);
3987 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3989 TeXErrors::Errors::const_iterator it = terr.begin();
3990 TeXErrors::Errors::const_iterator end = terr.end();
3991 ListOfBuffers clist = getDescendents();
3992 ListOfBuffers::const_iterator cen = clist.end();
3994 for (; it != end; ++it) {
3997 int errorRow = it->error_in_line;
3998 Buffer const * buf = 0;
4000 if (it->child_name.empty())
4001 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4003 // The error occurred in a child
4004 ListOfBuffers::const_iterator cit = clist.begin();
4005 for (; cit != cen; ++cit) {
4006 string const child_name =
4007 DocFileName(changeExtension(
4008 (*cit)->absFileName(), "tex")).
4010 if (it->child_name != child_name)
4012 (*cit)->d->texrow.getIdFromRow(errorRow,
4013 id_start, pos_start);
4014 if (id_start != -1) {
4015 buf = d->cloned_buffer_
4016 ? (*cit)->d->cloned_buffer_->d->owner_
4017 : (*cit)->d->owner_;
4028 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4029 } while (found && id_start == id_end && pos_start == pos_end);
4031 if (id_start != id_end) {
4032 // Next registered position is outside the inset where
4033 // the error occurred, so signal end-of-paragraph
4037 errorList.push_back(ErrorItem(it->error_desc,
4038 it->error_text, id_start, pos_start, pos_end, buf));
4043 void Buffer::setBuffersForInsets() const
4045 inset().setBuffer(const_cast<Buffer &>(*this));
4049 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4051 // Use the master text class also for child documents
4052 Buffer const * const master = masterBuffer();
4053 DocumentClass const & textclass = master->params().documentClass();
4055 // do this only if we are the top-level Buffer
4057 reloadBibInfoCache();
4059 // keep the buffers to be children in this set. If the call from the
4060 // master comes back we can see which of them were actually seen (i.e.
4061 // via an InsetInclude). The remaining ones in the set need still be updated.
4062 static std::set<Buffer const *> bufToUpdate;
4063 if (scope == UpdateMaster) {
4064 // If this is a child document start with the master
4065 if (master != this) {
4066 bufToUpdate.insert(this);
4067 master->updateBuffer(UpdateMaster, utype);
4068 // Do this here in case the master has no gui associated with it. Then,
4069 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4070 if (!master->d->gui_)
4073 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4074 if (bufToUpdate.find(this) == bufToUpdate.end())
4078 // start over the counters in the master
4079 textclass.counters().reset();
4082 // update will be done below for this buffer
4083 bufToUpdate.erase(this);
4085 // update all caches
4086 clearReferenceCache();
4089 Buffer & cbuf = const_cast<Buffer &>(*this);
4091 LASSERT(!text().paragraphs().empty(), /**/);
4094 ParIterator parit = cbuf.par_iterator_begin();
4095 updateBuffer(parit, utype);
4098 // TocBackend update will be done later.
4101 d->bibinfo_cache_valid_ = true;
4102 d->cite_labels_valid_ = true;
4103 cbuf.tocBackend().update();
4104 if (scope == UpdateMaster)
4105 cbuf.structureChanged();
4109 static depth_type getDepth(DocIterator const & it)
4111 depth_type depth = 0;
4112 for (size_t i = 0 ; i < it.depth() ; ++i)
4113 if (!it[i].inset().inMathed())
4114 depth += it[i].paragraph().getDepth() + 1;
4115 // remove 1 since the outer inset does not count
4119 static depth_type getItemDepth(ParIterator const & it)
4121 Paragraph const & par = *it;
4122 LabelType const labeltype = par.layout().labeltype;
4124 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4127 // this will hold the lowest depth encountered up to now.
4128 depth_type min_depth = getDepth(it);
4129 ParIterator prev_it = it;
4132 --prev_it.top().pit();
4134 // start of nested inset: go to outer par
4136 if (prev_it.empty()) {
4137 // start of document: nothing to do
4142 // We search for the first paragraph with same label
4143 // that is not more deeply nested.
4144 Paragraph & prev_par = *prev_it;
4145 depth_type const prev_depth = getDepth(prev_it);
4146 if (labeltype == prev_par.layout().labeltype) {
4147 if (prev_depth < min_depth)
4148 return prev_par.itemdepth + 1;
4149 if (prev_depth == min_depth)
4150 return prev_par.itemdepth;
4152 min_depth = min(min_depth, prev_depth);
4153 // small optimization: if we are at depth 0, we won't
4154 // find anything else
4155 if (prev_depth == 0)
4161 static bool needEnumCounterReset(ParIterator const & it)
4163 Paragraph const & par = *it;
4164 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4165 depth_type const cur_depth = par.getDepth();
4166 ParIterator prev_it = it;
4167 while (prev_it.pit()) {
4168 --prev_it.top().pit();
4169 Paragraph const & prev_par = *prev_it;
4170 if (prev_par.getDepth() <= cur_depth)
4171 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4173 // start of nested inset: reset
4178 // set the label of a paragraph. This includes the counters.
4179 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4181 BufferParams const & bp = owner_->masterBuffer()->params();
4182 DocumentClass const & textclass = bp.documentClass();
4183 Paragraph & par = it.paragraph();
4184 Layout const & layout = par.layout();
4185 Counters & counters = textclass.counters();
4187 if (par.params().startOfAppendix()) {
4188 // FIXME: only the counter corresponding to toplevel
4189 // sectioning should be reset
4191 counters.appendix(true);
4193 par.params().appendix(counters.appendix());
4195 // Compute the item depth of the paragraph
4196 par.itemdepth = getItemDepth(it);
4198 if (layout.margintype == MARGIN_MANUAL) {
4199 if (par.params().labelWidthString().empty())
4200 par.params().labelWidthString(par.expandLabel(layout, bp));
4201 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4202 // we do not need to do anything here, since the empty case is
4203 // handled during export.
4205 par.params().labelWidthString(docstring());
4208 switch(layout.labeltype) {
4210 if (layout.toclevel <= bp.secnumdepth
4211 && (layout.latextype != LATEX_ENVIRONMENT
4212 || it.text()->isFirstInSequence(it.pit()))) {
4213 if (counters.hasCounter(layout.counter))
4214 counters.step(layout.counter, utype);
4215 par.params().labelString(par.expandLabel(layout, bp));
4217 par.params().labelString(docstring());
4220 case LABEL_ITEMIZE: {
4221 // At some point of time we should do something more
4222 // clever here, like:
4223 // par.params().labelString(
4224 // bp.user_defined_bullet(par.itemdepth).getText());
4225 // for now, use a simple hardcoded label
4226 docstring itemlabel;
4227 switch (par.itemdepth) {
4229 itemlabel = char_type(0x2022);
4232 itemlabel = char_type(0x2013);
4235 itemlabel = char_type(0x2217);
4238 itemlabel = char_type(0x2219); // or 0x00b7
4241 par.params().labelString(itemlabel);
4245 case LABEL_ENUMERATE: {
4246 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4248 switch (par.itemdepth) {
4257 enumcounter += "iv";
4260 // not a valid enumdepth...
4264 // Maybe we have to reset the enumeration counter.
4265 if (needEnumCounterReset(it))
4266 counters.reset(enumcounter);
4267 counters.step(enumcounter, utype);
4269 string const & lang = par.getParLanguage(bp)->code();
4270 par.params().labelString(counters.theCounter(enumcounter, lang));
4275 case LABEL_SENSITIVE: {
4276 string const & type = counters.current_float();
4277 docstring full_label;
4279 full_label = owner_->B_("Senseless!!! ");
4281 docstring name = owner_->B_(textclass.floats().getType(type).name());
4282 if (counters.hasCounter(from_utf8(type))) {
4283 string const & lang = par.getParLanguage(bp)->code();
4284 counters.step(from_utf8(type), utype);
4285 full_label = bformat(from_ascii("%1$s %2$s:"),
4287 counters.theCounter(from_utf8(type), lang));
4289 full_label = bformat(from_ascii("%1$s #:"), name);
4291 par.params().labelString(full_label);
4295 case LABEL_NO_LABEL:
4296 par.params().labelString(docstring());
4300 case LABEL_TOP_ENVIRONMENT:
4301 case LABEL_CENTERED_TOP_ENVIRONMENT:
4304 par.params().labelString(par.expandLabel(layout, bp));
4310 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4312 LASSERT(parit.pit() == 0, /**/);
4314 // Set the position of the text in the buffer to be able
4315 // to resolve macros in it.
4316 parit.text()->setMacrocontextPosition(parit);
4318 depth_type maxdepth = 0;
4319 pit_type const lastpit = parit.lastpit();
4320 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4321 // reduce depth if necessary
4322 parit->params().depth(min(parit->params().depth(), maxdepth));
4323 maxdepth = parit->getMaxDepthAfter();
4325 if (utype == OutputUpdate) {
4326 // track the active counters
4327 // we have to do this for the master buffer, since the local
4328 // buffer isn't tracking anything.
4329 masterBuffer()->params().documentClass().counters().
4330 setActiveLayout(parit->layout());
4333 // set the counter for this paragraph
4334 d->setLabel(parit, utype);
4337 InsetList::const_iterator iit = parit->insetList().begin();
4338 InsetList::const_iterator end = parit->insetList().end();
4339 for (; iit != end; ++iit) {
4340 parit.pos() = iit->pos;
4341 iit->inset->updateBuffer(parit, utype);
4347 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4348 WordLangTuple & word_lang, docstring_list & suggestions) const
4352 suggestions.clear();
4353 word_lang = WordLangTuple();
4354 bool const to_end = to.empty();
4355 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4356 // OK, we start from here.
4357 for (; from != end; from.forwardPos()) {
4358 // We are only interested in text so remove the math CursorSlice.
4359 while (from.inMathed()) {
4363 // If from is at the end of the document (which is possible
4364 // when leaving the mathed) LyX will crash later otherwise.
4365 if (from.atEnd() || (!to_end && from >= end))
4368 from.paragraph().spellCheck();
4369 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4370 if (SpellChecker::misspelled(res)) {
4375 // Do not increase progress when from == to, otherwise the word
4376 // count will be wrong.
4386 Buffer::ReadStatus Buffer::reload()
4389 // c.f. bug http://www.lyx.org/trac/ticket/6587
4390 removeAutosaveFile();
4391 // e.g., read-only status could have changed due to version control
4392 d->filename.refresh();
4393 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4395 ReadStatus const status = loadLyXFile();
4396 if (status == ReadSuccess) {
4401 message(bformat(_("Document %1$s reloaded."), disp_fn));
4404 message(bformat(_("Could not reload document %1$s."), disp_fn));
4414 bool Buffer::saveAs(FileName const & fn)
4416 FileName const old_name = fileName();
4417 FileName const old_auto = getAutosaveFileName();
4418 bool const old_unnamed = isUnnamed();
4425 // bring the autosave file with us, just in case.
4426 moveAutosaveFile(old_auto);
4427 // validate version control data and
4428 // correct buffer title
4429 lyxvc().file_found_hook(fileName());
4431 // the file has now been saved to the new location.
4432 // we need to check that the locations of child buffers
4434 checkChildBuffers();
4438 // reset the old filename and unnamed state
4439 setFileName(old_name);
4440 setUnnamed(old_unnamed);
4446 // FIXME We could do better here, but it is complicated. What would be
4447 // nice is to offer either (a) to save the child buffer to an appropriate
4448 // location, so that it would "move with the master", or else (b) to update
4449 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4450 // complicated, because the code for this lives in GuiView.
4451 void Buffer::checkChildBuffers()
4453 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4454 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4455 for (; it != en; ++it) {
4456 DocIterator dit = it->second;
4457 Buffer * cbuf = const_cast<Buffer *>(it->first);
4458 if (!cbuf || !theBufferList().isLoaded(cbuf))
4460 Inset * inset = dit.nextInset();
4461 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4462 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4463 docstring const & incfile = inset_inc->getParam("filename");
4464 string oldloc = cbuf->absFileName();
4465 string newloc = makeAbsPath(to_utf8(incfile),
4466 onlyPath(absFileName())).absFileName();
4467 if (oldloc == newloc)
4469 // the location of the child file is incorrect.
4470 Alert::warning(_("Included File Invalid"),
4471 bformat(_("Saving this document to a new location has made the file:\n"
4473 "inaccessible. You will need to update the included filename."),
4474 from_utf8(oldloc)));
4476 inset_inc->setChildBuffer(0);
4478 // invalidate cache of children
4479 d->children_positions.clear();
4480 d->position_to_children.clear();