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);
142 /// a list of Buffers we cloned
143 set<Buffer *> cloned_buffer_list;
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_;
308 /// are we in the process of exporting this buffer?
309 mutable bool doing_export;
312 /// So we can force access via the accessors.
313 mutable Buffer const * parent_buffer;
318 /// Creates the per buffer temporary directory
319 static FileName createBufferTmpDir()
322 // We are in our own directory. Why bother to mangle name?
323 // In fact I wrote this code to circumvent a problematic behaviour
324 // (bug?) of EMX mkstemp().
325 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
326 convert<string>(count++));
328 if (!tmpfl.createDirectory(0777)) {
329 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
330 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
331 from_utf8(tmpfl.absFileName())));
337 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
338 Buffer const * cloned_buffer)
339 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
340 read_only(readonly_), filename(file), file_fully_loaded(false),
341 toc_backend(owner), macro_lock(false), timestamp_(0), checksum_(0),
342 wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
343 bibfile_cache_valid_(false), cite_labels_valid_(false),
344 preview_loader_(0), cloned_buffer_(cloned_buffer),
345 doing_export(false), parent_buffer(0)
347 if (!cloned_buffer_) {
348 temppath = createBufferTmpDir();
349 lyxvc.setBuffer(owner_);
351 wa_ = new frontend::WorkAreaManager;
354 temppath = cloned_buffer_->d->temppath;
355 file_fully_loaded = true;
356 params = cloned_buffer_->d->params;
357 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
358 bibinfo_ = cloned_buffer_->d->bibinfo_;
359 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
360 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
361 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
362 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
363 unnamed = cloned_buffer_->d->unnamed;
367 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
368 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
370 LYXERR(Debug::INFO, "Buffer::Buffer()");
372 d->inset = new InsetText(*cloned_buffer->d->inset);
373 d->inset->setBuffer(*this);
374 // FIXME: optimize this loop somewhat, maybe by creating a new
375 // general recursive Inset::setId().
376 DocIterator it = doc_iterator_begin(this);
377 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
378 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
379 it.paragraph().setId(cloned_it.paragraph().id());
381 d->inset = new InsetText(this);
382 d->inset->setAutoBreakRows(true);
383 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
389 LYXERR(Debug::INFO, "Buffer::~Buffer()");
390 // here the buffer should take care that it is
391 // saved properly, before it goes into the void.
393 // GuiView already destroyed
397 // No need to do additional cleanups for internal buffer.
403 // this is in case of recursive includes: we won't try to delete
404 // ourselves as a child.
405 cloned_buffer_list.erase(this);
406 // loop over children
407 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
408 Impl::BufferPositionMap::iterator end = d->children_positions.end();
409 for (; it != end; ++it) {
410 Buffer * child = const_cast<Buffer *>(it->first);
411 if (cloned_buffer_list.erase(child))
414 // FIXME Do we really need to do this right before we delete d?
415 // clear references to children in macro tables
416 d->children_positions.clear();
417 d->position_to_children.clear();
419 // loop over children
420 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
421 Impl::BufferPositionMap::iterator end = d->children_positions.end();
422 for (; it != end; ++it) {
423 Buffer * child = const_cast<Buffer *>(it->first);
424 if (theBufferList().isLoaded(child))
425 theBufferList().releaseChild(this, child);
429 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
430 msg += emergencyWrite();
431 Alert::warning(_("Attempting to close changed document!"), msg);
434 // FIXME Do we really need to do this right before we delete d?
435 // clear references to children in macro tables
436 d->children_positions.clear();
437 d->position_to_children.clear();
439 if (!d->temppath.destroyDirectory()) {
440 Alert::warning(_("Could not remove temporary directory"),
441 bformat(_("Could not remove the temporary directory %1$s"),
442 from_utf8(d->temppath.absFileName())));
451 Buffer * Buffer::clone() const
454 masterBuffer()->clone(bufmap);
456 // make sure we got cloned
457 BufferMap::const_iterator bit = bufmap.find(this);
458 LASSERT(bit != bufmap.end(), return 0);
459 Buffer * cloned_buffer = bit->second;
461 // record the list of cloned buffers in the cloned master
462 cloned_buffer_list.clear();
463 BufferMap::iterator it = bufmap.begin();
464 BufferMap::iterator en = bufmap.end();
465 for (; it != en; ++it)
466 cloned_buffer_list.insert(it->second);
468 return cloned_buffer;
472 void Buffer::clone(BufferMap & bufmap) const
474 // have we already been cloned?
475 if (bufmap.find(this) != bufmap.end())
478 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
479 bufmap[this] = buffer_clone;
480 buffer_clone->d->macro_lock = true;
481 buffer_clone->d->children_positions.clear();
482 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
483 // math macro caches need to be rethought and simplified.
484 // I am not sure wether we should handle Buffer cloning here or in BufferList.
485 // Right now BufferList knows nothing about buffer clones.
486 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
487 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
488 for (; it != end; ++it) {
489 DocIterator dit = it->first.clone(buffer_clone);
490 dit.setBuffer(buffer_clone);
491 Buffer * child = const_cast<Buffer *>(it->second.second);
493 child->clone(bufmap);
494 BufferMap::iterator const bit = bufmap.find(child);
495 LASSERT(bit != bufmap.end(), continue);
496 Buffer * child_clone = bit->second;
498 Inset * inset = dit.nextInset();
499 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
500 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
501 inset_inc->setChildBuffer(child_clone);
502 child_clone->d->setParent(buffer_clone);
503 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
504 buffer_clone->setChild(dit, child_clone);
506 buffer_clone->d->macro_lock = false;
511 bool Buffer::isClone() const
513 return d->cloned_buffer_;
517 void Buffer::changed(bool update_metrics) const
520 d->wa_->redrawAll(update_metrics);
524 frontend::WorkAreaManager & Buffer::workAreaManager() const
526 LASSERT(d->wa_, /**/);
531 Text & Buffer::text() const
533 return d->inset->text();
537 Inset & Buffer::inset() const
543 BufferParams & Buffer::params()
549 BufferParams const & Buffer::params() const
555 ParagraphList & Buffer::paragraphs()
557 return text().paragraphs();
561 ParagraphList const & Buffer::paragraphs() const
563 return text().paragraphs();
567 LyXVC & Buffer::lyxvc()
573 LyXVC const & Buffer::lyxvc() const
579 string const Buffer::temppath() const
581 return d->temppath.absFileName();
585 TexRow & Buffer::texrow()
591 TexRow const & Buffer::texrow() const
597 TocBackend & Buffer::tocBackend() const
599 return d->toc_backend;
603 Undo & Buffer::undo()
609 void Buffer::setChild(DocIterator const & dit, Buffer * child)
611 d->children_positions[child] = dit;
615 string Buffer::latexName(bool const no_path) const
617 FileName latex_name =
618 makeLatexName(d->exportFileName());
619 return no_path ? latex_name.onlyFileName()
620 : latex_name.absFileName();
624 FileName Buffer::Impl::exportFileName() const
626 docstring const branch_suffix =
627 params.branchlist().getFileNameSuffix();
628 if (branch_suffix.empty())
631 string const name = filename.onlyFileNameWithoutExt()
632 + to_utf8(branch_suffix);
633 FileName res(filename.onlyPath().absFileName() + "/" + name);
634 res.changeExtension(filename.extension());
640 string Buffer::logName(LogType * type) const
642 string const filename = latexName(false);
644 if (filename.empty()) {
650 string const path = temppath();
652 FileName const fname(addName(temppath(),
653 onlyFileName(changeExtension(filename,
656 // FIXME: how do we know this is the name of the build log?
657 FileName const bname(
658 addName(path, onlyFileName(
659 changeExtension(filename,
660 formats.extension(params().bufferFormat()) + ".out"))));
662 // Also consider the master buffer log file
663 FileName masterfname = fname;
665 if (masterBuffer() != this) {
666 string const mlogfile = masterBuffer()->logName(&mtype);
667 masterfname = FileName(mlogfile);
670 // If no Latex log or Build log is newer, show Build log
671 if (bname.exists() &&
672 ((!fname.exists() && !masterfname.exists())
673 || (fname.lastModified() < bname.lastModified()
674 && masterfname.lastModified() < bname.lastModified()))) {
675 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
678 return bname.absFileName();
679 // If we have a newer master file log or only a master log, show this
680 } else if (fname != masterfname
681 && (!fname.exists() && (masterfname.exists()
682 || fname.lastModified() < masterfname.lastModified()))) {
683 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
686 return masterfname.absFileName();
688 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
691 return fname.absFileName();
695 void Buffer::setReadonly(bool const flag)
697 if (d->read_only != flag) {
704 void Buffer::setFileName(FileName const & fname)
707 setReadonly(d->filename.isReadOnly());
713 int Buffer::readHeader(Lexer & lex)
715 int unknown_tokens = 0;
717 int begin_header_line = -1;
719 // Initialize parameters that may be/go lacking in header:
720 params().branchlist().clear();
721 params().preamble.erase();
722 params().options.erase();
723 params().master.erase();
724 params().float_placement.erase();
725 params().paperwidth.erase();
726 params().paperheight.erase();
727 params().leftmargin.erase();
728 params().rightmargin.erase();
729 params().topmargin.erase();
730 params().bottommargin.erase();
731 params().headheight.erase();
732 params().headsep.erase();
733 params().footskip.erase();
734 params().columnsep.erase();
735 params().fonts_cjk.erase();
736 params().listings_params.clear();
737 params().clearLayoutModules();
738 params().clearRemovedModules();
739 params().clearIncludedChildren();
740 params().pdfoptions().clear();
741 params().indiceslist().clear();
742 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
743 params().isbackgroundcolor = false;
744 params().fontcolor = RGBColor(0, 0, 0);
745 params().isfontcolor = false;
746 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
747 params().boxbgcolor = RGBColor(0xFF, 0, 0);
748 params().html_latex_start.clear();
749 params().html_latex_end.clear();
750 params().html_math_img_scale = 1.0;
751 params().output_sync_macro.erase();
753 for (int i = 0; i < 4; ++i) {
754 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
755 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
758 ErrorList & errorList = d->errorLists["Parse"];
767 if (token == "\\end_header")
771 if (token == "\\begin_header") {
772 begin_header_line = line;
776 LYXERR(Debug::PARSER, "Handling document header token: `"
779 string unknown = params().readToken(lex, token, d->filename.onlyPath());
780 if (!unknown.empty()) {
781 if (unknown[0] != '\\' && token == "\\textclass") {
782 Alert::warning(_("Unknown document class"),
783 bformat(_("Using the default document class, because the "
784 "class %1$s is unknown."), from_utf8(unknown)));
787 docstring const s = bformat(_("Unknown token: "
791 errorList.push_back(ErrorItem(_("Document header error"),
796 if (begin_header_line) {
797 docstring const s = _("\\begin_header is missing");
798 errorList.push_back(ErrorItem(_("Document header error"),
802 params().makeDocumentClass();
804 return unknown_tokens;
809 // changed to be public and have one parameter
810 // Returns true if "\end_document" is not read (Asger)
811 bool Buffer::readDocument(Lexer & lex)
813 ErrorList & errorList = d->errorLists["Parse"];
816 // remove dummy empty par
817 paragraphs().clear();
819 if (!lex.checkFor("\\begin_document")) {
820 docstring const s = _("\\begin_document is missing");
821 errorList.push_back(ErrorItem(_("Document header error"),
827 if (params().outputChanges) {
828 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
829 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
830 LaTeXFeatures::isAvailable("xcolor");
832 if (!dvipost && !xcolorulem) {
833 Alert::warning(_("Changes not shown in LaTeX output"),
834 _("Changes will not be highlighted in LaTeX output, "
835 "because neither dvipost nor xcolor/ulem are installed.\n"
836 "Please install these packages or redefine "
837 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
838 } else if (!xcolorulem) {
839 Alert::warning(_("Changes not shown in LaTeX output"),
840 _("Changes will not be highlighted in LaTeX output "
841 "when using pdflatex, because xcolor and ulem are not installed.\n"
842 "Please install both packages or redefine "
843 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
847 if (!params().master.empty()) {
848 FileName const master_file = makeAbsPath(params().master,
849 onlyPath(absFileName()));
850 if (isLyXFileName(master_file.absFileName())) {
852 checkAndLoadLyXFile(master_file, true);
854 // necessary e.g. after a reload
855 // to re-register the child (bug 5873)
856 // FIXME: clean up updateMacros (here, only
857 // child registering is needed).
858 master->updateMacros();
859 // set master as master buffer, but only
860 // if we are a real child
861 if (master->isChild(this))
863 // if the master is not fully loaded
864 // it is probably just loading this
865 // child. No warning needed then.
866 else if (master->isFullyLoaded())
867 LYXERR0("The master '"
869 << "' assigned to this document ("
871 << ") does not include "
872 "this document. Ignoring the master assignment.");
877 // assure we have a default index
878 params().indiceslist().addDefault(B_("Index"));
881 bool const res = text().read(lex, errorList, d->inset);
883 // inform parent buffer about local macros
885 Buffer const * pbuf = parent();
886 UserMacroSet::const_iterator cit = usermacros.begin();
887 UserMacroSet::const_iterator end = usermacros.end();
888 for (; cit != end; ++cit)
889 pbuf->usermacros.insert(*cit);
893 updateMacroInstances(InternalUpdate);
898 bool Buffer::readString(string const & s)
900 params().compressed = false;
905 FileName const fn = FileName::tempName("Buffer_readString");
908 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
909 if (ret_plf != ReadSuccess)
912 if (file_format != LYX_FORMAT) {
913 // We need to call lyx2lyx, so write the input to a file
914 ofstream os(fn.toFilesystemEncoding().c_str());
918 return readFile(fn) == ReadSuccess;
921 if (readDocument(lex))
927 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
931 if (!lex.setFile(fname)) {
932 Alert::error(_("File Not Found"),
933 bformat(_("Unable to open file `%1$s'."),
934 from_utf8(fn.absFileName())));
935 return ReadFileNotFound;
939 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
940 if (ret_plf != ReadSuccess)
943 if (file_format != LYX_FORMAT) {
945 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
946 if (ret_clf != ReadSuccess)
948 return readFile(tmpFile);
951 // FIXME: InsetInfo needs to know whether the file is under VCS
952 // during the parse process, so this has to be done before.
953 lyxvc().file_found_hook(d->filename);
955 if (readDocument(lex)) {
956 Alert::error(_("Document format failure"),
957 bformat(_("%1$s ended unexpectedly, which means"
958 " that it is probably corrupted."),
959 from_utf8(fn.absFileName())));
960 return ReadDocumentFailure;
963 d->file_fully_loaded = true;
964 d->read_only = !d->filename.isWritable();
965 params().compressed = d->filename.isZippedFile();
971 bool Buffer::isFullyLoaded() const
973 return d->file_fully_loaded;
977 void Buffer::setFullyLoaded(bool value)
979 d->file_fully_loaded = value;
983 PreviewLoader * Buffer::loader() const
985 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
987 if (!d->preview_loader_)
988 d->preview_loader_ = new PreviewLoader(*this);
989 return d->preview_loader_;
993 void Buffer::removePreviews() const
995 delete d->preview_loader_;
996 d->preview_loader_ = 0;
1000 void Buffer::updatePreviews() const
1002 PreviewLoader * ploader = loader();
1006 InsetIterator it = inset_iterator_begin(*d->inset);
1007 InsetIterator const end = inset_iterator_end(*d->inset);
1008 for (; it != end; ++it)
1009 it->addPreview(it, *ploader);
1011 ploader->startLoading();
1015 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1016 FileName const & fn, int & file_format) const
1018 if(!lex.checkFor("\\lyxformat")) {
1019 Alert::error(_("Document format failure"),
1020 bformat(_("%1$s is not a readable LyX document."),
1021 from_utf8(fn.absFileName())));
1022 return ReadNoLyXFormat;
1028 // LyX formats 217 and earlier were written as 2.17. This corresponds
1029 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1030 // these cases. See also: www.lyx.org/trac/changeset/1313.
1031 size_t dot = tmp_format.find_first_of(".,");
1032 if (dot != string::npos)
1033 tmp_format.erase(dot, 1);
1035 file_format = convert<int>(tmp_format);
1040 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1041 FileName & tmpfile, int from_format)
1043 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1044 if(tmpfile.empty()) {
1045 Alert::error(_("Conversion failed"),
1046 bformat(_("%1$s is from a different"
1047 " version of LyX, but a temporary"
1048 " file for converting it could"
1049 " not be created."),
1050 from_utf8(fn.absFileName())));
1051 return LyX2LyXNoTempFile;
1054 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1055 if (lyx2lyx.empty()) {
1056 Alert::error(_("Conversion script not found"),
1057 bformat(_("%1$s is from a different"
1058 " version of LyX, but the"
1059 " conversion script lyx2lyx"
1060 " could not be found."),
1061 from_utf8(fn.absFileName())));
1062 return LyX2LyXNotFound;
1066 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1067 ostringstream command;
1068 command << os::python()
1069 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1070 << " -t " << convert<string>(LYX_FORMAT)
1071 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1072 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1073 string const command_str = command.str();
1075 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1077 cmd_ret const ret = runCommand(command_str);
1078 if (ret.first != 0) {
1079 if (from_format < LYX_FORMAT) {
1080 Alert::error(_("Conversion script failed"),
1081 bformat(_("%1$s is from an older version"
1082 " of LyX and the lyx2lyx script"
1083 " failed to convert it."),
1084 from_utf8(fn.absFileName())));
1085 return LyX2LyXOlderFormat;
1087 Alert::error(_("Conversion script failed"),
1088 bformat(_("%1$s is from a newer version"
1089 " of LyX and the lyx2lyx script"
1090 " failed to convert it."),
1091 from_utf8(fn.absFileName())));
1092 return LyX2LyXNewerFormat;
1099 // Should probably be moved to somewhere else: BufferView? GuiView?
1100 bool Buffer::save() const
1102 docstring const file = makeDisplayPath(absFileName(), 20);
1103 d->filename.refresh();
1105 // check the read-only status before moving the file as a backup
1106 if (d->filename.exists()) {
1107 bool const read_only = !d->filename.isWritable();
1109 Alert::warning(_("File is read-only"),
1110 bformat(_("The file %1$s cannot be written because it "
1111 "is marked as read-only."), file));
1116 // ask if the disk file has been externally modified (use checksum method)
1117 if (fileName().exists() && isExternallyModified(checksum_method)) {
1119 bformat(_("Document %1$s has been externally modified. "
1120 "Are you sure you want to overwrite this file?"), file);
1121 int const ret = Alert::prompt(_("Overwrite modified file?"),
1122 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1127 // We don't need autosaves in the immediate future. (Asger)
1128 resetAutosaveTimers();
1130 FileName backupName;
1131 bool madeBackup = false;
1133 // make a backup if the file already exists
1134 if (lyxrc.make_backup && fileName().exists()) {
1135 backupName = FileName(absFileName() + '~');
1136 if (!lyxrc.backupdir_path.empty()) {
1137 string const mangledName =
1138 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1139 backupName = FileName(addName(lyxrc.backupdir_path,
1143 // Except file is symlink do not copy because of #6587.
1144 // Hard links have bad luck.
1145 if (fileName().isSymLink())
1146 madeBackup = fileName().copyTo(backupName);
1148 madeBackup = fileName().moveTo(backupName);
1151 Alert::error(_("Backup failure"),
1152 bformat(_("Cannot create backup file %1$s.\n"
1153 "Please check whether the directory exists and is writable."),
1154 from_utf8(backupName.absFileName())));
1155 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1159 if (writeFile(d->filename)) {
1163 // Saving failed, so backup is not backup
1165 backupName.moveTo(d->filename);
1171 bool Buffer::writeFile(FileName const & fname) const
1173 // FIXME Do we need to do these here? I don't think writing
1174 // the LyX file depends upon it. (RGH)
1176 // updateMacroInstances();
1178 if (d->read_only && fname == d->filename)
1181 bool retval = false;
1183 docstring const str = bformat(_("Saving document %1$s..."),
1184 makeDisplayPath(fname.absFileName()));
1187 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1189 if (params().compressed) {
1190 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1191 retval = ofs && write(ofs);
1193 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1194 retval = ofs && write(ofs);
1198 message(str + _(" could not write file!"));
1203 // removeAutosaveFile();
1206 message(str + _(" done."));
1212 docstring Buffer::emergencyWrite()
1214 // No need to save if the buffer has not changed.
1218 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1220 docstring user_message = bformat(
1221 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1223 // We try to save three places:
1224 // 1) Same place as document. Unless it is an unnamed doc.
1226 string s = absFileName();
1229 if (writeFile(FileName(s))) {
1231 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1232 return user_message;
1234 user_message += " " + _("Save failed! Trying again...\n");
1238 // 2) In HOME directory.
1239 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1241 lyxerr << ' ' << s << endl;
1242 if (writeFile(FileName(s))) {
1244 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1245 return user_message;
1248 user_message += " " + _("Save failed! Trying yet again...\n");
1250 // 3) In "/tmp" directory.
1251 // MakeAbsPath to prepend the current
1252 // drive letter on OS/2
1253 s = addName(package().temp_dir().absFileName(), absFileName());
1255 lyxerr << ' ' << s << endl;
1256 if (writeFile(FileName(s))) {
1258 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1259 return user_message;
1262 user_message += " " + _("Save failed! Bummer. Document is lost.");
1265 return user_message;
1269 bool Buffer::write(ostream & ofs) const
1272 // Use the standard "C" locale for file output.
1273 ofs.imbue(locale::classic());
1276 // The top of the file should not be written by params().
1278 // write out a comment in the top of the file
1279 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1280 << " created this file. For more info see http://www.lyx.org/\n"
1281 << "\\lyxformat " << LYX_FORMAT << "\n"
1282 << "\\begin_document\n";
1284 /// For each author, set 'used' to true if there is a change
1285 /// by this author in the document; otherwise set it to 'false'.
1286 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1287 AuthorList::Authors::const_iterator a_end = params().authors().end();
1288 for (; a_it != a_end; ++a_it)
1289 a_it->setUsed(false);
1291 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1292 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1293 for ( ; it != end; ++it)
1294 it->checkAuthors(params().authors());
1296 // now write out the buffer parameters.
1297 ofs << "\\begin_header\n";
1298 params().writeFile(ofs);
1299 ofs << "\\end_header\n";
1302 ofs << "\n\\begin_body\n";
1304 ofs << "\n\\end_body\n";
1306 // Write marker that shows file is complete
1307 ofs << "\\end_document" << endl;
1309 // Shouldn't really be needed....
1312 // how to check if close went ok?
1313 // Following is an attempt... (BE 20001011)
1315 // good() returns false if any error occured, including some
1316 // formatting error.
1317 // bad() returns true if something bad happened in the buffer,
1318 // which should include file system full errors.
1323 lyxerr << "File was not closed properly." << endl;
1330 bool Buffer::makeLaTeXFile(FileName const & fname,
1331 string const & original_path,
1332 OutputParams const & runparams_in,
1333 OutputWhat output) const
1335 OutputParams runparams = runparams_in;
1337 // This is necessary for LuaTeX/XeTeX with tex fonts.
1338 // See FIXME in BufferParams::encoding()
1339 if (runparams.isFullUnicode())
1340 runparams.encoding = encodings.fromLyXName("utf8-plain");
1342 string const encoding = runparams.encoding->iconvName();
1343 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1346 try { ofs.reset(encoding); }
1347 catch (iconv_codecvt_facet_exception & e) {
1348 lyxerr << "Caught iconv exception: " << e.what() << endl;
1349 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1350 "verify that the support software for your encoding (%1$s) is "
1351 "properly installed"), from_ascii(encoding)));
1354 if (!openFileWrite(ofs, fname))
1357 //TexStream ts(ofs.rdbuf(), &texrow());
1358 ErrorList & errorList = d->errorLists["Export"];
1360 bool failed_export = false;
1361 otexstream os(ofs, d->texrow);
1363 // make sure we are ready to export
1364 // this needs to be done before we validate
1365 // FIXME Do we need to do this all the time? I.e., in children
1366 // of a master we are exporting?
1368 updateMacroInstances(OutputUpdate);
1371 os.texrow().reset();
1372 writeLaTeXSource(os, original_path, runparams, output);
1374 catch (EncodingException & e) {
1375 odocstringstream ods;
1376 ods.put(e.failed_char);
1378 oss << "0x" << hex << e.failed_char << dec;
1379 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1380 " (code point %2$s)"),
1381 ods.str(), from_utf8(oss.str()));
1382 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1383 "representable in the chosen encoding.\n"
1384 "Changing the document encoding to utf8 could help."),
1385 e.par_id, e.pos, e.pos + 1));
1386 failed_export = true;
1388 catch (iconv_codecvt_facet_exception & e) {
1389 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1390 _(e.what()), -1, 0, 0));
1391 failed_export = true;
1393 catch (exception const & e) {
1394 errorList.push_back(ErrorItem(_("conversion failed"),
1395 _(e.what()), -1, 0, 0));
1396 failed_export = true;
1399 lyxerr << "Caught some really weird exception..." << endl;
1405 failed_export = true;
1406 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1410 return !failed_export;
1414 void Buffer::writeLaTeXSource(otexstream & os,
1415 string const & original_path,
1416 OutputParams const & runparams_in,
1417 OutputWhat output) const
1419 // The child documents, if any, shall be already loaded at this point.
1421 OutputParams runparams = runparams_in;
1423 // Classify the unicode characters appearing in math insets
1424 Encodings::initUnicodeMath(*this);
1426 // validate the buffer.
1427 LYXERR(Debug::LATEX, " Validating buffer...");
1428 LaTeXFeatures features(*this, params(), runparams);
1430 LYXERR(Debug::LATEX, " Buffer validation done.");
1432 bool const output_preamble =
1433 output == FullSource || output == OnlyPreamble;
1434 bool const output_body =
1435 output == FullSource || output == OnlyBody;
1437 // The starting paragraph of the coming rows is the
1438 // first paragraph of the document. (Asger)
1439 if (output_preamble && runparams.nice) {
1440 os << "%% LyX " << lyx_version << " created this file. "
1441 "For more info, see http://www.lyx.org/.\n"
1442 "%% Do not edit unless you really know what "
1445 LYXERR(Debug::INFO, "lyx document header finished");
1447 // There are a few differences between nice LaTeX and usual files:
1448 // usual files have \batchmode and special input@path to allow
1449 // inclusion of figures specified by an explicitly relative path
1450 // (i.e., a path starting with './' or '../') with either \input or
1451 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1452 // input@path is set when the actual parameter original_path is set.
1453 // This is done for usual tex-file, but not for nice-latex-file.
1454 // (Matthias 250696)
1455 // Note that input@path is only needed for something the user does
1456 // in the preamble, included .tex files or ERT, files included by
1457 // LyX work without it.
1458 if (output_preamble) {
1459 if (!runparams.nice) {
1460 // code for usual, NOT nice-latex-file
1461 os << "\\batchmode\n"; // changed from \nonstopmode
1463 if (!original_path.empty()) {
1465 // We don't know the encoding of inputpath
1466 docstring const inputpath = from_utf8(original_path);
1467 docstring uncodable_glyphs;
1468 Encoding const * const enc = runparams.encoding;
1470 for (size_t n = 0; n < inputpath.size(); ++n) {
1471 docstring const glyph =
1472 docstring(1, inputpath[n]);
1473 if (enc->latexChar(inputpath[n], true) != glyph) {
1474 LYXERR0("Uncodable character '"
1476 << "' in input path!");
1477 uncodable_glyphs += glyph;
1482 // warn user if we found uncodable glyphs.
1483 if (!uncodable_glyphs.empty()) {
1484 frontend::Alert::warning(
1485 _("Uncodable character in file path"),
1487 _("The path of your document\n"
1489 "contains glyphs that are unknown "
1490 "in the current document encoding "
1491 "(namely %2$s). This may result in "
1492 "incomplete output, unless "
1493 "TEXINPUTS contains the document "
1494 "directory and you don't use "
1495 "explicitly relative paths (i.e., "
1496 "paths starting with './' or "
1497 "'../') in the preamble or in ERT."
1498 "\n\nIn case of problems, choose "
1499 "an appropriate document encoding\n"
1500 "(such as utf8) or change the "
1502 inputpath, uncodable_glyphs));
1505 support::latex_path(original_path);
1506 if (contains(docdir, '#')) {
1507 docdir = subst(docdir, "#", "\\#");
1508 os << "\\catcode`\\#=11"
1509 "\\def\\#{#}\\catcode`\\#=6\n";
1511 if (contains(docdir, '%')) {
1512 docdir = subst(docdir, "%", "\\%");
1513 os << "\\catcode`\\%=11"
1514 "\\def\\%{%}\\catcode`\\%=14\n";
1516 os << "\\makeatletter\n"
1517 << "\\def\\input@path{{"
1518 << docdir << "/}}\n"
1519 << "\\makeatother\n";
1523 // get parent macros (if this buffer has a parent) which will be
1524 // written at the document begin further down.
1525 MacroSet parentMacros;
1526 listParentMacros(parentMacros, features);
1528 runparams.use_polyglossia = features.usePolyglossia();
1529 // Write the preamble
1530 runparams.use_babel = params().writeLaTeX(os, features,
1531 d->filename.onlyPath());
1533 runparams.use_japanese = features.isRequired("japanese");
1539 os << "\\begin{document}\n";
1541 // output the parent macros
1542 MacroSet::iterator it = parentMacros.begin();
1543 MacroSet::iterator end = parentMacros.end();
1544 for (; it != end; ++it) {
1545 int num_lines = (*it)->write(os.os(), true);
1546 os.texrow().newlines(num_lines);
1549 } // output_preamble
1551 os.texrow().start(paragraphs().begin()->id(), 0);
1553 LYXERR(Debug::INFO, "preamble finished, now the body.");
1555 // if we are doing a real file with body, even if this is the
1556 // child of some other buffer, let's cut the link here.
1557 // This happens for example if only a child document is printed.
1558 Buffer const * save_parent = 0;
1559 if (output_preamble) {
1560 save_parent = d->parent();
1565 latexParagraphs(*this, text(), os, runparams);
1567 // Restore the parenthood if needed
1568 if (output_preamble)
1569 d->setParent(save_parent);
1571 // add this just in case after all the paragraphs
1574 if (output_preamble) {
1575 os << "\\end{document}\n";
1576 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1578 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1580 runparams_in.encoding = runparams.encoding;
1582 // Just to be sure. (Asger)
1583 os.texrow().newline();
1585 //for (int i = 0; i<d->texrow.rows(); i++) {
1587 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1588 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1591 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1592 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1596 void Buffer::makeDocBookFile(FileName const & fname,
1597 OutputParams const & runparams,
1598 OutputWhat output) const
1600 LYXERR(Debug::LATEX, "makeDocBookFile...");
1603 if (!openFileWrite(ofs, fname))
1606 // make sure we are ready to export
1607 // this needs to be done before we validate
1609 updateMacroInstances(OutputUpdate);
1611 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1615 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1619 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1620 OutputParams const & runparams,
1621 OutputWhat output) const
1623 LaTeXFeatures features(*this, params(), runparams);
1628 DocumentClass const & tclass = params().documentClass();
1629 string const top_element = tclass.latexname();
1631 bool const output_preamble =
1632 output == FullSource || output == OnlyPreamble;
1633 bool const output_body =
1634 output == FullSource || output == OnlyBody;
1636 if (output_preamble) {
1637 if (runparams.flavor == OutputParams::XML)
1638 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1641 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1644 if (! tclass.class_header().empty())
1645 os << from_ascii(tclass.class_header());
1646 else if (runparams.flavor == OutputParams::XML)
1647 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1648 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1650 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1652 docstring preamble = from_utf8(params().preamble);
1653 if (runparams.flavor != OutputParams::XML ) {
1654 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1655 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1656 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1657 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1660 string const name = runparams.nice
1661 ? changeExtension(absFileName(), ".sgml") : fname;
1662 preamble += features.getIncludedFiles(name);
1663 preamble += features.getLyXSGMLEntities();
1665 if (!preamble.empty()) {
1666 os << "\n [ " << preamble << " ]";
1672 string top = top_element;
1674 if (runparams.flavor == OutputParams::XML)
1675 top += params().language->code();
1677 top += params().language->code().substr(0, 2);
1680 if (!params().options.empty()) {
1682 top += params().options;
1685 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1686 << " file was created by LyX " << lyx_version
1687 << "\n See http://www.lyx.org/ for more information -->\n";
1689 params().documentClass().counters().reset();
1691 sgml::openTag(os, top);
1693 docbookParagraphs(text(), *this, os, runparams);
1694 sgml::closeTag(os, top_element);
1699 void Buffer::makeLyXHTMLFile(FileName const & fname,
1700 OutputParams const & runparams) const
1702 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1705 if (!openFileWrite(ofs, fname))
1708 // make sure we are ready to export
1709 // this has to be done before we validate
1710 updateBuffer(UpdateMaster, OutputUpdate);
1711 updateMacroInstances(OutputUpdate);
1713 writeLyXHTMLSource(ofs, runparams, FullSource);
1717 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1721 void Buffer::writeLyXHTMLSource(odocstream & os,
1722 OutputParams const & runparams,
1723 OutputWhat output) const
1725 LaTeXFeatures features(*this, params(), runparams);
1727 d->bibinfo_.makeCitationLabels(*this);
1729 bool const output_preamble =
1730 output == FullSource || output == OnlyPreamble;
1731 bool const output_body =
1732 output == FullSource || output == OnlyBody;
1734 if (output_preamble) {
1735 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1736 << "<!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"
1737 // FIXME Language should be set properly.
1738 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1740 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1741 // FIXME Presumably need to set this right
1742 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1744 docstring const & doctitle = features.htmlTitle();
1746 << (doctitle.empty() ?
1747 from_ascii("LyX Document") :
1748 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1751 os << "\n<!-- Text Class Preamble -->\n"
1752 << features.getTClassHTMLPreamble()
1753 << "\n<!-- Preamble Snippets -->\n"
1754 << from_utf8(features.getPreambleSnippets());
1756 os << "\n<!-- Layout-provided Styles -->\n";
1757 docstring const styleinfo = features.getTClassHTMLStyles();
1758 if (!styleinfo.empty()) {
1759 os << "<style type='text/css'>\n"
1764 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1765 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1766 if (needfg || needbg) {
1767 os << "<style type='text/css'>\nbody {\n";
1770 << from_ascii(X11hexname(params().fontcolor))
1773 os << " background-color: "
1774 << from_ascii(X11hexname(params().backgroundcolor))
1776 os << "}\n</style>\n";
1784 params().documentClass().counters().reset();
1785 xhtmlParagraphs(text(), *this, xs, runparams);
1789 if (output_preamble)
1794 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1795 // Other flags: -wall -v0 -x
1796 int Buffer::runChktex()
1800 // get LaTeX-Filename
1801 FileName const path(temppath());
1802 string const name = addName(path.absFileName(), latexName());
1803 string const org_path = filePath();
1805 PathChanger p(path); // path to LaTeX file
1806 message(_("Running chktex..."));
1808 // Generate the LaTeX file if neccessary
1809 OutputParams runparams(¶ms().encoding());
1810 runparams.flavor = OutputParams::LATEX;
1811 runparams.nice = false;
1812 runparams.linelen = lyxrc.plaintext_linelen;
1813 makeLaTeXFile(FileName(name), org_path, runparams);
1816 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1817 int const res = chktex.run(terr); // run chktex
1820 Alert::error(_("chktex failure"),
1821 _("Could not run chktex successfully."));
1822 } else if (res > 0) {
1823 ErrorList & errlist = d->errorLists["ChkTeX"];
1825 bufferErrors(terr, errlist);
1836 void Buffer::validate(LaTeXFeatures & features) const
1838 params().validate(features);
1840 for_each(paragraphs().begin(), paragraphs().end(),
1841 bind(&Paragraph::validate, _1, ref(features)));
1843 if (lyxerr.debugging(Debug::LATEX)) {
1844 features.showStruct();
1849 void Buffer::getLabelList(vector<docstring> & list) const
1851 // If this is a child document, use the master's list instead.
1853 masterBuffer()->getLabelList(list);
1858 Toc & toc = d->toc_backend.toc("label");
1859 TocIterator toc_it = toc.begin();
1860 TocIterator end = toc.end();
1861 for (; toc_it != end; ++toc_it) {
1862 if (toc_it->depth() == 0)
1863 list.push_back(toc_it->str());
1868 void Buffer::updateBibfilesCache(UpdateScope scope) const
1870 // FIXME This is probably unnecssary, given where we call this.
1871 // If this is a child document, use the parent's cache instead.
1872 if (parent() && scope != UpdateChildOnly) {
1873 masterBuffer()->updateBibfilesCache();
1877 d->bibfiles_cache_.clear();
1878 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1879 if (it->lyxCode() == BIBTEX_CODE) {
1880 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1881 support::FileNameList const bibfiles = inset.getBibFiles();
1882 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1885 } else if (it->lyxCode() == INCLUDE_CODE) {
1886 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1887 Buffer const * const incbuf = inset.getChildBuffer();
1890 support::FileNameList const & bibfiles =
1891 incbuf->getBibfilesCache(UpdateChildOnly);
1892 if (!bibfiles.empty()) {
1893 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1899 d->bibfile_cache_valid_ = true;
1900 d->bibinfo_cache_valid_ = false;
1901 d->cite_labels_valid_ = false;
1905 void Buffer::invalidateBibinfoCache() const
1907 d->bibinfo_cache_valid_ = false;
1908 d->cite_labels_valid_ = false;
1909 // also invalidate the cache for the parent buffer
1910 Buffer const * const pbuf = d->parent();
1912 pbuf->invalidateBibinfoCache();
1916 void Buffer::invalidateBibfileCache() const
1918 d->bibfile_cache_valid_ = false;
1919 d->bibinfo_cache_valid_ = false;
1920 d->cite_labels_valid_ = false;
1921 // also invalidate the cache for the parent buffer
1922 Buffer const * const pbuf = d->parent();
1924 pbuf->invalidateBibfileCache();
1928 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1930 // FIXME This is probably unnecessary, given where we call this.
1931 // If this is a child document, use the master's cache instead.
1932 Buffer const * const pbuf = masterBuffer();
1933 if (pbuf != this && scope != UpdateChildOnly)
1934 return pbuf->getBibfilesCache();
1936 if (!d->bibfile_cache_valid_)
1937 this->updateBibfilesCache(scope);
1939 return d->bibfiles_cache_;
1943 BiblioInfo const & Buffer::masterBibInfo() const
1945 Buffer const * const tmp = masterBuffer();
1947 return tmp->masterBibInfo();
1952 void Buffer::checkIfBibInfoCacheIsValid() const
1954 // use the master's cache
1955 Buffer const * const tmp = masterBuffer();
1957 tmp->checkIfBibInfoCacheIsValid();
1961 // compare the cached timestamps with the actual ones.
1962 FileNameList const & bibfiles_cache = getBibfilesCache();
1963 FileNameList::const_iterator ei = bibfiles_cache.begin();
1964 FileNameList::const_iterator en = bibfiles_cache.end();
1965 for (; ei != en; ++ ei) {
1966 time_t lastw = ei->lastModified();
1967 time_t prevw = d->bibfile_status_[*ei];
1968 if (lastw != prevw) {
1969 d->bibinfo_cache_valid_ = false;
1970 d->cite_labels_valid_ = false;
1971 d->bibfile_status_[*ei] = lastw;
1977 void Buffer::reloadBibInfoCache() const
1979 // use the master's cache
1980 Buffer const * const tmp = masterBuffer();
1982 tmp->reloadBibInfoCache();
1986 checkIfBibInfoCacheIsValid();
1987 if (d->bibinfo_cache_valid_)
1990 d->bibinfo_.clear();
1992 d->bibinfo_cache_valid_ = true;
1996 void Buffer::collectBibKeys() const
1998 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1999 it->collectBibKeys(it);
2003 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2005 Buffer const * tmp = masterBuffer();
2006 BiblioInfo & masterbi = (tmp == this) ?
2007 d->bibinfo_ : tmp->d->bibinfo_;
2008 masterbi.mergeBiblioInfo(bi);
2012 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2014 Buffer const * tmp = masterBuffer();
2015 BiblioInfo & masterbi = (tmp == this) ?
2016 d->bibinfo_ : tmp->d->bibinfo_;
2021 bool Buffer::citeLabelsValid() const
2023 return masterBuffer()->d->cite_labels_valid_;
2027 bool Buffer::isDepClean(string const & name) const
2029 DepClean::const_iterator const it = d->dep_clean.find(name);
2030 if (it == d->dep_clean.end())
2036 void Buffer::markDepClean(string const & name)
2038 d->dep_clean[name] = true;
2042 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2045 // FIXME? if there is an Buffer LFUN that can be dispatched even
2046 // if internal, put a switch '(cmd.action)' here.
2052 switch (cmd.action()) {
2054 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2055 flag.setOnOff(isReadonly());
2058 // FIXME: There is need for a command-line import.
2059 //case LFUN_BUFFER_IMPORT:
2061 case LFUN_BUFFER_AUTO_SAVE:
2064 case LFUN_BUFFER_EXPORT_CUSTOM:
2065 // FIXME: Nothing to check here?
2068 case LFUN_BUFFER_EXPORT: {
2069 docstring const arg = cmd.argument();
2070 if (arg == "custom") {
2074 string format = to_utf8(arg);
2075 size_t pos = format.find(' ');
2076 if (pos != string::npos)
2077 format = format.substr(0, pos);
2078 enable = params().isExportable(format);
2080 flag.message(bformat(
2081 _("Don't know how to export to format: %1$s"), arg));
2085 case LFUN_BUFFER_CHKTEX:
2086 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2089 case LFUN_BUILD_PROGRAM:
2090 enable = params().isExportable("program");
2093 case LFUN_BRANCH_ACTIVATE:
2094 case LFUN_BRANCH_DEACTIVATE: {
2095 BranchList const & branchList = params().branchlist();
2096 docstring const branchName = cmd.argument();
2097 enable = !branchName.empty() && branchList.find(branchName);
2101 case LFUN_BRANCH_ADD:
2102 case LFUN_BRANCHES_RENAME:
2103 case LFUN_BUFFER_PRINT:
2104 // if no Buffer is present, then of course we won't be called!
2107 case LFUN_BUFFER_LANGUAGE:
2108 enable = !isReadonly();
2114 flag.setEnabled(enable);
2119 void Buffer::dispatch(string const & command, DispatchResult & result)
2121 return dispatch(lyxaction.lookupFunc(command), result);
2125 // NOTE We can end up here even if we have no GUI, because we are called
2126 // by LyX::exec to handled command-line requests. So we may need to check
2127 // whether we have a GUI or not. The boolean use_gui holds this information.
2128 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2131 // FIXME? if there is an Buffer LFUN that can be dispatched even
2132 // if internal, put a switch '(cmd.action())' here.
2133 dr.dispatched(false);
2136 string const argument = to_utf8(func.argument());
2137 // We'll set this back to false if need be.
2138 bool dispatched = true;
2139 undo().beginUndoGroup();
2141 switch (func.action()) {
2142 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2143 if (lyxvc().inUse())
2144 lyxvc().toggleReadOnly();
2146 setReadonly(!isReadonly());
2149 case LFUN_BUFFER_EXPORT: {
2150 ExportStatus const status = doExport(argument, false);
2151 dr.setError(status != ExportSuccess);
2152 if (status != ExportSuccess)
2153 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2158 case LFUN_BUILD_PROGRAM:
2159 doExport("program", true);
2162 case LFUN_BUFFER_CHKTEX:
2166 case LFUN_BUFFER_EXPORT_CUSTOM: {
2168 string command = split(argument, format_name, ' ');
2169 Format const * format = formats.getFormat(format_name);
2171 lyxerr << "Format \"" << format_name
2172 << "\" not recognized!"
2177 // The name of the file created by the conversion process
2180 // Output to filename
2181 if (format->name() == "lyx") {
2182 string const latexname = latexName(false);
2183 filename = changeExtension(latexname,
2184 format->extension());
2185 filename = addName(temppath(), filename);
2187 if (!writeFile(FileName(filename)))
2191 doExport(format_name, true, filename);
2194 // Substitute $$FName for filename
2195 if (!contains(command, "$$FName"))
2196 command = "( " + command + " ) < $$FName";
2197 command = subst(command, "$$FName", filename);
2199 // Execute the command in the background
2201 call.startscript(Systemcall::DontWait, command, filePath());
2205 // FIXME: There is need for a command-line import.
2207 case LFUN_BUFFER_IMPORT:
2212 case LFUN_BUFFER_AUTO_SAVE:
2214 resetAutosaveTimers();
2217 case LFUN_BRANCH_ADD: {
2218 docstring branch_name = func.argument();
2219 if (branch_name.empty()) {
2223 BranchList & branch_list = params().branchlist();
2224 vector<docstring> const branches =
2225 getVectorFromString(branch_name, branch_list.separator());
2227 for (vector<docstring>::const_iterator it = branches.begin();
2228 it != branches.end(); ++it) {
2230 Branch * branch = branch_list.find(branch_name);
2232 LYXERR0("Branch " << branch_name << " already exists.");
2236 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2238 branch_list.add(branch_name);
2239 branch = branch_list.find(branch_name);
2240 string const x11hexname = X11hexname(branch->color());
2241 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2242 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2244 dr.screenUpdate(Update::Force);
2252 case LFUN_BRANCH_ACTIVATE:
2253 case LFUN_BRANCH_DEACTIVATE: {
2254 BranchList & branchList = params().branchlist();
2255 docstring const branchName = func.argument();
2256 // the case without a branch name is handled elsewhere
2257 if (branchName.empty()) {
2261 Branch * branch = branchList.find(branchName);
2263 LYXERR0("Branch " << branchName << " does not exist.");
2265 docstring const msg =
2266 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2269 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2271 dr.screenUpdate(Update::Force);
2272 dr.forceBufferUpdate();
2277 case LFUN_BRANCHES_RENAME: {
2278 if (func.argument().empty())
2281 docstring const oldname = from_utf8(func.getArg(0));
2282 docstring const newname = from_utf8(func.getArg(1));
2283 InsetIterator it = inset_iterator_begin(inset());
2284 InsetIterator const end = inset_iterator_end(inset());
2285 bool success = false;
2286 for (; it != end; ++it) {
2287 if (it->lyxCode() == BRANCH_CODE) {
2288 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2289 if (ins.branch() == oldname) {
2290 undo().recordUndo(it);
2291 ins.rename(newname);
2296 if (it->lyxCode() == INCLUDE_CODE) {
2297 // get buffer of external file
2298 InsetInclude const & ins =
2299 static_cast<InsetInclude const &>(*it);
2300 Buffer * child = ins.getChildBuffer();
2303 child->dispatch(func, dr);
2308 dr.screenUpdate(Update::Force);
2309 dr.forceBufferUpdate();
2314 case LFUN_BUFFER_PRINT: {
2315 // we'll assume there's a problem until we succeed
2317 string target = func.getArg(0);
2318 string target_name = func.getArg(1);
2319 string command = func.getArg(2);
2322 || target_name.empty()
2323 || command.empty()) {
2324 LYXERR0("Unable to parse " << func.argument());
2325 docstring const msg =
2326 bformat(_("Unable to parse \"%1$s\""), func.argument());
2330 if (target != "printer" && target != "file") {
2331 LYXERR0("Unrecognized target \"" << target << '"');
2332 docstring const msg =
2333 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2338 if (!doExport("dvi", true)) {
2339 showPrintError(absFileName());
2340 dr.setMessage(_("Error exporting to DVI."));
2344 // Push directory path.
2345 string const path = temppath();
2346 // Prevent the compiler from optimizing away p
2350 // there are three cases here:
2351 // 1. we print to a file
2352 // 2. we print directly to a printer
2353 // 3. we print using a spool command (print to file first)
2356 string const dviname = changeExtension(latexName(true), "dvi");
2358 if (target == "printer") {
2359 if (!lyxrc.print_spool_command.empty()) {
2360 // case 3: print using a spool
2361 string const psname = changeExtension(dviname,".ps");
2362 command += ' ' + lyxrc.print_to_file
2365 + quoteName(dviname);
2367 string command2 = lyxrc.print_spool_command + ' ';
2368 if (target_name != "default") {
2369 command2 += lyxrc.print_spool_printerprefix
2373 command2 += quoteName(psname);
2375 // If successful, then spool command
2376 res = one.startscript(Systemcall::Wait, command,
2380 // If there's no GUI, we have to wait on this command. Otherwise,
2381 // LyX deletes the temporary directory, and with it the spooled
2382 // file, before it can be printed!!
2383 Systemcall::Starttype stype = use_gui ?
2384 Systemcall::DontWait : Systemcall::Wait;
2385 res = one.startscript(stype, command2,
2389 // case 2: print directly to a printer
2390 if (target_name != "default")
2391 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2393 Systemcall::Starttype stype = use_gui ?
2394 Systemcall::DontWait : Systemcall::Wait;
2395 res = one.startscript(stype, command +
2396 quoteName(dviname), filePath());
2400 // case 1: print to a file
2401 FileName const filename(makeAbsPath(target_name, filePath()));
2402 FileName const dvifile(makeAbsPath(dviname, path));
2403 if (filename.exists()) {
2404 docstring text = bformat(
2405 _("The file %1$s already exists.\n\n"
2406 "Do you want to overwrite that file?"),
2407 makeDisplayPath(filename.absFileName()));
2408 if (Alert::prompt(_("Overwrite file?"),
2409 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2412 command += ' ' + lyxrc.print_to_file
2413 + quoteName(filename.toFilesystemEncoding())
2415 + quoteName(dvifile.toFilesystemEncoding());
2417 Systemcall::Starttype stype = use_gui ?
2418 Systemcall::DontWait : Systemcall::Wait;
2419 res = one.startscript(stype, command, filePath());
2425 dr.setMessage(_("Error running external commands."));
2426 showPrintError(absFileName());
2435 dr.dispatched(dispatched);
2436 undo().endUndoGroup();
2440 void Buffer::changeLanguage(Language const * from, Language const * to)
2442 LASSERT(from, /**/);
2445 for_each(par_iterator_begin(),
2447 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2451 bool Buffer::isMultiLingual() const
2453 ParConstIterator end = par_iterator_end();
2454 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2455 if (it->isMultiLingual(params()))
2462 std::set<Language const *> Buffer::getLanguages() const
2464 std::set<Language const *> languages;
2465 getLanguages(languages);
2470 void Buffer::getLanguages(std::set<Language const *> & languages) const
2472 ParConstIterator end = par_iterator_end();
2473 // add the buffer language, even if it's not actively used
2474 languages.insert(language());
2475 // iterate over the paragraphs
2476 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2477 it->getLanguages(languages);
2479 ListOfBuffers clist = getDescendents();
2480 ListOfBuffers::const_iterator cit = clist.begin();
2481 ListOfBuffers::const_iterator const cen = clist.end();
2482 for (; cit != cen; ++cit)
2483 (*cit)->getLanguages(languages);
2487 DocIterator Buffer::getParFromID(int const id) const
2489 Buffer * buf = const_cast<Buffer *>(this);
2491 // John says this is called with id == -1 from undo
2492 lyxerr << "getParFromID(), id: " << id << endl;
2493 return doc_iterator_end(buf);
2496 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2497 if (it.paragraph().id() == id)
2500 return doc_iterator_end(buf);
2504 bool Buffer::hasParWithID(int const id) const
2506 return !getParFromID(id).atEnd();
2510 ParIterator Buffer::par_iterator_begin()
2512 return ParIterator(doc_iterator_begin(this));
2516 ParIterator Buffer::par_iterator_end()
2518 return ParIterator(doc_iterator_end(this));
2522 ParConstIterator Buffer::par_iterator_begin() const
2524 return ParConstIterator(doc_iterator_begin(this));
2528 ParConstIterator Buffer::par_iterator_end() const
2530 return ParConstIterator(doc_iterator_end(this));
2534 Language const * Buffer::language() const
2536 return params().language;
2540 docstring const Buffer::B_(string const & l10n) const
2542 return params().B_(l10n);
2546 bool Buffer::isClean() const
2548 return d->lyx_clean;
2552 bool Buffer::isExternallyModified(CheckMethod method) const
2554 LASSERT(d->filename.exists(), /**/);
2555 // if method == timestamp, check timestamp before checksum
2556 return (method == checksum_method
2557 || d->timestamp_ != d->filename.lastModified())
2558 && d->checksum_ != d->filename.checksum();
2562 void Buffer::saveCheckSum() const
2564 FileName const & file = d->filename;
2567 if (file.exists()) {
2568 d->timestamp_ = file.lastModified();
2569 d->checksum_ = file.checksum();
2571 // in the case of save to a new file.
2578 void Buffer::markClean() const
2580 if (!d->lyx_clean) {
2581 d->lyx_clean = true;
2584 // if the .lyx file has been saved, we don't need an
2586 d->bak_clean = true;
2587 d->undo_.markDirty();
2591 void Buffer::setUnnamed(bool flag)
2597 bool Buffer::isUnnamed() const
2604 /// Don't check unnamed, here: isInternal() is used in
2605 /// newBuffer(), where the unnamed flag has not been set by anyone
2606 /// yet. Also, for an internal buffer, there should be no need for
2607 /// retrieving fileName() nor for checking if it is unnamed or not.
2608 bool Buffer::isInternal() const
2610 return fileName().extension() == "internal";
2614 void Buffer::markDirty()
2617 d->lyx_clean = false;
2620 d->bak_clean = false;
2622 DepClean::iterator it = d->dep_clean.begin();
2623 DepClean::const_iterator const end = d->dep_clean.end();
2625 for (; it != end; ++it)
2630 FileName Buffer::fileName() const
2636 string Buffer::absFileName() const
2638 return d->filename.absFileName();
2642 string Buffer::filePath() const
2644 return d->filename.onlyPath().absFileName() + "/";
2648 bool Buffer::isReadonly() const
2650 return d->read_only;
2654 void Buffer::setParent(Buffer const * buffer)
2656 // Avoids recursive include.
2657 d->setParent(buffer == this ? 0 : buffer);
2662 Buffer const * Buffer::parent() const
2668 ListOfBuffers Buffer::allRelatives() const
2670 ListOfBuffers lb = masterBuffer()->getDescendents();
2671 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2676 Buffer const * Buffer::masterBuffer() const
2678 // FIXME Should be make sure we are not in some kind
2679 // of recursive include? A -> B -> A will crash this.
2680 Buffer const * const pbuf = d->parent();
2684 return pbuf->masterBuffer();
2688 bool Buffer::isChild(Buffer * child) const
2690 return d->children_positions.find(child) != d->children_positions.end();
2694 DocIterator Buffer::firstChildPosition(Buffer const * child)
2696 Impl::BufferPositionMap::iterator it;
2697 it = d->children_positions.find(child);
2698 if (it == d->children_positions.end())
2699 return DocIterator(this);
2704 bool Buffer::hasChildren() const
2706 return !d->children_positions.empty();
2710 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2712 // loop over children
2713 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2714 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2715 for (; it != end; ++it) {
2716 Buffer * child = const_cast<Buffer *>(it->first);
2718 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2719 if (bit != clist.end())
2721 clist.push_back(child);
2723 // there might be grandchildren
2724 child->collectChildren(clist, true);
2729 ListOfBuffers Buffer::getChildren() const
2732 collectChildren(v, false);
2733 // Make sure we have not included ourselves.
2734 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2735 if (bit != v.end()) {
2736 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2743 ListOfBuffers Buffer::getDescendents() const
2746 collectChildren(v, true);
2747 // Make sure we have not included ourselves.
2748 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2749 if (bit != v.end()) {
2750 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2757 template<typename M>
2758 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2763 typename M::const_iterator it = m.lower_bound(x);
2764 if (it == m.begin())
2772 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2773 DocIterator const & pos) const
2775 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2777 // if paragraphs have no macro context set, pos will be empty
2781 // we haven't found anything yet
2782 DocIterator bestPos = owner_->par_iterator_begin();
2783 MacroData const * bestData = 0;
2785 // find macro definitions for name
2786 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2787 if (nameIt != macros.end()) {
2788 // find last definition in front of pos or at pos itself
2789 PositionScopeMacroMap::const_iterator it
2790 = greatest_below(nameIt->second, pos);
2791 if (it != nameIt->second.end()) {
2793 // scope ends behind pos?
2794 if (pos < it->second.first) {
2795 // Looks good, remember this. If there
2796 // is no external macro behind this,
2797 // we found the right one already.
2798 bestPos = it->first;
2799 bestData = &it->second.second;
2803 // try previous macro if there is one
2804 if (it == nameIt->second.begin())
2811 // find macros in included files
2812 PositionScopeBufferMap::const_iterator it
2813 = greatest_below(position_to_children, pos);
2814 if (it == position_to_children.end())
2815 // no children before
2819 // do we know something better (i.e. later) already?
2820 if (it->first < bestPos )
2823 // scope ends behind pos?
2824 if (pos < it->second.first
2825 && (cloned_buffer_ ||
2826 theBufferList().isLoaded(it->second.second))) {
2827 // look for macro in external file
2829 MacroData const * data
2830 = it->second.second->getMacro(name, false);
2833 bestPos = it->first;
2839 // try previous file if there is one
2840 if (it == position_to_children.begin())
2845 // return the best macro we have found
2850 MacroData const * Buffer::getMacro(docstring const & name,
2851 DocIterator const & pos, bool global) const
2856 // query buffer macros
2857 MacroData const * data = d->getBufferMacro(name, pos);
2861 // If there is a master buffer, query that
2862 Buffer const * const pbuf = d->parent();
2864 d->macro_lock = true;
2865 MacroData const * macro = pbuf->getMacro(
2866 name, *this, false);
2867 d->macro_lock = false;
2873 data = MacroTable::globalMacros().get(name);
2882 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2884 // set scope end behind the last paragraph
2885 DocIterator scope = par_iterator_begin();
2886 scope.pit() = scope.lastpit() + 1;
2888 return getMacro(name, scope, global);
2892 MacroData const * Buffer::getMacro(docstring const & name,
2893 Buffer const & child, bool global) const
2895 // look where the child buffer is included first
2896 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2897 if (it == d->children_positions.end())
2900 // check for macros at the inclusion position
2901 return getMacro(name, it->second, global);
2905 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2907 pit_type const lastpit = it.lastpit();
2909 // look for macros in each paragraph
2910 while (it.pit() <= lastpit) {
2911 Paragraph & par = it.paragraph();
2913 // iterate over the insets of the current paragraph
2914 InsetList const & insets = par.insetList();
2915 InsetList::const_iterator iit = insets.begin();
2916 InsetList::const_iterator end = insets.end();
2917 for (; iit != end; ++iit) {
2918 it.pos() = iit->pos;
2920 // is it a nested text inset?
2921 if (iit->inset->asInsetText()) {
2922 // Inset needs its own scope?
2923 InsetText const * itext = iit->inset->asInsetText();
2924 bool newScope = itext->isMacroScope();
2926 // scope which ends just behind the inset
2927 DocIterator insetScope = it;
2930 // collect macros in inset
2931 it.push_back(CursorSlice(*iit->inset));
2932 updateMacros(it, newScope ? insetScope : scope);
2937 if (iit->inset->asInsetTabular()) {
2938 CursorSlice slice(*iit->inset);
2939 size_t const numcells = slice.nargs();
2940 for (; slice.idx() < numcells; slice.forwardIdx()) {
2941 it.push_back(slice);
2942 updateMacros(it, scope);
2948 // is it an external file?
2949 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2950 // get buffer of external file
2951 InsetInclude const & inset =
2952 static_cast<InsetInclude const &>(*iit->inset);
2954 Buffer * child = inset.getChildBuffer();
2959 // register its position, but only when it is
2960 // included first in the buffer
2961 if (children_positions.find(child) ==
2962 children_positions.end())
2963 children_positions[child] = it;
2965 // register child with its scope
2966 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2970 InsetMath * im = iit->inset->asInsetMath();
2971 if (doing_export && im) {
2972 InsetMathHull * hull = im->asHullInset();
2974 hull->recordLocation(it);
2977 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2981 MathMacroTemplate & macroTemplate =
2982 *iit->inset->asInsetMath()->asMacroTemplate();
2983 MacroContext mc(owner_, it);
2984 macroTemplate.updateToContext(mc);
2987 bool valid = macroTemplate.validMacro();
2988 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2989 // then the BufferView's cursor will be invalid in
2990 // some cases which leads to crashes.
2995 // FIXME (Abdel), I don't understandt why we pass 'it' here
2996 // instead of 'macroTemplate' defined above... is this correct?
2997 macros[macroTemplate.name()][it] =
2998 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3008 void Buffer::updateMacros() const
3013 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3015 // start with empty table
3017 d->children_positions.clear();
3018 d->position_to_children.clear();
3020 // Iterate over buffer, starting with first paragraph
3021 // The scope must be bigger than any lookup DocIterator
3022 // later. For the global lookup, lastpit+1 is used, hence
3023 // we use lastpit+2 here.
3024 DocIterator it = par_iterator_begin();
3025 DocIterator outerScope = it;
3026 outerScope.pit() = outerScope.lastpit() + 2;
3027 d->updateMacros(it, outerScope);
3031 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3033 InsetIterator it = inset_iterator_begin(inset());
3034 InsetIterator const end = inset_iterator_end(inset());
3035 for (; it != end; ++it) {
3036 if (it->lyxCode() == BRANCH_CODE) {
3037 InsetBranch & br = static_cast<InsetBranch &>(*it);
3038 docstring const name = br.branch();
3039 if (!from_master && !params().branchlist().find(name))
3040 result.push_back(name);
3041 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3042 result.push_back(name);
3045 if (it->lyxCode() == INCLUDE_CODE) {
3046 // get buffer of external file
3047 InsetInclude const & ins =
3048 static_cast<InsetInclude const &>(*it);
3049 Buffer * child = ins.getChildBuffer();
3052 child->getUsedBranches(result, true);
3055 // remove duplicates
3060 void Buffer::updateMacroInstances(UpdateType utype) const
3062 LYXERR(Debug::MACROS, "updateMacroInstances for "
3063 << d->filename.onlyFileName());
3064 DocIterator it = doc_iterator_begin(this);
3066 DocIterator const end = doc_iterator_end(this);
3067 for (; it != end; it.forwardInset()) {
3068 // look for MathData cells in InsetMathNest insets
3069 InsetMath * minset = it.nextInset()->asInsetMath();
3073 // update macro in all cells of the InsetMathNest
3074 DocIterator::idx_type n = minset->nargs();
3075 MacroContext mc = MacroContext(this, it);
3076 for (DocIterator::idx_type i = 0; i < n; ++i) {
3077 MathData & data = minset->cell(i);
3078 data.updateMacros(0, mc, utype);
3084 void Buffer::listMacroNames(MacroNameSet & macros) const
3089 d->macro_lock = true;
3091 // loop over macro names
3092 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3093 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3094 for (; nameIt != nameEnd; ++nameIt)
3095 macros.insert(nameIt->first);
3097 // loop over children
3098 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3099 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3100 for (; it != end; ++it)
3101 it->first->listMacroNames(macros);
3104 Buffer const * const pbuf = d->parent();
3106 pbuf->listMacroNames(macros);
3108 d->macro_lock = false;
3112 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3114 Buffer const * const pbuf = d->parent();
3119 pbuf->listMacroNames(names);
3122 MacroNameSet::iterator it = names.begin();
3123 MacroNameSet::iterator end = names.end();
3124 for (; it != end; ++it) {
3126 MacroData const * data =
3127 pbuf->getMacro(*it, *this, false);
3129 macros.insert(data);
3131 // we cannot access the original MathMacroTemplate anymore
3132 // here to calls validate method. So we do its work here manually.
3133 // FIXME: somehow make the template accessible here.
3134 if (data->optionals() > 0)
3135 features.require("xargs");
3141 Buffer::References & Buffer::references(docstring const & label)
3144 return const_cast<Buffer *>(masterBuffer())->references(label);
3146 RefCache::iterator it = d->ref_cache_.find(label);
3147 if (it != d->ref_cache_.end())
3148 return it->second.second;
3150 static InsetLabel const * dummy_il = 0;
3151 static References const dummy_refs;
3152 it = d->ref_cache_.insert(
3153 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3154 return it->second.second;
3158 Buffer::References const & Buffer::references(docstring const & label) const
3160 return const_cast<Buffer *>(this)->references(label);
3164 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3166 masterBuffer()->d->ref_cache_[label].first = il;
3170 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3172 return masterBuffer()->d->ref_cache_[label].first;
3176 void Buffer::clearReferenceCache() const
3179 d->ref_cache_.clear();
3183 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3186 //FIXME: This does not work for child documents yet.
3187 LASSERT(code == CITE_CODE, /**/);
3189 reloadBibInfoCache();
3191 // Check if the label 'from' appears more than once
3192 BiblioInfo const & keys = masterBibInfo();
3193 BiblioInfo::const_iterator bit = keys.begin();
3194 BiblioInfo::const_iterator bend = keys.end();
3195 vector<docstring> labels;
3197 for (; bit != bend; ++bit)
3199 labels.push_back(bit->first);
3201 if (count(labels.begin(), labels.end(), from) > 1)
3204 string const paramName = "key";
3205 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3206 if (it->lyxCode() == code) {
3207 InsetCommand * inset = it->asInsetCommand();
3210 docstring const oldValue = inset->getParam(paramName);
3211 if (oldValue == from)
3212 inset->setParam(paramName, to);
3218 void Buffer::getSourceCode(odocstream & os, string const format,
3219 pit_type par_begin, pit_type par_end,
3220 OutputWhat output) const
3222 OutputParams runparams(¶ms().encoding());
3223 runparams.nice = true;
3224 runparams.flavor = params().getOutputFlavor(format);
3225 runparams.linelen = lyxrc.plaintext_linelen;
3226 // No side effect of file copying and image conversion
3227 runparams.dryrun = true;
3229 if (output == CurrentParagraph) {
3230 runparams.par_begin = par_begin;
3231 runparams.par_end = par_end;
3232 if (par_begin + 1 == par_end) {
3234 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3238 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3239 convert<docstring>(par_begin),
3240 convert<docstring>(par_end - 1))
3247 // output paragraphs
3248 if (params().isDocBook())
3249 docbookParagraphs(text(), *this, os, runparams);
3250 else if (runparams.flavor == OutputParams::HTML) {
3252 xhtmlParagraphs(text(), *this, xs, runparams);
3254 // latex or literate
3255 otexstream ots(os, texrow);
3256 latexParagraphs(*this, text(), ots, runparams);
3260 if (output == FullSource)
3261 os << _("Preview source code");
3262 else if (output == OnlyPreamble)
3263 os << _("Preview preamble");
3264 else if (output == OnlyBody)
3265 os << _("Preview body");
3268 d->texrow.newline();
3269 d->texrow.newline();
3270 if (params().isDocBook())
3271 writeDocBookSource(os, absFileName(), runparams, output);
3272 else if (runparams.flavor == OutputParams::HTML)
3273 writeLyXHTMLSource(os, runparams, output);
3275 // latex or literate
3276 otexstream ots(os, d->texrow);
3277 writeLaTeXSource(ots, string(), runparams, output);
3283 ErrorList & Buffer::errorList(string const & type) const
3285 return d->errorLists[type];
3289 void Buffer::updateTocItem(std::string const & type,
3290 DocIterator const & dit) const
3293 d->gui_->updateTocItem(type, dit);
3297 void Buffer::structureChanged() const
3300 d->gui_->structureChanged();
3304 void Buffer::errors(string const & err, bool from_master) const
3307 d->gui_->errors(err, from_master);
3311 void Buffer::message(docstring const & msg) const
3314 d->gui_->message(msg);
3318 void Buffer::setBusy(bool on) const
3321 d->gui_->setBusy(on);
3325 void Buffer::updateTitles() const
3328 d->wa_->updateTitles();
3332 void Buffer::resetAutosaveTimers() const
3335 d->gui_->resetAutosaveTimers();
3339 bool Buffer::hasGuiDelegate() const
3345 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3354 class AutoSaveBuffer : public ForkedProcess {
3357 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3358 : buffer_(buffer), fname_(fname) {}
3360 virtual shared_ptr<ForkedProcess> clone() const
3362 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3367 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3368 from_utf8(fname_.absFileName())));
3369 return run(DontWait);
3373 virtual int generateChild();
3375 Buffer const & buffer_;
3380 int AutoSaveBuffer::generateChild()
3382 #if defined(__APPLE__)
3383 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3384 * We should use something else like threads.
3386 * Since I do not know how to determine at run time what is the OS X
3387 * version, I just disable forking altogether for now (JMarc)
3389 pid_t const pid = -1;
3391 // tmp_ret will be located (usually) in /tmp
3392 // will that be a problem?
3393 // Note that this calls ForkedCalls::fork(), so it's
3394 // ok cross-platform.
3395 pid_t const pid = fork();
3396 // If you want to debug the autosave
3397 // you should set pid to -1, and comment out the fork.
3398 if (pid != 0 && pid != -1)
3402 // pid = -1 signifies that lyx was unable
3403 // to fork. But we will do the save
3405 bool failed = false;
3406 FileName const tmp_ret = FileName::tempName("lyxauto");
3407 if (!tmp_ret.empty()) {
3408 buffer_.writeFile(tmp_ret);
3409 // assume successful write of tmp_ret
3410 if (!tmp_ret.moveTo(fname_))
3416 // failed to write/rename tmp_ret so try writing direct
3417 if (!buffer_.writeFile(fname_)) {
3418 // It is dangerous to do this in the child,
3419 // but safe in the parent, so...
3420 if (pid == -1) // emit message signal.
3421 buffer_.message(_("Autosave failed!"));
3425 if (pid == 0) // we are the child so...
3434 FileName Buffer::getEmergencyFileName() const
3436 return FileName(d->filename.absFileName() + ".emergency");
3440 FileName Buffer::getAutosaveFileName() const
3442 // if the document is unnamed try to save in the backup dir, else
3443 // in the default document path, and as a last try in the filePath,
3444 // which will most often be the temporary directory
3447 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3448 : lyxrc.backupdir_path;
3449 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3452 string const fname = "#" + d->filename.onlyFileName() + "#";
3454 return makeAbsPath(fname, fpath);
3458 void Buffer::removeAutosaveFile() const
3460 FileName const f = getAutosaveFileName();
3466 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3468 FileName const newauto = getAutosaveFileName();
3470 if (newauto != oldauto && oldauto.exists())
3471 if (!oldauto.moveTo(newauto))
3472 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3476 bool Buffer::autoSave() const
3478 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3479 if (buf->d->bak_clean || isReadonly())
3482 message(_("Autosaving current document..."));
3483 buf->d->bak_clean = true;
3485 FileName const fname = getAutosaveFileName();
3486 if (d->cloned_buffer_) {
3487 // If this buffer is cloned, we assume that
3488 // we are running in a separate thread already.
3489 FileName const tmp_ret = FileName::tempName("lyxauto");
3490 if (!tmp_ret.empty()) {
3492 // assume successful write of tmp_ret
3493 if (tmp_ret.moveTo(fname))
3496 // failed to write/rename tmp_ret so try writing direct
3497 return writeFile(fname);
3499 /// This function is deprecated as the frontend needs to take care
3500 /// of cloning the buffer and autosaving it in another thread. It
3501 /// is still here to allow (QT_VERSION < 0x040400).
3502 AutoSaveBuffer autosave(*this, fname);
3509 // helper class, to guarantee this gets reset properly
3510 class Buffer::MarkAsExporting {
3512 MarkAsExporting(Buffer const * buf) : buf_(buf)
3514 LASSERT(buf_, /* */);
3515 buf_->setExportStatus(true);
3519 buf_->setExportStatus(false);
3522 Buffer const * const buf_;
3527 void Buffer::setExportStatus(bool e) const
3529 d->doing_export = e;
3530 ListOfBuffers clist = getDescendents();
3531 ListOfBuffers::const_iterator cit = clist.begin();
3532 ListOfBuffers::const_iterator const cen = clist.end();
3533 for (; cit != cen; ++cit)
3534 (*cit)->d->doing_export = e;
3538 bool Buffer::isExporting() const
3540 return d->doing_export;
3544 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3548 return doExport(target, put_in_tempdir, result_file);
3551 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3552 string & result_file) const
3554 bool const update_unincluded =
3555 params().maintain_unincluded_children
3556 && !params().getIncludedChildren().empty();
3558 // (1) export with all included children (omit \includeonly)
3559 if (update_unincluded) {
3560 ExportStatus const status =
3561 doExport(target, put_in_tempdir, true, result_file);
3562 if (status != ExportSuccess)
3565 // (2) export with included children only
3566 return doExport(target, put_in_tempdir, false, result_file);
3570 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3571 bool includeall, string & result_file) const
3573 LYXERR(Debug::FILES, "target=" << target);
3574 OutputParams runparams(¶ms().encoding());
3575 string format = target;
3576 string dest_filename;
3577 size_t pos = target.find(' ');
3578 if (pos != string::npos) {
3579 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3580 format = target.substr(0, pos);
3581 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3582 FileName(dest_filename).onlyPath().createPath();
3583 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3585 MarkAsExporting exporting(this);
3586 string backend_format;
3587 runparams.flavor = OutputParams::LATEX;
3588 runparams.linelen = lyxrc.plaintext_linelen;
3589 runparams.includeall = includeall;
3590 vector<string> backs = params().backends();
3591 Converters converters = theConverters();
3592 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3593 // Get shortest path to format
3594 converters.buildGraph();
3595 Graph::EdgePath path;
3596 for (vector<string>::const_iterator it = backs.begin();
3597 it != backs.end(); ++it) {
3598 Graph::EdgePath p = converters.getPath(*it, format);
3599 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3600 backend_format = *it;
3605 if (!put_in_tempdir) {
3606 // Only show this alert if this is an export to a non-temporary
3607 // file (not for previewing).
3608 Alert::error(_("Couldn't export file"), bformat(
3609 _("No information for exporting the format %1$s."),
3610 formats.prettyName(format)));
3612 return ExportNoPathToFormat;
3614 runparams.flavor = converters.getFlavor(path);
3617 backend_format = format;
3618 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3619 // FIXME: Don't hardcode format names here, but use a flag
3620 if (backend_format == "pdflatex")
3621 runparams.flavor = OutputParams::PDFLATEX;
3622 else if (backend_format == "luatex")
3623 runparams.flavor = OutputParams::LUATEX;
3624 else if (backend_format == "dviluatex")
3625 runparams.flavor = OutputParams::DVILUATEX;
3626 else if (backend_format == "xetex")
3627 runparams.flavor = OutputParams::XETEX;
3630 string filename = latexName(false);
3631 filename = addName(temppath(), filename);
3632 filename = changeExtension(filename,
3633 formats.extension(backend_format));
3634 LYXERR(Debug::FILES, "filename=" << filename);
3636 // Plain text backend
3637 if (backend_format == "text") {
3638 runparams.flavor = OutputParams::TEXT;
3639 writePlaintextFile(*this, FileName(filename), runparams);
3642 else if (backend_format == "xhtml") {
3643 runparams.flavor = OutputParams::HTML;
3644 switch (params().html_math_output) {
3645 case BufferParams::MathML:
3646 runparams.math_flavor = OutputParams::MathAsMathML;
3648 case BufferParams::HTML:
3649 runparams.math_flavor = OutputParams::MathAsHTML;
3651 case BufferParams::Images:
3652 runparams.math_flavor = OutputParams::MathAsImages;
3654 case BufferParams::LaTeX:
3655 runparams.math_flavor = OutputParams::MathAsLaTeX;
3658 makeLyXHTMLFile(FileName(filename), runparams);
3659 } else if (backend_format == "lyx")
3660 writeFile(FileName(filename));
3662 else if (params().isDocBook()) {
3663 runparams.nice = !put_in_tempdir;
3664 makeDocBookFile(FileName(filename), runparams);
3667 else if (backend_format == format) {
3668 runparams.nice = true;
3669 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3670 if (d->cloned_buffer_) {
3671 d->cloned_buffer_->d->errorLists["Export"] =
3672 d->errorLists["Export"];
3676 } else if (!lyxrc.tex_allows_spaces
3677 && contains(filePath(), ' ')) {
3678 Alert::error(_("File name error"),
3679 _("The directory path to the document cannot contain spaces."));
3680 return ExportTexPathHasSpaces;
3682 runparams.nice = false;
3683 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3684 if (d->cloned_buffer_) {
3685 d->cloned_buffer_->d->errorLists["Export"] =
3686 d->errorLists["Export"];
3692 string const error_type = (format == "program")
3693 ? "Build" : params().bufferFormat();
3694 ErrorList & error_list = d->errorLists[error_type];
3695 string const ext = formats.extension(format);
3696 FileName const tmp_result_file(changeExtension(filename, ext));
3697 bool const success = converters.convert(this, FileName(filename),
3698 tmp_result_file, FileName(absFileName()), backend_format, format,
3701 // Emit the signal to show the error list or copy it back to the
3702 // cloned Buffer so that it can be emitted afterwards.
3703 if (format != backend_format) {
3704 if (d->cloned_buffer_) {
3705 d->cloned_buffer_->d->errorLists[error_type] =
3706 d->errorLists[error_type];
3709 // also to the children, in case of master-buffer-view
3710 ListOfBuffers clist = getDescendents();
3711 ListOfBuffers::const_iterator cit = clist.begin();
3712 ListOfBuffers::const_iterator const cen = clist.end();
3713 for (; cit != cen; ++cit) {
3714 if (d->cloned_buffer_) {
3715 // Enable reverse search by copying back the
3716 // texrow object to the cloned buffer.
3717 // FIXME: this is not thread safe.
3718 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3719 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3720 (*cit)->d->errorLists[error_type];
3722 (*cit)->errors(error_type, true);
3726 if (d->cloned_buffer_) {
3727 // Enable reverse dvi or pdf to work by copying back the texrow
3728 // object to the cloned buffer.
3729 // FIXME: There is a possibility of concurrent access to texrow
3730 // here from the main GUI thread that should be securized.
3731 d->cloned_buffer_->d->texrow = d->texrow;
3732 string const error_type = params().bufferFormat();
3733 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3737 return ExportConverterError;
3739 if (put_in_tempdir) {
3740 result_file = tmp_result_file.absFileName();
3741 return ExportSuccess;
3744 if (dest_filename.empty())
3745 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3747 result_file = dest_filename;
3748 // We need to copy referenced files (e. g. included graphics
3749 // if format == "dvi") to the result dir.
3750 vector<ExportedFile> const files =
3751 runparams.exportdata->externalFiles(format);
3752 string const dest = runparams.export_folder.empty() ?
3753 onlyPath(result_file) : runparams.export_folder;
3754 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3755 : force_overwrite == ALL_FILES;
3756 CopyStatus status = use_force ? FORCE : SUCCESS;
3758 vector<ExportedFile>::const_iterator it = files.begin();
3759 vector<ExportedFile>::const_iterator const en = files.end();
3760 for (; it != en && status != CANCEL; ++it) {
3761 string const fmt = formats.getFormatFromFile(it->sourceName);
3762 string fixedName = it->exportName;
3763 if (!runparams.export_folder.empty()) {
3764 // Relative pathnames starting with ../ will be sanitized
3765 // if exporting to a different folder
3766 while (fixedName.substr(0, 3) == "../")
3767 fixedName = fixedName.substr(3, fixedName.length() - 3);
3769 FileName fixedFileName = makeAbsPath(fixedName, dest);
3770 fixedFileName.onlyPath().createPath();
3771 status = copyFile(fmt, it->sourceName,
3773 it->exportName, status == FORCE,
3774 runparams.export_folder.empty());
3777 if (status == CANCEL) {
3778 message(_("Document export cancelled."));
3779 return ExportCancel;
3782 if (tmp_result_file.exists()) {
3783 // Finally copy the main file
3784 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3785 : force_overwrite != NO_FILES;
3786 if (status == SUCCESS && use_force)
3788 status = copyFile(format, tmp_result_file,
3789 FileName(result_file), result_file,
3791 if (status == CANCEL) {
3792 message(_("Document export cancelled."));
3793 return ExportCancel;
3795 message(bformat(_("Document exported as %1$s "
3797 formats.prettyName(format),
3798 makeDisplayPath(result_file)));
3801 // This must be a dummy converter like fax (bug 1888)
3802 message(bformat(_("Document exported as %1$s"),
3803 formats.prettyName(format)));
3806 return ExportSuccess;
3810 Buffer::ExportStatus Buffer::preview(string const & format) const
3812 bool const update_unincluded =
3813 params().maintain_unincluded_children
3814 && !params().getIncludedChildren().empty();
3815 return preview(format, update_unincluded);
3818 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3820 MarkAsExporting exporting(this);
3822 // (1) export with all included children (omit \includeonly)
3824 ExportStatus const status = doExport(format, true, true, result_file);
3825 if (status != ExportSuccess)
3828 // (2) export with included children only
3829 ExportStatus const status = doExport(format, true, false, result_file);
3830 if (status != ExportSuccess)
3832 if (!formats.view(*this, FileName(result_file), format))
3833 return PreviewError;
3834 return PreviewSuccess;
3838 Buffer::ReadStatus Buffer::extractFromVC()
3840 bool const found = LyXVC::file_not_found_hook(d->filename);
3842 return ReadFileNotFound;
3843 if (!d->filename.isReadableFile())
3849 Buffer::ReadStatus Buffer::loadEmergency()
3851 FileName const emergencyFile = getEmergencyFileName();
3852 if (!emergencyFile.exists()
3853 || emergencyFile.lastModified() <= d->filename.lastModified())
3854 return ReadFileNotFound;
3856 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3857 docstring const text = bformat(_("An emergency save of the document "
3858 "%1$s exists.\n\nRecover emergency save?"), file);
3860 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3861 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3867 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3868 bool const success = (ret_llf == ReadSuccess);
3871 Alert::warning(_("File is read-only"),
3872 bformat(_("An emergency file is successfully loaded, "
3873 "but the original file %1$s is marked read-only. "
3874 "Please make sure to save the document as a different "
3875 "file."), from_utf8(d->filename.absFileName())));
3878 str = _("Document was successfully recovered.");
3880 str = _("Document was NOT successfully recovered.");
3881 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3882 makeDisplayPath(emergencyFile.absFileName()));
3884 int const del_emerg =
3885 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3886 _("&Remove"), _("&Keep"));
3887 if (del_emerg == 0) {
3888 emergencyFile.removeFile();
3890 Alert::warning(_("Emergency file deleted"),
3891 _("Do not forget to save your file now!"), true);
3893 return success ? ReadSuccess : ReadEmergencyFailure;
3896 int const del_emerg =
3897 Alert::prompt(_("Delete emergency file?"),
3898 _("Remove emergency file now?"), 1, 1,
3899 _("&Remove"), _("&Keep"));
3901 emergencyFile.removeFile();
3902 return ReadOriginal;
3912 Buffer::ReadStatus Buffer::loadAutosave()
3914 // Now check if autosave file is newer.
3915 FileName const autosaveFile = getAutosaveFileName();
3916 if (!autosaveFile.exists()
3917 || autosaveFile.lastModified() <= d->filename.lastModified())
3918 return ReadFileNotFound;
3920 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3921 docstring const text = bformat(_("The backup of the document %1$s "
3922 "is newer.\n\nLoad the backup instead?"), file);
3923 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3924 _("&Load backup"), _("Load &original"), _("&Cancel"));
3929 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3930 // the file is not saved if we load the autosave file.
3931 if (ret_llf == ReadSuccess) {
3933 Alert::warning(_("File is read-only"),
3934 bformat(_("A backup file is successfully loaded, "
3935 "but the original file %1$s is marked read-only. "
3936 "Please make sure to save the document as a "
3938 from_utf8(d->filename.absFileName())));
3943 return ReadAutosaveFailure;
3946 // Here we delete the autosave
3947 autosaveFile.removeFile();
3948 return ReadOriginal;
3956 Buffer::ReadStatus Buffer::loadLyXFile()
3958 if (!d->filename.isReadableFile()) {
3959 ReadStatus const ret_rvc = extractFromVC();
3960 if (ret_rvc != ReadSuccess)
3964 ReadStatus const ret_re = loadEmergency();
3965 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3968 ReadStatus const ret_ra = loadAutosave();
3969 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3972 return loadThisLyXFile(d->filename);
3976 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3978 return readFile(fn);
3982 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3984 TeXErrors::Errors::const_iterator it = terr.begin();
3985 TeXErrors::Errors::const_iterator end = terr.end();
3986 ListOfBuffers clist = getDescendents();
3987 ListOfBuffers::const_iterator cen = clist.end();
3989 for (; it != end; ++it) {
3992 int errorRow = it->error_in_line;
3993 Buffer const * buf = 0;
3995 if (it->child_name.empty())
3996 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
3998 // The error occurred in a child
3999 ListOfBuffers::const_iterator cit = clist.begin();
4000 for (; cit != cen; ++cit) {
4001 string const child_name =
4002 DocFileName(changeExtension(
4003 (*cit)->absFileName(), "tex")).
4005 if (it->child_name != child_name)
4007 (*cit)->d->texrow.getIdFromRow(errorRow,
4008 id_start, pos_start);
4009 if (id_start != -1) {
4010 buf = d->cloned_buffer_
4011 ? (*cit)->d->cloned_buffer_->d->owner_
4012 : (*cit)->d->owner_;
4023 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4024 } while (found && id_start == id_end && pos_start == pos_end);
4026 if (id_start != id_end) {
4027 // Next registered position is outside the inset where
4028 // the error occurred, so signal end-of-paragraph
4032 errorList.push_back(ErrorItem(it->error_desc,
4033 it->error_text, id_start, pos_start, pos_end, buf));
4038 void Buffer::setBuffersForInsets() const
4040 inset().setBuffer(const_cast<Buffer &>(*this));
4044 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4046 // Use the master text class also for child documents
4047 Buffer const * const master = masterBuffer();
4048 DocumentClass const & textclass = master->params().documentClass();
4050 // do this only if we are the top-level Buffer
4052 reloadBibInfoCache();
4054 // keep the buffers to be children in this set. If the call from the
4055 // master comes back we can see which of them were actually seen (i.e.
4056 // via an InsetInclude). The remaining ones in the set need still be updated.
4057 static std::set<Buffer const *> bufToUpdate;
4058 if (scope == UpdateMaster) {
4059 // If this is a child document start with the master
4060 if (master != this) {
4061 bufToUpdate.insert(this);
4062 master->updateBuffer(UpdateMaster, utype);
4063 // Do this here in case the master has no gui associated with it. Then,
4064 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4065 if (!master->d->gui_)
4068 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4069 if (bufToUpdate.find(this) == bufToUpdate.end())
4073 // start over the counters in the master
4074 textclass.counters().reset();
4077 // update will be done below for this buffer
4078 bufToUpdate.erase(this);
4080 // update all caches
4081 clearReferenceCache();
4084 Buffer & cbuf = const_cast<Buffer &>(*this);
4086 LASSERT(!text().paragraphs().empty(), /**/);
4089 ParIterator parit = cbuf.par_iterator_begin();
4090 updateBuffer(parit, utype);
4093 // TocBackend update will be done later.
4096 d->bibinfo_cache_valid_ = true;
4097 d->cite_labels_valid_ = true;
4098 cbuf.tocBackend().update();
4099 if (scope == UpdateMaster)
4100 cbuf.structureChanged();
4104 static depth_type getDepth(DocIterator const & it)
4106 depth_type depth = 0;
4107 for (size_t i = 0 ; i < it.depth() ; ++i)
4108 if (!it[i].inset().inMathed())
4109 depth += it[i].paragraph().getDepth() + 1;
4110 // remove 1 since the outer inset does not count
4114 static depth_type getItemDepth(ParIterator const & it)
4116 Paragraph const & par = *it;
4117 LabelType const labeltype = par.layout().labeltype;
4119 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4122 // this will hold the lowest depth encountered up to now.
4123 depth_type min_depth = getDepth(it);
4124 ParIterator prev_it = it;
4127 --prev_it.top().pit();
4129 // start of nested inset: go to outer par
4131 if (prev_it.empty()) {
4132 // start of document: nothing to do
4137 // We search for the first paragraph with same label
4138 // that is not more deeply nested.
4139 Paragraph & prev_par = *prev_it;
4140 depth_type const prev_depth = getDepth(prev_it);
4141 if (labeltype == prev_par.layout().labeltype) {
4142 if (prev_depth < min_depth)
4143 return prev_par.itemdepth + 1;
4144 if (prev_depth == min_depth)
4145 return prev_par.itemdepth;
4147 min_depth = min(min_depth, prev_depth);
4148 // small optimization: if we are at depth 0, we won't
4149 // find anything else
4150 if (prev_depth == 0)
4156 static bool needEnumCounterReset(ParIterator const & it)
4158 Paragraph const & par = *it;
4159 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4160 depth_type const cur_depth = par.getDepth();
4161 ParIterator prev_it = it;
4162 while (prev_it.pit()) {
4163 --prev_it.top().pit();
4164 Paragraph const & prev_par = *prev_it;
4165 if (prev_par.getDepth() <= cur_depth)
4166 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4168 // start of nested inset: reset
4173 // set the label of a paragraph. This includes the counters.
4174 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4176 BufferParams const & bp = owner_->masterBuffer()->params();
4177 DocumentClass const & textclass = bp.documentClass();
4178 Paragraph & par = it.paragraph();
4179 Layout const & layout = par.layout();
4180 Counters & counters = textclass.counters();
4182 if (par.params().startOfAppendix()) {
4183 // FIXME: only the counter corresponding to toplevel
4184 // sectioning should be reset
4186 counters.appendix(true);
4188 par.params().appendix(counters.appendix());
4190 // Compute the item depth of the paragraph
4191 par.itemdepth = getItemDepth(it);
4193 if (layout.margintype == MARGIN_MANUAL) {
4194 if (par.params().labelWidthString().empty())
4195 par.params().labelWidthString(par.expandLabel(layout, bp));
4196 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4197 // we do not need to do anything here, since the empty case is
4198 // handled during export.
4200 par.params().labelWidthString(docstring());
4203 switch(layout.labeltype) {
4205 if (layout.toclevel <= bp.secnumdepth
4206 && (layout.latextype != LATEX_ENVIRONMENT
4207 || it.text()->isFirstInSequence(it.pit()))) {
4208 if (counters.hasCounter(layout.counter))
4209 counters.step(layout.counter, utype);
4210 par.params().labelString(par.expandLabel(layout, bp));
4212 par.params().labelString(docstring());
4215 case LABEL_ITEMIZE: {
4216 // At some point of time we should do something more
4217 // clever here, like:
4218 // par.params().labelString(
4219 // bp.user_defined_bullet(par.itemdepth).getText());
4220 // for now, use a simple hardcoded label
4221 docstring itemlabel;
4222 switch (par.itemdepth) {
4224 itemlabel = char_type(0x2022);
4227 itemlabel = char_type(0x2013);
4230 itemlabel = char_type(0x2217);
4233 itemlabel = char_type(0x2219); // or 0x00b7
4236 par.params().labelString(itemlabel);
4240 case LABEL_ENUMERATE: {
4241 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4243 switch (par.itemdepth) {
4252 enumcounter += "iv";
4255 // not a valid enumdepth...
4259 // Maybe we have to reset the enumeration counter.
4260 if (needEnumCounterReset(it))
4261 counters.reset(enumcounter);
4262 counters.step(enumcounter, utype);
4264 string const & lang = par.getParLanguage(bp)->code();
4265 par.params().labelString(counters.theCounter(enumcounter, lang));
4270 case LABEL_SENSITIVE: {
4271 string const & type = counters.current_float();
4272 docstring full_label;
4274 full_label = owner_->B_("Senseless!!! ");
4276 docstring name = owner_->B_(textclass.floats().getType(type).name());
4277 if (counters.hasCounter(from_utf8(type))) {
4278 string const & lang = par.getParLanguage(bp)->code();
4279 counters.step(from_utf8(type), utype);
4280 full_label = bformat(from_ascii("%1$s %2$s:"),
4282 counters.theCounter(from_utf8(type), lang));
4284 full_label = bformat(from_ascii("%1$s #:"), name);
4286 par.params().labelString(full_label);
4290 case LABEL_NO_LABEL:
4291 par.params().labelString(docstring());
4295 case LABEL_TOP_ENVIRONMENT:
4296 case LABEL_CENTERED_TOP_ENVIRONMENT:
4299 par.params().labelString(par.expandLabel(layout, bp));
4305 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4307 LASSERT(parit.pit() == 0, /**/);
4309 // Set the position of the text in the buffer to be able
4310 // to resolve macros in it.
4311 parit.text()->setMacrocontextPosition(parit);
4313 depth_type maxdepth = 0;
4314 pit_type const lastpit = parit.lastpit();
4315 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4316 // reduce depth if necessary
4317 parit->params().depth(min(parit->params().depth(), maxdepth));
4318 maxdepth = parit->getMaxDepthAfter();
4320 if (utype == OutputUpdate) {
4321 // track the active counters
4322 // we have to do this for the master buffer, since the local
4323 // buffer isn't tracking anything.
4324 masterBuffer()->params().documentClass().counters().
4325 setActiveLayout(parit->layout());
4328 // set the counter for this paragraph
4329 d->setLabel(parit, utype);
4332 InsetList::const_iterator iit = parit->insetList().begin();
4333 InsetList::const_iterator end = parit->insetList().end();
4334 for (; iit != end; ++iit) {
4335 parit.pos() = iit->pos;
4336 iit->inset->updateBuffer(parit, utype);
4342 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4343 WordLangTuple & word_lang, docstring_list & suggestions) const
4347 suggestions.clear();
4348 word_lang = WordLangTuple();
4349 bool const to_end = to.empty();
4350 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4351 // OK, we start from here.
4352 for (; from != end; from.forwardPos()) {
4353 // We are only interested in text so remove the math CursorSlice.
4354 while (from.inMathed()) {
4358 // If from is at the end of the document (which is possible
4359 // when leaving the mathed) LyX will crash later otherwise.
4360 if (from.atEnd() || (!to_end && from >= end))
4363 from.paragraph().spellCheck();
4364 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4365 if (SpellChecker::misspelled(res)) {
4370 // Do not increase progress when from == to, otherwise the word
4371 // count will be wrong.
4381 Buffer::ReadStatus Buffer::reload()
4384 // c.f. bug http://www.lyx.org/trac/ticket/6587
4385 removeAutosaveFile();
4386 // e.g., read-only status could have changed due to version control
4387 d->filename.refresh();
4388 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4390 ReadStatus const status = loadLyXFile();
4391 if (status == ReadSuccess) {
4396 message(bformat(_("Document %1$s reloaded."), disp_fn));
4399 message(bformat(_("Could not reload document %1$s."), disp_fn));
4409 bool Buffer::saveAs(FileName const & fn)
4411 FileName const old_name = fileName();
4412 FileName const old_auto = getAutosaveFileName();
4413 bool const old_unnamed = isUnnamed();
4420 // bring the autosave file with us, just in case.
4421 moveAutosaveFile(old_auto);
4422 // validate version control data and
4423 // correct buffer title
4424 lyxvc().file_found_hook(fileName());
4426 // the file has now been saved to the new location.
4427 // we need to check that the locations of child buffers
4429 checkChildBuffers();
4433 // reset the old filename and unnamed state
4434 setFileName(old_name);
4435 setUnnamed(old_unnamed);
4441 // FIXME We could do better here, but it is complicated. What would be
4442 // nice is to offer either (a) to save the child buffer to an appropriate
4443 // location, so that it would "move with the master", or else (b) to update
4444 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4445 // complicated, because the code for this lives in GuiView.
4446 void Buffer::checkChildBuffers()
4448 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4449 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4450 for (; it != en; ++it) {
4451 DocIterator dit = it->second;
4452 Buffer * cbuf = const_cast<Buffer *>(it->first);
4453 if (!cbuf || !theBufferList().isLoaded(cbuf))
4455 Inset * inset = dit.nextInset();
4456 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4457 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4458 docstring const & incfile = inset_inc->getParam("filename");
4459 string oldloc = cbuf->absFileName();
4460 string newloc = makeAbsPath(to_utf8(incfile),
4461 onlyPath(absFileName())).absFileName();
4462 if (oldloc == newloc)
4464 // the location of the child file is incorrect.
4465 Alert::warning(_("Included File Invalid"),
4466 bformat(_("Saving this document to a new location has made the file:\n"
4468 "inaccessible. You will need to update the included filename."),
4469 from_utf8(oldloc)));
4471 inset_inc->setChildBuffer(0);
4473 // invalidate cache of children
4474 d->children_positions.clear();
4475 d->position_to_children.clear();