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 cloned_buffers.push_back(new CloneList());
525 CloneList * clones = cloned_buffers.back();
526 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
527 clones->insert(buffer_clone);
528 buffer_clone->d->clone_list_ = clones;
529 // we won't be cloning the children
530 buffer_clone->d->children_positions.clear();
535 bool Buffer::isClone() const
537 return d->cloned_buffer_;
541 void Buffer::changed(bool update_metrics) const
544 d->wa_->redrawAll(update_metrics);
548 frontend::WorkAreaManager & Buffer::workAreaManager() const
550 LASSERT(d->wa_, /**/);
555 Text & Buffer::text() const
557 return d->inset->text();
561 Inset & Buffer::inset() const
567 BufferParams & Buffer::params()
573 BufferParams const & Buffer::params() const
579 ParagraphList & Buffer::paragraphs()
581 return text().paragraphs();
585 ParagraphList const & Buffer::paragraphs() const
587 return text().paragraphs();
591 LyXVC & Buffer::lyxvc()
597 LyXVC const & Buffer::lyxvc() const
603 string const Buffer::temppath() const
605 return d->temppath.absFileName();
609 TexRow & Buffer::texrow()
615 TexRow const & Buffer::texrow() const
621 TocBackend & Buffer::tocBackend() const
623 return d->toc_backend;
627 Undo & Buffer::undo()
633 void Buffer::setChild(DocIterator const & dit, Buffer * child)
635 d->children_positions[child] = dit;
639 string Buffer::latexName(bool const no_path) const
641 FileName latex_name =
642 makeLatexName(d->exportFileName());
643 return no_path ? latex_name.onlyFileName()
644 : latex_name.absFileName();
648 FileName Buffer::Impl::exportFileName() const
650 docstring const branch_suffix =
651 params.branchlist().getFileNameSuffix();
652 if (branch_suffix.empty())
655 string const name = filename.onlyFileNameWithoutExt()
656 + to_utf8(branch_suffix);
657 FileName res(filename.onlyPath().absFileName() + "/" + name);
658 res.changeExtension(filename.extension());
664 string Buffer::logName(LogType * type) const
666 string const filename = latexName(false);
668 if (filename.empty()) {
674 string const path = temppath();
676 FileName const fname(addName(temppath(),
677 onlyFileName(changeExtension(filename,
680 // FIXME: how do we know this is the name of the build log?
681 FileName const bname(
682 addName(path, onlyFileName(
683 changeExtension(filename,
684 formats.extension(params().bufferFormat()) + ".out"))));
686 // Also consider the master buffer log file
687 FileName masterfname = fname;
689 if (masterBuffer() != this) {
690 string const mlogfile = masterBuffer()->logName(&mtype);
691 masterfname = FileName(mlogfile);
694 // If no Latex log or Build log is newer, show Build log
695 if (bname.exists() &&
696 ((!fname.exists() && !masterfname.exists())
697 || (fname.lastModified() < bname.lastModified()
698 && masterfname.lastModified() < bname.lastModified()))) {
699 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
702 return bname.absFileName();
703 // If we have a newer master file log or only a master log, show this
704 } else if (fname != masterfname
705 && (!fname.exists() && (masterfname.exists()
706 || fname.lastModified() < masterfname.lastModified()))) {
707 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
710 return masterfname.absFileName();
712 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
715 return fname.absFileName();
719 void Buffer::setReadonly(bool const flag)
721 if (d->read_only != flag) {
728 void Buffer::setFileName(FileName const & fname)
731 setReadonly(d->filename.isReadOnly());
737 int Buffer::readHeader(Lexer & lex)
739 int unknown_tokens = 0;
741 int begin_header_line = -1;
743 // Initialize parameters that may be/go lacking in header:
744 params().branchlist().clear();
745 params().preamble.erase();
746 params().options.erase();
747 params().master.erase();
748 params().float_placement.erase();
749 params().paperwidth.erase();
750 params().paperheight.erase();
751 params().leftmargin.erase();
752 params().rightmargin.erase();
753 params().topmargin.erase();
754 params().bottommargin.erase();
755 params().headheight.erase();
756 params().headsep.erase();
757 params().footskip.erase();
758 params().columnsep.erase();
759 params().fonts_cjk.erase();
760 params().listings_params.clear();
761 params().clearLayoutModules();
762 params().clearRemovedModules();
763 params().clearIncludedChildren();
764 params().pdfoptions().clear();
765 params().indiceslist().clear();
766 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
767 params().isbackgroundcolor = false;
768 params().fontcolor = RGBColor(0, 0, 0);
769 params().isfontcolor = false;
770 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
771 params().boxbgcolor = RGBColor(0xFF, 0, 0);
772 params().html_latex_start.clear();
773 params().html_latex_end.clear();
774 params().html_math_img_scale = 1.0;
775 params().output_sync_macro.erase();
777 for (int i = 0; i < 4; ++i) {
778 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
779 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
782 ErrorList & errorList = d->errorLists["Parse"];
791 if (token == "\\end_header")
795 if (token == "\\begin_header") {
796 begin_header_line = line;
800 LYXERR(Debug::PARSER, "Handling document header token: `"
803 string unknown = params().readToken(lex, token, d->filename.onlyPath());
804 if (!unknown.empty()) {
805 if (unknown[0] != '\\' && token == "\\textclass") {
806 Alert::warning(_("Unknown document class"),
807 bformat(_("Using the default document class, because the "
808 "class %1$s is unknown."), from_utf8(unknown)));
811 docstring const s = bformat(_("Unknown token: "
815 errorList.push_back(ErrorItem(_("Document header error"),
820 if (begin_header_line) {
821 docstring const s = _("\\begin_header is missing");
822 errorList.push_back(ErrorItem(_("Document header error"),
826 params().makeDocumentClass();
828 return unknown_tokens;
833 // changed to be public and have one parameter
834 // Returns true if "\end_document" is not read (Asger)
835 bool Buffer::readDocument(Lexer & lex)
837 ErrorList & errorList = d->errorLists["Parse"];
840 // remove dummy empty par
841 paragraphs().clear();
843 if (!lex.checkFor("\\begin_document")) {
844 docstring const s = _("\\begin_document is missing");
845 errorList.push_back(ErrorItem(_("Document header error"),
851 if (params().outputChanges) {
852 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
853 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
854 LaTeXFeatures::isAvailable("xcolor");
856 if (!dvipost && !xcolorulem) {
857 Alert::warning(_("Changes not shown in LaTeX output"),
858 _("Changes will not be highlighted in LaTeX output, "
859 "because neither dvipost nor xcolor/ulem are installed.\n"
860 "Please install these packages or redefine "
861 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
862 } else if (!xcolorulem) {
863 Alert::warning(_("Changes not shown in LaTeX output"),
864 _("Changes will not be highlighted in LaTeX output "
865 "when using pdflatex, because xcolor and ulem are not installed.\n"
866 "Please install both packages or redefine "
867 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
871 if (!params().master.empty()) {
872 FileName const master_file = makeAbsPath(params().master,
873 onlyPath(absFileName()));
874 if (isLyXFileName(master_file.absFileName())) {
876 checkAndLoadLyXFile(master_file, true);
878 // necessary e.g. after a reload
879 // to re-register the child (bug 5873)
880 // FIXME: clean up updateMacros (here, only
881 // child registering is needed).
882 master->updateMacros();
883 // set master as master buffer, but only
884 // if we are a real child
885 if (master->isChild(this))
887 // if the master is not fully loaded
888 // it is probably just loading this
889 // child. No warning needed then.
890 else if (master->isFullyLoaded())
891 LYXERR0("The master '"
893 << "' assigned to this document ("
895 << ") does not include "
896 "this document. Ignoring the master assignment.");
901 // assure we have a default index
902 params().indiceslist().addDefault(B_("Index"));
905 bool const res = text().read(lex, errorList, d->inset);
907 // inform parent buffer about local macros
909 Buffer const * pbuf = parent();
910 UserMacroSet::const_iterator cit = usermacros.begin();
911 UserMacroSet::const_iterator end = usermacros.end();
912 for (; cit != end; ++cit)
913 pbuf->usermacros.insert(*cit);
917 updateMacroInstances(InternalUpdate);
922 bool Buffer::readString(string const & s)
924 params().compressed = false;
929 FileName const fn = FileName::tempName("Buffer_readString");
932 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
933 if (ret_plf != ReadSuccess)
936 if (file_format != LYX_FORMAT) {
937 // We need to call lyx2lyx, so write the input to a file
938 ofstream os(fn.toFilesystemEncoding().c_str());
942 return readFile(fn) == ReadSuccess;
945 if (readDocument(lex))
951 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
955 if (!lex.setFile(fname)) {
956 Alert::error(_("File Not Found"),
957 bformat(_("Unable to open file `%1$s'."),
958 from_utf8(fn.absFileName())));
959 return ReadFileNotFound;
963 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
964 if (ret_plf != ReadSuccess)
967 if (file_format != LYX_FORMAT) {
969 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
970 if (ret_clf != ReadSuccess)
972 return readFile(tmpFile);
975 // FIXME: InsetInfo needs to know whether the file is under VCS
976 // during the parse process, so this has to be done before.
977 lyxvc().file_found_hook(d->filename);
979 if (readDocument(lex)) {
980 Alert::error(_("Document format failure"),
981 bformat(_("%1$s ended unexpectedly, which means"
982 " that it is probably corrupted."),
983 from_utf8(fn.absFileName())));
984 return ReadDocumentFailure;
987 d->file_fully_loaded = true;
988 d->read_only = !d->filename.isWritable();
989 params().compressed = d->filename.isZippedFile();
995 bool Buffer::isFullyLoaded() const
997 return d->file_fully_loaded;
1001 void Buffer::setFullyLoaded(bool value)
1003 d->file_fully_loaded = value;
1007 PreviewLoader * Buffer::loader() const
1009 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1011 if (!d->preview_loader_)
1012 d->preview_loader_ = new PreviewLoader(*this);
1013 return d->preview_loader_;
1017 void Buffer::removePreviews() const
1019 delete d->preview_loader_;
1020 d->preview_loader_ = 0;
1024 void Buffer::updatePreviews() const
1026 PreviewLoader * ploader = loader();
1030 InsetIterator it = inset_iterator_begin(*d->inset);
1031 InsetIterator const end = inset_iterator_end(*d->inset);
1032 for (; it != end; ++it)
1033 it->addPreview(it, *ploader);
1035 ploader->startLoading();
1039 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1040 FileName const & fn, int & file_format) const
1042 if(!lex.checkFor("\\lyxformat")) {
1043 Alert::error(_("Document format failure"),
1044 bformat(_("%1$s is not a readable LyX document."),
1045 from_utf8(fn.absFileName())));
1046 return ReadNoLyXFormat;
1052 // LyX formats 217 and earlier were written as 2.17. This corresponds
1053 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1054 // these cases. See also: www.lyx.org/trac/changeset/1313.
1055 size_t dot = tmp_format.find_first_of(".,");
1056 if (dot != string::npos)
1057 tmp_format.erase(dot, 1);
1059 file_format = convert<int>(tmp_format);
1064 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1065 FileName & tmpfile, int from_format)
1067 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1068 if(tmpfile.empty()) {
1069 Alert::error(_("Conversion failed"),
1070 bformat(_("%1$s is from a different"
1071 " version of LyX, but a temporary"
1072 " file for converting it could"
1073 " not be created."),
1074 from_utf8(fn.absFileName())));
1075 return LyX2LyXNoTempFile;
1078 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1079 if (lyx2lyx.empty()) {
1080 Alert::error(_("Conversion script not found"),
1081 bformat(_("%1$s is from a different"
1082 " version of LyX, but the"
1083 " conversion script lyx2lyx"
1084 " could not be found."),
1085 from_utf8(fn.absFileName())));
1086 return LyX2LyXNotFound;
1090 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1091 ostringstream command;
1092 command << os::python()
1093 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1094 << " -t " << convert<string>(LYX_FORMAT)
1095 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1096 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1097 string const command_str = command.str();
1099 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1101 cmd_ret const ret = runCommand(command_str);
1102 if (ret.first != 0) {
1103 if (from_format < LYX_FORMAT) {
1104 Alert::error(_("Conversion script failed"),
1105 bformat(_("%1$s is from an older version"
1106 " of LyX and the lyx2lyx script"
1107 " failed to convert it."),
1108 from_utf8(fn.absFileName())));
1109 return LyX2LyXOlderFormat;
1111 Alert::error(_("Conversion script failed"),
1112 bformat(_("%1$s is from a newer version"
1113 " of LyX and the lyx2lyx script"
1114 " failed to convert it."),
1115 from_utf8(fn.absFileName())));
1116 return LyX2LyXNewerFormat;
1123 // Should probably be moved to somewhere else: BufferView? GuiView?
1124 bool Buffer::save() const
1126 docstring const file = makeDisplayPath(absFileName(), 20);
1127 d->filename.refresh();
1129 // check the read-only status before moving the file as a backup
1130 if (d->filename.exists()) {
1131 bool const read_only = !d->filename.isWritable();
1133 Alert::warning(_("File is read-only"),
1134 bformat(_("The file %1$s cannot be written because it "
1135 "is marked as read-only."), file));
1140 // ask if the disk file has been externally modified (use checksum method)
1141 if (fileName().exists() && isExternallyModified(checksum_method)) {
1143 bformat(_("Document %1$s has been externally modified. "
1144 "Are you sure you want to overwrite this file?"), file);
1145 int const ret = Alert::prompt(_("Overwrite modified file?"),
1146 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1151 // We don't need autosaves in the immediate future. (Asger)
1152 resetAutosaveTimers();
1154 FileName backupName;
1155 bool madeBackup = false;
1157 // make a backup if the file already exists
1158 if (lyxrc.make_backup && fileName().exists()) {
1159 backupName = FileName(absFileName() + '~');
1160 if (!lyxrc.backupdir_path.empty()) {
1161 string const mangledName =
1162 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1163 backupName = FileName(addName(lyxrc.backupdir_path,
1167 // Except file is symlink do not copy because of #6587.
1168 // Hard links have bad luck.
1169 if (fileName().isSymLink())
1170 madeBackup = fileName().copyTo(backupName);
1172 madeBackup = fileName().moveTo(backupName);
1175 Alert::error(_("Backup failure"),
1176 bformat(_("Cannot create backup file %1$s.\n"
1177 "Please check whether the directory exists and is writable."),
1178 from_utf8(backupName.absFileName())));
1179 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1183 if (writeFile(d->filename)) {
1187 // Saving failed, so backup is not backup
1189 backupName.moveTo(d->filename);
1195 bool Buffer::writeFile(FileName const & fname) const
1197 // FIXME Do we need to do these here? I don't think writing
1198 // the LyX file depends upon it. (RGH)
1200 // updateMacroInstances();
1202 if (d->read_only && fname == d->filename)
1205 bool retval = false;
1207 docstring const str = bformat(_("Saving document %1$s..."),
1208 makeDisplayPath(fname.absFileName()));
1211 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1213 if (params().compressed) {
1214 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1215 retval = ofs && write(ofs);
1217 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1218 retval = ofs && write(ofs);
1222 message(str + _(" could not write file!"));
1227 // removeAutosaveFile();
1230 message(str + _(" done."));
1236 docstring Buffer::emergencyWrite()
1238 // No need to save if the buffer has not changed.
1242 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1244 docstring user_message = bformat(
1245 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1247 // We try to save three places:
1248 // 1) Same place as document. Unless it is an unnamed doc.
1250 string s = absFileName();
1253 if (writeFile(FileName(s))) {
1255 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1256 return user_message;
1258 user_message += " " + _("Save failed! Trying again...\n");
1262 // 2) In HOME directory.
1263 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1265 lyxerr << ' ' << s << endl;
1266 if (writeFile(FileName(s))) {
1268 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1269 return user_message;
1272 user_message += " " + _("Save failed! Trying yet again...\n");
1274 // 3) In "/tmp" directory.
1275 // MakeAbsPath to prepend the current
1276 // drive letter on OS/2
1277 s = addName(package().temp_dir().absFileName(), absFileName());
1279 lyxerr << ' ' << s << endl;
1280 if (writeFile(FileName(s))) {
1282 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1283 return user_message;
1286 user_message += " " + _("Save failed! Bummer. Document is lost.");
1289 return user_message;
1293 bool Buffer::write(ostream & ofs) const
1296 // Use the standard "C" locale for file output.
1297 ofs.imbue(locale::classic());
1300 // The top of the file should not be written by params().
1302 // write out a comment in the top of the file
1303 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1304 << " created this file. For more info see http://www.lyx.org/\n"
1305 << "\\lyxformat " << LYX_FORMAT << "\n"
1306 << "\\begin_document\n";
1308 /// For each author, set 'used' to true if there is a change
1309 /// by this author in the document; otherwise set it to 'false'.
1310 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1311 AuthorList::Authors::const_iterator a_end = params().authors().end();
1312 for (; a_it != a_end; ++a_it)
1313 a_it->setUsed(false);
1315 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1316 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1317 for ( ; it != end; ++it)
1318 it->checkAuthors(params().authors());
1320 // now write out the buffer parameters.
1321 ofs << "\\begin_header\n";
1322 params().writeFile(ofs);
1323 ofs << "\\end_header\n";
1326 ofs << "\n\\begin_body\n";
1328 ofs << "\n\\end_body\n";
1330 // Write marker that shows file is complete
1331 ofs << "\\end_document" << endl;
1333 // Shouldn't really be needed....
1336 // how to check if close went ok?
1337 // Following is an attempt... (BE 20001011)
1339 // good() returns false if any error occured, including some
1340 // formatting error.
1341 // bad() returns true if something bad happened in the buffer,
1342 // which should include file system full errors.
1347 lyxerr << "File was not closed properly." << endl;
1354 bool Buffer::makeLaTeXFile(FileName const & fname,
1355 string const & original_path,
1356 OutputParams const & runparams_in,
1357 OutputWhat output) const
1359 OutputParams runparams = runparams_in;
1361 // This is necessary for LuaTeX/XeTeX with tex fonts.
1362 // See FIXME in BufferParams::encoding()
1363 if (runparams.isFullUnicode())
1364 runparams.encoding = encodings.fromLyXName("utf8-plain");
1366 string const encoding = runparams.encoding->iconvName();
1367 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1370 try { ofs.reset(encoding); }
1371 catch (iconv_codecvt_facet_exception & e) {
1372 lyxerr << "Caught iconv exception: " << e.what() << endl;
1373 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1374 "verify that the support software for your encoding (%1$s) is "
1375 "properly installed"), from_ascii(encoding)));
1378 if (!openFileWrite(ofs, fname))
1381 //TexStream ts(ofs.rdbuf(), &texrow());
1382 ErrorList & errorList = d->errorLists["Export"];
1384 bool failed_export = false;
1385 otexstream os(ofs, d->texrow);
1387 // make sure we are ready to export
1388 // this needs to be done before we validate
1389 // FIXME Do we need to do this all the time? I.e., in children
1390 // of a master we are exporting?
1392 updateMacroInstances(OutputUpdate);
1395 os.texrow().reset();
1396 writeLaTeXSource(os, original_path, runparams, output);
1398 catch (EncodingException & e) {
1399 odocstringstream ods;
1400 ods.put(e.failed_char);
1402 oss << "0x" << hex << e.failed_char << dec;
1403 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1404 " (code point %2$s)"),
1405 ods.str(), from_utf8(oss.str()));
1406 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1407 "representable in the chosen encoding.\n"
1408 "Changing the document encoding to utf8 could help."),
1409 e.par_id, e.pos, e.pos + 1));
1410 failed_export = true;
1412 catch (iconv_codecvt_facet_exception & e) {
1413 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1414 _(e.what()), -1, 0, 0));
1415 failed_export = true;
1417 catch (exception const & e) {
1418 errorList.push_back(ErrorItem(_("conversion failed"),
1419 _(e.what()), -1, 0, 0));
1420 failed_export = true;
1423 lyxerr << "Caught some really weird exception..." << endl;
1429 failed_export = true;
1430 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1434 return !failed_export;
1438 void Buffer::writeLaTeXSource(otexstream & os,
1439 string const & original_path,
1440 OutputParams const & runparams_in,
1441 OutputWhat output) const
1443 // The child documents, if any, shall be already loaded at this point.
1445 OutputParams runparams = runparams_in;
1447 // Classify the unicode characters appearing in math insets
1448 Encodings::initUnicodeMath(*this);
1450 // validate the buffer.
1451 LYXERR(Debug::LATEX, " Validating buffer...");
1452 LaTeXFeatures features(*this, params(), runparams);
1454 LYXERR(Debug::LATEX, " Buffer validation done.");
1456 bool const output_preamble =
1457 output == FullSource || output == OnlyPreamble;
1458 bool const output_body =
1459 output == FullSource || output == OnlyBody;
1461 // The starting paragraph of the coming rows is the
1462 // first paragraph of the document. (Asger)
1463 if (output_preamble && runparams.nice) {
1464 os << "%% LyX " << lyx_version << " created this file. "
1465 "For more info, see http://www.lyx.org/.\n"
1466 "%% Do not edit unless you really know what "
1469 LYXERR(Debug::INFO, "lyx document header finished");
1471 // There are a few differences between nice LaTeX and usual files:
1472 // usual files have \batchmode and special input@path to allow
1473 // inclusion of figures specified by an explicitly relative path
1474 // (i.e., a path starting with './' or '../') with either \input or
1475 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1476 // input@path is set when the actual parameter original_path is set.
1477 // This is done for usual tex-file, but not for nice-latex-file.
1478 // (Matthias 250696)
1479 // Note that input@path is only needed for something the user does
1480 // in the preamble, included .tex files or ERT, files included by
1481 // LyX work without it.
1482 if (output_preamble) {
1483 if (!runparams.nice) {
1484 // code for usual, NOT nice-latex-file
1485 os << "\\batchmode\n"; // changed from \nonstopmode
1487 if (!original_path.empty()) {
1489 // We don't know the encoding of inputpath
1490 docstring const inputpath = from_utf8(original_path);
1491 docstring uncodable_glyphs;
1492 Encoding const * const enc = runparams.encoding;
1494 for (size_t n = 0; n < inputpath.size(); ++n) {
1495 docstring const glyph =
1496 docstring(1, inputpath[n]);
1497 if (enc->latexChar(inputpath[n], true) != glyph) {
1498 LYXERR0("Uncodable character '"
1500 << "' in input path!");
1501 uncodable_glyphs += glyph;
1506 // warn user if we found uncodable glyphs.
1507 if (!uncodable_glyphs.empty()) {
1508 frontend::Alert::warning(
1509 _("Uncodable character in file path"),
1511 _("The path of your document\n"
1513 "contains glyphs that are unknown "
1514 "in the current document encoding "
1515 "(namely %2$s). This may result in "
1516 "incomplete output, unless "
1517 "TEXINPUTS contains the document "
1518 "directory and you don't use "
1519 "explicitly relative paths (i.e., "
1520 "paths starting with './' or "
1521 "'../') in the preamble or in ERT."
1522 "\n\nIn case of problems, choose "
1523 "an appropriate document encoding\n"
1524 "(such as utf8) or change the "
1526 inputpath, uncodable_glyphs));
1529 support::latex_path(original_path);
1530 if (contains(docdir, '#')) {
1531 docdir = subst(docdir, "#", "\\#");
1532 os << "\\catcode`\\#=11"
1533 "\\def\\#{#}\\catcode`\\#=6\n";
1535 if (contains(docdir, '%')) {
1536 docdir = subst(docdir, "%", "\\%");
1537 os << "\\catcode`\\%=11"
1538 "\\def\\%{%}\\catcode`\\%=14\n";
1540 os << "\\makeatletter\n"
1541 << "\\def\\input@path{{"
1542 << docdir << "/}}\n"
1543 << "\\makeatother\n";
1547 // get parent macros (if this buffer has a parent) which will be
1548 // written at the document begin further down.
1549 MacroSet parentMacros;
1550 listParentMacros(parentMacros, features);
1552 runparams.use_polyglossia = features.usePolyglossia();
1553 // Write the preamble
1554 runparams.use_babel = params().writeLaTeX(os, features,
1555 d->filename.onlyPath());
1557 runparams.use_japanese = features.isRequired("japanese");
1563 os << "\\begin{document}\n";
1565 // output the parent macros
1566 MacroSet::iterator it = parentMacros.begin();
1567 MacroSet::iterator end = parentMacros.end();
1568 for (; it != end; ++it) {
1569 int num_lines = (*it)->write(os.os(), true);
1570 os.texrow().newlines(num_lines);
1573 } // output_preamble
1575 os.texrow().start(paragraphs().begin()->id(), 0);
1577 LYXERR(Debug::INFO, "preamble finished, now the body.");
1579 // if we are doing a real file with body, even if this is the
1580 // child of some other buffer, let's cut the link here.
1581 // This happens for example if only a child document is printed.
1582 Buffer const * save_parent = 0;
1583 if (output_preamble) {
1584 save_parent = d->parent();
1589 latexParagraphs(*this, text(), os, runparams);
1591 // Restore the parenthood if needed
1592 if (output_preamble)
1593 d->setParent(save_parent);
1595 // add this just in case after all the paragraphs
1598 if (output_preamble) {
1599 os << "\\end{document}\n";
1600 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1602 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1604 runparams_in.encoding = runparams.encoding;
1606 // Just to be sure. (Asger)
1607 os.texrow().newline();
1609 //for (int i = 0; i<d->texrow.rows(); i++) {
1611 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1612 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1615 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1616 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1620 void Buffer::makeDocBookFile(FileName const & fname,
1621 OutputParams const & runparams,
1622 OutputWhat output) const
1624 LYXERR(Debug::LATEX, "makeDocBookFile...");
1627 if (!openFileWrite(ofs, fname))
1630 // make sure we are ready to export
1631 // this needs to be done before we validate
1633 updateMacroInstances(OutputUpdate);
1635 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1639 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1643 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1644 OutputParams const & runparams,
1645 OutputWhat output) const
1647 LaTeXFeatures features(*this, params(), runparams);
1652 DocumentClass const & tclass = params().documentClass();
1653 string const top_element = tclass.latexname();
1655 bool const output_preamble =
1656 output == FullSource || output == OnlyPreamble;
1657 bool const output_body =
1658 output == FullSource || output == OnlyBody;
1660 if (output_preamble) {
1661 if (runparams.flavor == OutputParams::XML)
1662 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1665 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1668 if (! tclass.class_header().empty())
1669 os << from_ascii(tclass.class_header());
1670 else if (runparams.flavor == OutputParams::XML)
1671 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1672 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1674 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1676 docstring preamble = from_utf8(params().preamble);
1677 if (runparams.flavor != OutputParams::XML ) {
1678 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1679 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1680 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1681 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1684 string const name = runparams.nice
1685 ? changeExtension(absFileName(), ".sgml") : fname;
1686 preamble += features.getIncludedFiles(name);
1687 preamble += features.getLyXSGMLEntities();
1689 if (!preamble.empty()) {
1690 os << "\n [ " << preamble << " ]";
1696 string top = top_element;
1698 if (runparams.flavor == OutputParams::XML)
1699 top += params().language->code();
1701 top += params().language->code().substr(0, 2);
1704 if (!params().options.empty()) {
1706 top += params().options;
1709 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1710 << " file was created by LyX " << lyx_version
1711 << "\n See http://www.lyx.org/ for more information -->\n";
1713 params().documentClass().counters().reset();
1715 sgml::openTag(os, top);
1717 docbookParagraphs(text(), *this, os, runparams);
1718 sgml::closeTag(os, top_element);
1723 void Buffer::makeLyXHTMLFile(FileName const & fname,
1724 OutputParams const & runparams) const
1726 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1729 if (!openFileWrite(ofs, fname))
1732 // make sure we are ready to export
1733 // this has to be done before we validate
1734 updateBuffer(UpdateMaster, OutputUpdate);
1735 updateMacroInstances(OutputUpdate);
1737 writeLyXHTMLSource(ofs, runparams, FullSource);
1741 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1745 void Buffer::writeLyXHTMLSource(odocstream & os,
1746 OutputParams const & runparams,
1747 OutputWhat output) const
1749 LaTeXFeatures features(*this, params(), runparams);
1751 d->bibinfo_.makeCitationLabels(*this);
1753 bool const output_preamble =
1754 output == FullSource || output == OnlyPreamble;
1755 bool const output_body =
1756 output == FullSource || output == OnlyBody;
1758 if (output_preamble) {
1759 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1760 << "<!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"
1761 // FIXME Language should be set properly.
1762 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1764 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1765 // FIXME Presumably need to set this right
1766 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1768 docstring const & doctitle = features.htmlTitle();
1770 << (doctitle.empty() ?
1771 from_ascii("LyX Document") :
1772 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1775 os << "\n<!-- Text Class Preamble -->\n"
1776 << features.getTClassHTMLPreamble()
1777 << "\n<!-- Preamble Snippets -->\n"
1778 << from_utf8(features.getPreambleSnippets());
1780 // we will collect CSS information in a stream, and then output it
1781 // either here, as part of the header, or else in a separate file.
1782 odocstringstream css;
1783 docstring styles = from_utf8(features.getCSSSnippets());
1784 if (!styles.empty())
1785 css << "/* LyX Provided Styles */\n" << styles << '\n';
1787 styles = features.getTClassHTMLStyles();
1788 if (!styles.empty())
1789 css << "/* Layout-provided Styles */\n" << styles << '\n';
1791 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1792 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1793 if (needfg || needbg) {
1794 css << "\nbody {\n";
1797 << from_ascii(X11hexname(params().fontcolor))
1800 css << " background-color: "
1801 << from_ascii(X11hexname(params().backgroundcolor))
1806 docstring const dstyles = css.str();
1807 if (!dstyles.empty()) {
1808 os << "<style type='text/css'>\n"
1818 params().documentClass().counters().reset();
1819 xhtmlParagraphs(text(), *this, xs, runparams);
1823 if (output_preamble)
1828 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1829 // Other flags: -wall -v0 -x
1830 int Buffer::runChktex()
1834 // get LaTeX-Filename
1835 FileName const path(temppath());
1836 string const name = addName(path.absFileName(), latexName());
1837 string const org_path = filePath();
1839 PathChanger p(path); // path to LaTeX file
1840 message(_("Running chktex..."));
1842 // Generate the LaTeX file if neccessary
1843 OutputParams runparams(¶ms().encoding());
1844 runparams.flavor = OutputParams::LATEX;
1845 runparams.nice = false;
1846 runparams.linelen = lyxrc.plaintext_linelen;
1847 makeLaTeXFile(FileName(name), org_path, runparams);
1850 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1851 int const res = chktex.run(terr); // run chktex
1854 Alert::error(_("chktex failure"),
1855 _("Could not run chktex successfully."));
1856 } else if (res > 0) {
1857 ErrorList & errlist = d->errorLists["ChkTeX"];
1859 bufferErrors(terr, errlist);
1870 void Buffer::validate(LaTeXFeatures & features) const
1872 params().validate(features);
1874 for_each(paragraphs().begin(), paragraphs().end(),
1875 bind(&Paragraph::validate, _1, ref(features)));
1877 if (lyxerr.debugging(Debug::LATEX)) {
1878 features.showStruct();
1883 void Buffer::getLabelList(vector<docstring> & list) const
1885 // If this is a child document, use the master's list instead.
1887 masterBuffer()->getLabelList(list);
1892 Toc & toc = d->toc_backend.toc("label");
1893 TocIterator toc_it = toc.begin();
1894 TocIterator end = toc.end();
1895 for (; toc_it != end; ++toc_it) {
1896 if (toc_it->depth() == 0)
1897 list.push_back(toc_it->str());
1902 void Buffer::updateBibfilesCache(UpdateScope scope) const
1904 // FIXME This is probably unnecssary, given where we call this.
1905 // If this is a child document, use the parent's cache instead.
1906 if (parent() && scope != UpdateChildOnly) {
1907 masterBuffer()->updateBibfilesCache();
1911 d->bibfiles_cache_.clear();
1912 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1913 if (it->lyxCode() == BIBTEX_CODE) {
1914 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1915 support::FileNameList const bibfiles = inset.getBibFiles();
1916 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1919 } else if (it->lyxCode() == INCLUDE_CODE) {
1920 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1921 Buffer const * const incbuf = inset.getChildBuffer();
1924 support::FileNameList const & bibfiles =
1925 incbuf->getBibfilesCache(UpdateChildOnly);
1926 if (!bibfiles.empty()) {
1927 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1933 d->bibfile_cache_valid_ = true;
1934 d->bibinfo_cache_valid_ = false;
1935 d->cite_labels_valid_ = false;
1939 void Buffer::invalidateBibinfoCache() const
1941 d->bibinfo_cache_valid_ = false;
1942 d->cite_labels_valid_ = false;
1943 // also invalidate the cache for the parent buffer
1944 Buffer const * const pbuf = d->parent();
1946 pbuf->invalidateBibinfoCache();
1950 void Buffer::invalidateBibfileCache() const
1952 d->bibfile_cache_valid_ = false;
1953 d->bibinfo_cache_valid_ = false;
1954 d->cite_labels_valid_ = false;
1955 // also invalidate the cache for the parent buffer
1956 Buffer const * const pbuf = d->parent();
1958 pbuf->invalidateBibfileCache();
1962 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1964 // FIXME This is probably unnecessary, given where we call this.
1965 // If this is a child document, use the master's cache instead.
1966 Buffer const * const pbuf = masterBuffer();
1967 if (pbuf != this && scope != UpdateChildOnly)
1968 return pbuf->getBibfilesCache();
1970 if (!d->bibfile_cache_valid_)
1971 this->updateBibfilesCache(scope);
1973 return d->bibfiles_cache_;
1977 BiblioInfo const & Buffer::masterBibInfo() const
1979 Buffer const * const tmp = masterBuffer();
1981 return tmp->masterBibInfo();
1986 void Buffer::checkIfBibInfoCacheIsValid() const
1988 // use the master's cache
1989 Buffer const * const tmp = masterBuffer();
1991 tmp->checkIfBibInfoCacheIsValid();
1995 // compare the cached timestamps with the actual ones.
1996 FileNameList const & bibfiles_cache = getBibfilesCache();
1997 FileNameList::const_iterator ei = bibfiles_cache.begin();
1998 FileNameList::const_iterator en = bibfiles_cache.end();
1999 for (; ei != en; ++ ei) {
2000 time_t lastw = ei->lastModified();
2001 time_t prevw = d->bibfile_status_[*ei];
2002 if (lastw != prevw) {
2003 d->bibinfo_cache_valid_ = false;
2004 d->cite_labels_valid_ = false;
2005 d->bibfile_status_[*ei] = lastw;
2011 void Buffer::reloadBibInfoCache() const
2013 // use the master's cache
2014 Buffer const * const tmp = masterBuffer();
2016 tmp->reloadBibInfoCache();
2020 checkIfBibInfoCacheIsValid();
2021 if (d->bibinfo_cache_valid_)
2024 d->bibinfo_.clear();
2026 d->bibinfo_cache_valid_ = true;
2030 void Buffer::collectBibKeys() const
2032 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2033 it->collectBibKeys(it);
2037 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2039 Buffer const * tmp = masterBuffer();
2040 BiblioInfo & masterbi = (tmp == this) ?
2041 d->bibinfo_ : tmp->d->bibinfo_;
2042 masterbi.mergeBiblioInfo(bi);
2046 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2048 Buffer const * tmp = masterBuffer();
2049 BiblioInfo & masterbi = (tmp == this) ?
2050 d->bibinfo_ : tmp->d->bibinfo_;
2055 bool Buffer::citeLabelsValid() const
2057 return masterBuffer()->d->cite_labels_valid_;
2061 void Buffer::removeBiblioTempFiles() const
2063 // We remove files that contain LaTeX commands specific to the
2064 // particular bibliographic style being used, in order to avoid
2065 // LaTeX errors when we switch style.
2066 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2067 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2068 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2069 aux_file.removeFile();
2070 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2071 bbl_file.removeFile();
2072 // Also for the parent buffer
2073 Buffer const * const pbuf = parent();
2075 pbuf->removeBiblioTempFiles();
2079 bool Buffer::isDepClean(string const & name) const
2081 DepClean::const_iterator const it = d->dep_clean.find(name);
2082 if (it == d->dep_clean.end())
2088 void Buffer::markDepClean(string const & name)
2090 d->dep_clean[name] = true;
2094 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2097 // FIXME? if there is an Buffer LFUN that can be dispatched even
2098 // if internal, put a switch '(cmd.action)' here.
2104 switch (cmd.action()) {
2106 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2107 flag.setOnOff(isReadonly());
2110 // FIXME: There is need for a command-line import.
2111 //case LFUN_BUFFER_IMPORT:
2113 case LFUN_BUFFER_AUTO_SAVE:
2116 case LFUN_BUFFER_EXPORT_CUSTOM:
2117 // FIXME: Nothing to check here?
2120 case LFUN_BUFFER_EXPORT: {
2121 docstring const arg = cmd.argument();
2122 if (arg == "custom") {
2126 string format = to_utf8(arg);
2127 size_t pos = format.find(' ');
2128 if (pos != string::npos)
2129 format = format.substr(0, pos);
2130 enable = params().isExportable(format);
2132 flag.message(bformat(
2133 _("Don't know how to export to format: %1$s"), arg));
2137 case LFUN_BUFFER_CHKTEX:
2138 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2141 case LFUN_BUILD_PROGRAM:
2142 enable = params().isExportable("program");
2145 case LFUN_BRANCH_ADD:
2146 case LFUN_BRANCHES_RENAME:
2147 case LFUN_BUFFER_PRINT:
2148 // if no Buffer is present, then of course we won't be called!
2151 case LFUN_BUFFER_LANGUAGE:
2152 enable = !isReadonly();
2158 flag.setEnabled(enable);
2163 void Buffer::dispatch(string const & command, DispatchResult & result)
2165 return dispatch(lyxaction.lookupFunc(command), result);
2169 // NOTE We can end up here even if we have no GUI, because we are called
2170 // by LyX::exec to handled command-line requests. So we may need to check
2171 // whether we have a GUI or not. The boolean use_gui holds this information.
2172 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2175 // FIXME? if there is an Buffer LFUN that can be dispatched even
2176 // if internal, put a switch '(cmd.action())' here.
2177 dr.dispatched(false);
2180 string const argument = to_utf8(func.argument());
2181 // We'll set this back to false if need be.
2182 bool dispatched = true;
2183 undo().beginUndoGroup();
2185 switch (func.action()) {
2186 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2187 if (lyxvc().inUse())
2188 lyxvc().toggleReadOnly();
2190 setReadonly(!isReadonly());
2193 case LFUN_BUFFER_EXPORT: {
2194 ExportStatus const status = doExport(argument, false);
2195 dr.setError(status != ExportSuccess);
2196 if (status != ExportSuccess)
2197 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2202 case LFUN_BUILD_PROGRAM:
2203 doExport("program", true);
2206 case LFUN_BUFFER_CHKTEX:
2210 case LFUN_BUFFER_EXPORT_CUSTOM: {
2212 string command = split(argument, format_name, ' ');
2213 Format const * format = formats.getFormat(format_name);
2215 lyxerr << "Format \"" << format_name
2216 << "\" not recognized!"
2221 // The name of the file created by the conversion process
2224 // Output to filename
2225 if (format->name() == "lyx") {
2226 string const latexname = latexName(false);
2227 filename = changeExtension(latexname,
2228 format->extension());
2229 filename = addName(temppath(), filename);
2231 if (!writeFile(FileName(filename)))
2235 doExport(format_name, true, filename);
2238 // Substitute $$FName for filename
2239 if (!contains(command, "$$FName"))
2240 command = "( " + command + " ) < $$FName";
2241 command = subst(command, "$$FName", filename);
2243 // Execute the command in the background
2245 call.startscript(Systemcall::DontWait, command, filePath());
2249 // FIXME: There is need for a command-line import.
2251 case LFUN_BUFFER_IMPORT:
2256 case LFUN_BUFFER_AUTO_SAVE:
2258 resetAutosaveTimers();
2261 case LFUN_BRANCH_ADD: {
2262 docstring branch_name = func.argument();
2263 if (branch_name.empty()) {
2267 BranchList & branch_list = params().branchlist();
2268 vector<docstring> const branches =
2269 getVectorFromString(branch_name, branch_list.separator());
2271 for (vector<docstring>::const_iterator it = branches.begin();
2272 it != branches.end(); ++it) {
2274 Branch * branch = branch_list.find(branch_name);
2276 LYXERR0("Branch " << branch_name << " already exists.");
2280 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2282 branch_list.add(branch_name);
2283 branch = branch_list.find(branch_name);
2284 string const x11hexname = X11hexname(branch->color());
2285 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2286 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2288 dr.screenUpdate(Update::Force);
2296 case LFUN_BRANCHES_RENAME: {
2297 if (func.argument().empty())
2300 docstring const oldname = from_utf8(func.getArg(0));
2301 docstring const newname = from_utf8(func.getArg(1));
2302 InsetIterator it = inset_iterator_begin(inset());
2303 InsetIterator const end = inset_iterator_end(inset());
2304 bool success = false;
2305 for (; it != end; ++it) {
2306 if (it->lyxCode() == BRANCH_CODE) {
2307 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2308 if (ins.branch() == oldname) {
2309 undo().recordUndo(it);
2310 ins.rename(newname);
2315 if (it->lyxCode() == INCLUDE_CODE) {
2316 // get buffer of external file
2317 InsetInclude const & ins =
2318 static_cast<InsetInclude const &>(*it);
2319 Buffer * child = ins.getChildBuffer();
2322 child->dispatch(func, dr);
2327 dr.screenUpdate(Update::Force);
2328 dr.forceBufferUpdate();
2333 case LFUN_BUFFER_PRINT: {
2334 // we'll assume there's a problem until we succeed
2336 string target = func.getArg(0);
2337 string target_name = func.getArg(1);
2338 string command = func.getArg(2);
2341 || target_name.empty()
2342 || command.empty()) {
2343 LYXERR0("Unable to parse " << func.argument());
2344 docstring const msg =
2345 bformat(_("Unable to parse \"%1$s\""), func.argument());
2349 if (target != "printer" && target != "file") {
2350 LYXERR0("Unrecognized target \"" << target << '"');
2351 docstring const msg =
2352 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2357 if (!doExport("dvi", true)) {
2358 showPrintError(absFileName());
2359 dr.setMessage(_("Error exporting to DVI."));
2363 // Push directory path.
2364 string const path = temppath();
2365 // Prevent the compiler from optimizing away p
2369 // there are three cases here:
2370 // 1. we print to a file
2371 // 2. we print directly to a printer
2372 // 3. we print using a spool command (print to file first)
2375 string const dviname = changeExtension(latexName(true), "dvi");
2377 if (target == "printer") {
2378 if (!lyxrc.print_spool_command.empty()) {
2379 // case 3: print using a spool
2380 string const psname = changeExtension(dviname,".ps");
2381 command += ' ' + lyxrc.print_to_file
2384 + quoteName(dviname);
2386 string command2 = lyxrc.print_spool_command + ' ';
2387 if (target_name != "default") {
2388 command2 += lyxrc.print_spool_printerprefix
2392 command2 += quoteName(psname);
2394 // If successful, then spool command
2395 res = one.startscript(Systemcall::Wait, command,
2399 // If there's no GUI, we have to wait on this command. Otherwise,
2400 // LyX deletes the temporary directory, and with it the spooled
2401 // file, before it can be printed!!
2402 Systemcall::Starttype stype = use_gui ?
2403 Systemcall::DontWait : Systemcall::Wait;
2404 res = one.startscript(stype, command2,
2408 // case 2: print directly to a printer
2409 if (target_name != "default")
2410 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2412 Systemcall::Starttype stype = use_gui ?
2413 Systemcall::DontWait : Systemcall::Wait;
2414 res = one.startscript(stype, command +
2415 quoteName(dviname), filePath());
2419 // case 1: print to a file
2420 FileName const filename(makeAbsPath(target_name, filePath()));
2421 FileName const dvifile(makeAbsPath(dviname, path));
2422 if (filename.exists()) {
2423 docstring text = bformat(
2424 _("The file %1$s already exists.\n\n"
2425 "Do you want to overwrite that file?"),
2426 makeDisplayPath(filename.absFileName()));
2427 if (Alert::prompt(_("Overwrite file?"),
2428 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2431 command += ' ' + lyxrc.print_to_file
2432 + quoteName(filename.toFilesystemEncoding())
2434 + quoteName(dvifile.toFilesystemEncoding());
2436 Systemcall::Starttype stype = use_gui ?
2437 Systemcall::DontWait : Systemcall::Wait;
2438 res = one.startscript(stype, command, filePath());
2444 dr.setMessage(_("Error running external commands."));
2445 showPrintError(absFileName());
2454 dr.dispatched(dispatched);
2455 undo().endUndoGroup();
2459 void Buffer::changeLanguage(Language const * from, Language const * to)
2461 LASSERT(from, /**/);
2464 for_each(par_iterator_begin(),
2466 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2470 bool Buffer::isMultiLingual() const
2472 ParConstIterator end = par_iterator_end();
2473 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2474 if (it->isMultiLingual(params()))
2481 std::set<Language const *> Buffer::getLanguages() const
2483 std::set<Language const *> languages;
2484 getLanguages(languages);
2489 void Buffer::getLanguages(std::set<Language const *> & languages) const
2491 ParConstIterator end = par_iterator_end();
2492 // add the buffer language, even if it's not actively used
2493 languages.insert(language());
2494 // iterate over the paragraphs
2495 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2496 it->getLanguages(languages);
2498 ListOfBuffers clist = getDescendents();
2499 ListOfBuffers::const_iterator cit = clist.begin();
2500 ListOfBuffers::const_iterator const cen = clist.end();
2501 for (; cit != cen; ++cit)
2502 (*cit)->getLanguages(languages);
2506 DocIterator Buffer::getParFromID(int const id) const
2508 Buffer * buf = const_cast<Buffer *>(this);
2510 // John says this is called with id == -1 from undo
2511 lyxerr << "getParFromID(), id: " << id << endl;
2512 return doc_iterator_end(buf);
2515 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2516 if (it.paragraph().id() == id)
2519 return doc_iterator_end(buf);
2523 bool Buffer::hasParWithID(int const id) const
2525 return !getParFromID(id).atEnd();
2529 ParIterator Buffer::par_iterator_begin()
2531 return ParIterator(doc_iterator_begin(this));
2535 ParIterator Buffer::par_iterator_end()
2537 return ParIterator(doc_iterator_end(this));
2541 ParConstIterator Buffer::par_iterator_begin() const
2543 return ParConstIterator(doc_iterator_begin(this));
2547 ParConstIterator Buffer::par_iterator_end() const
2549 return ParConstIterator(doc_iterator_end(this));
2553 Language const * Buffer::language() const
2555 return params().language;
2559 docstring const Buffer::B_(string const & l10n) const
2561 return params().B_(l10n);
2565 bool Buffer::isClean() const
2567 return d->lyx_clean;
2571 bool Buffer::isExternallyModified(CheckMethod method) const
2573 LASSERT(d->filename.exists(), /**/);
2574 // if method == timestamp, check timestamp before checksum
2575 return (method == checksum_method
2576 || d->timestamp_ != d->filename.lastModified())
2577 && d->checksum_ != d->filename.checksum();
2581 void Buffer::saveCheckSum() const
2583 FileName const & file = d->filename;
2586 if (file.exists()) {
2587 d->timestamp_ = file.lastModified();
2588 d->checksum_ = file.checksum();
2590 // in the case of save to a new file.
2597 void Buffer::markClean() const
2599 if (!d->lyx_clean) {
2600 d->lyx_clean = true;
2603 // if the .lyx file has been saved, we don't need an
2605 d->bak_clean = true;
2606 d->undo_.markDirty();
2610 void Buffer::setUnnamed(bool flag)
2616 bool Buffer::isUnnamed() const
2623 /// Don't check unnamed, here: isInternal() is used in
2624 /// newBuffer(), where the unnamed flag has not been set by anyone
2625 /// yet. Also, for an internal buffer, there should be no need for
2626 /// retrieving fileName() nor for checking if it is unnamed or not.
2627 bool Buffer::isInternal() const
2629 return fileName().extension() == "internal";
2633 void Buffer::markDirty()
2636 d->lyx_clean = false;
2639 d->bak_clean = false;
2641 DepClean::iterator it = d->dep_clean.begin();
2642 DepClean::const_iterator const end = d->dep_clean.end();
2644 for (; it != end; ++it)
2649 FileName Buffer::fileName() const
2655 string Buffer::absFileName() const
2657 return d->filename.absFileName();
2661 string Buffer::filePath() const
2663 return d->filename.onlyPath().absFileName() + "/";
2667 bool Buffer::isReadonly() const
2669 return d->read_only;
2673 void Buffer::setParent(Buffer const * buffer)
2675 // Avoids recursive include.
2676 d->setParent(buffer == this ? 0 : buffer);
2681 Buffer const * Buffer::parent() const
2687 ListOfBuffers Buffer::allRelatives() const
2689 ListOfBuffers lb = masterBuffer()->getDescendents();
2690 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2695 Buffer const * Buffer::masterBuffer() const
2697 // FIXME Should be make sure we are not in some kind
2698 // of recursive include? A -> B -> A will crash this.
2699 Buffer const * const pbuf = d->parent();
2703 return pbuf->masterBuffer();
2707 bool Buffer::isChild(Buffer * child) const
2709 return d->children_positions.find(child) != d->children_positions.end();
2713 DocIterator Buffer::firstChildPosition(Buffer const * child)
2715 Impl::BufferPositionMap::iterator it;
2716 it = d->children_positions.find(child);
2717 if (it == d->children_positions.end())
2718 return DocIterator(this);
2723 bool Buffer::hasChildren() const
2725 return !d->children_positions.empty();
2729 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2731 // loop over children
2732 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2733 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2734 for (; it != end; ++it) {
2735 Buffer * child = const_cast<Buffer *>(it->first);
2737 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2738 if (bit != clist.end())
2740 clist.push_back(child);
2742 // there might be grandchildren
2743 child->collectChildren(clist, true);
2748 ListOfBuffers Buffer::getChildren() const
2751 collectChildren(v, false);
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 ListOfBuffers Buffer::getDescendents() const
2765 collectChildren(v, true);
2766 // Make sure we have not included ourselves.
2767 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2768 if (bit != v.end()) {
2769 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2776 template<typename M>
2777 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2782 typename M::const_iterator it = m.lower_bound(x);
2783 if (it == m.begin())
2791 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2792 DocIterator const & pos) const
2794 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2796 // if paragraphs have no macro context set, pos will be empty
2800 // we haven't found anything yet
2801 DocIterator bestPos = owner_->par_iterator_begin();
2802 MacroData const * bestData = 0;
2804 // find macro definitions for name
2805 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2806 if (nameIt != macros.end()) {
2807 // find last definition in front of pos or at pos itself
2808 PositionScopeMacroMap::const_iterator it
2809 = greatest_below(nameIt->second, pos);
2810 if (it != nameIt->second.end()) {
2812 // scope ends behind pos?
2813 if (pos < it->second.first) {
2814 // Looks good, remember this. If there
2815 // is no external macro behind this,
2816 // we found the right one already.
2817 bestPos = it->first;
2818 bestData = &it->second.second;
2822 // try previous macro if there is one
2823 if (it == nameIt->second.begin())
2830 // find macros in included files
2831 PositionScopeBufferMap::const_iterator it
2832 = greatest_below(position_to_children, pos);
2833 if (it == position_to_children.end())
2834 // no children before
2838 // do we know something better (i.e. later) already?
2839 if (it->first < bestPos )
2842 // scope ends behind pos?
2843 if (pos < it->second.first
2844 && (cloned_buffer_ ||
2845 theBufferList().isLoaded(it->second.second))) {
2846 // look for macro in external file
2848 MacroData const * data
2849 = it->second.second->getMacro(name, false);
2852 bestPos = it->first;
2858 // try previous file if there is one
2859 if (it == position_to_children.begin())
2864 // return the best macro we have found
2869 MacroData const * Buffer::getMacro(docstring const & name,
2870 DocIterator const & pos, bool global) const
2875 // query buffer macros
2876 MacroData const * data = d->getBufferMacro(name, pos);
2880 // If there is a master buffer, query that
2881 Buffer const * const pbuf = d->parent();
2883 d->macro_lock = true;
2884 MacroData const * macro = pbuf->getMacro(
2885 name, *this, false);
2886 d->macro_lock = false;
2892 data = MacroTable::globalMacros().get(name);
2901 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2903 // set scope end behind the last paragraph
2904 DocIterator scope = par_iterator_begin();
2905 scope.pit() = scope.lastpit() + 1;
2907 return getMacro(name, scope, global);
2911 MacroData const * Buffer::getMacro(docstring const & name,
2912 Buffer const & child, bool global) const
2914 // look where the child buffer is included first
2915 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2916 if (it == d->children_positions.end())
2919 // check for macros at the inclusion position
2920 return getMacro(name, it->second, global);
2924 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2926 pit_type const lastpit = it.lastpit();
2928 // look for macros in each paragraph
2929 while (it.pit() <= lastpit) {
2930 Paragraph & par = it.paragraph();
2932 // iterate over the insets of the current paragraph
2933 InsetList const & insets = par.insetList();
2934 InsetList::const_iterator iit = insets.begin();
2935 InsetList::const_iterator end = insets.end();
2936 for (; iit != end; ++iit) {
2937 it.pos() = iit->pos;
2939 // is it a nested text inset?
2940 if (iit->inset->asInsetText()) {
2941 // Inset needs its own scope?
2942 InsetText const * itext = iit->inset->asInsetText();
2943 bool newScope = itext->isMacroScope();
2945 // scope which ends just behind the inset
2946 DocIterator insetScope = it;
2949 // collect macros in inset
2950 it.push_back(CursorSlice(*iit->inset));
2951 updateMacros(it, newScope ? insetScope : scope);
2956 if (iit->inset->asInsetTabular()) {
2957 CursorSlice slice(*iit->inset);
2958 size_t const numcells = slice.nargs();
2959 for (; slice.idx() < numcells; slice.forwardIdx()) {
2960 it.push_back(slice);
2961 updateMacros(it, scope);
2967 // is it an external file?
2968 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2969 // get buffer of external file
2970 InsetInclude const & inset =
2971 static_cast<InsetInclude const &>(*iit->inset);
2973 Buffer * child = inset.getChildBuffer();
2978 // register its position, but only when it is
2979 // included first in the buffer
2980 if (children_positions.find(child) ==
2981 children_positions.end())
2982 children_positions[child] = it;
2984 // register child with its scope
2985 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2989 InsetMath * im = iit->inset->asInsetMath();
2990 if (doing_export && im) {
2991 InsetMathHull * hull = im->asHullInset();
2993 hull->recordLocation(it);
2996 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3000 MathMacroTemplate & macroTemplate =
3001 *iit->inset->asInsetMath()->asMacroTemplate();
3002 MacroContext mc(owner_, it);
3003 macroTemplate.updateToContext(mc);
3006 bool valid = macroTemplate.validMacro();
3007 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3008 // then the BufferView's cursor will be invalid in
3009 // some cases which leads to crashes.
3014 // FIXME (Abdel), I don't understandt why we pass 'it' here
3015 // instead of 'macroTemplate' defined above... is this correct?
3016 macros[macroTemplate.name()][it] =
3017 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3027 void Buffer::updateMacros() const
3032 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3034 // start with empty table
3036 d->children_positions.clear();
3037 d->position_to_children.clear();
3039 // Iterate over buffer, starting with first paragraph
3040 // The scope must be bigger than any lookup DocIterator
3041 // later. For the global lookup, lastpit+1 is used, hence
3042 // we use lastpit+2 here.
3043 DocIterator it = par_iterator_begin();
3044 DocIterator outerScope = it;
3045 outerScope.pit() = outerScope.lastpit() + 2;
3046 d->updateMacros(it, outerScope);
3050 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3052 InsetIterator it = inset_iterator_begin(inset());
3053 InsetIterator const end = inset_iterator_end(inset());
3054 for (; it != end; ++it) {
3055 if (it->lyxCode() == BRANCH_CODE) {
3056 InsetBranch & br = static_cast<InsetBranch &>(*it);
3057 docstring const name = br.branch();
3058 if (!from_master && !params().branchlist().find(name))
3059 result.push_back(name);
3060 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3061 result.push_back(name);
3064 if (it->lyxCode() == INCLUDE_CODE) {
3065 // get buffer of external file
3066 InsetInclude const & ins =
3067 static_cast<InsetInclude const &>(*it);
3068 Buffer * child = ins.getChildBuffer();
3071 child->getUsedBranches(result, true);
3074 // remove duplicates
3079 void Buffer::updateMacroInstances(UpdateType utype) const
3081 LYXERR(Debug::MACROS, "updateMacroInstances for "
3082 << d->filename.onlyFileName());
3083 DocIterator it = doc_iterator_begin(this);
3085 DocIterator const end = doc_iterator_end(this);
3086 for (; it != end; it.forwardInset()) {
3087 // look for MathData cells in InsetMathNest insets
3088 InsetMath * minset = it.nextInset()->asInsetMath();
3092 // update macro in all cells of the InsetMathNest
3093 DocIterator::idx_type n = minset->nargs();
3094 MacroContext mc = MacroContext(this, it);
3095 for (DocIterator::idx_type i = 0; i < n; ++i) {
3096 MathData & data = minset->cell(i);
3097 data.updateMacros(0, mc, utype);
3103 void Buffer::listMacroNames(MacroNameSet & macros) const
3108 d->macro_lock = true;
3110 // loop over macro names
3111 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3112 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3113 for (; nameIt != nameEnd; ++nameIt)
3114 macros.insert(nameIt->first);
3116 // loop over children
3117 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3118 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3119 for (; it != end; ++it)
3120 it->first->listMacroNames(macros);
3123 Buffer const * const pbuf = d->parent();
3125 pbuf->listMacroNames(macros);
3127 d->macro_lock = false;
3131 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3133 Buffer const * const pbuf = d->parent();
3138 pbuf->listMacroNames(names);
3141 MacroNameSet::iterator it = names.begin();
3142 MacroNameSet::iterator end = names.end();
3143 for (; it != end; ++it) {
3145 MacroData const * data =
3146 pbuf->getMacro(*it, *this, false);
3148 macros.insert(data);
3150 // we cannot access the original MathMacroTemplate anymore
3151 // here to calls validate method. So we do its work here manually.
3152 // FIXME: somehow make the template accessible here.
3153 if (data->optionals() > 0)
3154 features.require("xargs");
3160 Buffer::References & Buffer::references(docstring const & label)
3163 return const_cast<Buffer *>(masterBuffer())->references(label);
3165 RefCache::iterator it = d->ref_cache_.find(label);
3166 if (it != d->ref_cache_.end())
3167 return it->second.second;
3169 static InsetLabel const * dummy_il = 0;
3170 static References const dummy_refs;
3171 it = d->ref_cache_.insert(
3172 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3173 return it->second.second;
3177 Buffer::References const & Buffer::references(docstring const & label) const
3179 return const_cast<Buffer *>(this)->references(label);
3183 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3185 masterBuffer()->d->ref_cache_[label].first = il;
3189 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3191 return masterBuffer()->d->ref_cache_[label].first;
3195 void Buffer::clearReferenceCache() const
3198 d->ref_cache_.clear();
3202 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3205 //FIXME: This does not work for child documents yet.
3206 LASSERT(code == CITE_CODE, /**/);
3208 reloadBibInfoCache();
3210 // Check if the label 'from' appears more than once
3211 BiblioInfo const & keys = masterBibInfo();
3212 BiblioInfo::const_iterator bit = keys.begin();
3213 BiblioInfo::const_iterator bend = keys.end();
3214 vector<docstring> labels;
3216 for (; bit != bend; ++bit)
3218 labels.push_back(bit->first);
3220 if (count(labels.begin(), labels.end(), from) > 1)
3223 string const paramName = "key";
3224 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3225 if (it->lyxCode() == code) {
3226 InsetCommand * inset = it->asInsetCommand();
3229 docstring const oldValue = inset->getParam(paramName);
3230 if (oldValue == from)
3231 inset->setParam(paramName, to);
3237 void Buffer::getSourceCode(odocstream & os, string const format,
3238 pit_type par_begin, pit_type par_end,
3239 OutputWhat output) const
3241 OutputParams runparams(¶ms().encoding());
3242 runparams.nice = true;
3243 runparams.flavor = params().getOutputFlavor(format);
3244 runparams.linelen = lyxrc.plaintext_linelen;
3245 // No side effect of file copying and image conversion
3246 runparams.dryrun = true;
3248 if (output == CurrentParagraph) {
3249 runparams.par_begin = par_begin;
3250 runparams.par_end = par_end;
3251 if (par_begin + 1 == par_end) {
3253 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3257 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3258 convert<docstring>(par_begin),
3259 convert<docstring>(par_end - 1))
3266 // output paragraphs
3267 if (params().isDocBook())
3268 docbookParagraphs(text(), *this, os, runparams);
3269 else if (runparams.flavor == OutputParams::HTML) {
3271 setMathFlavor(runparams);
3272 xhtmlParagraphs(text(), *this, xs, runparams);
3274 // latex or literate
3275 otexstream ots(os, texrow);
3276 latexParagraphs(*this, text(), ots, runparams);
3280 if (output == FullSource)
3281 os << _("Preview source code");
3282 else if (output == OnlyPreamble)
3283 os << _("Preview preamble");
3284 else if (output == OnlyBody)
3285 os << _("Preview body");
3288 d->texrow.newline();
3289 d->texrow.newline();
3290 if (params().isDocBook())
3291 writeDocBookSource(os, absFileName(), runparams, output);
3292 else if (runparams.flavor == OutputParams::HTML)
3293 writeLyXHTMLSource(os, runparams, output);
3295 // latex or literate
3296 otexstream ots(os, d->texrow);
3297 writeLaTeXSource(ots, string(), runparams, output);
3303 ErrorList & Buffer::errorList(string const & type) const
3305 return d->errorLists[type];
3309 void Buffer::updateTocItem(std::string const & type,
3310 DocIterator const & dit) const
3313 d->gui_->updateTocItem(type, dit);
3317 void Buffer::structureChanged() const
3320 d->gui_->structureChanged();
3324 void Buffer::errors(string const & err, bool from_master) const
3327 d->gui_->errors(err, from_master);
3331 void Buffer::message(docstring const & msg) const
3334 d->gui_->message(msg);
3338 void Buffer::setBusy(bool on) const
3341 d->gui_->setBusy(on);
3345 void Buffer::updateTitles() const
3348 d->wa_->updateTitles();
3352 void Buffer::resetAutosaveTimers() const
3355 d->gui_->resetAutosaveTimers();
3359 bool Buffer::hasGuiDelegate() const
3365 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3374 class AutoSaveBuffer : public ForkedProcess {
3377 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3378 : buffer_(buffer), fname_(fname) {}
3380 virtual shared_ptr<ForkedProcess> clone() const
3382 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3387 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3388 from_utf8(fname_.absFileName())));
3389 return run(DontWait);
3393 virtual int generateChild();
3395 Buffer const & buffer_;
3400 int AutoSaveBuffer::generateChild()
3402 #if defined(__APPLE__)
3403 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3404 * We should use something else like threads.
3406 * Since I do not know how to determine at run time what is the OS X
3407 * version, I just disable forking altogether for now (JMarc)
3409 pid_t const pid = -1;
3411 // tmp_ret will be located (usually) in /tmp
3412 // will that be a problem?
3413 // Note that this calls ForkedCalls::fork(), so it's
3414 // ok cross-platform.
3415 pid_t const pid = fork();
3416 // If you want to debug the autosave
3417 // you should set pid to -1, and comment out the fork.
3418 if (pid != 0 && pid != -1)
3422 // pid = -1 signifies that lyx was unable
3423 // to fork. But we will do the save
3425 bool failed = false;
3426 FileName const tmp_ret = FileName::tempName("lyxauto");
3427 if (!tmp_ret.empty()) {
3428 buffer_.writeFile(tmp_ret);
3429 // assume successful write of tmp_ret
3430 if (!tmp_ret.moveTo(fname_))
3436 // failed to write/rename tmp_ret so try writing direct
3437 if (!buffer_.writeFile(fname_)) {
3438 // It is dangerous to do this in the child,
3439 // but safe in the parent, so...
3440 if (pid == -1) // emit message signal.
3441 buffer_.message(_("Autosave failed!"));
3445 if (pid == 0) // we are the child so...
3454 FileName Buffer::getEmergencyFileName() const
3456 return FileName(d->filename.absFileName() + ".emergency");
3460 FileName Buffer::getAutosaveFileName() const
3462 // if the document is unnamed try to save in the backup dir, else
3463 // in the default document path, and as a last try in the filePath,
3464 // which will most often be the temporary directory
3467 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3468 : lyxrc.backupdir_path;
3469 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3472 string const fname = "#" + d->filename.onlyFileName() + "#";
3474 return makeAbsPath(fname, fpath);
3478 void Buffer::removeAutosaveFile() const
3480 FileName const f = getAutosaveFileName();
3486 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3488 FileName const newauto = getAutosaveFileName();
3490 if (newauto != oldauto && oldauto.exists())
3491 if (!oldauto.moveTo(newauto))
3492 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3496 bool Buffer::autoSave() const
3498 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3499 if (buf->d->bak_clean || isReadonly())
3502 message(_("Autosaving current document..."));
3503 buf->d->bak_clean = true;
3505 FileName const fname = getAutosaveFileName();
3506 if (d->cloned_buffer_) {
3507 // If this buffer is cloned, we assume that
3508 // we are running in a separate thread already.
3509 FileName const tmp_ret = FileName::tempName("lyxauto");
3510 if (!tmp_ret.empty()) {
3512 // assume successful write of tmp_ret
3513 if (tmp_ret.moveTo(fname))
3516 // failed to write/rename tmp_ret so try writing direct
3517 return writeFile(fname);
3519 /// This function is deprecated as the frontend needs to take care
3520 /// of cloning the buffer and autosaving it in another thread. It
3521 /// is still here to allow (QT_VERSION < 0x040400).
3522 AutoSaveBuffer autosave(*this, fname);
3529 // helper class, to guarantee this gets reset properly
3530 class Buffer::MarkAsExporting {
3532 MarkAsExporting(Buffer const * buf) : buf_(buf)
3534 LASSERT(buf_, /* */);
3535 buf_->setExportStatus(true);
3539 buf_->setExportStatus(false);
3542 Buffer const * const buf_;
3547 void Buffer::setExportStatus(bool e) const
3549 d->doing_export = e;
3550 ListOfBuffers clist = getDescendents();
3551 ListOfBuffers::const_iterator cit = clist.begin();
3552 ListOfBuffers::const_iterator const cen = clist.end();
3553 for (; cit != cen; ++cit)
3554 (*cit)->d->doing_export = e;
3558 bool Buffer::isExporting() const
3560 return d->doing_export;
3564 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3568 return doExport(target, put_in_tempdir, result_file);
3571 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3572 string & result_file) const
3574 bool const update_unincluded =
3575 params().maintain_unincluded_children
3576 && !params().getIncludedChildren().empty();
3578 // (1) export with all included children (omit \includeonly)
3579 if (update_unincluded) {
3580 ExportStatus const status =
3581 doExport(target, put_in_tempdir, true, result_file);
3582 if (status != ExportSuccess)
3585 // (2) export with included children only
3586 return doExport(target, put_in_tempdir, false, result_file);
3590 void Buffer::setMathFlavor(OutputParams & op) const
3592 switch (params().html_math_output) {
3593 case BufferParams::MathML:
3594 op.math_flavor = OutputParams::MathAsMathML;
3596 case BufferParams::HTML:
3597 op.math_flavor = OutputParams::MathAsHTML;
3599 case BufferParams::Images:
3600 op.math_flavor = OutputParams::MathAsImages;
3602 case BufferParams::LaTeX:
3603 op.math_flavor = OutputParams::MathAsLaTeX;
3609 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3610 bool includeall, string & result_file) const
3612 LYXERR(Debug::FILES, "target=" << target);
3613 OutputParams runparams(¶ms().encoding());
3614 string format = target;
3615 string dest_filename;
3616 size_t pos = target.find(' ');
3617 if (pos != string::npos) {
3618 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3619 format = target.substr(0, pos);
3620 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3621 FileName(dest_filename).onlyPath().createPath();
3622 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3624 MarkAsExporting exporting(this);
3625 string backend_format;
3626 runparams.flavor = OutputParams::LATEX;
3627 runparams.linelen = lyxrc.plaintext_linelen;
3628 runparams.includeall = includeall;
3629 vector<string> backs = params().backends();
3630 Converters converters = theConverters();
3631 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3632 // Get shortest path to format
3633 converters.buildGraph();
3634 Graph::EdgePath path;
3635 for (vector<string>::const_iterator it = backs.begin();
3636 it != backs.end(); ++it) {
3637 Graph::EdgePath p = converters.getPath(*it, format);
3638 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3639 backend_format = *it;
3644 if (!put_in_tempdir) {
3645 // Only show this alert if this is an export to a non-temporary
3646 // file (not for previewing).
3647 Alert::error(_("Couldn't export file"), bformat(
3648 _("No information for exporting the format %1$s."),
3649 formats.prettyName(format)));
3651 return ExportNoPathToFormat;
3653 runparams.flavor = converters.getFlavor(path);
3656 backend_format = format;
3657 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3658 // FIXME: Don't hardcode format names here, but use a flag
3659 if (backend_format == "pdflatex")
3660 runparams.flavor = OutputParams::PDFLATEX;
3661 else if (backend_format == "luatex")
3662 runparams.flavor = OutputParams::LUATEX;
3663 else if (backend_format == "dviluatex")
3664 runparams.flavor = OutputParams::DVILUATEX;
3665 else if (backend_format == "xetex")
3666 runparams.flavor = OutputParams::XETEX;
3669 string filename = latexName(false);
3670 filename = addName(temppath(), filename);
3671 filename = changeExtension(filename,
3672 formats.extension(backend_format));
3673 LYXERR(Debug::FILES, "filename=" << filename);
3675 // Plain text backend
3676 if (backend_format == "text") {
3677 runparams.flavor = OutputParams::TEXT;
3678 writePlaintextFile(*this, FileName(filename), runparams);
3681 else if (backend_format == "xhtml") {
3682 runparams.flavor = OutputParams::HTML;
3683 setMathFlavor(runparams);
3684 makeLyXHTMLFile(FileName(filename), runparams);
3685 } else if (backend_format == "lyx")
3686 writeFile(FileName(filename));
3688 else if (params().isDocBook()) {
3689 runparams.nice = !put_in_tempdir;
3690 makeDocBookFile(FileName(filename), runparams);
3693 else if (backend_format == format) {
3694 runparams.nice = true;
3695 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3696 if (d->cloned_buffer_) {
3697 d->cloned_buffer_->d->errorLists["Export"] =
3698 d->errorLists["Export"];
3702 } else if (!lyxrc.tex_allows_spaces
3703 && contains(filePath(), ' ')) {
3704 Alert::error(_("File name error"),
3705 _("The directory path to the document cannot contain spaces."));
3706 return ExportTexPathHasSpaces;
3708 runparams.nice = false;
3709 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3710 if (d->cloned_buffer_) {
3711 d->cloned_buffer_->d->errorLists["Export"] =
3712 d->errorLists["Export"];
3718 string const error_type = (format == "program")
3719 ? "Build" : params().bufferFormat();
3720 ErrorList & error_list = d->errorLists[error_type];
3721 string const ext = formats.extension(format);
3722 FileName const tmp_result_file(changeExtension(filename, ext));
3723 bool const success = converters.convert(this, FileName(filename),
3724 tmp_result_file, FileName(absFileName()), backend_format, format,
3727 // Emit the signal to show the error list or copy it back to the
3728 // cloned Buffer so that it can be emitted afterwards.
3729 if (format != backend_format) {
3730 if (d->cloned_buffer_) {
3731 d->cloned_buffer_->d->errorLists[error_type] =
3732 d->errorLists[error_type];
3735 // also to the children, in case of master-buffer-view
3736 ListOfBuffers clist = getDescendents();
3737 ListOfBuffers::const_iterator cit = clist.begin();
3738 ListOfBuffers::const_iterator const cen = clist.end();
3739 for (; cit != cen; ++cit) {
3740 if (d->cloned_buffer_) {
3741 // Enable reverse search by copying back the
3742 // texrow object to the cloned buffer.
3743 // FIXME: this is not thread safe.
3744 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3745 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3746 (*cit)->d->errorLists[error_type];
3748 (*cit)->errors(error_type, true);
3752 if (d->cloned_buffer_) {
3753 // Enable reverse dvi or pdf to work by copying back the texrow
3754 // object to the cloned buffer.
3755 // FIXME: There is a possibility of concurrent access to texrow
3756 // here from the main GUI thread that should be securized.
3757 d->cloned_buffer_->d->texrow = d->texrow;
3758 string const error_type = params().bufferFormat();
3759 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3763 return ExportConverterError;
3765 if (put_in_tempdir) {
3766 result_file = tmp_result_file.absFileName();
3767 return ExportSuccess;
3770 if (dest_filename.empty())
3771 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3773 result_file = dest_filename;
3774 // We need to copy referenced files (e. g. included graphics
3775 // if format == "dvi") to the result dir.
3776 vector<ExportedFile> const files =
3777 runparams.exportdata->externalFiles(format);
3778 string const dest = runparams.export_folder.empty() ?
3779 onlyPath(result_file) : runparams.export_folder;
3780 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3781 : force_overwrite == ALL_FILES;
3782 CopyStatus status = use_force ? FORCE : SUCCESS;
3784 vector<ExportedFile>::const_iterator it = files.begin();
3785 vector<ExportedFile>::const_iterator const en = files.end();
3786 for (; it != en && status != CANCEL; ++it) {
3787 string const fmt = formats.getFormatFromFile(it->sourceName);
3788 string fixedName = it->exportName;
3789 if (!runparams.export_folder.empty()) {
3790 // Relative pathnames starting with ../ will be sanitized
3791 // if exporting to a different folder
3792 while (fixedName.substr(0, 3) == "../")
3793 fixedName = fixedName.substr(3, fixedName.length() - 3);
3795 FileName fixedFileName = makeAbsPath(fixedName, dest);
3796 fixedFileName.onlyPath().createPath();
3797 status = copyFile(fmt, it->sourceName,
3799 it->exportName, status == FORCE,
3800 runparams.export_folder.empty());
3803 if (status == CANCEL) {
3804 message(_("Document export cancelled."));
3805 return ExportCancel;
3808 if (tmp_result_file.exists()) {
3809 // Finally copy the main file
3810 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3811 : force_overwrite != NO_FILES;
3812 if (status == SUCCESS && use_force)
3814 status = copyFile(format, tmp_result_file,
3815 FileName(result_file), result_file,
3817 if (status == CANCEL) {
3818 message(_("Document export cancelled."));
3819 return ExportCancel;
3821 message(bformat(_("Document exported as %1$s "
3823 formats.prettyName(format),
3824 makeDisplayPath(result_file)));
3827 // This must be a dummy converter like fax (bug 1888)
3828 message(bformat(_("Document exported as %1$s"),
3829 formats.prettyName(format)));
3832 return ExportSuccess;
3836 Buffer::ExportStatus Buffer::preview(string const & format) const
3838 bool const update_unincluded =
3839 params().maintain_unincluded_children
3840 && !params().getIncludedChildren().empty();
3841 return preview(format, update_unincluded);
3844 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3846 MarkAsExporting exporting(this);
3848 // (1) export with all included children (omit \includeonly)
3850 ExportStatus const status = doExport(format, true, true, result_file);
3851 if (status != ExportSuccess)
3854 // (2) export with included children only
3855 ExportStatus const status = doExport(format, true, false, result_file);
3856 if (status != ExportSuccess)
3858 if (!formats.view(*this, FileName(result_file), format))
3859 return PreviewError;
3860 return PreviewSuccess;
3864 Buffer::ReadStatus Buffer::extractFromVC()
3866 bool const found = LyXVC::file_not_found_hook(d->filename);
3868 return ReadFileNotFound;
3869 if (!d->filename.isReadableFile())
3875 Buffer::ReadStatus Buffer::loadEmergency()
3877 FileName const emergencyFile = getEmergencyFileName();
3878 if (!emergencyFile.exists()
3879 || emergencyFile.lastModified() <= d->filename.lastModified())
3880 return ReadFileNotFound;
3882 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3883 docstring const text = bformat(_("An emergency save of the document "
3884 "%1$s exists.\n\nRecover emergency save?"), file);
3886 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3887 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3893 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3894 bool const success = (ret_llf == ReadSuccess);
3897 Alert::warning(_("File is read-only"),
3898 bformat(_("An emergency file is successfully loaded, "
3899 "but the original file %1$s is marked read-only. "
3900 "Please make sure to save the document as a different "
3901 "file."), from_utf8(d->filename.absFileName())));
3904 str = _("Document was successfully recovered.");
3906 str = _("Document was NOT successfully recovered.");
3907 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3908 makeDisplayPath(emergencyFile.absFileName()));
3910 int const del_emerg =
3911 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3912 _("&Remove"), _("&Keep"));
3913 if (del_emerg == 0) {
3914 emergencyFile.removeFile();
3916 Alert::warning(_("Emergency file deleted"),
3917 _("Do not forget to save your file now!"), true);
3919 return success ? ReadSuccess : ReadEmergencyFailure;
3922 int const del_emerg =
3923 Alert::prompt(_("Delete emergency file?"),
3924 _("Remove emergency file now?"), 1, 1,
3925 _("&Remove"), _("&Keep"));
3927 emergencyFile.removeFile();
3928 return ReadOriginal;
3938 Buffer::ReadStatus Buffer::loadAutosave()
3940 // Now check if autosave file is newer.
3941 FileName const autosaveFile = getAutosaveFileName();
3942 if (!autosaveFile.exists()
3943 || autosaveFile.lastModified() <= d->filename.lastModified())
3944 return ReadFileNotFound;
3946 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3947 docstring const text = bformat(_("The backup of the document %1$s "
3948 "is newer.\n\nLoad the backup instead?"), file);
3949 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3950 _("&Load backup"), _("Load &original"), _("&Cancel"));
3955 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3956 // the file is not saved if we load the autosave file.
3957 if (ret_llf == ReadSuccess) {
3959 Alert::warning(_("File is read-only"),
3960 bformat(_("A backup file is successfully loaded, "
3961 "but the original file %1$s is marked read-only. "
3962 "Please make sure to save the document as a "
3964 from_utf8(d->filename.absFileName())));
3969 return ReadAutosaveFailure;
3972 // Here we delete the autosave
3973 autosaveFile.removeFile();
3974 return ReadOriginal;
3982 Buffer::ReadStatus Buffer::loadLyXFile()
3984 if (!d->filename.isReadableFile()) {
3985 ReadStatus const ret_rvc = extractFromVC();
3986 if (ret_rvc != ReadSuccess)
3990 ReadStatus const ret_re = loadEmergency();
3991 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3994 ReadStatus const ret_ra = loadAutosave();
3995 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3998 return loadThisLyXFile(d->filename);
4002 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4004 return readFile(fn);
4008 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4010 TeXErrors::Errors::const_iterator it = terr.begin();
4011 TeXErrors::Errors::const_iterator end = terr.end();
4012 ListOfBuffers clist = getDescendents();
4013 ListOfBuffers::const_iterator cen = clist.end();
4015 for (; it != end; ++it) {
4018 int errorRow = it->error_in_line;
4019 Buffer const * buf = 0;
4021 if (it->child_name.empty())
4022 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4024 // The error occurred in a child
4025 ListOfBuffers::const_iterator cit = clist.begin();
4026 for (; cit != cen; ++cit) {
4027 string const child_name =
4028 DocFileName(changeExtension(
4029 (*cit)->absFileName(), "tex")).
4031 if (it->child_name != child_name)
4033 (*cit)->d->texrow.getIdFromRow(errorRow,
4034 id_start, pos_start);
4035 if (id_start != -1) {
4036 buf = d->cloned_buffer_
4037 ? (*cit)->d->cloned_buffer_->d->owner_
4038 : (*cit)->d->owner_;
4049 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4050 } while (found && id_start == id_end && pos_start == pos_end);
4052 if (id_start != id_end) {
4053 // Next registered position is outside the inset where
4054 // the error occurred, so signal end-of-paragraph
4058 errorList.push_back(ErrorItem(it->error_desc,
4059 it->error_text, id_start, pos_start, pos_end, buf));
4064 void Buffer::setBuffersForInsets() const
4066 inset().setBuffer(const_cast<Buffer &>(*this));
4070 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4072 // Use the master text class also for child documents
4073 Buffer const * const master = masterBuffer();
4074 DocumentClass const & textclass = master->params().documentClass();
4076 // do this only if we are the top-level Buffer
4078 reloadBibInfoCache();
4080 // keep the buffers to be children in this set. If the call from the
4081 // master comes back we can see which of them were actually seen (i.e.
4082 // via an InsetInclude). The remaining ones in the set need still be updated.
4083 static std::set<Buffer const *> bufToUpdate;
4084 if (scope == UpdateMaster) {
4085 // If this is a child document start with the master
4086 if (master != this) {
4087 bufToUpdate.insert(this);
4088 master->updateBuffer(UpdateMaster, utype);
4089 // Do this here in case the master has no gui associated with it. Then,
4090 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4091 if (!master->d->gui_)
4094 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4095 if (bufToUpdate.find(this) == bufToUpdate.end())
4099 // start over the counters in the master
4100 textclass.counters().reset();
4103 // update will be done below for this buffer
4104 bufToUpdate.erase(this);
4106 // update all caches
4107 clearReferenceCache();
4110 Buffer & cbuf = const_cast<Buffer &>(*this);
4112 LASSERT(!text().paragraphs().empty(), /**/);
4115 ParIterator parit = cbuf.par_iterator_begin();
4116 updateBuffer(parit, utype);
4119 // TocBackend update will be done later.
4122 d->bibinfo_cache_valid_ = true;
4123 d->cite_labels_valid_ = true;
4124 cbuf.tocBackend().update();
4125 if (scope == UpdateMaster)
4126 cbuf.structureChanged();
4130 static depth_type getDepth(DocIterator const & it)
4132 depth_type depth = 0;
4133 for (size_t i = 0 ; i < it.depth() ; ++i)
4134 if (!it[i].inset().inMathed())
4135 depth += it[i].paragraph().getDepth() + 1;
4136 // remove 1 since the outer inset does not count
4140 static depth_type getItemDepth(ParIterator const & it)
4142 Paragraph const & par = *it;
4143 LabelType const labeltype = par.layout().labeltype;
4145 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4148 // this will hold the lowest depth encountered up to now.
4149 depth_type min_depth = getDepth(it);
4150 ParIterator prev_it = it;
4153 --prev_it.top().pit();
4155 // start of nested inset: go to outer par
4157 if (prev_it.empty()) {
4158 // start of document: nothing to do
4163 // We search for the first paragraph with same label
4164 // that is not more deeply nested.
4165 Paragraph & prev_par = *prev_it;
4166 depth_type const prev_depth = getDepth(prev_it);
4167 if (labeltype == prev_par.layout().labeltype) {
4168 if (prev_depth < min_depth)
4169 return prev_par.itemdepth + 1;
4170 if (prev_depth == min_depth)
4171 return prev_par.itemdepth;
4173 min_depth = min(min_depth, prev_depth);
4174 // small optimization: if we are at depth 0, we won't
4175 // find anything else
4176 if (prev_depth == 0)
4182 static bool needEnumCounterReset(ParIterator const & it)
4184 Paragraph const & par = *it;
4185 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4186 depth_type const cur_depth = par.getDepth();
4187 ParIterator prev_it = it;
4188 while (prev_it.pit()) {
4189 --prev_it.top().pit();
4190 Paragraph const & prev_par = *prev_it;
4191 if (prev_par.getDepth() <= cur_depth)
4192 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4194 // start of nested inset: reset
4199 // set the label of a paragraph. This includes the counters.
4200 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4202 BufferParams const & bp = owner_->masterBuffer()->params();
4203 DocumentClass const & textclass = bp.documentClass();
4204 Paragraph & par = it.paragraph();
4205 Layout const & layout = par.layout();
4206 Counters & counters = textclass.counters();
4208 if (par.params().startOfAppendix()) {
4209 // FIXME: only the counter corresponding to toplevel
4210 // sectioning should be reset
4212 counters.appendix(true);
4214 par.params().appendix(counters.appendix());
4216 // Compute the item depth of the paragraph
4217 par.itemdepth = getItemDepth(it);
4219 if (layout.margintype == MARGIN_MANUAL) {
4220 if (par.params().labelWidthString().empty())
4221 par.params().labelWidthString(par.expandLabel(layout, bp));
4222 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4223 // we do not need to do anything here, since the empty case is
4224 // handled during export.
4226 par.params().labelWidthString(docstring());
4229 switch(layout.labeltype) {
4231 if (layout.toclevel <= bp.secnumdepth
4232 && (layout.latextype != LATEX_ENVIRONMENT
4233 || it.text()->isFirstInSequence(it.pit()))) {
4234 if (counters.hasCounter(layout.counter))
4235 counters.step(layout.counter, utype);
4236 par.params().labelString(par.expandLabel(layout, bp));
4238 par.params().labelString(docstring());
4241 case LABEL_ITEMIZE: {
4242 // At some point of time we should do something more
4243 // clever here, like:
4244 // par.params().labelString(
4245 // bp.user_defined_bullet(par.itemdepth).getText());
4246 // for now, use a simple hardcoded label
4247 docstring itemlabel;
4248 switch (par.itemdepth) {
4250 itemlabel = char_type(0x2022);
4253 itemlabel = char_type(0x2013);
4256 itemlabel = char_type(0x2217);
4259 itemlabel = char_type(0x2219); // or 0x00b7
4262 par.params().labelString(itemlabel);
4266 case LABEL_ENUMERATE: {
4267 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4269 switch (par.itemdepth) {
4278 enumcounter += "iv";
4281 // not a valid enumdepth...
4285 // Maybe we have to reset the enumeration counter.
4286 if (needEnumCounterReset(it))
4287 counters.reset(enumcounter);
4288 counters.step(enumcounter, utype);
4290 string const & lang = par.getParLanguage(bp)->code();
4291 par.params().labelString(counters.theCounter(enumcounter, lang));
4296 case LABEL_SENSITIVE: {
4297 string const & type = counters.current_float();
4298 docstring full_label;
4300 full_label = owner_->B_("Senseless!!! ");
4302 docstring name = owner_->B_(textclass.floats().getType(type).name());
4303 if (counters.hasCounter(from_utf8(type))) {
4304 string const & lang = par.getParLanguage(bp)->code();
4305 counters.step(from_utf8(type), utype);
4306 full_label = bformat(from_ascii("%1$s %2$s:"),
4308 counters.theCounter(from_utf8(type), lang));
4310 full_label = bformat(from_ascii("%1$s #:"), name);
4312 par.params().labelString(full_label);
4316 case LABEL_NO_LABEL:
4317 par.params().labelString(docstring());
4321 case LABEL_TOP_ENVIRONMENT:
4322 case LABEL_CENTERED_TOP_ENVIRONMENT:
4325 par.params().labelString(par.expandLabel(layout, bp));
4331 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4333 LASSERT(parit.pit() == 0, /**/);
4335 // Set the position of the text in the buffer to be able
4336 // to resolve macros in it.
4337 parit.text()->setMacrocontextPosition(parit);
4339 depth_type maxdepth = 0;
4340 pit_type const lastpit = parit.lastpit();
4341 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4342 // reduce depth if necessary
4343 parit->params().depth(min(parit->params().depth(), maxdepth));
4344 maxdepth = parit->getMaxDepthAfter();
4346 if (utype == OutputUpdate) {
4347 // track the active counters
4348 // we have to do this for the master buffer, since the local
4349 // buffer isn't tracking anything.
4350 masterBuffer()->params().documentClass().counters().
4351 setActiveLayout(parit->layout());
4354 // set the counter for this paragraph
4355 d->setLabel(parit, utype);
4358 InsetList::const_iterator iit = parit->insetList().begin();
4359 InsetList::const_iterator end = parit->insetList().end();
4360 for (; iit != end; ++iit) {
4361 parit.pos() = iit->pos;
4362 iit->inset->updateBuffer(parit, utype);
4368 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4369 WordLangTuple & word_lang, docstring_list & suggestions) const
4373 suggestions.clear();
4374 word_lang = WordLangTuple();
4375 bool const to_end = to.empty();
4376 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4377 // OK, we start from here.
4378 for (; from != end; from.forwardPos()) {
4379 // We are only interested in text so remove the math CursorSlice.
4380 while (from.inMathed()) {
4384 // If from is at the end of the document (which is possible
4385 // when leaving the mathed) LyX will crash later otherwise.
4386 if (from.atEnd() || (!to_end && from >= end))
4389 from.paragraph().spellCheck();
4390 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4391 if (SpellChecker::misspelled(res)) {
4396 // Do not increase progress when from == to, otherwise the word
4397 // count will be wrong.
4407 Buffer::ReadStatus Buffer::reload()
4410 // c.f. bug http://www.lyx.org/trac/ticket/6587
4411 removeAutosaveFile();
4412 // e.g., read-only status could have changed due to version control
4413 d->filename.refresh();
4414 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4416 ReadStatus const status = loadLyXFile();
4417 if (status == ReadSuccess) {
4422 message(bformat(_("Document %1$s reloaded."), disp_fn));
4425 message(bformat(_("Could not reload document %1$s."), disp_fn));
4435 bool Buffer::saveAs(FileName const & fn)
4437 FileName const old_name = fileName();
4438 FileName const old_auto = getAutosaveFileName();
4439 bool const old_unnamed = isUnnamed();
4446 // bring the autosave file with us, just in case.
4447 moveAutosaveFile(old_auto);
4448 // validate version control data and
4449 // correct buffer title
4450 lyxvc().file_found_hook(fileName());
4452 // the file has now been saved to the new location.
4453 // we need to check that the locations of child buffers
4455 checkChildBuffers();
4459 // reset the old filename and unnamed state
4460 setFileName(old_name);
4461 setUnnamed(old_unnamed);
4467 // FIXME We could do better here, but it is complicated. What would be
4468 // nice is to offer either (a) to save the child buffer to an appropriate
4469 // location, so that it would "move with the master", or else (b) to update
4470 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4471 // complicated, because the code for this lives in GuiView.
4472 void Buffer::checkChildBuffers()
4474 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4475 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4476 for (; it != en; ++it) {
4477 DocIterator dit = it->second;
4478 Buffer * cbuf = const_cast<Buffer *>(it->first);
4479 if (!cbuf || !theBufferList().isLoaded(cbuf))
4481 Inset * inset = dit.nextInset();
4482 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4483 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4484 docstring const & incfile = inset_inc->getParam("filename");
4485 string oldloc = cbuf->absFileName();
4486 string newloc = makeAbsPath(to_utf8(incfile),
4487 onlyPath(absFileName())).absFileName();
4488 if (oldloc == newloc)
4490 // the location of the child file is incorrect.
4491 Alert::warning(_("Included File Invalid"),
4492 bformat(_("Saving this document to a new location has made the file:\n"
4494 "inaccessible. You will need to update the included filename."),
4495 from_utf8(oldloc)));
4497 inset_inc->setChildBuffer(0);
4499 // invalidate cache of children
4500 d->children_positions.clear();
4501 d->position_to_children.clear();